Why do we need to make the methods small? How small a method should be? How making our methods small keeps the code organized and easy to read? We wil

A key to clean code — small methods

submited by
Style Pass
2021-06-13 07:30:04

Why do we need to make the methods small? How small a method should be? How making our methods small keeps the code organized and easy to read? We will answer that and many other questions, let’s begin.

This article is part of a clean code in-depth course called “Software Practices And Writing Clean Code” you can check it out. It’s currently available at an 87% off discount.

The main thing you should remember is: make the methods small. A method should do one thing and one thing only. But what does this mean? Let’s see an example:

Does this method do one thing? It saves an Employer, so it’s one thing, right? Nope. There are actually two things. We are mapping the DTO to an entity and then we are saving it. Okay, that was kind of obvious. You should split the method as much as you can and as much is logical to do so. So let’s refactor it:

That’s better. You see, every method has different responsibilities. But the code can be even better. For more flexibility, we can have a wrapper method that will connect the save and the toEmployer method. In this case, we will create another save method that will play that role. So let’s refactor the code again:

Leave a Comment