Java Conventions: use getters/setters WITHIN the class?

前端 未结 12 1822
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 02:32

My professor really emphasizes protecting against privacy leaks by always using accessors and mutators to access private instance variables; however, do I have to use the ge

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 03:00

    In general, no. If your getter returns something other than the value of the field then you should use the method, but in that rare case your method should have a more descriptive name. For a bad example, if you have:

    public void setName(String name)
    {
      _name = name;
    }
    

    and your getter returned something else, like

    public String getName()
    {
      return _name.toUpperCase();
    }
    

    then yes, you should use the getter. It would be better, though, to have a more descriptive name for that getter:

    public String getNameAsUppercase()
    {
      return _name.toUpperCase();
    }
    

提交回复
热议问题