Using these principles allows you to write clear code.
Table of contents
- Keep It Simple, Stupid (KISS)
- Write DRY Code
- Open/Closed
- Composition Over Inheritance
- Single Responsibility
- Separation Of Concerns
- You Aren’t Going To Need It (YAGNI)
- Document Your Code
- Refactor
- Clean Code At All Costs
Keep It Simple, Stupid (KISS)
Unnecessary complexity should be avoided.
Source code:
fun sum(a: Int, b: Int): Int {
val result = a + b
return result
}
Problems:
- Using an extra variable
- Unnecessary lines of code
Refactored code:
fun sum(a: Int, b: Int): Int = a + b
Write DRY Code (Don’t Repeat Yourself)
Do not repeat data, do not repeat logic or DO NOT USE Copy-Paste.
Source code:
fun retrieveCountries(): List<Country> {
httpClient.get<List<Country>>("https://server/api/countries") {
header("Platform", "Android")
header("Version", "1.0.0")
header("Auth-Token", "")
}
}
fun retrieveUsers(): List<User> {
httpClient.get<List<User>>("https://server/api/users") {
header("Platform", "Android")
header("Version", "1.0.0")
header("Auth-Token")
}
}
Problems:
- Repeating the same code lines
- After editing a line in one place, you may forget to make changes in another
- Reading unnecessary lines of code
Refactored code:
fun retrieveCountries(): List<Country> {
httpClient.get<List<Country>>("https://server/api/countries") {
addDefaultHeaders()
}
}
fun retrieveUsers(): List<User> {
httpClient.get<List<User>>("https://server/api/users") {
addDefaultHeaders()
}
}
// Extract logic in single place by making extensions, function and etc.
fun HttpRequestBuilder.addDefaultHeaders() {
header("Platform", "Android")
header("Version", "1.0.0")
header("Auth-Token")
}
// Or use http client functionality like request interceptor, default request builder and etc.
val httpClient = HttpClient {
install(DefaultRequest) {
header("Platform", "Android")
header("Version", "1.0.0")
header("Auth-Token")
}
}