Welcome to HEITS website terminalOpening backend communication...Backend operational.Downloading themes...OKOpening user track plugin...ErrorError opening plugin. Running manual track scripttrack --usercalling /api/track?unHashToken=eits.digitalGET https://heits.digital/api/track?unHashToken=eits.digital 400 (Bad Request)Request response:Error unhashing user location. Invalid unHashToken. token must be 13 chars long.Log hash: RXJyb3IgdW5oYXNoaW4gdXNlciBsb2NhdGlvbi4gSW52YWxpZCB1bkhhc2hUb2tlbi4gdG9rZW4gbXVzdCBiZSAxMyBjaGFycyBsb25nClZhbGlkIHRva2VucyBmb3IgdGhpcyBkb21haW46ICJoZWl0cy5kaWdpdGFsIg==open /Opening /mode --defaultengineer mode set to falsereading --stoptheme --defaultTheme set succesfully
Code Quality 25 Nov 2021

Code Readability - Mixing Programming Paradigms in Javascript

Mihai Cicioc

Senior Software Engineer

Share this article
Intro

Javascript is a flexible programming language. Like anything in life, this has pros and cons, so we must carefully choose where we use it and how we use it.

Where do we use it? Obviously our first thought is in web related projects, either end user facing (i.e browser) or on the server side (Node.js). We can even build CLI apps (Node.js). However, surprisingly or not, Javascript is used even in the Linux ecosystem, for example almost 50% of gnome-shell (the graphical user interface for the Gnome desktop environment) is written in Javascript… Nice!

How do we use it? Well, here is where the fun / heated debates start. Because of its “flexibility”, we can use JS with many programming paradigms, like:

  • Procedural
  • Object oriented, with it’s 2 flavors:
    • Class based (what we commonly refer to as OOP, even though that’s not 100% accurate)
      • JS class paradigm is implemented via functions and some tweaks in the prototype chain.
    • Prototype based
      • The main paradigm of JS.
  • Functional

Many times it happens that we mix together all of these paradigms in the same JS codebase, which can be a powerful tool (otherwise we would have to use specialized languages for every purpose, like Java, Scala etc.).
If we add other JS concepts into the mix (like closures, arrow functions, this), it becomes pretty clear that we will have some problems down the road, which is what we will discuss next.

Details

Let’s start with a simplistic code comparison between the previously mentioned paradigms. We will use Node.js code snippets.

1
2  // procedural  
3
4  function sum(x, y, z) {
5    return x + y + z;
6  }      
7
8  module.exports = {
9    sum,
10  };
11        
1
2  // procedural use
3
4  const { sum } = require('./...');      
5
6  const s = sum(1, 2, 3);  
7  
8  console.log(s); // 6
9
10
11        
1
2  // class based
3
4  class Arithmetic {
5    iV = 0;
6    
7    constructor(initialValue) {
8      this.iV = initialValue;
9    }
10    
11    sum(x, y, z) {
12      return this.iV + x + y + z;
13    }
14  }      
15
16  module.exports = {
17    Arithmetic,
18  };
19        
1
2  // class based use      
3  
4  const { Arithmetic } = require('./...');      
5  
6  const a = new Arithmetic(0);      
7  
8  const s = a.sum(1, 2, 3);      
9  
10  console.log(s); // 6
11
12
13
14
15
16
17
18
19        
1
2  // prototype based  
3
4  const arithmetic = {
5    iV: 0,
6    sum(x, y, z) {
7      return this.iV + x + y + z;
8    },
9  };      
10
11  module.exports = {
12    arithmetic,
13  };
14        
1
2  // prototype based use  
3
4  const { arithmetic } = require('./...');      
5
6  const a = Object.create(arithmetic);      
7
8  a.iV = 0;      
9
10  const s = a.sum(1, 2, 3);      
11
12  console.log(s); // 6
13
14        
1
2  // functional based
3
4
5  function sum(iV) {
6    return function w1(x) {
7      return function w2(y) {
8        return function w3(z) {
9          return iV + x + y + z;
10        };
11      };
12    };
13  }
14  
15
16  module.exports = {
17    sum,
18  };
19        
1
2  // functional based use
3
4
5  const { sum } = require('./...');
6  
7
8  const mySum = sum(0);
9  
10
11  const s = mySum(1)(2)(3);
12  
13
14  console.log(s); // 6
15
16
17
18
19        

Looking at them separately, everything is nice and easy. But what if we have all of them in a single file? Or in a single function?! (yes, when we have a 2000-line function, which unfortunately is seen in the wild, anything can happen down there).

And to make things a bit more complex, we add arrow functions into the mix.
So we have the equivalent:

1
2  function sum(iV) {
3    return function s1(x) {
4      return function s2(y) {
5        return function s3(z) {
6          return iV + x + y + z;
7        };
8      };
9    };
10  }
11        
1
2  const sum = iV => x => y => z => iV + x + y + z;
3
4
5
6
7
8
9
10
11        

Let’s see some situations where all these together might cause problems.

Confusion for newcomers

Newcomers doesn’t mean just juniors, they can be mid/senior people that just joined a team.

There is a big chance that their onboarding process will take longer than expected, because now they have to adapt to this new “mixed” environment. However, this can also be a good thing, because this is how we learn (i.e. we encounter new things), so it will really help them to have someone guide them through the (new) codebase, and explain to them why certain paradigms were chosen in certain places. This will add clarity and will encourage them to learn and use the new paradigms.

If we are talking about juniors, then the above explanation process is mandatory. Juniors usually tend to learn procedural (which is good, I guess) and class-based (which is bad, because JS in principle has nothing to do with classes). So if they encounter these new “strange” looking things, some of them might reject them and just “stick to what they already know”.

Even mid/seniors can fall into traps. You know what they say: “if it ain’t broke, don’t fix it”, but guess what, things break, and when they break we want to be able to fix it fast. So when we encounter “mixed” paradigm code, we will spend too much effort to understand the code, then we will want to refactor it so that it “looks better”, but we don’t have enough time because the manager wants the bug fixed ASAP, then we get frustrated… You know how it goes…

Debugging is more difficult
Breakpoints

There are certain times when we just want to do an “oldies but goldies” debug session, meaning putting breakpoints, going through the code line by line, nice and easy… No “console.log()” is allowed, please.

Well, at that moment we will start to appreciate all those linting rules that we never wanted to use because “why put curly braces when they’re not necessary?”. For example:

1
2  // put breakpoints wherever you want  
3
4  function sum(iV) {
5    return function s1(x) {
6      return function s2(y) {
7        return function s3(z) {
8          return iV + x + y + z;
9        };
10      };
11    };
12  }
13        
1
2  // good luck putting breakpoints  
3
4  const sum = iV => x => y => z => iV + x + y + z;
5
6
7
8
9
10
11
12
13        
Navigation

Another situation is when we nicely navigate the code with “Ctrl + click”, when all of a sudden, we encounter some code where this doesn’t work:

1
2  // procedural  
3
4  const r1 = f1(0); // ctrl+click works
5
6
7
8
9        
1
2  // class  
3
4  const { ABC } = require('./...');      
5
6  const a = new ABC();  
7  
8  const r1 = a.f1(0); // ctrl+click works
9        
1
2  // prototype
3
4  const b = {
5    f1(x) {},
6  };  
7  
8  const a = Object.create(b);  
9  
10  const r1 = a.f1(0); // ctrl+click doesn’t work (in VSCode)
11        
1
2  // functional  
3
4  const r = f(1)(2)(3);
5  // ctrl+click works for f,
6  // but we can’t go straight to f1(2) or f2(3).
7
8
9
10
11        
Problems with currying
Definitions

Let’s say we decided to spice out our life and use some functional concepts in our JS code. Some concepts that I’ve seen in the wild are “function currying” and “partial application”. They are different concepts, so we should not mistake one for the other.

