Search code examples
c++attributesaccessormutators

Accessor and Mutator Methods


Possible Duplicate:
Why use getters and setters?

It seems to me like a major hassle to write accessor and mutator methods, particularly when dealing with very simple attributes. Why should I bother using them?


Solution

  • The answer mainly depends on what are you writing code for and how much you trust yourself if working alone:

    • keeping variables private is useful when you work with people or when you want to enforce a compile time check to be sure you are not using them outside the class
    • setters are useful if you have side effects
    • getters are useful if you have side effects or when you want to keep variables read only
    • having or not having getters and setters is your choice, if other people are going to use your classes then encapsulation maybe a good thing because of information hiding principle
    • if you are the only one working on your project just do what you feel to do, you will be in time to add them at a later step if you really feel the need to
    • since we're talking about C++ don't forget the friend directive that allows fine grain encapsulation without the bother of having setters and getters (even if it encourages coupling so there are two different schools of thinking here)