3개월차 신입 비전공 개발자가 읽기 좋은 코드를 만들어보고자 공부하는 내용입니다. 부족하거나 새롭게 공부해보면 좋을 것 같은 추천, 글에서 발견된 문제에 대한 이야기는 언제든 환영합니다!
public class ExampleService {
private int a = 10;
private int b = 20;
public int escapeBooleanCompare() {
if (compareIntA(100) == true) {
return a;
} else {
return b;
}
}
private boolean compareIntA(int param) {
return param == a;
}
}
==
비교하지 말자.public int escapeBooleanCompare() {
if (compareIntA(100)) {
return a;
}
return b;
}
if(!isTrue())
보다 if(isTrue())
처럼 !가 들어가는 부정은 사용하지 않는 게 좋다 → 긍정의 표현은 부정의 표현보다 코드의 이해도를 높이는데 도움이 됨public class ExampleService {
private String name;
private int age;
public boolean checkUserInfo(String name, int age) {
if (age < 19 || Objects.isNull(name) || name.trim().isEmpty()) {
return false;
} else {
return true;
}
}
}
public boolean checkUserInfo(String name, int age) {
return age > 19 && !Objects.isNull(name) && !name.trim().isEmpty();
}
public boolean checkUserInfo(String name, int age) {
boolean isValidAge = age > 19;
boolean isValidName = !Objects.isNull(name) && !name.trim().isEmpty();
return isValidAge && isValidName;
}
public void writeMessage(String message, Path location) {
if (Files.isDirectory(location)) {
throw new IllegalArgumentException("유효하지 않은 경로입니다.");
}
if (message.trim().isEmpty() || Objects.isNull(message)) {
throw new IllegalArgumentException("유효하지 않은 메시지입니다.");
}
}
public void writeMessage(String message, Path location) {
if (Objects.isNull(message) || message.trim().isEmpty()) {
throw new IllegalArgumentException("유효하지 않은 메시지입니다.");
}
if (Objects.isNull(location) || Files.isDirectory(location)) {
throw new IllegalArgumentException("유효하지 않은 경로입니다.");
}
}
public void writeMessage(int a) {
String result;
switch (a) {
case 1 :
result = "one";
case 2 :
result = "two";
break;
case 3 :
result = "three";
break;
default:
result = "other";
break;
}
}
case 1
블록에 break;
가 빠져있음 → 즉, 첫번째 case는 무조건 실패하고 두번째 case부터 나아가게 됨. → switch case가 버그로 악명 높은 이유 중 하나public void writeMessage(int a) {
String result;
if (a == 1)
result = "one";
if (a == 2)
result = "two";
if (a == 3)
result = "three";
a++;
}
if(a == 3)
구문에 a++;가 연결되어 있는 것으로 보임public void checkAuth() {
if (checkUserUnknown()) {
return;
} else if (checkSupplier()) {
System.out.println("반갑습니다. 판매자님");
} else if (checkConsumer()) {
System.out.println("반갑습니다. 고객님");
}
}
checkUserUnknown()
과 checkSupplier()
, checkConsumer()
는 서로 처리하는 관심사가 다름 → 사용자의 로그인 여부와 사용자의 페르조나(권한) 설정 2개의 관심사로 분리됨 → 얘를 분리해서 코드의 대칭성을 이루자.public void checkAuth() {
if (checkUserUnknown()) {
return;
}
if (checkSupplier()) {
System.out.println("반갑습니다. 판매자님");
} else if (checkConsumer()) {
System.out.println("반갑습니다. 고객님");
}
}