How to write a better function

Best practices for a clean and perfect function

Dinuka Kasun Medis
3 min readDec 29, 2020
https://bit.ly/3541ulj

In this article I am going to share my learnings about functions. As software engineers we can not give just a solution. Because we are not developers. We have to remember we are engineers and engineers have to give the most accurate and most perfect solution for a problem. So when we writing a function for our project we have to follow some ruls. There may be more than these. But I think this little also may help for some one. So let’s start…

Functions should small, smaller than that.

Every time try to write a small function and try again to reduce complexity and keep as much as small. Because if you write a very big (long) function means that there may be a hidden function which can extract to another function.(long functions may hide classes 😉)

Function should do one thing, Do it well And Do it only.

First thing is this. Double check your function, if you can extract another function from your function, it means your function doing more than one thing.

Best functions have max 3 arguments if possible. But 0 is the best

When we write a function always we have remember to use only few arguments. If we need more arguments we can find another way to do that. (ex: create a model and pass that as an argument). I think 2 arguments are better, because the problem in 3 argument is hard to remember the order .

No boolean arguments ever

Ex:

doFormReadable(context, true)

In here we do not know what mean by true. And also if you pass 2 boolean values, It can use for 8 results. Sooo confusing thing.

Therefore better to write two functions, one for True case and other for false case.

Null defence (Do not use null as a argument)

Same as the no boolean arguments. In here also we can use 2 functions for non null case and null case.

But in this case we can go for Defensive programming for nulls.

No output arguments (Double take)

private String toSimpleText(Table table, StringBuffer returnText){.
.
.
convertToCustomerTable(table, returnText);.
.
.
return returnText.toString;}

In here we do not know why is this returnText argument going in. Because it go in to the function and come out from the function. (do both 😉)

But this is not good. Always try to passing using only return values. Not using output arguments.

Choose a proper name

In my naming article you can find more about this.

Extra tip 😉

Public stuff on the top and private are in the bottom

When we write functions in a class we have to follow step down rule.

Step Down Rule

In this rule, functions at the top are very high level (abstract), bottom are very low level and detailed.

So when we write a function this rule also help us to keep code clean.

--

--

Dinuka Kasun Medis

Hej, jag heter Dinuka Kasun. Välkommen till min profil. Arbeta som mjukvaruingenjör. Och nu för tiden lär jag mig svenska. 🤓🇱🇰 🇸🇪