According to Wikipedia:

Function currying is the technique of converting a function that takes multiple arguments into a sequence of functions that each takes a single argument.

1
2  // we want to  transform f(x, y, z) into g(x)(y)(z)
3
4  function f(x, y, z) {
5    return x + y + z;
6  }  
7  
8  function curry(myFunc) {
9    return function w1(x) { // w = wrapper
10      return function w2(y) {
11        return function w3(z) {
12          return myFunc(x, y, z);
13        };
14      };
15    };
16  }  
17  
18  const g = curry(f);  
19  
20  // OR defining it directly  
21  
22  function h(x) {
23  return function w2(y) { // w = wrapper
24    return function w3(z) {
25      return f(x, y, z);
26      };
27    };
28  };  
29  
30  console.log(f(1, 2, 3)); // 6  
31
32  console.log(g(1)(2)(3)); // 6  
33
34  console.log(h(1)(2)(3)); // 6
35        

Partial application refers to the process of fixing a number of arguments to a function, producing another function of smaller arity.

1
2  // we want to  transform f(x, y, z) into g(y, z)  
3
4  function f(x, y, z) {
5    return x + y + z;
6  }      
7
8  function partialApply(myF, x) {
9    return function w(y, z) {
10      return myF(x, y, z);
11    };
12  }
13    
14  const g = partialApply(f, 1);      
15
16  // OR defining it directly      
17
18  function plus1(y, z) {
19    return f(1, y, z);
20  }  
21  
22  console.log(f(1, 2, 3)); // 6
23
24  console.log(g(2, 3)); // 6
25
26  console.log(plus1(2, 3)); // 6
27        

Ok, so let’s discuss each of them.

Function currying

Currying is really helpful for things like composition and partial application.

For composition it works great because curried functions are unary functions (i.e. they take only 1 parameter, and return a function that again takes only 1 parameter and so on…).

However, it can happen that we define all these nice curried unary functions, but we never use them in a composition, meaning we never use them for their intended purpose, but instead just end up calling them separately. So when we read the code, that currying will just add an extra layer of difficulty which is not really needed.

Partial application

For partial application, currying also makes sense, because what we’re actually doing is fix some parameters values, or “bind” them if you will. For example:

1
2  function f(x, y, z) {
3    return x + y + z;
4  }  
5
6  function g(x) {
7    return function w2(y) {
8      return function w3(z) {
9        return f(x, y, z);
10      };
11    };
12  };  
13  
14  const h = g(1)(2); // binding the params to values 1, 2.  
15  
16  console.log(f(1, 2, 3)); // 6
17
18  console.log(h(3)); // 6
19        

But we can easily accomplish the same thing with JS “bind” function, so we don’t actually need currying. See:

1
2  function f(x, y, z) {
3    return x + y + z;
4  }  
5
6  const h = f.bind(null, 1, 2);  
7  
8  console.log(f(1, 2, 3)); // 6  
9  
10  console.log(h(3)); // 6
11        

Also, one of the bigger problems from a code readability perspective, is when we see something like “f(x);”. It is not clear if:

  • the invocation is a partial application.
  • it’s the final execution of the function.

There is a proposal that if accepted, it will introduce a new syntax for partial application, which will help us in dealing better with these kinds of situations.

I know the next part is not related to readability, but I’ll mention it anyway.
At the end of the day, (almost) everything in JS (we exclude primitives) is an object, so functions are objects, arrays are objects, objects are objects etc... And we will end up with passing functions around as params. Because JS has the mechanism of closures, we should be careful with how we write our currying (or in general, functions that return functions), because there might be some performance problems (at one point I had to fix a memory leak that was caused by an unwanted closure).

Code review on many programming languages

This is more of a code readability thing rather than mixing programming paradigms, but I thought of mentioning it since it is something that happens frequently.

