With Kotlin we can write concise, expressive, and safe code. Sounds like clean code, doesn’t it?
In this article we will recap what clean code is, we will highlight the importance of defining meaningful names, and how to write clean functions and classes.
Finally, we will be able to learn more about the advantages of immutability, how to handle the errors in Kotlin, and what are the best practices in terms of writing tests. By the end of this blog post, you will better understand what clean code means and learn a series of tips and tricks ready to be applied in your code.
“Coding is not a sprint, is a marathon” so let’s exercise together our clean code skills.
What is Clean Code?
Uncle Bob in the book “Clean Code” mentioned that “Clean code is readable. It tells a story.”
Venkat Subramaniam in the book “Practices of an Agile Developer: Working in the Real World” emphasis the importance of expressing clear our intentions “Express your intentions clearly to the reader of the code. Unreadable code isn’t clever.”
How to measure if we have Clean Code?
Now that we defined the concept of clean code, how do we measure the quality of the code?
An unofficial measure is wtfs/min. If we have few wtf/min we have a team of happy developers, if we have many wtf/min we have a team with not so happy developers. An important thing to mention here is that wtf means “what a terrible feature”.
But how to write clean code? There is a set of rules that should be applied. Let’s start by talking about meaningful names.
When we write code we create packages, classes, functions, variables. And all of these elements should have names. By choosing a name we should reveal our intention for that component, even if it’s just a variable or a class. To make sure that our code is readable when we search for a name we should answer at these 3 questions:
- Why it exists?
- What does it do?
- How it is used?
To provide relevant samples we will have 2 types of code snippets: “unclean” code samples (Evil Jerry), and clean code samples (Angel Jerry).
By using Kotlin we are able to say more often YES to immutability:
- Prefer to use val over var
- Prefer to use read-only properties over mutable properties
- Prefer to use read-only collections over mutable collections
- Prefer to use data classes that give us copy()
What are the rules when it comes to write functions in Kotlin:
- First rule: The functions should be small
- Second rule: The functions should be smaller than that
Why is it not ok to have long functions?
Because long functions are:
- Hard to test
- Hard to read
- Hard to reuse
- Leads to duplication
- Many reasons to change
- Hard to debug
Extra-rules to be applied when we write functions in Kotlin:
- Many arguments => group them in objects or use lists (same type)
- A function should not have side effects => side effects are lies
- The indent level of a function => max 2
- if, else, while statements contain a block with one line of code
- A long descriptive name is better than a short enigmatic name
- Change and restructure the code until it easy enough to read it
- Apply Command Query Separation Principle
Command Query Separation Principle
The main idea is that we should divide an object’s methods into two separated categories:
- Queries: Return a result and do not change the observable state of the system (are free of side effects).
- Commands: Change the state of a system but do not return a value.
A class should be smaller than small. It should have only one responsibility and a single reason to change. A class collaborates with a few others to achieve the desired system behaviors.
A class file is like a newspaper article:
- The name should be simple and self-explanatory
- The parts from the top contain the high-level concepts and algorithms
- Details appear as we move downward
- At the end we find the lowest level functions
- Cohesion is a measure of the degree to which the elements of the class/ module are functionally related.
- When classes lose cohesion, split them.
- Coupling is the measure of the degree of interdependence between the modules.
- This isolation makes it easier to understand each element of the system.
✨✨✨Best case scenario: high cohesion and loosed coupling
Other than having high cohesion and loosed coupling, when we write classes we should follow also principles like:
- Don’t Repeat Yourself
- Applicable whenever we copy / paste a piece of code
- It reduces the cost of development
- Keep It Simple and Stupid
- Whenever we want to implement a method to do all things
- Simple things fail less
- Simple is different than familiar: a for loop is familiar, but it is not necessary a simple one
- You Ain’t Gonna Need It
- Don’t write code which is not yet necessary
- How much do you know?
- Evaluate the cost of implementation: it is expensive to do it now, postpone it if it is possible
- Single Responsibility Principle (SRP) states that a class or module should have one, and only one, reason to change.
- Open-closed (OCP) – Software entities like classes, modules and functions should be open for extension but closed for modifications.
- Liskov substitution (LSP) – Objects in a program should be replaceable with instances of their subtypes without changing the behavior of that program.
- Interface segregation (ISP) – Classes that implement interfaces, should not be forced to implement methods they do not use.
- Dependency inversion (DIP) – High level modules should not depend on low level modules rather both should depend on abstraction. Abstraction should not depend on details; rather detail should depend on abstraction
When we talk about how to handle the unexpected scenarios we should:
- Prefer standard errors to custom ones.
- Error handling is important, but if it obscures logic, it’s wrong.
- In Kotlin we have only unchecked exceptions.
- Prefer null or Failure result when the lack of result is possible
In Kotlin we could use Nothing whenever the functions don’t return anything.
Based on the official documentation “Sealed classes are used for representing restricted class hierarchies, when a value can have one of the types from a limited set, but cannot have any other type. They are, in a sense, an extension of enum classes: the set of values for an enum type is also restricted, but each enum constant exists only as a single instance, whereas a subclass of a sealed class can have multiple instances which can contain state.”
Keep your tests clean:
- Use same quality standards for tests as for production code and readability is again important
- Tests should preserve and enhance:
- Even for tests we should use the same domain language that also helps readability.
- Refactor the tests, just like we do with the production code.
Include only one asset per test:
- Every test function in a JUnit test should have one and only one assert statement.
- Given, When, Then naming (BDD – Behavior Driven Development)
- The best thing to do is to minimize the number of asserts.
- Test just one concept per test function.
A test should have only one reason to fail.
Respect the FIRST principle when you write tests:
- Fast – tests should be fast / run quickly
- Independent – tests should NOT depend on each other – tests should be able to be run in any order they like
- Repeatable – they should be repeatable in ANY environment without need for any specific infrastructure
- Self-validating – they should have a boolean output – pass or fail, nothing else
- Timely – they need to be written in a timely fashion – just before the production code is written – ensures they are easy to code against
The rule: Don’t add comments on the bad code, just rewrite it until it’s self-explanatory.
When we write code is almost impossible to get it right the first time, so software is never written, it is always rewritten. Don’t attach too much to your code, refactor it until is clear enough. And remember…
👩🏽💻Code Review Best Practices
Code Review advantages:
- Help to improve the quality and consistency of the code
- Exchange of knowledge and best practices
- Learn the code base
- New perspective(s) on your code
- Learn new tips and tricks about writing code
When we talk about code review, 3 entities are involved: the author of the code, the reviewer of the code, and the code itself.
If you are the author of the code:
- Writing the code
- Make sure you understand your task and start a new branch for it
- Write the code and check if your code is easy to understand or if it can be improved (refactored)
- Respect the boy scout rule
- Write tests and make sure your code follows the team conventions and practices
- Format your code before commit it
- Use tools like Ktlint or SonarKotlin to check your code before it is sent for review
- Before the Pull Request is sent
- Add relevant commit comments for the reviewer(s)
- Send pull requests often and specify if the task is fully done or not
- Have minimum 2 reviewers, one of them should be a senior
- After your code is reviewed
- Be humble, your code is reviewed, not you as a person
- You are part of the team, so you are on the same side with your reviewer(s)
- Development is continuous so also feedback is continuous
- Know when to unlearn the old habits
- Opportunity to learn new best practices, tips and tricks
If you are the reviewer of the code:
- Use I… comments
- I think…
- I would…
- I believe…
- I suggest…
- Ask questions to help the author of the code to think at different perspectives
- Have you consider using…
- What do you think about…
- Have you tried to…
- Remember that it’s about the code, not about the coder
- This code…
- This function…
- This line of code…
- Use the feedback equation to make your comments relevant and based on measurable observations
- Define with your team a set of conventions and make sure they are aware about them
- Justify technology use, do not use a framework or library, just because is trendy or cool
- Enforce good practices (XP): pair programming, coding standards, coding katas
- Question until you understand: make sure you know and understand what problem do you want to solve
- Criticize ideas, not people: remember to give honest and relevant feedback based on measurable observations
- Testing, testing, testing: test your code, learn about testing pyramid
- Integrate early, integrate often: will speed up the releases
- Emphasize collective ownership of code: you are part of the team, and all the team is responsible for the delivered code
- Prioritize and actively evaluate trade-offs: asses the pros and cons of implementing features, make decisions based on data
- Listen to users: we are delivering software for people, so keep your focus on your customers’ needs and feedback.
- CommandQuerySeparation by Martin Fowler
- One Assertion Per Test by Dave Astels
- The Tragedy Of Checked Exceptions by Howard Lewis Ship
- Exceptions are Bad by Jed Wesley-Smith
- Checked exceptions I love you, but you have to go by Miško Hevery
- One Assertion Per Test by Dave Astels
- Clean Code playlist on Youtube
- “Clean Code” book by Uncle Bob
- “Practices of an Agile Developer: Working in the Real World” book by Andy Hunt and Venkat Subramaniam
- Slides Clean Code with Kotlin