In functional programming languages, a developer is always cautious about writing pure functions. Some functional languages simply do not allow impure functions, and some other functional languages force to to state explicitly when something impure is happening. But in imperative languages, there is usually no such distinction between pure and impure codes/functions. And impure fictions are quite the norm in imperative languages. But someone can still write pure functions in imperative languages and that is good for code health in my opinion.
So, how can we convince or encourage others to write pure functions within an imperative languages?
object.updateName("Bob")
orupdateName(object,"Bob")
in a pure way in an imperative language that doesn't go through excessive contortions?object
with all fields identical exceptname
set to"Bob"
. That's what the auto-generatedcopy
method for case classes does in Scala, for example. Lenses are objects which encapsulate the notion of updating other objects in a purely functional manner (basically, lenses are purely functional getters and setters). The cool thing about lenses as opposed to properties or getter/setter pairs is that they are first-class objects. In a sense, lenses are reified lvalues, but being first-class you can e.g. pass them to functions or return them.