This question already has an answer here:
- When are Getters and Setters Justified 14 answers
As a student in programming, I learned that encapsulation is one of the most important principles of object-oriented programming.
However, I only follow that principle when I feel like it suits my purpose. I sometimes leave internal class variables public if they are intended to be directly read at some time, and only use things like setters and getters when there are actual calculations (and assignments of other variables) involved in the assignment/evaluation of a variable (say, a
getDegrees() of an
Angle class that only stores radians internally).
If I find that some procedure done with a class involves a lot of modification of internal variables and is easily groupable into a single operation, I will put it into a function of the class rather than having the outside code call multiple smaller functions. However, I will not always enforce this in the interface by making the affected variables private instead.
Am I violating any principles by doing this? If so, how severely? The code that does this usually doesn't face outward, as I pay a lot of attention to how out-of-program input is processed.