Inheritance or Service for common Domain methods?

寵の児 提交于 2019-12-22 00:26:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!