To create Clean Code there are some rules that you can follow. If you haven’t already read the first article explaining what Clean Code is, you can find it here. But if you already have read it, let’s get to the rules.

Rule nº 1: The Boy Scout Rule: always leave the camp cleaner than you found it

Everytime you open a code that is messy, you should clean it before you leave. It doesn’t have to be a huge change, it could only be a variable that you rename better or an outdated comment that you delete. If everyone has that same attitude, the code will grow better.

Rule nº 2: Respect indentation

If you use a modern IDE (Integrated Development Environment) to write your code, you probably have an option under your configurations that does the indentation automatically for you. I strongly recommend you use a good indentation, this way you can see what is inside what more easily.

 

For example, take a look at this:

Future<Either<Failure, LoggedUserInfo>> loginWithCredentials(

    LoginCredentials credentials) async {

  try {

    final result = await remoteDataSource.loginWithCredentials(

      email: credentials.email,

      password: credentials.password,

    );

    await localDataSource.saveInCache(result);

    return right(result);

  } on ServerException {

    return left(ServerFailure());

  } on UnauthorizedCredentialsException {

    return left(UnauthorizedCredentialsFailure());

  }

}

 

And now see the same code without indentation:

Future<Either<Failure, LoggedUserInfo>> loginWithCredentials(

LoginCredentials credentials) async {

try {

final result = await remoteDataSource.loginWithCredentials(

email: credentials.email,

password: credentials.password,

);

await localDataSource.saveInCache(result);

return right(result);

} on ServerException {

return left(ServerFailure());

} on UnauthorizedCredentialsException {

return left(UnauthorizedCredentialsFailure());

}

}

 

Do you see that it’s much harder to read if it’s not indented?

Rule nº 3: Keep your lines short

Even though our screens are getting bigger every year, there is one thing that has never changed: the average number of characters in a line (which is around 30 to 40 characters). 

Long lines are harder to read; it’s easy to get distracted when your eyes have to move from the end of one long line to the beginning of the next. It’s very easy to establish limits on our IDEs nowadays, they usually come with a default limit around 120 characters, and using this feature is a simple way to keep your lines short.

Rule nº 4: Keep your files also short

Uncle Bob (Robert C. Martin, author of Clean Code) shows us that the size of a file is not related to the size of the project. What is important is to keep your classes short, because it’s easier to digest information that is broken into smaller pieces.

Rule nº 5: Isolate business rules from the UI

Business rules are the logic you have on your application and UI is your User Interface, where all your design goes. Uncle Bob tells us that the User Interface changes a lot for silly reasons, like a color being updated when someone presses a button, but the business rules should not act the same. A logout rule should not be affected when the UI changes its color, so they need to be separated into different layers. 

This leads us to his Clean Architecture lectures (we won’t talk a lot about it in this article, but know that you need to separate your application in layers). Your business rules, User Interface and data communication should be in separated layers; this way you will know where to find everything and your structure will be clear for everyone as you have established a pattern. Also, there will be fewer bugs because you won’t have too much code on just one file, and you won’t make mistakes changing things on your business rules when you were only supposed to change the color of your text.

Rule nº 6: Avoid using too many Strings

When you are coding and you depend on Strings, you might misspell a word and get errors for that, oftentimes in a way you can’t prevent.

For example, try NOT to do this:

void signIn({String email, String password}) {

   final result = repository.login(email, password);

   if(result.message == ‘success’) { }

   else if(result.message == ‘invalid email’) { }

   else if (result.message == ‘invalid password’) { }

   else { }

}

If for some reason you absolutely need to depend on a String, try to pass it into a variable, like this:

String successMessage = ‘success’;

String invalidEmail = ‘invalid email’;

String invalidPassword = ‘invalid password’;

This way, if you need to use these Strings in many places you can use variable directly, avoiding misspellings.

Rule nº 7: Don’t use magic numbers

If there is a number in your code that is used in a conditional statement, it seems that it came out of nowhere, just like magic.

DON’T do this:

List<int> avarageMathGrades;

void addGradeToAverageList(int grade) {

   if(grade < 6) {

      avarageMathGrades.add(grade);

   }

}

Do this instead:

List<int> avarageMathGrades;

const int averageGrade = 6;

void addGradeToAverageList(int grade) {

   if(grade < averageGrade) {

      avarageMathGrades.add(grade);

   }

}

In the next article, we will talk about rules applied to comments and names.


References

Martin, Robert C. Clean Code: A Handbook of Agile Software Management. Prentice Hall, 2008.

Calm Experts - Logo

Let's have a chat

Learn how we Can help from here to launch.