Domanda

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?

È stato utile?

Soluzione

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)

Altri suggerimenti

I can't speak to the C++ syntax burden but in general object oriented terms you should supply getters and setters because other classes have no business knowing how you store your internal state, including which properties are directly stored, which are computed based on other state and which are devolved further to other objects. Making a contractual announcement with the wider world about how a class will store state will limit the adjustments you can make in the future, often inhibiting optimisation and breaking your code as the problem you're solving becomes more nuanced.

  1. They enable one to control access. You can have read only, read/write or even just write
  2. It enables one to change the underlying implementation if necessary. Consider computing the average speed for a number of vehicles. You could implement this by storing a list of speeds and then compute the average when required OR keep a running total and number.
  3. All access to class is via methods. Makes it easier to spot errors.
  4. It is not a lot of effort. Can use a script to just create them.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top