Why does Google name accessors and mutators after member variables? - c++

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Function_Names#Function_Names
Regular functions have mixed case; accessors and mutators match the
name of the variable: MyExcitingFunction(), MyExcitingMethod(),
my_exciting_member_variable(), set_my_exciting_member_variable().
Isn't it the whole point of encapsulation to hide implementation details from the user so he/she is not aware of whether the accessor/mutator method returns/modifies a member variable or not? What if I change the variable name or change the way it's stored inside the object?
EDIT:
If I have an instance variable int foo_ it seems straightforward
int foo() const { return foo_; }
but if I add another method that returns foo_ + 2, should I name if bar or GetBar?
int bar() const { return foo_ + 2; }
int GetBar() const { return foo_ + 2; }
If I choose GetBar and later decide to cache the returned value in another member variable bar_, will I have to rename the method to bar?

Actually, the point of encapsulation is to hide the inner workings of a class, not necessarily to hide the names of things. The name of the member variable doesn't matter; it's the level of indirection that the accessor or mutator provides.
Having an accessor gives you the ability to change the inner workings of the class (including the names of member variables) without breaking the class's interface with the outside world. The user of the class need not concern himself with implementation details, including what things are named inside the class, but only on the behavior of the class, as seen from the outside.
To put it another way, users of a class should not rely on Google's style guide to determine whether or not they are modifying a member variable.

Because google style guide is only meant to be followed by google employees. Rather - it's not that good of a style guide.
Case in point - they explicitly ban passing by non-const reference because it can be "confusing".
So you're right, it defeats the purpose of encapsulation. Don't guide yourself by it.

When considering a class, it may conceptually have visible
state, which can be accessed by the client. How this state is
represented inside the class is another matter, and that's what
accessors (getters and setters) hide. My own naming convention
also makes this distinction: if the function is conceptually
a getter or a setter, it has the name of the attribute, which
would normally be a noun; otherwise, it is a verb. And
I distinguish between cases where the function is getting or
setting something which isn't conceptually part of the class
(e.g. which partially depends on an argument), which have the
verb get or set in their name, and the case where the
function is actually modifying what is conceptually an
attribute, in which case they don't.
For the rest, like most style guides, not everyone is in total
agreement with this one. I'm not sure I like their naming
conventions, for example. They're called naming conventions
because they are just that: arbitrary conventions. The only
real hard rule is that types, macros and other things must be
distinguished, and that names should never start or end with an
underscore. (There are also some softer rules: I'd be very
suspicious of a convention which ended up making the names of
local variables longer than those of globals.)

I may be taking an assumption of common sense too far, but I'm pretty sure that retaining a published interface takes precedence over following the naming guide.
Since your original bar / GetBar function is not an accessor, I presume it should follow the regular name guide and be called GetBar.
If you later introduce bar_ so that in some sense the function becomes an accessor, I'm pretty sure you should not remove GetBar. I suppose you could add a function bar() as well, defined to do the same thing, but I don't think I'd interpret the style guide to require that.
I'm also pretty sure that as soon as your published interface includes functions that you (and callers) think of as "accessors", encapsulation is in any case out the window to some extent, because you're talking about the state of the object instead of its behavior. Just because a function returns the value of a member variable in the current implementation does not mean that it has to be documented as an accessor. But if you do insist on writing functions that are publicly recognized as accessors, Google tells you how to name them. The classic example is that a sufficiently dumb data record object might reasonably have accessors, since the whole class is publicly defined to be a bundle of fields with maybe a little bit of behavior.
I've read that style guide a few times before, but I have never worked for Google so I'm not privy to how their code reviews tend to apply it in practice. I should think that an organization that size cannot be wholly consistent in every detail. So your guess is probably as good as mine.

Related

