Search code examples
javaconstructorencapsulation

Can I call a set Method inside a Constructor


I have a number of set methods setup and using a constructor to initiate their value as follows. It is working but I am concerned as to whether it is a normal Java convention to do so (is it normal to call a set method inside a constructor?).

The alternative way I can think of is to call an empty constructor and call the set methods one by one in the main method to set the value. I find this second method tedious. Please advice if what I have done is fine/ within Java convention or if there is a better way to do it. Do tell if I need to post more code to make my question more clearer. I can post it all if it would make better sense. Thank you.

public Person(String foreName,String surName, int age, double height, String gender){
        personCount++; 
        setForeName(foreName);
        setSurName(surName);
        setAge(age);
        setHeight(height);
        setGender(gender); 
    }

Solution

  • It's not just a matter of taste. If there isn't any extra logic in the setXXX() methods, the convention is to assign the attributes directly in the constructor:

    this.foreName = foreName;
    this.surName = surName;
    

    ... And so on. But if there is extra logic in the setXXX() methods, then you should use them as required. Say, a call to logging logic or similar:

    public void setForeName(String pForeName) {
        log.info("setting new foreName value: " + pForeName);
        this.foreName = pForeName;
    }
    

    See how the last line in setForeName() is the same as performing a direct assignment? Also notice that calling a setXXX() might have a very, very small cost in performance (most likely optimized away by the JIT compiler). Under normal circumstances you should optimize for readability and clarity above all, and IMHO using a direct assignment here is the preferred option.