How many times have I seen this pattern in object oriented code?
- Public Class
- All members of the class are private
- All members can be accessed with accessor functions
- All members can be changed with modifier functions
I hate to break it to y’all, but that’s just a struct. The only thing you’ve done is add a hundred lines to a simple process.
Access Functions: Only What You Need
The purpose of an access function is simple: to provide access to a portion of the data, while hiding the structure of the class.
As such, it only makes sense to provide access functions in two cases:
- When it’s important to obscure how a structure works (due to complex operations, typedef abstraction, etc.)
- When it’s important to restrict how much information you reveal
In either of those cases, you only need enough functions to suit the need. If you’re exposing the entire structure to the world, there was no reason to make anything private in the first place.
Modifier Functions: Only what you want to change
If your structure or class contains constants you set only once, why would you create explicit modifier functions for it?
Or, if you always modify a set of values simultaneously, why would you create individual modifier functions?
Think about your design before coding up modifier functions.
Constructors: Two Types
There are two reasons to create an explicit constructor function:
- You have to allocate values inside of the new structure (a char *, for example)
- You want to fill the new structure with default values of some kind (perhaps by input)
In the first case, you usually call either another constructor or an allocation function inside of the constructor, and don’t worry so much about anything else.
In the second case, you have two options:
- Take no arguments, and fill in the variables with a general default value
- Take some arguments, and fill in some variables with specific values
Note that I don’t list among the options “Fill every variable at once”. While not inherently bad, this pattern shows up with alarming frequency in poorly-designed code. I recommend that you consider exactly how many variables you need to fill with a non-default value on initialization.
Destructors: Only One Type
Destructor functions should always follow the same pattern:
- Destroy any allocated values inside the structure
- Destroy the structure
If your destructor does anything else (besides, perhaps, print something), you should reevaluate your design.