C++ Why should I use get and set functions when working with classes [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 9 years ago.
I've been told not to make my variables public inside a class. I should always make a get and a set function. For example :
class Whatever
{
public:
void setSentence(const std::string &str) { sentence = str; }
void setAnInteger(const int integer) { anInteger = integer; }
std::string getSentence() { return sentence; }
int getAnInteger() { return anInteger; }
private:
std::string sentence;
int anInteger;
};
Why should I do that? Isn't just simply using those variables more convenient? Also, is that a good c++ programming style?
The main reason is to increase encapsulation. If your class exposes those member variables, many functions in your client code will have a dependency towards those variables.
Suppose one day you want want to change the name of those variables, or you want to change the implementation of your class so that the type and number of member variables would be different than the current one: how many functions would be affected by this change? How many functions would you have to re-write (at least in part)?
Right, potentially infinite. You just can't count them all. On the other hand, if you have getters and setters, only those 4 functions will have access to the internal representation of your class. Changing the internal representation won't require any change to the code of your client functions; only those 4 member functions may have to be changed.
In general, encapsulation makes your life easier with respect to future changes. At a certain point in time you may want to log a message every time a certain property is set. You may want to fire an event every time a certain property is set. You may want to compute a certain value on the fly rather than reading it each time from a cache data member, or read it from a database, or whatever.
Having getters and setters allow you to implement any of those changes without requiring to change the client code.
As far as general design philosophy is concerned, there is no "always" or "never" when it comes to implementing accessors versus not implementing accessors that the community as a whole agrees on.
Many will advise you to make all data members private and provide accessors & mutators. Always.
Others will tell you to make data members private if changing them from client code is undesirable, and leave them public otherwise.
Yet others will tell you that classes shouldn't have more than one or so data member at all, and all the data should be encapsulated in yet another object, preferably a struct.
You have to decide for yourself which is right, keeping in mind that this will depend not only on your approach, but also that of the organization for which you work.
If you ask me, my preference is to make everything public until I have a reason not to. Simple. But that's just me.
You write explicit getters and setters as a sane plan for future development. If your class' users are directly accessing its members and you need to change the class in a way that is incompatible with that habit, you have to change every chunk of code that interfaces with you in this way. If you write a getter and setter, the compiler will optimize it to be time-equivalent to direct access (if that is all it does) and you can later change the logic if you need to - without having to change a ton of other code.
When you make get or set method and use it 40 times in your code, you can handle future changes more easily.
Imagine, that you use public variable and use it 40 times in your code. After a month of developing your program, you'll come up with a great idea: What if I divide this variable by 1000 and so I would have better values to calculate with!
Wow, great, but now I have to find every single line, where I use it and change it. If I only had a get method :(
That's the main reason of getters and setters, even if they are very simple, it's better to have it. You will thank yourself once.
Data encapsulation is one of the major principles of OOP. It is the process of combining data and functions into a single unit called class. Using the method of encapsulation, the programmer cannot directly access the data. Data is only accessible through the functions existing inside the class so that the implementation details of a class that are hidden from the user. It's to protect both the caller and the function from accidentally changing the behavior of a method, or from needing to know how a method works.
The textbook-ish answer recalled from me taking the first OOP class was: Get and set methods are used to wrap around private variables. Usually people compare between having get and set or just simply set those variables to be public; in this case, get and set approach is good because it protects those variables from being modified accidentally due to bugs and etc..
People (me when I took that class) might ask "isn't get and set also modify those variables, if so, how is that different than being modified as a public variable".
The rationale is: to have get and set function, you are asking the user or yourself to explicitly specify they want to modify the variable by calling those functions. Without calling those functions, the private variables will be less likely (still possible depends on implementation) modified unwillingly or accidentally.
In short, you should not do that.
In general, I suggest to read Fowler's Refactoring, then you will have a picture what gets hindered by having naked data, and what kind of access aligns well. And importantly whether the whole thing applies to your cases or not.
And as you know pros&cons you can safely ignore "should do/don't" stuff like at start of this answer or others.

Whether to go for a member function or friend function when the function is supposed to change state of object?

In the book The C++ Programming Language, by Bjarne Stroustrup, the author introduces
a class Matrix which has to implement a function inv(). In section 11.5.1, he talks
about two possibilities of doing that. One is to make a member function and other is to
make a friend function inv(). Then towards the end of section 11.5.2, where he talks about
making the choice of whether to use a friend or a member function, he says:
If inv() really does invert Matrix m itself, rather than returning a new Matrix that
is the inverse of m, it should be a member.
Why is it so? Can't a friend function change the state of the Matrix and return the
reference to that matrix? Is it because of the possibility of passing a temporary matrix
when we call the function?..
To be honest, I think the only reasons to make such a decision are syntactic convenience and tradition. I'll explain why by showing what are (not) the differences between the two and how these differences matter when making a decision.
What differences are there between non-member friend functions and public member functions? Not much. After all, a member function is just a regular function with a hidden this parameter and access to the class's private members.
// what is the difference between the two inv functions?
// --- our code ---
struct matrix1x1 { // this one is simple :P
private:
double x;
public:
//... blah blah
void inv() { x = 1/x; }
friend void inv(matrix1x1& self) { self.x = 1/self.x; }
};
matrix1x1 a;
// --- client code ---
// pretty much just this:
a.inv();
// vs this:
inv(a);
void lets_try_to_break_encapsulation(matrix1x1& thingy) {
thingy.x = 42; // oops, error. Nope, still encapsulated.
}
They both provide the same functionality, and in no way do they change what other functions can do. The same internals get exposed to the outside world: there's no difference in terms of encapsulation. There's absolutely nothing that other functions can do differently because there's a friend function that modifies private state.
In fact, one could write most classes with most functions as non-member friend functions (virtual functions and some overloaded operators must be members) providing the exact same amount of encapsulation: users cannot write any other friend function without modifying the class, and no function other than the friend functions can access private members. Why don't we do that? Because it would be against the style of 99.99% of C++ programmers and there's no great advantage to be taken from it.
The differences lie in the nature of the functions and the way you call them. Being a member function means you can get a pointer to member function from it, and being a non-member function means you can get a function pointer to it. But that's rarely relevant (especially with generic function wrappers like std::function around).
The remaining difference is syntactic. The designers of the D language decided to just unify the whole thing and say that you can call a member function directly by passing it an object like inv(a), and call a free function as a member of its first argument, like a.inv(). And no class suddenly got badly encapsulated because of that or anything.1
To address the particular example in the question, should inv be a member or a non-member? I'd probably make it a member, for the familarity argument I outlined above. Non-stylistically, it doesn't make a difference.
1. This is unlikely to happen in C++ because at this point it would be a breaking change, for no substantial benefit. It would, for an extreme example, break the matrix1x1 class I wrote above because it makes both calls ambiguous.
The encapsulation philosophy inherent to OOD (which C++ tries to promote) dictates that object state can only be modified from within.
It is syntactically correct (the compiler allows it) but it should be avoided.
It is error prone to let elements throughout the system alter each other without using predefined interfaces.
Object storage and functionality could change and looking around for code (that might be huge) that uses a specific part of an object would be a nightmare.
There are two opposing arguments regarding using friends:
One side says friends reduces encapsulation because now you're letting external entities access the internals of a class and the internals should only be modified by member methods.
The other side says that friends could actually increase encapsulation, since you can give access to the internals of a class to a small set of external entities, thus obviating the need to make internal class attributes public to everyone so these external entities can access/manipulate them.
Both sides could be argued, but I tend to agree with the first option.
As for your question, its as PherricOxide mentioned in his comment: If the internal attributes of a class need to be modified, its better that that be done by a member method, thus enforcing encapsulation. This is inline with the first option mentioned above.

Private set / get functions -- Why private and how to use?

I've read a lot of guides that explain why I should use "private" and the answer is always "Because we don't want anyone else setting this as something". So, let me ask the following questions:
Assuming that I want to have a variable that is set-once (perhaps something like a character name in a video game, ask once, then it's set, and then you just use the get variable(edit:function) for the rest of the game) how do I handle that one set? How would I handle the get for this as well?
What is the actual advantage of using a private access modifier in this case? If I never prompt the user to enter the name again, and never store information back to class.name shouldn't the data remain safe (moderately, assuming code works as intended) anyways?
I hope someone will help me out with this as the explanations I've googled and seen on here have not quite put my thoughts to rest.
Thanks!
The access specifiers mainly serve to denote the class interface, not to effectively limit the programmer's access or protect things. They serve to prevent accidental hacking.
If something is set once, then you should try to set it when it is created, and make it const.
If the interface doesn't need to be especially clear (for example, if few people need to learn it) then it doesn't make sense to spend effort engineering it. Moreover changes that don't make much difference in how the interface is used can be applied later. The exposed variable can be changed to a getter/setter using simple search-and-replace.
If it were a published binary interface, then you would want to get it right the first time. But you're just talking about the internals of your program.
And it's fairly unlikely that anyone will reset the player name by accident.
I won't try to justify the private set method as that sounds a bit weird to me. You could handle the one set by using a friend declaration. But then why would you define a setter when the friend could just set the value directly?
I generally avoid setters if I can at all manage it. Instead I prefer provide facility to set member variables via the constructor. I am quite happy to provide getters if they make sense.
class player_character_t {
std::string name_;
public:
player_character_t(std::string const& name)
: name_ (name)
{
}
std::string const& name() const { return name_; }
};
This forces you to delay construction of the object until you have all the information you require. It simplifies the logic of your objects (ie they have a trivial state diagram) and means you never have to check is something is set before reading it (if the object exists, it is set properly).
http://en.wikipedia.org/wiki/State_diagram
Marking things as private helps prevent accidents. So when you make a mistake and it is no longer the case that the "code works as intended" the compiler may help you detect it. Likewise const can be a big help in detecting when you are using objects incorrectly.
It's that last parenthetical that is important: assuming code works as intended.
In my mind it's similar to permissions in Linux systems. You know the root password and you can delete any file, but you don't stay logged in as root so you don't do anything by accident. Similarly, when you have a private variable characterNameString, and someone (or you) later tries to give it a new value, it will fail. That person will have to go look at the code and see that it's marked private. That person will have to ask themselves "why is this private? Should I be modifying it? Should I be doing this another way?" If they decide they want to, then, they can. But it prevents silly mistakes.
Don't confuse the private and the public interfaces of the class. In theory these are completely different interfaces, and this is just a design feature of C++ that they're located physically in the same class declaration.
It's perfectly ok to have a public getter/setter when the object property should be exposed via the public interface, so there is no rule such as 'setter is always private'.
More on that topic in the (More) Exceptional C++ books by Herb Sutter. It's an absolutely neccessary reading for someone who wants to understand C++ and be proficient with it.
If you have doubts over deciding whether to use getter/setters over the class variables, there are numerous explanations on the internet why getters/setters are better.
If the variable is 'write once then forever read only' I'd recommend making it a const member that is initialized during construction. There's no value in a private 'setter' function because it won't be used. Also you avoid people using the setter function to set the name when it's never meant to be set.
For example:
class Player
{
private:
const std::string m_name;
public:
Player(const std::string& name) : m_name(name) {}
};
Private getters and setters all make sense when the data in question involves several variables, have additional constraints you want to make sure you adhere to, and these operations are done several times in your class. Or when you plan further modifications to the data model and wish to abstract operations on the data, like using std::vector but planning to make it std::map or similar cases.
For a personal example, I have a smart pointer implementation with a private reset(T*, int*) method that is essentially a setter for the stored object and its reference count. It handles checking validity of objects and reference counts, incrementing and decrementing reference counts, and deleting objects and reference counts. It is called eight times in the class, so it made perfect sense to put it into a method instead of just screwing around with member variables each time, slowing programming, bloating code and risking errors in the process.
I am sure private getters can also make sense if you are abstracting the data from the model and/or you have to implement error checking, for example throwing instructions if the data is NULL instead of returning NULL.

Convention of using underscores in C++ class member names

The large majority of my programming knowledge is self-taught, so I was never taught proper design patterns, conventions, and so on and so forth.
I've been digging through a lot of my company's software libraries lately, and I notice that a lot of class data members have underscores in their names.
For example:
class Image
{
// various things
// data members
char* _data;
ImageSettings* _imageSettings;
// (and so on...)
};
I see this in a lot of online example code as well. Is there a reason behind this convention? Sorry I couldn't provide better examples, I'm really trying to remember off the top of my head, but I see it a lot.
I am aware of Hungarian notation, but I am trying to get a handle on all of the other conventions used for C++ OOP programming.
It is simply intended to make it clear what variables are members, and which are not. There is no deeper meaning. There is less possibility for confusion when implementing member functions, and you are able to chose more succinct names.
void Class::SomeFunction() {
int imageID;
//...
SetID(imageID + baseID); //wait, where did baseID come from?
}
Personally, I put the underscore at the end instead of the begining [if you accidently follow a leading underscore with a capital letter, your code becomes ill formed]. Some people put mBlah or m_Blah. Others do nothing at all, and explicitly use this->blah to indicate their member variables when confusion is possible. There is no global standard; just do what you want for private projects, and adhere to the existing practices elsewhere.
I have seen _ typing in front of the member, just to notify the reader that it's a class member variable.
More conventional way I have seen is putting m_; i.e. m_data;
Usually underscore before a member is used when the member is private.
It is usefull in language that does not have a builtin way to declare members private, like python.
Usually an underscore is used in member variables so as to distinguish between member variables, static member variables & local variables.
m_ is used for normal member variables &
s_ for static member variables
This way the scope of the variable is visible in the variable name itself.
Also, sometimes underscores are used in member name so that you can name your get and set methods with the member name itself.
For example:
class Image
{
// various things
// data members
char* _data;
ImageSettings* _imageSettings;
// (and so on...)
public:
ImageSettings* imageSettings()
{
//return pointer
}
void imageSettings(ImageSettings *ptr)
{
//set member variable value
}
};
However, different organizations adopt different conventions & coding styles and one should stick to them. Follow the principle,
When in Rome think & act like the Romans :)
I don't think there is a universal rule for naming. However, one of the most important one is to stick to what's already used in your company/project. Don't break it. Otherwise, it's most likely that your tech lead or mentor will challenge you about it.
For your reference, Google C++ style for naming
What I've learned is that having an underscore before or after a variable means that it's a member of that class - private, public, or protected.
The reason for this convention is that member names beginning with underscores show up first in Intellisense. Generally, you have to follow the convention of the project you are contributting to. If you are starting a new project, it is a good idea to follow a commonly accepted convention, such as Sutter's and Alexandrescu's C++ Coding Standards.

Access members directly or always use getters

I personally find it weird/ugly when a class uses a getter to access its own member data. I know the performance impact is none but I just don't like to see all those method calls.
Are there any strong arguments either way, or is it just one of those things that's personal preference and should be left to each coder, or arbitrarily controlled in a coding standard?
Update: I'm meaning simple getters, specifically for a class' non-public members.
The reason you might want to use a getter/setter is because it conceals the implementation. You won't have to rewrite all of your code if you are using getters/setters in case the implementation does change, because those members can continue to work.
EDIT based on the many clever comments:
As for a class using setters and getters on itself, that may depend on the particulars. After all, the implementation of a particular class is available to the class itself. In the cases where a class is normally instantiated, the class should use the member values directly for its own members (private or otherwise) and its parent classes (if they are protected) and only use getters/setters in the case that those members are private to the parent class.
In the case of an abstract type, which will usually not contain any implementation at all, it should provide pure virtual getters and setters and use only those in the methods it does implement.
Willingness to use getters/setters within class member implementation is the canary in the mine telling that your class is growing unreasonably. It tells that your class is trying to do too many different things, that it serves several purposes where it should serve one instead.
In fact, this is usually encountered when you are using one part of your class to store or access your data, and another part to make operations on it. Maybe you should consider using a standalone class to store and give access to your data, and another one to provide a higher view, with more complex operations with your data.
THE OBVIOUS
getters and setters for protected members makes as much sense as for public... derived classes are just another form of client code, and encapsulating implementation details from them can still be useful. I'm not saying always do it, just to weight pros and cons along the normal lines.
getters and setters for private members is rarely a net benefit, though:
it does provide the same kind of encapsulation benefits
single place for breakpoints/logging of get/set + invariant checks during dev (if used consistently)
virtual potential
etc...
but only to the presumably relatively small implementation of the same struct/class. In enterprise environments, and for public/protected member data, those benefits can be substantial enough to justify get/set methods: a logging function may end up having millions of lines of code depedent on it, and hundreds or thousands of libraries and apps for which a change to a header may trigger recompilation. Generally a single class implementation shouldn't be more than a few hundred (or at worst thousand) lines - not big or complex enough to justify encapsulating internal private data like this... it could be said to constitute a "code smell".
THE NOT-SO OBVIOUS
get/set methods can very occasionally be more readable than direct variable access (though more often less readable)
get/set methods may be able to provide a more uniform and convenient interface for code-generated member or friend methods (whether from macros or external tools/scripts)
less work required to transition between being a member or friend to a freestanding helper function should that become possible
implementation may be rendered more understandable (and hence maintainable) to people who're normally only users of the class (as more operations are expressed via, or in the style of, the public interface)
It's a bit out of scope for the question, but it's worth noting that classes should generally provide action-oriented commands, event-triggered callbacks etc. rather than encouraging a get/set usage pattern.
It seems most people didn't read your question properly, the question is concerning whether or not class methods accessing its own class' members should use getters and setters; not about an external entity accessing the class' members.
I wouldn't bother using getter and setter for accessing a class' own members.
However, I also keep my classes small (typically about 200-500 lines), such that if I do need to change the fields or change its implementations or how they are calculated, search and replace wouldn't be too much work (indeed, I often change variable/class/function names in the early development period, I'm picky name chooser).
I only use getter and setters for accessing my own class members when I am expecting to change the implementation in the near future (e.g. if I'm writing a suboptimal code that can be written quickly, but plans to optimize it in the future) that might involve radically changing the data structure used. Conversely, I don't use getter and setter before I already have the plan; in particular, I don't use getter and setter in expectation of changing things I'm very likely never going to change anyway.
For external interface though, I strictly adhere to the public interface; all variables are private, and I avoid friend except for operator overloads; I use protected members conservatively and they are considered a public interface. However, even for public interface, I usually still avoid having direct getters and setters methods, as they are often indicative of bad OO design (every OO programmers in any language should read: Why getter and setter methods are Evil). Instead, I have methods that does something useful, instead of just fetching the values. For example:
class Rectangle {
private:
int x, y, width, height;
public:
// avoid getX, setX, getY, setY, getWidth, setWidth, getHeight, setHeight
void move(int new_x, int new_y);
void resize(int new_width, int new_height);
int area();
}
The only advantage is that it allows changing internal representation without changing external interface, permitting lazy evaluation, or why not access counting.
In my experience, the number of times I did this is very, very low. And it seems you do, I also prefer to avoid the uglyness and weightyness of getter/setters. It is not that difficult to change it afterwards if I really need it.
As you speak about a class using its own getter/setters in its own implementation functions, then you should consider writing non-friend non-member functions where possible. They improve encapsulation as explained here.
An argument in favor of using getters is that you might decide one day to change how the member field is calculated. You may decide that you need it to be qualified with some other member, for instance. If you used a getter, all you have to do is change that one getter function. If you didn't you have to change each and every place where that field is used currently and in the future.
Just a crude example. Does this help?
struct myclass{
int buf[10];
int getAt(int i){
if(i >= 0 && i < sizeof(buf)){
return buf[i];
}
}
void g(){
int index = 0;
// some logic
// Is it worth repeating the check here (what getAt does) to ensure
// index is within limits
int val = buf[index];
}
};
int main(){}
EDIT:
I would say that it depends. In case the getters do some kind of validation, it is better to go through the validation even if it means the class members being subjected to that validation. Another case where going through a common entry point could be helpful is when the access needs to be essentially in a sequential and synchronized manner e.g. in a multithreaded scenario.
Protecting a member variable by wrapping its access with get/set functions has its advantages. One day you may wish to make your class thread-safe - and in that instance, you'll thank yourself for using those get/set functions
this is actually for supporting the object oriented-ness of the class by abstracting the way to get(getter). and just providing its easier access.
Simple answer. If you are writing a one shoot program, that will never change, you can leave the getters at peace and do without any.
However if you write a program that could change or been written over time, or others might use that code, use getters.
If you use getters it helps change the code faster later on, like putting a guard on the property to verify correctness of value, or counting access to the property(debugging).
Getters to me are about easy possibilities(free lunch). The programmer who write the code does not need getters, he wants them.
hope that help.
My thoughts are as follows.
Everything should be static, constant, and private if possible.
As you need a variable to be instanced meaning more than one unique
copy you remove static.
As you need a variable to be modifiable you remove the const.
As you need a class/variable to be accessed by other classes you remove
the private.
The Usage of Setters/Getters - General Purpose.
Getter's are okay if the value is to ONLY be changed by the class and
we want to protect it. This way we can retrieve the current state of
this value without the chance of it's value getting changed.
Getter's should not be used if you are planning to provide a Setter
with it. At this point you should simply convert the value to public
and just modify it directly. Since this is the intent with a Get/Set.
A Setter is plain useless if you are planning to do more then simply
"this.value = value". Then you shouldn't be calling it "SetValue"
rather describe what it is actually doing.
If let's say you want to make modifications to a value before you
"GET" it's value. Then DO NOT call it "GetValue". This is ambiguous
to your intent and although YOU might know what's happening. Someone
else wouldn't unless they viewed the source code of that function.
If let's say you are indeed only Getting/Setting a value, but you are
doing some form of security. I.e. Size check, Null Check, etc.. this
is an alternative scenario. However you should still clarify that in
the name E.g. "SafeSetValue" , "SafeGetValue" or like in the "printf"
there is "printf_s".
Alternatives to the Get/Set situations
An example that I personally have. Which you can see how I handle a
Get/Set scenario. Is I have a GameTime class which stores all kinds
of values and every game tick these values get changed.
https://github.com/JeremyDX/DX_B/blob/master/DX_B/GameTime.cpp
As you will see in the above my "GETS" are not actually "GETS" of
values except in small cases where modification wasn't needed. Rather
they are descriptions of values I am trying to retrieve out of this
GameTime class. Every value is "Static Private". I cannot do Const
given the information is obtained until runtime and I keep this
static as there is no purpose to have multiple instances of Timing.
As you will also see I don't have any way of performing a "SET" on any of this data, but there are two functions "Begin()" and "Tick()" which both change the values. This is how ALL "setters" should be handled. Basically the "Begin()" function resets all the data and loads in our constants which we CANT set as constants since this is data we retrieve at runtime. Then TICK() updates specific values as time passes in this case so we have fresh up to date information.
If you look far into the code you'll find the values "ResetWindowFrameTime()" and "ElapsedFrameTicks()". Typically I wouldn't do something like this and would have just set the value to public. Since as you'll see I'm retrieving the value and setting the value. This is another form of Set/Get, but it still uses naming that fits the scenario and it uses data from private variables so it didn't make sense to pull another private variable and then multiply it by this rather do the work here and pull the result. There is also NO need to edit the value other then to reset it to the current frame index and then retrieve the elapsed frames. It is used when I open a new window onto my screen so I can know how long I've been viewing this window for and proceed accordingly.