Best Practices For Writing Clean Code
This article aims to foster a mindset of writing maintainable, elegant, and readable code. The examples are written in Groovy/Java, but the concepts are applicable to most languages. It covers essential principles and practices to help you create high quality software. Clean and well designed code can be easily reused across different applications and features.
1. Make most of Groovy, and be consistent with it
Groovy has its own coding conventions and style guide. Adhering to these conventions ensures consistency in your codebase.
2. Leverage closures
Groovy’s support for closures allows you to write concise and expressive code. Use closures to simplify repetitive tasks and improve readability:
// Without closures
[1, 2, 3].each { println it }
// With closures// Without closures
[1, 2, 3].each { println it }
[1, 2, 3].each { num ->
println num
}
3. Favor String interpolation
Groovy supports string interpolation, making it easier to build strings with dynamic content:
def name = 'Wagner'
println "Hello, $name!"
If you’re not interpolating strings, it’s better to use simple quotes instead of double quotes.
4. Avoid unnecessary code
Groovy is a dynamic language that doesn’t require excessive parentheses, semicolons or even return statement at the end of methods. Keep your code as clean as possible:
// Unnecessary parentheses, semicolon and return statement
if ((condition)) {
// ...
};
return false
领英推荐
// Cleaner code
if (condition) {
// ...
}
false
The last expression evaluated in the body of a method can be returned without necessitating the return keyword. Especially for short methods and for closures, it’s nicer to omit it for brevity. Worth mentioning that Codenarc will analyse it for code smells, inconsistencies and style issues.
5. Prefer Groovy’s built-in methods
Groovy enhances Java collections with additional methods like each, collect, and findAll. These methods simplify iteration and transformation of lists, maps, and other collections. Familiarise yourself with these methods to simplify your code and make it more idiomatic:
// Use built-in methods
def jiraVersions = [8.20.0, 9.15.2, 10.0.0]
jiraVersions.each { println it }
jiraVersions.collect { it * 2 }
...
Remember, clean code isn’t just about syntax; it’s about writing code that is easy to read, understand, and maintain. Often times the code would look more sophisticated or shorter in a given way — like a one liner that does all at once — but is likely harder to read and maintain.
6. Testing strategies
Write unit tests to verify your code’s correctness. Test-driven development (TDD) can help you write cleaner code by forcing you to consider edge cases and expected behaviour upfront. Well-tested code is more reliable and easier to refactor.
Integration tests need a more involving setup process, are usually harder to write, maintain and are slower to run. Additionally, integration tests usually require a strict execution order and can’t be run simultaneously. On the other hand, unit tests run faster, are easier to maintain and can be executed in any order, or even simultaneously.
Depending on your task, you might need to create browser tests (aka Geb). Keep in mind that these tests can be time-consuming, fragile, and complex to maintain. If the functionality you’re working on doesn’t require this type of test, it’s best not to add it.
Use the Spock naming convention where test classes end with “Spec”, i.e. “TestNameSpec.groovy”.
7. Use comments sparingly, and when you do, make them meaningful
Please don’t add comments on obvious things. Excessive or unclear comments can clutter the codebase and become outdated, leading to confusion and a messy codebase. Ideally, classes, methods and variables should have meaningful names, so comments would simply state the same.
When necessary, use comments to explain the “why” behind specific actions or explain unusual behaviours and potential pitfalls.
References: