Sobes.tech
Middle

What do you consider to be quality code?

sobes.tech AI

Answer from AI

A quality code for me possesses the following characteristics:

  • Readability: It is easy for other developers (and yourself after six months) to understand.
  • Maintainability: Making changes and fixing bugs is quick and safe.
  • Testability: The code is divided into modules that are easy to isolate and test.
  • Cleanliness: No duplication (DRY), clear variable and function names, adherence to code style.
  • Efficiency: Optimal use of resources (CPU, memory) for the given task.
  • Reliability: It considers possible errors (exceptions, null values) and handles them correctly.
  • Documentation: Contains clear comments or documentation if necessary.

Example of clean code avoiding duplication:

// Bad: duplication of logic
fun processUser(user: User) {
    if (user.isActive) {
        println("Processing active user ${user.name}")
        // Lots of code...
    } else {
        println("Processing inactive user ${user.name}")
        // Same lots of code...
    }
}

// Good: extracting repeated logic
fun processUser(user: User) {
    println("Processing user ${user.name}") // Common logic
    if (user.isActive) {
        processActiveUser(user)
    } else {
        processInactiveUser(user)
    }
    // Lots of code... // Common logic after if/else
}

fun processActiveUser(user: User) {
    // Only specific logic for active users
}

fun processInactiveUser(user: User) {
    // Only specific logic for inactive users
}

Example demonstrating readability and clear names:

// Bad
fun calc(a: Int, b: Int): Int {
    return a + b
}

// Good
fun calculateSum(firstNumber: Int, secondNumber: Int): Int {
    return firstNumber + secondNumber
}