Writing clean code: 11 day to day self reminders

Below are the 11  principles that one should bear in mind for every single line of code written. It has been repeated over and over in almost any books or tutorials about this topic, however, knowing these principles does not mean one can apply it all the time. I wrote it down as a self reminder once again.

1. Keep consistent with all the naming conventions inside a project or for a particular language.

2. Don’t use magic numbers. Use constant or enum instead.

3. Using indicative names that is self-explanatory.

4. Nested conditions(complex logic) should be simplified as much as possible. Normally, there’s a cleaner way rewriting it using &&, ||, ternary operator or factor it into a more descriptive method.

5. Comment only why and how, NOT what to do with the code. If you have to comment what to do, then it’s an indication of bad naming used.

6. Parameter list should be short(less than 3 or 4), otherwise use a new class to encapsulate.

7. Output parameters should be avoided and it should be put into return type. If more than one results need to be returned, create a new return type.

8. A method should be short and small, ideally less than 10 lines of code. It should be doing only one thing and doing it really well. Break it down into separate methods if it violate single responsibility principle.

9. Avoid using switch statement. Normally it can be replaced by polymorphism in an object-oriented language.

10. Do not repeated your self. Factor duplicated code into a separate method for reuse.

11. Declare variable close to where it is used.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *