I have a std::vector
object in my class, vector<float> foo
, this gets modified by two different class functions function1
and function2
.
Currently, I have made the variable public, and both the functions have direct access to the variable without me explicitly passing.
But it occurred to me that I can write the code like;
vector<float> function1()
{
...
return foo;
}
int function2(vector<float> foo)
{
process(foo);
return 1;
}
Both the approaches give the same results and are working, but I want to know what is the correct and optimal way to do this. The class is not going to be inherited.
Programs get complex.
In order to modify a piece of code without introducing bugs, you need to either get lucky, understand the code, have every bug be tested and eliminated, or a combination of the 3.
Programs act on some set of "state"; variables, threads, OS and computer state. If you do not know what state a program acts on, it is impossible to understand it, and getting good test coverage is equally impossible.
Functions that operate on clear parameters and output clear parameters are easier to know what state they are interacting with. A function that interacts with a global variable means that code that calls it never passed in that global variable, nor got it back from the function, but the state of the global variable changed what the call did, and all other code after the call can now act differently.
If the function took state as a parameter and returned it, the caller of the function can know it only modifies what it passed in. So they can reason about what does not change withoout reading the function. And they have hints about what it changed.
Inside the function, the same problem happens when it calls another function. If it is operating on global state, it has to know if the functions it calls read or write it in strange ways.
The goal here is to reduce the amount of things you have to understand about a specific piece of code to know what it does, allowing programs to scale larger. There is a classic style of programming that involves learning code so well that you have the program "in your brain", where you don't care if the parameter is passed by global variable or as a function argument; that style works until it doesn't. Most often it fails when you switch to code you aren't working in, or when the code complexity of what is in your head overwealms you. So modern programming seeks to find ways to manage code that does not require holding entire programs in your head.