Clean code part 3: functions
That's what we do: we write function and methods. Following the discipline of clean code we must follow the rules and be sure we are proceeding in the right way.
Small! Functions must be even smaller than that!
Functions must be small! And the other rules is: the must be smaller than that
- Maximum 5 rows, 3 rows is even better!
- Big functions is where classes are going to hide. They should become new classes. Big classes can be split into multiple classes following the SOLID principles. It's better to have many files with all small classes and a good name that we can easily search on our IDE than big files hard to update, test and maintain.
- Functions must do one thing and one thing only. Let's be clear when we say "one thing". What is "one thing" and how we can define it? Following the extract until you drop practice, if you can extract another function from another function with a name, do it!
It's always a good time to rewrite our code better. Refactoring is the process of restructuring existing computer code. So how we can improve the quality of our code rewriting it without breaking anything? We must learn the discipline of test driven development (TDD). Legacy code is considered unprofessional and it identifies the code not covered by tests. There are many refactoring techniques and we always must try to learn and practice them in a real world. This is another very big step but if you have never heard about all of this, you have to try to be part of these world and I ensure you will never come back! I am not a true fan of agile methodologies but all these concepts including all about extreme programming are the best things I have learned when I started working with Kanban and Scrum. Let's see a small list of refactoring techniques, but this time I will show some very important links, resources and books:
Refactoring in the real world...
In the real world, you can find even big projects with almost all legacy code. This is a very big trouble, not only for developers. We don't have time to write test and we can prefer to write a new software. But even this step is almost always very hard: how can you prefer to work hard and write the same software? Even if all will be perfect, I don't think your boss will let you to spend a lot of time on an old project. Books
- Working Effectively with Legacy Code
- Refactoring: Improving the Design of Existing Code
- Clean code by Robert Martin contains also important informations about refactoring practices
- Refactoring to Patterns by Joshua Kerievsky