Many times a developer is part of a team which owns multiple projects, which can be written in multiple programming languages. This is a challenge itself, because we need to learn those programming languages. However, most of the time we can get away with learning just some aspects of those languages, we don’t really need to be experts in all of them (even though this would be so nice…).

Another challenge with multiple projects is that we need to do a lot of code reviews, and if we add multiple programming languages into the mix, it would really help if those projects were written in a similar fashion, so that we spend our effort on the main logic of the program, and not in some particularities of a programming language.

We can give many examples here, but I’ll just show you my favourite: using the “function” keyword.

Let’s look at some examples with Python, Golang and JS:

1
2  # python  
3
4  def sum(x, y, z):
5    return x + y + z  
6  
7  a = sum(1, 2, 3)  
8  
9  print(a)
10
11
12
13
14
15
16
17
18
19        
1
2  // golang  
3
4  package main  
5  
6  import (
7    "fmt"
8  )  
9  
10  func sum(x int, y int, z int) int {
11    return x + y + z
12  }  
13  
14  var a int = sum(1, 2, 3)  
15  
16  func main() {
17    fmt.Printf("%d", a)
18  }
19        
1
2  // JS  
3
4  function sum(x, y, z) {
5    return x + y + z;
6  }  
7  
8  const a = sum(1, 2, 3);  
9  
10  console.log(a);
11
12
13
14
15
16
17
18
19        

If we quickly scan through this code, we will see the following:

  • Function declarations:
    • def sum(...
    • func sum(...
    • function sum(...
  • Variable declarations:
    • a = …
    • var a = …
    • const a = …

Everything is nice and intuitive.

The JS part can also be written with arrow functions:

1
2  // JS  
3
4  const sum = (x, y, z) => {
5    return x + y + z;
6  };  
7  
8  const a = sum(1, 2, 3);  
9  
10  console.log(a);
11        

Now the function declarations become:

  • def sum(...
  • func sum(...
  • const sum = …

See where I’m getting at …?
When I see “const sum = …” I intuitively think of a variable declaration, not a function. Ok, you will counter me and say “But you can see the parentheses after =, meaning const sum = (...”.
Yes, that’s true, but because arrow functions can have many forms, we might also have const sum = x => … , so we need to process more information.

Furthermore, I start wondering “Why do we use an arrow function? Are we trying to bypass the regular this mechanism or what’s the deal here?”.

Don’t get me wrong, I have nothing against arrow functions, I use them myself a lot. It’s just that I use them in some contexts, not all over the place.

Another one of my favourite examples is “Use better naming of variables or functions (const u = … VS const activeUsers = …)”, but this is for another time.

The main point I’m trying to make here is that all these little things add up. And I didn’t even mention all the other stuff that a software developer needs to know nowadays (devops, security, databases, cloud, etc…), all of which come with their own language, quirks and so on.
Everybody's free to choose what they want, but if we spend some time choosing in a smart way, that will bring us way more benefits in the long run.

Conclusions

Mixing paradigms is not a bad thing, sometimes it is even necessary. But we can make some choices that will make our life easier. Here are some of which we discussed:

  • Try to avoid mixing paradigms in the same file or even in the same function.
  • When you have newcomers in the team, spend some time with them and explain why you chose a certain thing in a certain place.
  • Try to make navigation and debugging as easy as possible, you never know when that critical production bug will pop up (using a linter is helpful).
  • Use currying for specific reasons, not just because “it is cool”.
  • Learn the existing capabilities of JS, in our situation use “bind” if you can, and if not then ok, use partial application with currying.
  • Keep code reviews in mind, there are people that have to do reviews every day on 10 projects in different languages, so help them by writing your code in a consistent and intuitive manner, and they will help you back with good code reviews that focus on logic, and not on quirks.

Senior Software Engineer

Mihai Cicioc

Share this article
Explore

Next

Let's chat

Office

28 Avram Iancu street, 400083 Cluj-Napoca, Cluj, Romania

Email

Social

LinkedIn

©2021, HEITS.DIGITAL

Privacy Policy
Cookies