Junior
What are the principles of DRY and KISS in programming?
sobes.tech AI
Answer from AI
The DRY principle (Don't Repeat Yourself) means "Don't Repeat Yourself." Its essence is to avoid duplication of code and data. Instead of copying logic, it is extracted into reusable functions, components, or modules. This simplifies maintenance, reduces the likelihood of errors during changes, and improves code readability.
The KISS principle (Keep It Simple, Stupid) means "Keep It Simple, Stupid." It encourages creating as simple and understandable solutions as possible. Avoid unnecessary complexity, premature optimization, or using complex patterns if simpler ones suffice. Simple code is easier to understand, test, and debug.
Example of DRY in React:
// Duplication in two components
function ButtonPrimary({ text, onClick }) {
return <button className="button button--primary" onClick={onClick}>{text}</button>;
}
function LinkPrimary({ text, href }) {
// Part of styles is duplicated
return <a className="button button--primary" href={href}>{text}</a>;
}
// Applying DRY with a common component
function PrimaryStyling({ children, as: Component = 'button', ...props }) {
return <Component className="button button--primary" {...props}>{children}</Component>;
}
function ButtonPrimaryDRY({ text, onClick }) {
return <PrimaryStyling onClick={onClick}>{text}</PrimaryStyling>;
}
function LinkPrimaryDRY({ text, href }) {
return <PrimaryStyling as="a" href={href}>{text}</PrimaryStyling>;
}
Example of KISS in JavaScript:
// Overly complex solution for summing
function calculateSumComplex(numbers) {
let sum = 0;
if (Array.isArray(numbers)) {
for (let i = 0; i < numbers.length; i++) {
if (typeof numbers[i] === 'number' && !isNaN(numbers[i])) {
sum += numbers[i];
}
}
}
return sum;
}
// Simple and understandable sum calculation (assuming expected input data)
function calculateSumKISS(numbers) {
return numbers.reduce((sum, current) => sum + current, 0);
}