Writing code for others using functions

Naren Naik
2 min readJun 29, 2021

Consider you have a business requirement that asks you to

  • Take a list of items domainList
  • Convert them into URLs with HTTPS protocol
  • Add a specific parameter in the query callback=false

The below code solves the problem.

But ask yourself, how will someone new to this piece of code understand the business logic?

  • Why did we add HTTPS protocol?
  • Why did we add callback=false?

We could solve this by adding comments.

It makes more sense now.

But fast forward a couple of weeks, and the logic needs to be updated!

It turns out HTTPS needs to be added only to valid domains (valid: true). Let's make that change too.

Oops! I forgot to update the comments! So a new developer will probably skip updating it as well.

Solution?

Split the logic into multiple functions that do only one thing ideally.

//TODO: mentions that addCallbackParameter is temporary and needs to be removed in the future. However, making that change would be clean and straightforward.

Now, don’t you think the code is more readable and business logic intuitive enough? Testing will be easier since any logic update will have localized code change since all functions do one thing only.

The code is neater, but all the competitive coders will go crazy over .map being called twice. Honestly, calling it twice doesn't matter unless the number of items is large in number. Would you even know/see a lag if you call .map 10 times on just 20 items? Writing convoluted code to ensure you are using a single loop is not worth it.

However, we could also solve this by using pipe utility function from Ramda library. Infact you could write your own pipe function, its quite simple.

Using pipe

You can add comments to the individual functions as well. But the idea is to write code the way your business logic defines it.

  • Now, if the developer has to add one more parameter called redirect_url=https://www.some-endpoint.com and the URL is provided by a config.

Imagine the conversation the Developer would have

“Currently we are generating the URL and then adding a callback parameter, do we need to add one more? Should I retain the existing one? Will the existing parameter need to be updated?”

The right questions surface up, and you look for clarification from your team and Product. Writing code like this also improves your thought process. You start thinking in simpler terms and have a straightforward way to express the business logic into code.

Note: The article applies functional programming concepts to improve code readability and is not detailed enough to explain the FP concepts.

--

--