Is it bad to put helper functions on a data class?...
# announcements
Is it bad to put helper functions on a data class? For example say I have data classes that hold configuration/setting data for different kinds of actions. There can be lots of different types so it has a type field. Eventually I need to map it to the actual action class with business logic that uses the configuration/setting data. I could do a when(type) and instantiate respective action class and pass in the config data class. Or could I add something like: fun toActionClass(): SpecificActionClass = SpecificActionClass(this)
I'd define the function you gave as an extension function. Then it doesn't clutter the data class itself but is usable with that nice syntax in the scope you find appropriate
I don't see any problem in your conversion/map function, but don't add too much logic inside your Data Class.
I really like to follow the information provided by #detekt about it: This rule reports functions inside data classes which have not been whitelisted as a conversion function. Data classes should mainly be used to store data. This rule assumes that they should not contain any extra functions aside functions that help with converting objects from/to one another. Data classes will automatically have a generated
function by the compiler.
@escodro So that's saying as long as it's a version method (toSomething) then it's fine?
@Drew Hamilton I'd rather define it in data class, it's a quick one liner and anyone adding a data class in the future will look at an example of one and know they need it. Are extension functions really that much better?
🤷 It's a nice delineation of responsibility to me. It's not `Something`'s purpose to know what
is, only to hold some data. Conversion function as extension or not is a one-liner either way.
@dMusicb I think so, in general. But if your app is separated in modules, for example, maybe this conversion should be done in a separate class, in the module where it would need to be converted. Otherwise it will not match the module scope.
☝️ 1