Java Conventions: use getters/setters WITHIN the class?

前端 未结 12 1818
被撕碎了的回忆
被撕碎了的回忆 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:01

    When I design a class I try to make a clear distinction between the inside (implementation details) and the outside (the interface exposed to the world). Getters and setters provide a convenient place to convert values between the form in which they are stored in the object’s instance members and the form in which the outside world sees them. Using getters and setters internally would muck that up, because they'd be getting used by both the inside and outside.

    If you find yourself wanting to hide part of a class from another part of the same class, consider breaking off the part you want to hide into its own class.

提交回复
热议问题