Search code examples
javaencapsulationpojoseparation-of-concerns

Java state checking methods in object vs separation of concerns


I have a class as below

public class Employee {
    private String id;
    private String name;
    private String address;
    private String department;

    //setters and getters
    //overridden equals and hashcode methods

    public Boolean hasAllEmployeeFields() {
        //null and empty check on fields
    }

    public Boolean hasAddress() {
        //null and empty check on Address
    }

    public Boolean hasAssignedDepartment() {
        return department != null;
    }
}

Apart from the setters and getters, this also has some methods to determine the state of the object. As these methods are meant to determine the state of the object, I think these methods very much belong to the class. Some of the examples are Java’s Date, Calendar and String classes etc. These objects hold the data and also have several methods to determine the state.

Another approach is the ‘Separation of Concerns’ where we leave the object as POJO with attributes, setters and getters and move the methods to a utility. With this approach, everyone checking the state should first remember to check the utility classes for the existence of a utility method. And I have seen several applications that had code duplication with logic to check these states in multiple places.

I am more leaning towards my first approach to keep these methods in the Employee object. But when I put this for discussion I think most of our colleagues would support for separation of concerns approach. Could someone please help me understand how my thoughts would stand compared to separation of concerns.


Solution

  • Encapsulation is one of fundamental characteristics of OOP in java.

    In my opinion, an object should be able to query its characteristics with the highest security (Think when its state is stored in private field with no getter) and accurarcy (because the object contains all internal properties). An object is atomic, autonomous if designed this way.

    If you want to determine a characteristics of an object, ask it, right?

    Your methods: hasAllEmployeeFields, hasAddress... are perfect examples for this.

    A characteristic should be queryable from outside if and only if the object itself cannot determine it, and needs cooperation from another object.

    For example: We have an object Market {double avgPrice;} and an entobject ty Product {double price;}. To determine if this Product is luxury, we need to cooperate these two objects by the equation price > 5 * avgPrice. Hence that characteristics determination logic should be placed in an utility method.