svg
Post Image
By Daniel Tanque26 de Outubro, 2023In Clean CodeCoding

Clean Code – Functions

One important part of coding is defining functions, functions must be atomic, have just one purpose and simple to understand by other developers. In this article you will learn about what are the best practices you should have in mind to develop clean and understandable functions.

Atomicity

When you use per example the square root of a math library you can see that it gets one argument and returns a result, not much more than that, doesn’t give a json or ascii animation.

Because what is expected is just the calculation of a square root. And as developers our code must follow the same philosophy, if you want to fetch data, only do that. If you want to display something only do that.

One good tip to have in mind is that if/case and while should have only line, if there’s more it’s something that you should take attention because you can refactor properly. Also a function in overall should not pass the 20 lines, if it does there’s a good chance that your function is doing more than one thing.

Returns

There are two approaches here you can return immediately or you can hold the result in a variable and return the variable. The way to do it depends on the desired outcome.

Per example calculate a square root, you get the argument, call the math method, and you can return immediately the result, of course for that you can just literally use the math method and call it, but the goal is to give an idea of atomicity. Calculating the yearly payment is just multiply the argument monthly fee per 12 and it’s done.

But to calculate that fee with the currency value we may want to store in a variable and concatenate with the currency picked ” $”.

Arguments

Functions have arguments and you can calculate the distance of two locations, but for that you can go via the GPS coordinates, that will require, latitudeStart, longitudeStart, latitudeEnd, longitudeEnd, but that’s in overall 4 arguments, you take an option of just having 2, start and end. For that you create a entity or a structure that holds the latitude and longitude, so you just pass coordinateStart, coordinateEnd, to the function.

Conclusion – Why

Why this matters? It’s not just for readability it’s as well for the testing part, the more arguments the more you have to pass and ensure if it exists or not, if it is valid or not. By making atomic function you can focus on each building block at a time.

svgDocker - Dockerfile
svg
svgDocker Storage and Network

Leave a reply