Monthly Archives: August 2019

Object-Oriented vs. Functional Programming

λ

When I first started programming in high school (GW-BASIC by the way) I wondered why people thought that global variables were a bad idea.  Why would anyone want to restrict their variable scopes?  I intuited that wider variable scopes increase optionality, and that increased optionality is better.

After learning more in college and then in the workplace, I finally figured out that it actually works backwards from that.  The better a programming language is, the more it allows a programmer to PROMISE WHAT THEY WON’T DO.  And the more the programmer promises what they didn’t do, the easier it is to figure out what a piece of code does.

For example, if our language allows it, we can create initialize-only constants instead of variables.  Then we can be sure that its contents have not changed in the hundred lines between when it was declared and when we are looking at it.  Better yet, declare it as a constant and let it be collected after just five lines by limiting its scope.

If we are editing a function, wouldn’t it be nice to know for sure all the places it was called so that we could evaluate all the impacts of the change we are making?  Promising that you only called a function inside a class is a way of making an ironclad promise of how you have restricted yourself.

There was an interesting article recently that took a strong stand and said that Object-Oriented Programming (OOP) is basically a bad thing.  If Alan Kay, one of the founders of OOP, says: “Java is the most distressing thing to happen to computing since MS-DOS,” [because of the way its OO works] what is the problem?

I believe the root of the issue is that OOP, in practice, tends to be used to create lots of state as well as increase the scope of fields and functions.  Design Patterns and SOLID principles are complicated ways to encourage programmers not to do this or at least to do it in predictable ways.

Note that mutable state is a big deal.  It drastically increases complexity and non-static objects that have a shifting state are a recipe for disaster.

I believe that stateless, functional programming is, by and large, the best way to go, though it may require a major change of mindset.  But functional doesn’t need to be ideologically pure.  OOP has a place in our lives too.

Procedural, OOP, and Functional can all live together in peace if we:

  • Keep function definitions and class definitions short.
  • Keep variables and functions limited in scope.
  • Minimize the use of non-static functions (and static fields).
  • Worry about pragmatism, not purity.