Search code examples
classoopinheritancecomposition

Domain Class vs Implementation Class


I was reading an article about composition vs inheritance and the article uses the terms "domain class" and "implementation class". The author specifically says "Domain classes should use implementation classes, not inherit from them". Please explain the difference between a domain class and an implementation class.


Solution

  • The example of an implementation class given in the article is ArrayList. It's not part of the code describing business entities, it's just a commonly-used general purpose class.

    This contrasts with the Customer class that they mention. Customer would be a class that is part of the domain, where it is describing an entity specific to the business.

    The article is telling you not to extend from utility classes like this when creating domain classes.

    How to Misuse Inheritance - Example 2

    Creating a domain-concept class by inheriting from an implementation class is a common misuse of inheritance. For example, suppose we want to do something with a certain segment of our customers. The easy and obvious thing to do is to subclass ArrayList, call it CustomerGroup, and start coding, right?

    Wrong. That would be a cross-domain inheritance relationship, and those should be avoided:

    1) ArrayList is a subclass of list already, a utility collection - an implementation class.

    2) CustomerGroup is another subclass - a domain class.

    3) Domain classes should use implementation classes, not inherit from them.

    If you need to implement a CustomerGroup class it could have an ArrayList as an instance member, like this:

    public class CustomerGroup {
        private List<Customer> customers = new ArrayList<>();
    
        public List<Customer> getCustomers() {return customers;}
    } 
    

    but you wouldn't make the class itself be a subclass of ArrayList.

    The reason is that when you subclass something the users of your class get all the functionality of the superclass even if it isn't appropriate. You don't really need a domain class to see this in action, just go check out the source for java.util.Properties, which is badly designed, extending java.util.Hashtable. When you use a Properties object the methods from Hashtable are available to you, even though they are totally unnecessary and confusing, and using the superclass methods doesn't work or causes problems.