It’s a newbie question. In my simple learning rock-scissors-paper game program I have single game instance class. Game instace class has several private members like total turns count, wins count, tie count etc. These class members are used only in public game instance’s class method, which starting and processing a game. Should I create special private getters and setters methods for my class members following good code style? Does it better to work directly with class members in game processing method?
class GameInstance{
unsigned int m_totalTurns;
unsigned int m_wins;
unsigned int m_loses;
unsigned int m_ties;
int getWins() const; // is it a bad idea?
int getLoses() const; // is it a bad idea?
int getTotalTurns() const; // is it a bad idea?
int getTies() const; // is it a bad idea?
// some setters-like incrementing // is it a bad idea?
// same private members functions // is it a bad idea?
// .... // is it a bad idea?
void finishGame();
public:
explicit GameInstance():m_totalTurns(0), m_wins(0), m_loses(0), m_ties(0){};
void startGame();
};
You’d probably make the getters public or there is no point in having them.
With regards to any getters or setters, they are part of the interface of the class. If you don’t want to externally allow getting these members directly or setting them, do not expose getters and setters.
With yours, getters might be an idea, setters looks it might be a bad idea, if you would rather have
addResult()which specifies a win, tie or loss and adds one to the relevant stat.As an alternative to individual getters you might have a “getGameStats()” which returns all 4 in one go.
If you are asking about getters rather than giving public access (rather than not giving access at all), for classes that have methods you should normally make all your data members private and use getters and if necessary, setters. It is also easier to debug code that is using them as you can insert breakpoints to the point the variables are being accessed.
In a “pure data” struct you can make members public. In fact in this case you might have a “GameStats” struct that you would return from a getGameStats() function. GameStats itself would just contain numbers and you could make these public. However the instance of GameStats within your class should be a private instance.