简体   繁体   中英

Terminology: What do you call a function that does not change object state?

For example, I have a class Employee , with functions getName() and pay() . The first function simply returns the persons name (an immutable property), but the second function changes the object significantly (so calling this second function from different threads is bad for example).

Is there a term for a function that do not alter an objects state such as getName() ? All functions in an immutable class will have this property.

I don't think there is a globally esteblished terminology for such a function.

Maybe "side effect free" and "pure" are close to what you want, but they mean that the function does not alter any state (neither of the object you call it on, and nor of any other object).

The word "pure" comes from the functional programming world, and means that the return value a function only depends on the value of its parameters. In object oriented programming it is common to also consider the object you call it on as one of the input parameters, so that property getters can be seen as "pure" functions.

There is no special naming for that. The reasonable thing to expect is that a method named "getSomething()" should have no side effects. In addition to that, for an immutable property, it should always return the same result.

In other words: when you implement such methods, you write them in a way that confirms those rules. (that also somehow tells you to not do premature optimization by doing some lazy-init somewhere; to avoid side effects when calling the method the first time!)

For good or bad, Java doesn't have the idea of a "const" keyword that could be used to make it clear that a certain method is side-effect free.

Besides, from a design point of view: you should be looking into making your Employee class fully immutable . In the sense of: why should invoking a "pay" method change anything within the Employee object?! When I receive my salary, by bank account goes up, but me, the Employee, I don't change because of that!

In that sense: you could be searching the net for "Agile practices" by Robert Martin. He does an extended full scale OO design for a real-world Employee/Payroll application. (and hint: the C# version PDF seems to be available for free).

“查询”类似于Command-Query-Separation原理。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM