I'm currently thinking about an interface to a class I'm writing. This class contains styles for a character, for example whether the character is bold, italic, underlined, etc. I've been debating with myself for two days whether I should use getters/setters or logical names for the methods which change the values to these styles. While I tend to prefer logical names, it does mean writing code that is not as efficient and not as logical. Let me give you an example.
I've got a class CharacterStyles
which has member variables bold
, italic
, underline
(and some others, but I'll leave them out to keep it simple). The easiest way to allow other parts of the program to access these variables, would be to write getter/setter methods, so that you can do styles.setBold(true)
and styles.setItalic(false)
.
But I do not like this. Not only because a lot of people say that getters/setters break encapsulation (is it really that bad?), but mostly because it doesn't seem logical to me. I expect to style a character through one method, styles.format("bold", true)
or something like that, but not through all these methods.
There is one problem though. Since you can't access an object member variable by the contents of a string in C++, I would either have to write a big if-statement/switch container for all styles, or I would have to store the styles in an associative array (map).
I can't figure out what the best way is. One moment I think I should write the getters/setters, and the next moment I lean towards the other way. My question is: what would you do? And why would you do that?
bold
set totrue
and the other variables undefined, the getter methods for the other variables should return the value of the parent style (which is stored in another property), while the getter for thebold
property should returntrue
. There are some other things like a name and the way it's displayed in the interface as well.