packagecom.fromitive.MyFirstPackage;publicclassMultiplicationTable{voidprint(){print(5);}voidprint(inttable){print(table,1,9);}voidprint(inttable,intfrom,intto){for(inti=from;i<=to;i++){System.out.printf("%d * %d = %d",table,i,table*i).println();}}// 코드의 구조가 변경되지 않음publicstaticvoidmain(String[]args){MultiplicationTablemulti=newMultiplicationTable();multi.print();// execute print() methodmulti.print(6);// execute print(int form) methodmulti.print(8,2,18);// execute print(int table, int from, int to)}
이로써 main함수의 구조를 변경하지 않고 코드를 유지보수 하기 쉽게 그리고 읽기 쉽게 변경되었음을 볼 수 있다.
하지만, 개인적으로 5번째 줄처럼 무조건 중복을 제거하는게 맞는건지 판단이 서지 않는다. 왜냐하면 print() 함수를 분석할 때, print(int table)을 본 후 마지막으로 print(int table, int from, int to)를 분석해야 하기 때문이다.
메인으로 사용하는 함수만 분석할 수 있게 최종적으로 아래와 같이 리펙토링을 하면, 더욱 가독성 있게 보이지 않을까? 생각된다.
packagecom.fromitive.MyFirstPackage;publicclassMultiplicationTable{voidprint(){print(5,1,9);// print(int table, int from, int to) 만 분석할 수 있게 변경}voidprint(inttable){print(table,1,9);}voidprint(inttable,intfrom,intto){for(inti=from;i<=to;i++){System.out.printf("%d * %d = %d",table,i,table*i).println();}}// 코드의 구조가 변경되지 않음publicstaticvoidmain(String[]args){MultiplicationTablemulti=newMultiplicationTable();multi.print();// execute print() methodmulti.print(6);// execute print(int form) methodmulti.print(8,2,18);// execute print(int table, int from, int to)}