728x90
if-else 조건문을 많이 사용하게 되면 코드 라인이 길어지고 indent가 많아져 가독성이 떨어지는 문제가 발생합니다. 이때 Guard Clausing과 Polymorhism(다형성)을 사용하면 코드를 클린하게 짤 수 있습니다.
Guard clause
일반적으로 if-else문이 중첩(nestsed)될수록 코드는 복잡해지고 보기 지저분해집니다.
// BAD
if(){
...
if(){
...
if(){
...
while(){
...
...
}
}
}
}
nested 코드를 줄이고 가독성을 높이기 위해선, 코드 상단에 Fail이 되는 로직을 위로 넣어두는 것이 좋습니다.
- as-is
function sayHiToSpringUser(developer){
if (developer.isFrontEnd){
throw new Exception("프론트 엔지니어입니다")
else if (developer.isBackEnd){
if (!developer.useJava){
throw new Exception("자바를 사용하지 않습니다")
} else{
if (developer.useSpring){
console.log("안녕하세요!")
} else{
throw new Exception("자바의 다른 프레임워크를 사용합니다")
}
}
} else{
throw new Exception("who are you?")
}
}
}
- to-be
// Fail이 되는 부분을 상위로 올리면 코드를 더 쉽게 읽을 수 있습니다.
function sayHiToSpringUser(developer){
if (!developer.isFrontEnd){
throw new Exception("백엔드 엔지니어가 아닙니다")
}
if (!developer.useJava){
throw new Exception("자바를 사용하지 않습니다")
}
if {!developer.useSpring){
throw new Exception("스프링을 사용하지 않습니다")
}
console.log("안녕하세요!")
}
Polymorphism(다형성)
객체 지향의 꽃이라고 불리는 다형성을 활용하여 if-condition을 줄일 수 있습니다.
- to-be
// Employee로 추상화해둡니다.
class Employee{
work(){
}
}
// 혹은 interface로 설정해도 됩니다.
class Developer extends Employee{
work(){
console.log("코딩을 합니다")
}
}
class Designer extends Employee{
work(){
console.log("디자인을 합니다")
}
}
class Analyst extends Employee{
work(){
console.log("분석을 합니다")
}
}
type jobs = Developer | Designer | Analyst
class Company{
private employees: jobs
constructor(employees: jobs){
this.employees = employees
}
// if문을 사용하지 않고 다형성을 통해서 이를 해결합니다.
makeWork(){
this.employees.work()
}
}
const Kim = new Developer()
const google = new Company(Kim)
google.makeWork()
728x90