DEV Community

joshdrichest
joshdrichest

Posted on • Updated on

Five Rules You Should Stick to when Refactoring a Code

Rule 1: A method should not have more than five lines

This rule prevents a method from performing too many tasks. If a method performs too many tasks, it is advisable to divide it into smaller methods.

Rule 2: Only inherit from interfaces

Usually, when refactoring a code, one would inherit from classes or abstract classes. However, it is better to only inherit from interfaces because we promote tight coupling when sharing code between classes.

Rule 3: No interfaces with only one method

You shouldn't have interfaces that only have one implementation. This helps you reduce boilerplate code.

Rule 4: If only at the start

If statements should always be at the top of a method. Nothing else should happen after the “If” statement. This doesn't mean that we should separate the “If” from the “else” (they go together).

Rule 5: Never use “If” with “else”

You should not use “If” with “else” unless you check against a data type. Using if-else statements makes the code more rigid because you're saying that a decision has to be made at a specific point.

What rule(s) of your own would you be adding to the list?

Top comments (0)