Convention for calculating class attribute in Java constructor

Viewed 59

What's the convention for calculating a class attribute in Java?

For example, doing the calculation directly in the constructor:

public class Person {
    public Person(int birthyear){
        this.birthyear = birthyear;
        this.age = 2020 - birthyear;
    }    
}

compared to calling a method that does the calculation:

public class Person {
    public Person(int birthyear){
        this.birthyear = birthyear;
        this.age = calculateAge(birthyear);
    }    
}

Where the calculation is complex (not like here), I'm inclined to go with the second example, but would like to follow conventions, where possible.

This may be a duplicate, in which case please point me in the right direction (couldn't find it from my searching).

1 Answers

There is not really a convention. It rather depends on the complexity or readability of the calculations. For a simple one like 2020 - birthyear I would consider it perfectly fine if it were put right there in the constructor.

With more complex cases, I would rather defer it to a method. But remember: make sure you make it private, otherwise a subclass can get access to a not fully constructed object.

Related