If - procedural, functional, object-oriented

Part of "fp vs oop" series

  1. Function vs Object
  2. Category vs Design pattern
  3. If - procedural, functional, object-oriented

Let’s talk about the if statement. A lot of people view it as the corner-stone of programming, for example, whenever I discuss the question if CSS is a programming language or not (it is) somebody would say: “CSS doesn’t have if statement so it can’t be considered as PL”. I don’t know where this idea comes from. if statement is one of the many control flow structures, like goto, jump, exceptions, loops, etc.


I guess the most known form of if is it’s “procedural” (or structured) form:

1if (condition) {
2  thenAction();
3} else {
4  elseAction();

By “procedural” I mean the type of imperative programming, but more organized than just Von Neumann machine. (Imperative style of programming is when you give direct instructions to the machine do step 1, step 2, etc.)

Instead of the precise definition, I will give examples:

  • Most imperative languages: assembly, Fortran.
  • Less imperative languages, so-called “procedural” or structured): Algol, Pascal (I guess Go as well).


To impelemnt if in functional style we need to restrict ourselves to functions only:

1// Implementation:
2const True = (x) => (y) => x;
3const False = (x) => (y) => y;
4const If = (condition, thenAction, elseAction) => {
5  const action = condition(thenAction)(elseAction);
6  return action();
8// Usage:
9If(condition, thenAction, elseAction);

This idea is a direct translation of Church Encoded True, False in lambda calculus:

True = λx.λy.x
False = λx.λy.y


To impelemnt if in functional style we need to restrict ourselves to objects only:

 1// Implementation:
 2class TrueClass {
 3  Then(callBack) {
 4    callBack.call()
 5    return this
 6  }
 7  Else(callBack) {
 8    return this
 9  }
11class FalseClass {
12  Then(callBack){
13    return this
14  }
15  Else(callBack){
16    callBack.call()
17    return this
18  }
20const True = new TrueClass();
21const False = new FalseClass();
22// Usage:
23// const condition = True


In practice, a lot of OOP and FP languages use procedural-style if (you can get away without it).

The reason I presented those examples is to show “pure” FP and OOP implementations so you could compare them. For the full picture, I need to mention that OOP example is SmallTalk style, and SmallTalk took some inspiration from Scheme, which in turn uses ideas from lambda calculus ¯\_(ツ)_/¯. Some people would argue definition of “pure” OOP as SmallTalk, let’s leave it for another article.

Except where otherwise noted, content on this site is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0