Calling a getter multiple times or calling once and assigning to a variable?

后端 未结 13 1720
无人共我
无人共我 2021-02-05 15:26

say suppose I have class as :

public class Age {

    private int age;

    public int getAge() {
       return this.age;
    }

}

In my Main c

13条回答
  •  南笙
    南笙 (楼主)
    2021-02-05 15:59

    In this case, I'd suggest don't look at performance, look at usability and code reuse. Your current implementation is the simplest of getters, one that returns an integer.

    But what if somewhere down the line you store a person's birthdate and want to dynamically generate the age? If you simply call the property directly, you then are forced to refactor your code. However, altering getAge()'s internals, you can put the calculation in there, and you're done.

    I'd really like programming languages to introduce a 'super-private' property / field modifier, one that basically says 'You can only access this property through its accessor'.

提交回复
热议问题