The meaning of changing state of the program

terminology

I was reading about common practices for naming functions and variables. Most of the seasoned programmers say verb should be used when a function changes the state of the program, and noun should be used if the function is used to return a certain value.

UPDATE: please check https://stackoverflow.com/a/1991341/1088314 and https://softwareengineering.stackexchange.com/a/184867/217771 Both the authors have a reputation score of few thousands and they recommend it.

I am not quite clear about the meaning of change in the state of the program. What does it mean?

Best Answer

In general changing in state of the program occurs when the program alters some computer resource (eg. memory value at a given address) within the process address space related to the process your program is represented by and that change will have an effect on further execution of the process. For example you call mutator (setter) on your object to alter its property (in Object Oriented approach). After that the result returned by calling getter (accessor) method related to that property will be distinct from the result returned before calling the mutator. That difference has to be persisted in the state of the program (in the object's property in that case which is mapped to a given memory address on program heap).

In procedural approach the counterpart will be altering a variable stored not on stack but on heap memory. So the change has to be permanent (persistent) not temporary (eg. global variable but not local variable). Local variables are stored on stack which is volatile and lives until a given function returns so the changes on stack are not permanent and in this case we cannot say the program state has been changed. Let's say you have a function named with a noun int factorial(int argument). You can have some local variables declared within the scope of the function (on the stack) that help you to do some computations but the changes made to these variables are gone after computation finishes and the function returns. There was no change in the state of the program in that case.