Fri, 02 Dec 2005

OOP Strikes Back

Steinar, you missed my point. I explicitly said not to get bogged down in my example. The point is that changing the internal details of your class shouldn't result in your users being forced to change their code. As I said, exposing your implementation tightly couples your code and your users. As Matthew pointed out, you shouldn't have sets and gets for every item in your class. You should have a clearly thought out api that isn't tied to the internal detail. Exposing internal, either through making data public or blindly creating gets and sets for private data members is just bad OO design.

An addition to my example that makes things little cleared would be a subclass that validated the words you could use. With a public variable I couldn't enforce that, but I could override my setter to add validation.

[] | # Read Comments (0) |

Comments

Thu, 01 Dec 2005

Return of Accessors vs. public member variables

Steinar, Imagine a Word class:

class WordA {
   public:
      char * word;
};
class WordB {
   private:
      char * word;
   public:
      void setWord(char * w) { word = w; }
      char * getWord() { return word; }
};

WordA worda; 
worda.word = "WordA";

WordB wordb;
wordb.setWord("WordB");

printf("%s %s", worda.word, wordb.getWord());

Fine, this works well. Now imagine that you want to change word from a char * to a std::string to stop you dealing with pointers. For the WordBclass you only need to change the getWord function. You don't need to change any of your class's users. For the WordA class, you have a problem because you can't automatically convert from a std::string to a char *, so all your users have to change from object.word to object.word.c_str().

class WordA {
   public:
      std::string word;
};
class WordB {
   private:
      std::string word;
   public:
      void setWord(char * w) { word = w; }
      char * getWord() { return word.c_str(); }
};

WordA worda; 
worda.word = "WordA";

WordB wordb;
wordb.setWord("WordB");

printf("%s %s", worda.word.c_str(), wordb.getWord());

This is the punishment you get for exposing the internal details of your class to your users. Please ignore any specific mistakes in my examples; the principles work the same with different types.

[, ] | # Read Comments (0) |

Comments

Wed, 30 Nov 2005

Accessors vs. public member variables

Steinar, you use accessor rather than public data members because you may need to change the behaviour of the class to do something when you set a member variable. If you have all your data public, you can't do this. If you force people to go via a function, you can make changes to the class without affecting its users. You have a similar issue with inherited classes.

[] | # Read Comments (0) |

Comments