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

后端 未结 13 1689
无人共我
无人共我 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:44

    Depending on how your application is designed, the two options might actually give different results! If the age instance you're using is shared and mutable, different places in your application might change its value in between your calls to getAge(). In this case, it's a matter of correctness to decide which is the best option for your code, and it's up to you to decide. As the old adage says: "first make it right, then make it fast". And, as others have already mentioned, you probably won't need to worry about the "make it fast" part in this case.

    A related example is when you're changing a collection while iterating through it. You have to iterate over a snapshot to not get a ConcurrentModificationException.

提交回复
热议问题