Eight tips to Write Functions like a Senior Developer

Dhruba Dahal | Software Engineer
3 min readMar 29, 2022

A Function is a small segment of a story telling about a system

Photo by Joan Gamell on Unsplash

According to Robert C. Martin, while writing code we should always think of it as a story telling and our goal should be telling it as beautifully as possible. It makes not only the code readers happy but also helps developers to address the issues like: readable ,less prone to error, easy to change, scalable, testable, fault tolerant etc.

Today, I am going to discuss some of the useful tips that make your functions better in several ways.

1.Do one thing and do it well

Your function should do a single task. But some time while doing a single task we indirectly do other sub tasks also. So the question is are we breaching the rule in that case? The answer might be No if we have maintained the same level of abstraction inside that function.

2.Hide switch statements inside a low level class

Switch statement always does N things and we can not always avoid it. So what we do in that case is that we should hide it somewhere inside the base class or a low level class so we do not have to repeat it. We can achieve it through polymorphism.

3.Keep arguments minimum

It is always a good practice to keep arguments to a function minimum. Because it demands a lot of conceptual power if we use many arguments. It is more harder from testing point of view also. Out argument is even more confusing because we do not usually expect information to be going out through the arguments.

4.Never use flag arguments

If a function have a bool argument it does minimum two things. It does one thing in true and does another in false. So it is a terrible practice.

5.Pass arguments as an object

It is always a good idea to pass arguments as an object instead of passing a long list of arguments.

6.Prefer exceptions over error codes

If we return error codes, we have to deal with multiple conditional statements (if else) that makes code ugly. On the other hand, returning exceptions make job easy and eliminate the necessity of multiple conditional statements. For example: