Sobes.tech
Junior

What are the principles of DRY and KISS?

sobes.tech AI

Answer from AI

DRY (Don't Repeat Yourself) — a principle that encourages avoiding code duplication. Each piece of information or logic should exist in one, single place.

KISS (Keep It Simple, Stupid) — a principle aimed at simplicity and clarity of design and logic. Code should be as simple as possible and easy to maintain.

  • Advantages of DRY:
    • Reducing errors: Changes in logic need to be made in only one place.
    • Accelerating development: No need to write the same code multiple times.
    • Improving readability: Lack of duplication makes the code more structured.
  • Advantages of KISS:
    • Ease of understanding: Simple code is easier to read and understand.
    • Debugging convenience: Fewer points for potential errors.
    • Quick support: Simple code is easier to modify and extend.

Applying these principles:

<?php
// Example without applying DRY (logic duplication of discount calculation)
function calculatePriceWithDiscountA(float $price): float {
    if ($price > 1000) {
        return $price * 0.9;
    }
    return $price;
}

function calculatePriceWithDiscountB(float $price): float {
    if ($price > 1000) {
        return $price * 0.9;
    }
    return $price;
}

// Example with DRY applied (logic extracted into a separate function)
function applyDiscount(float $price): float {
    if ($price > 1000) {
        return $price * 0.9;
    }
    return $price;
}

function calculateFinalPriceA(float $price): float {
    return applyDiscount($price);
}

function calculateFinalPriceB(float $price): float {
    return applyDiscount($price);
}

// Example of simple code (KISS)
function sum(int $a, int $b): int {
    return $a + $b;
}

// Example of more complex code that can be simplified
function complexSum(int $a, int $b): int {
    $result = 0;
    $result += $a;
    $result += $b;
    return $result;
}

Applying these principles leads to the creation of more quality, easily maintainable, and extendable code.