DRY principle
DRY stands for Don't Repeat Yourself. If you write the same code more than once, extract it into a function or component. Repeated code means if you need to change something, you have to change it in multiple places, which leads to bugs.
// BAD: repeated code
function getUserAge(user) {
const now = new Date()
const birth = new Date(user.birthDate)
return now.getFullYear() - birth.getFullYear()
}
function getEmployeeAge(employee) {
const now = new Date()
const birth = new Date(employee.birthDate)
return now.getFullYear() - birth.getFullYear()
}
// GOOD: one function, used everywhere
function getAge(birthDate: string): number {
const now = new Date()
const birth = new Date(birthDate)
return now.getFullYear() - birth.getFullYear()
}
getUserAge = (user) => getAge(user.birthDate)
getEmployeeAge = (emp) => getAge(emp.birthDate)