Getter and Setter, Pointers or References, and Good Syntax to Use in C++

Getter and setter, pointers or references, and good syntax to use in c++?

As a general law:

  • If NULL is a valid parameter or return value, use pointers.
  • If NULL is NOT a valid parameter or return value, use references.

So if the setter should possibly be called with NULL, use a pointer as a parameter. Otherwise use a reference.

If it's valid to call the getter of a object containing a NULL pointer, it should return a pointer. If such a case is an illegal invariant, the return value should be a reference. The getter then should throw a exception, if the member variable is NULL.

Conventions for accessor methods (getters and setters) in C++

From my perspective as sitting with 4 million lines of C++ code (and that's just one project) from a maintenance perspective I would say:

  • It's ok to not use getters/setters if members are immutable (i.e. const) or simple with no dependencies (like a point class with members X and Y).

  • If member is private only it's also ok to skip getters/setters. I also count members of internal pimpl-classes as private if the .cpp unit is smallish.

  • If member is public or protected (protected is just as bad as public) and non-const, non-simple or has dependencies then use getters/setters.

As a maintenance guy my main reason for wanting to have getters/setters is because then I have a place to put break points / logging / something else.

I prefer the style of alternative 2. as that's more searchable (a key component in writing maintainable code).

Return by reference or create a typical setter/getter?

Unless you feel very strongly against it, use getter and setter member functions.

The reason int& num_chests() or a public field is bad is that you are coupling client code that uses the num_chests value to the fact that it is actually a field (an internal implementation detail).

Suppose that later you decided you would have a std::vector<Chest> chests private field in your class. Then you wouldn't want to have a int num_chests field -- it's horribly redundant. You would want to have int num_chests() { return chests.size(); }.

If you were using a public field, now all of your client code needs to use this function instead of the previous field access -- every usage of the num_chests value needs to be updated, because the interface has changed.

If you were using a function that returns a reference, you now have a problem because chests.size() is a return by value -- you can't in-turn return that by reference.

Always encapsulate your data. It requires only a minimal amount of boilerplate code.

In response to comments saying you should just use public fields:

Keep in mind that the only benefit of using public fields (other than the remote possibility of some micro-optimization) is that you don't have to write the boilerplate code. "My teacher used to hate when I used public fields (and he was sooo annoying)" is a very poor argument for using public fields.

Getters and setters in pure C?

First of all, don't listen to anyone saying "there is no object-orientation in language x" because they have truly not understood that OO is a program design method, completely apart from language syntax.

Some languages have elegant ways to implement OO, some have not. Yet it is possible to write an object-oriented program in any language, for example in C. Similarly, your program will not automagically get a proper OO design just because you wrote it in Java, or because you used certain language keywords.

The way you implement private encapsulation in C is a bit more crude than in languages with OO support, but it does like this:

// module.h

void set_x (int n);
int get_x (void);

// module.c

static int x; // private variable

void set_x (int n)
{
x = n;
}

int get_x (void)
{
return x;
}

// main.c

#include "module.h"

int main (void)
{
set_x(5);
printf("%d", get_x());
}

Can call it "class" or "ADT" or "code module" as you prefer.

This is how every reasonable C program out there is written. And has been written for the past 30-40 years or so, as long as program design has existed. If you say there are no setters/getters in a C program, then that is because you have no experience of using C.

What should a C++ getter return

You can provide both const and non-const versions:

MyType       & MyClass::getMyType()       { return mMyType; }
MyType const & MyClass::getMyType() const { return mMyType; }

I wouldn't provide a pointer version, since that implies that the return value might be the null pointer, which it can never be in this instance.

The real point, however, is that you are basically giving the caller direct access to the internal object. If this is your intent, then you may as well make the data member public. If it isn't, then you will need to work harder to hide the object.

One option is to retain the MyType const & accessor, but provide more indirect means to modify the internal object (setMyType(…) or something more tailored to the semantics that you are trying to express at the level of the containing class).

how to do setter and getter functions for a pointer class variable?

Why you need pointers in your program at all? By the way here is an example:

class clsStudent
{
public:
void setProgram(clsProgram *x) { programEnrolled=x; }
clsProgram *getProgram() const { return programEnrolled; }

...
};

clsStudent student;
student.getProgram()->programName;

C++ getters/setters coding style

It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future.

In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're locking down the underlying implementation. For example, if in the future you wanted to change the internal representation to a C-string or a Unicode string, or something else, then you'd break all the client code. With a getter, you could convert to the legacy representation for existing clients while providing the newer functionality to new users via a new getter.

I'd still suggest having a getter method like the one you have placed above. This will maximize your future flexibility.

References and pointers in setters and getters. Need example

The code you provide compiles with clang on mac OS X with no error. But I don't see where do you return reference or pointer, in Config you can do this:

class Config
{
public:
Config();
const string& getResourceDir() const;
const JustExample& getExmp() { return exmp; }
void setResourceDir(const string& dir);
void setExmp(const JustExample& example) { exmp = example; }
private:
JustExample exmp;
string res_dir;
};

return by pointer is similar, just replace & with *, although it may be better to return reference in this case.



Related Topics



Leave a reply



Submit