问题
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
}
回答1:
For that case I would use a Mixin
: Mixin Reading and Further Mixin Reading
For example:
@Mixin(MyCompare)
class DomainA {
}
@Mixin(MyCompare)
class DomainB {
}
class MyCompare {
def compare(instance1, instance2, propertyName) {
instance1[propertyName] == instance2[propertyname]
}
}
Now all instances of DomainA and DomainB would have your compare
method. 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 your compare
method 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 have mixin
's mixing in other mixin
'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 mixin
you can refer to this
which will be the instance of the object that is using the mixin
. For instance in the example above you could remove the instance1
and replace it with this
. At runtime this
will 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.
来源:https://stackoverflow.com/questions/10125053/inheritance-or-service-for-common-domain-methods