Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good Practice: To Modify Only Function Parameters?

Tags:

c++

Say, I develop a complex application: Within object member functions, should I modify only those objects, that are passed to the member functions as parameters, or can I access and modify any other objects I have access to(say public or static objects)?

Technically, I know that it is possible to modify anything I have access to. I am asking about good practices.

Sometimes, it is bothering to pass as an argument everythying i will access and modify, especially if I know that the object member function will not be used by anybody else, but me. Thanks.

like image 321
Bunkai.Satori Avatar asked Mar 02 '26 11:03

Bunkai.Satori


2 Answers

Global state is never a good idea (though it is sometimes simpler, for example logging), because it introduces dependencies that are not documented in the interface and increase coupling between components. Therefore, modifying a global state (static variables for example) should be avoided at all costs. Note: global constants are perfectly okay

In C++, you have the const keyword, to document (and have the compiler enforce) what can be modified and what cannot.

A const method is a guarantee that the visible state of an object will be untouched, an argument passed by const reference, or value, will not be touched either.

As long as it is documented, it is fine... and you should strive for having as few non-const methods in your class interface and as few non-const parameters in your methods.

like image 123
Matthieu M. Avatar answered Mar 04 '26 23:03

Matthieu M.


If you have a class with member variables, then it is entirely acceptable to modify those member variables in a member method regardless of whether those member variables are private, protected, or public. This is want is meant by encapsulation.

In fact, modifying the variables passed into the member method is probably a bad idea; returning a new value is what you'd want, or getting a new value back from a separate member method.

like image 20
Robert Gowland Avatar answered Mar 05 '26 01:03

Robert Gowland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!