Good Practice: To Modify Only Function Parameters?
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 (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.
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.
精彩评论