KISS Software Design Principle - DevOli/Marvel-chars GitHub Wiki

KISS - Keep it Simple, Stupid

Code as simple and clear as possible. Following this principle our system will improve its performance, be simpler to maintain and easier for the other members of our team to understand the logic behind our code.

To achieve this, we must be aware of:

Lines of code

Keep our methods small. Should not be more than 40-50 lines of code

Method complexity

Divide complex or lengthy code into multiple methods so each one of these will solve a single problem

How the problem is being solved

If there are too many conditions in a method, most probably the code can be improved

Think of more than one way to solve the problem and choose the simpler

Example 1

This piece of code can be optimized

public String weekday1(int day) {
    switch (day) {
        case 1:
            return "Monday";
        case 2:
            return "Tuesday";
        case 3:
            return "Wednesday";
        case 4:
            return "Thursday";
        case 5:
            return "Friday";
        case 6:
            return "Saturday";
        case 7:
            return "Sunday";
        default:
            throw new InvalidOperationException("day must be in range 1 to 7");
    }
}

Into

public String weekday2(int day) {
    if ((day < 1) || (day > 7)) throw new InvalidOperationException("day must be in range 1 to 7");

    string[] days = {
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
        "Sunday"
    };

    return days[day - 1];
}

Example 2

This piece of code can be optimized

function checkName(name) {
  if (name === null || name === undefined || name === "") {
    console.log("name not defined!");
  } else {
    console.log(name);
  }
}
checkName();

Into

function checkName(name) {
  console.log(name || "name not defined!");
}
checkName();

Example 3

This piece of code can be optimized

const getData = (url) => {
  return $.getJSON(url)
    .then((data) => {
      console.log(data);
    })
    .catch((err) => {
      console.log(err);

    });
};

getData("https://jsonplaceholder.typicode.com/todos/1");

Into

const getData = async (url) => {
  try {
    const data = await $.getJSON(url);
    console.log(data);
  } catch (err) {
    console.log(err);
  }
};
getData("https://jsonplaceholder.typicode.com/todos/1");

Example 4

This piece of code can be optimized

const even = [2,4,6]
const nums = [10,12,16].concat(even); // 10,12,16,2,4,5

Into

const even = [2,4,6]
const nums = [10,12,16,...even]