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?
6
The only good way to encourage others to work a certain way, is to demonstrate the benefits of doing so. You could also force people to work a certain way, via code reviews, but if the people don’t understand the benefits, you will simply make everyone unhappy.
Pure functions have plenty of benefits even in imperative languages:
- Predictability: with the same input, you always have the same output.
- Isolation: invoking a pure function cannot modify program behavior, since the function has no side effects. Explaining the benefits of isolation is probably a big task in itself…
- Easier to debug, in part due to the above attributes.
- Less places to debug: most bugs occur when the program state is modified.
This is off the top of my head, so I hope others will chime in.