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.
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 (
staticvariables for example) should be avoided at all costs. Note: global constants are perfectly okayIn C++, you have the
constkeyword, to document (and have the compiler enforce) what can be modified and what cannot.A
constmethod is a guarantee that the visible state of an object will be untouched, an argument passed byconstreference, 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-
constmethods in your class interface and as few non-constparameters in your methods.