Sobes.tech
Middle

What criteria for evaluating code in procedural style can be considered good, and which ones are bad?

sobes.tech AI

Answer from AI

Good criteria:

  • Readability: How easy it is to understand what the code does by reading it from top to bottom.
  • Clarity of variables and functions: Using descriptive names for variables and functions that reflect their purpose and logic.
  • Decomposition: Breaking down complex tasks into smaller, manageable functions. Each function should perform one specific task.
  • Absence of global variables: Minimizing the use of global variables to reduce dependencies and side effects.
  • Error handling: Explicit handling of possible errors and exceptions.
  • Comments: Present where the code is not obvious or to explain logic.
  • Consistent style: Uniform formatting and naming conventions throughout the project.
  • Minimization of code duplication: Avoiding repetition of the same code blocks.
# Good example of decomposition and clear naming
def calculate_average(numbers):
    """Calculates the average of a list of numbers."""
    if not numbers:
        return 0
    total = sum(numbers)
    return total / len(numbers)

def process_data(data):
    # Assuming 'data' is a list of lists of numbers
    averages = []
    for row in data:
        avg = calculate_average(row)
        averages.append(avg)
    return averages

Bad criteria:

  • Lack of clarity: Code is hard to understand due to convoluted logic, non-optimal naming, or lack of structure.
  • "Spaghetti code": Numerous jumps and dependencies making execution flow hard to trace.
  • "Lash" code: Long, monolithic functions performing many unrelated tasks.
  • Use of "magic numbers": Unexplained numeric constants in the code.
  • Lack of error handling: Program "crashes" on unforeseen situations.
  • Code duplication: Same or very similar blocks of code are repeated in different places.
  • Inconsistent style: Different formatting and naming hinder readability.
# Bad example of "lash" and magic numbers
def process(d):
    t = 0
    for r in d:
        s = 0
        c = 0
        for n in r:
            s += n
            c += 1
        if c > 0:
            t += s / c
    return t / len(d) if len(d) > 0 else 0

Comparison:

Good Bad
Readability Lack of clarity ("spaghetti", "lash")
Clear variables and functions Unreadable names
Decomposition Monolithic functions
No global variables Excessive use of global variables
Explicit error handling No error handling
Comments where needed No comments
Consistent style Inconsistent style
Minimized code duplication Code duplication