I have some methods that are common across a few of my domain classes. I want to reduce the amount of replicated code and two solutions came to mind:
1) Put the common methods in a baseDomain class and inherit the methods from it in my domains
2) Put the common methods in a commonDomainMethodService which I can import into my domains
I am thinking I should leave inheritance alone unless the domains share common properties, but I’m not sure. Is one of these methods more beneficial than the other? Is one more in line with Grails best practices?
For example a method that compares two domain instances based on a parameter:
int compareInstances(instance, otherInstance, propertyName){
return //some logic to compare the instances based on the type of property
}
For that case I would use a
Mixin: Mixin Reading and Further Mixin ReadingFor example:
Now all instances of DomainA and DomainB would have your
comparemethod. This way you can implement multiple Mixins to add functionality to the domain classes that you want to without having to extend a super class or implement it in a service. (I’d assume that you’d want yourcomparemethod to be a little more sophisticated than this but you get the idea)Some potential Gotchas:
1) private methods within
mixin‘s seem to not work.2) having a circular dependency of
mixin‘s is also bad: MixinClassA mixes in MixinClassB which mixes in MixinClassA (for your setup I don’t think you would havemixin‘s mixing in othermixin‘s).3) I forget what happens with a method collision so you should probably experiment. Example: ClassA has a doStuff() method and mixes in DoStuffMixin which also has a doStuff() method.
4) Keep in mind that in a class that you’re using as a
mixinyou can refer tothiswhich will be the instance of the object that is using themixin. For instance in the example above you could remove theinstance1and replace it withthis. At runtimethiswill be either an instance of DomainA or DomainB (which I feel is a very powerful part of mixins).Those are the big gotchas I can think of.