What is the naming convention for a method / function that sets and gets a value?

This may come up as a strange question, since convention usually has a separate set and get method. But in my case, this is a little different: the function argument decides whether this function is a getter or setter, so I'm looking for a function name that will point to such a function.

Some of the names I found were getset, setget, rw, etc., but I find these names rather strange. Which naming convention is suitable for such functions?

+4
source share
2 answers

While Java beans did not agree with the get / set naming convention, some of them often saw functions (especially methods in C ++ and other OO languages) that performed exactly the way you describe.

They were often called after the variable they set or received, for example:

int counter_; int counter () { return counter_; } int counter (int c) { counter_ = c; return counter_; } 

In languages ​​with different namespaces for variables and functions, you can even have a variable, and get / set functions have exactly the same name (without the need to use trailing _, as I showed here).

In languages ​​with default parameters, you can write getter and setter as one function, for example. something like that:

 int counter (int c = MAX_INT) { if (c != MAX_INT) { counter_ = c; } return counter_; } 

... although I was not particularly keen on this approach because it led to subtle errors if someone called counter (MAX_INT) , for example.

I always thought this naming approach made sense, and I wrote several libraries that worked just that way.

However, this naming convention potentially confused the reader with the code, especially in languages ​​where it would be possible to call a function without parameters without end brackets, so it was difficult to see if the function was called or if the public variable was accessed directly. Of course, some will call the latter as a function, not a problem ...
+5
source

How to simply name a function after the name of the variable that it fills? As a property, when the passed parameter is null or another special value, then it is get, otherwise it is set.

+1
source

All Articles