Wed, 07 Dec 2005
Comments
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.
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.