SlideShare uma empresa Scribd logo
1 de 13
Baixar para ler offline
Clean Code
     Ch.15 JUnit
     chois79




12년 9월 3일 월요일
JUnit 프레임워크
     • JUnit 소개


          • Java 언어용 테스트 프레임워크


          • 저자: 켄트벡, 에릭감마 등


          • v3.x 구조


                • 모든 테스트 클래스는 testCase를 상속 받음


                • 테스트 메소드의 이름은 test로 시작해야 함
                  import junit.framework.TestCase;

                  public class ComparisoncompactorTest extends TestCase{
                  	    public void testMessage() {
                  	    	    String failure = new ComparisonCompactor(0, "b", "c").compact("a");
                  	    	    assertTrue("a expected:<[b]> but was:<[c]>".equals(failure));
                  	    }
                  	
                  	
                  	
                  }



     • But, 이 장에서는 JUnit에서 가져온 예제 코드 ComparisonCompactor.java 를 평가




12년 9월 3일 월요일
ComparisonCompactor Class

     • 두 문자열을 받아 차이를 반환


          • ex) ABCDE, ABXDE => ...B[X]D...
       public class ComparisonCompactor {
       	    private static final String ELLIPSIS = "...";
       	    private static final String DELTA_END = "]";
       	    private static final String DELTA_START= "[";
       	    private int fContextLength;
       	    private String fExpected;
       	    private String fActual;
       	    private int fPrefix;
       	    private int fSuffix;
       	
       	    public ComparisonCompactor(int contextLength, String expected, String actual) {
       	    	    fContextLength = contextLength;
       	    	    fExpected = expected;
       	    	    fActual = actual;
       	    }
       	
       	    public String compact(String message) {
       	    	    if(fExpected == null || fActual == null || areStringEqual())
       	    	    	    return assertFormat(message, fExpected, fActual);
       	    	    findCommonPrefix();
       	    	    findCommonSuffix();
       	    	    String expected = compactString(fExpected);
       	    	    String actual = compactString(fActual);
       	    	    return assertFormat(message, expected, actual);
       	    }



12년 9월 3일 월요일
ComparisonCompactor Class
      	    private String compactString(String source) {
      	    	    String result = DELTA_START + source.substring(fPrefix,   source.length() -
      	    	    	    	    fSuffix + 1) + DELTA_END;
      	    	
      	    	    if(fPrefix > 0) {
      	    	    	    result = computeCommonPrefix() + result;
      	    	    }
      	    	
      	    	    if(fSuffix > 0) {
      	    	    	    result = result + computeCommonSuffix();
      	    	    }
      	    	    return result;
      	    }

      	    private void findCommonSuffix() {
      	    	    int expectedSuffix = fExpected.length() - 1;
      	    	    int actualSuffix = fActual.length() - 1;
      	    	    for(; actualSuffix >= fPrefix && expectedSuffix >= fPrefix;
      	    	    	    	    actualSuffix--, expectedSuffix--) {
      	    	    	    if(fExpected.charAt(expectedSuffix) != fActual.charAt(actualSuffix))
      	    	    	    	    break;
      	    	    }
      	    	    fSuffix = fExpected.length() - expectedSuffix;
      	    }

      	    private void findCommonPrefix() {
      	    	    fPrefix = 0;
      	    	    int end = Math.min(fExpected.length(), fActual.length());
      	    	    for(; fPrefix < end; fPrefix++) {
      	    	    	    if(fExpected.charAt(fPrefix) != fActual.charAt(fPrefix))
      	    	    	    	    break;
      	    	    }
      	    }




12년 9월 3일 월요일
ComparisonCompactor Class

       	    private String computeCommonPrefix() {
       	    	    return (fPrefix > fContextLength? ELLIPSIS: "") +
       	    	    	    	    fExpected.substring(Math.max(0, fPrefix - fContextLength), fPrefix);
       	    }

       	    private String computeCommonSuffix() {
       	    	    int end = Math.min(fExpected.length() - fSuffix + 1 + fContextLength,
       	    	    	    	    fExpected.length());
       	    	
       	    	    return fExpected.substring(fExpected.length() - fSuffix + 1, end) +
       	    	    	    	    (fExpected.length() - fSuffix + 1 < fExpected.length() -
       	    	    	    	     fContextLength? ELLIPSIS: "");
       	    }



       	    private boolean areStringEqual() {
       	    	    return fExpected.equals(fActual);
       	    }

       	    private String assertFormat(String message, String fExpected,
       	    	    	    String fActual) {
       	    	    return message + “expected: <” + fExpected + “> but was: <” + fActual + “>”;
       	    }



       }




12년 9월 3일 월요일
Clean Code 적용

        • 접두어 제거
         	      private   static final String ELLIPSIS = "...";       	       private   static final String ELLIPSIS = "...";
         	      private   static final String DELTA_END = "]";        	       private   static final String DELTA_END = "]";
         	      private   static final String DELTA_START= "[";       	       private   static final String DELTA_START= "[";
         	      private   int fContextLength;                         	       private   int contextLength;
         	      private   String fExpected;                           	       private   String expected;
         	      private   String fActual;                             	       private   String actual;
         	      private   int fPrefix;                                	       private   int prefix;
         	      private   int fSuffix;                                	       private   int suffix;




        • 접두어 제거로 인한 충돌
                                                                          public String compact(String message) {
    public String compact(String message) {
                                                                          	    if(expected == null || actual == null || areStringEqual())
    	    if(expected == null || actual == null || areStringEqual())
                                                                          	    	    return assertFormat(message, expected, actual);
    	    	    return assertFormat(message, expected, actual);
                                                                          	    findCommonPrefix();
    	    findCommonPrefix();
                                                                          	    findCommonSuffix();
    	    findCommonSuffix();
                                                                          	    String compactExpected = compactString(expected);
    	    String expected = compactString(expected);
                                                                          	    String compactActual = compactString(actual);
    	    String actual = compactString(actual);
                                                                          	    return assertFormat(message, compactExpected,
    	    return assertFormat(message, expected, actual);
                                                                          	    	    compactActual);;
    }
                                                                          }




12년 9월 3일 월요일
Clean Code 적용

     • 조건문 캡슐화                                                       public String compact(String message) {
                                                                     	    if(shouldNotCompact())
   public String compact(String message) {                           	    	    return assertFormat(message, expected, actual);
   	    if(expected == null || actual == null || areStringEqual())   	    findCommonPrefix();
   	    	    return assertFormat(message, expected, actual);         	    findCommonSuffix();
   	    findCommonPrefix();                                          	    compactExpected = compactString(expected);
   	    findCommonSuffix();                                          	    compactActual = compactString(actual);
   	    compactExpected = compactString(expected);                   	    return assertFormat(message, compactExpected,
   	    compactActual = compactString(actual);                       	    	    compactActual);
   	    return assertFormat(message, compactExpected,                }
   	    	    compactActual);                                         private boolean shouldNotCompact() {
   }                                                                 	    return expected == null || actual == null ||
                                                                                  areStringEqual();
                                                                     }
                                                                     public String compact(String message) {
     • 긍정 표현으로 변경                                                    	    if(canBeCompacted()) {
                                                                     	    	    findCommonPrefix();
      public String compact(String message) {                        	    	    findCommonSuffix();
      	    if(shouldNotCompact())                                    	    	    compactExpected = compactString(expected);
      	    	    return assertFormat(message, expected, actual);      	    	    compactActual = compactString(actual);
      	    findCommonPrefix();                                       	    	    return assertFormat(message, compactExpected,
      	    findCommonSuffix();                                       	    	    	    compactActual);
      	    compactExpected = compactString(expected);                	    } else {
      	    compactActual = compactString(actual);                    	    	    return assertFormat(message, expected, actual);
      	    return assertFormat(message, compactExpected,             	    }
      	    	    compactActual);                                      }
      }
                                                                     private boolean canBeCompacted() {
      private boolean shouldNotCompact() {
                                                                     	    return expected != null && actual != null &&
      	    return expected == null || actual == null ||
                                                                                  areStringEqual();
                  areStringEqual();
                                                                     }
      }




12년 9월 3일 월요일
Clean Code 적용

     • 함수의 의미를 명확하게 변경, Extract Method 적용
        public String compact(String message) {                     private String compactExpected;
        if(canBeCompacted()) {                                      private String compactActual;
        	    	    findCommonPrefix();
        	    	    findCommonSuffix();                               public String formatCompactedComparison(String message) {
        	    	    compactExpected = compactString(expected);        	    if(canBeCompacted()) {
        	    	    compactActual = compactString(actual);            	    	    compactExpectedAndActual();
        	    	    return assertFormat(message, compactExpected,     	    	    return assertFormat(message, compactExpected,
        	    	    	    compactActual);                              	    	    compactActual);
        	    } else {                                               	    }
        	    	    return assertFormat(message, expected, actual);   	    return assertFormat(message, expected, actual);
        	    }                                                      }
        }
                                                                    private void compactExpectedAndActual() {
                                                                    	    findCommonPrefix();
                                                                    	    findCommonSuffix();
                                                                    	    compactExpected = compactString(expected);
                                                                    	    compactActual = compactString(actual);
                                                                    }




12년 9월 3일 월요일
Clean Code 적용

     • 함수 내부의 사용 방식 통일
                                                                   private void compactExpectedAndActual() {
    private void compactExpectedAndActual() {                      	    prefixIndex = findCommonPrefix();
    	    findCommonPrefix();
                                                                   	   suffixIndex = findCommonSuffix();
    	    findCommonSuffix();
                                                                   	   compactExpected = compactString(expected);
    	    compactExpected = compactString(expected);
                                                                   	   compactActual = compactString(actual);
    	    compactActual = compactString(actual);
                                                                   }
    }

                                                                   private int findCommonPrefix() {
    private void findCommonPrefix() {
                                                                   	    int prefixIndex = 0;
    	    prefix = 0;
    	    int end = Math.min(expected.length(), actual.length());   	    int end = Math.min(expected.length(), actual.length());
    	    for(; prefix < end; prefix++) {                           	    for(; prefixIndex < end; prefixIndex ++) {
    	    	    if(expected.charAt(prefix)                           	    	    if(expected.charAt(prefixIndex)
    	    	    	    	    != actual.charAt(prefix))                  	    	    	    	    != actual.charAt(prefixIndex))
    	    	    	    break;                                          	    	    	    break;
    	    }                                                         	    }
    }                                                              	   return prefixIndex;
                                                                   }
    private void findCommonSuffix() {
    	    int expectedSuffix = expected.length() - 1;               private int findCommonSuffix() {
    	    int actualSuffix = actual.length() - 1;                   	    int expectedSuffix = expected.length() - 1;
    	    for(; actualSuffix >= prefix                              	    int actualSuffix = actual.length() - 1;
    	    	    	    && expectedSuffix >= prefix;                    	    for(; actualSuffix >= prefixIndex
    	    	    	    actualSuffix--, expectedSuffix--) {             	    	    	    && expectedSuffix >= prefixIndex;
    	    	    if( expected.charAt(expectedSuffix)                  	    	    	    actualSuffix--, expectedSuffix--) {
    	    	    	    	    != actual.charAt(actualSuffix))            	    	    if( expected.charAt(expectedSuffix)
    	    	    	    break;                                          	    	    	    	    != actual.charAt(actualSuffix))
    	    }                                                         	    	    	    break;
    	    suffix = expected.length() - expectedSuffix;              	    }
    }                                                              	    return expected.length() - expectedSuffix;
                                                                   }




12년 9월 3일 월요일
Clean Code 적용

     • 시간 결합 제거
        private void compactExpectedAndActual() {             private void compactExpectedAndActual() {
        	    prefixIndex = findCommonPrefix();                	    prefixIndex = findCommonPrefix();
        	    suffixIndex = findCommonSuffix();                	    suffixIndex = findCommonSuffix(prefixIndex);
        	    compactExpected = compactString(expected);       	    compactExpected = compactString(expected);
        	    compactActual = compactString(actual);           	    compactActual = compactString(actual);
        }                                                     }

        private int findCommonSuffix() {                      private int findCommonSuffix(int prefixIndex) {
        	    int expectedSuffix = expected.length() - 1;      	    int expectedSuffix = expected.length() - 1;
        	    int actualSuffix = actual.length() - 1;          	    int actualSuffix = actual.length() - 1;
        	    for(; actualSuffix >= prefixIndex                	    for(; actualSuffix >= prefixIndex
        	    	    	    && expectedSuffix >= prefixIndex;      	    	    	    && expectedSuffix >= prefixIndex;
        	    	    	    actualSuffix--, expectedSuffix--) {    	    	    	    actualSuffix--, expectedSuffix--) {
        	    	    if( expected.charAt(expectedSuffix)         	    	    if( expected.charAt(expectedSuffix)
        	    	    	    	    != actual.charAt(actualSuffix))   	    	    	    	    != actual.charAt(actualSuffix))
        	    	    	    break;                                 	    	    	    break;
        	    }                                                	    }
        	    return expected.length() - expectedSuffix;       	    return expected.length() - expectedSuffix;
        }                                                     }




                                                                    적절하지 못하다


12년 9월 3일 월요일
Clean Code 적용

     • 시간 결합 제거 ver2
                                                             private void compactExpectedAndActual() {
       private void compactExpectedAndActual() {
       	    prefixIndex = findCommonPrefix();                	    findCommonPrefixAndSuffix();
       	    suffixIndex = findCommonSuffix(prefixIndex);     	    compactExpected = compactString(expected);
       	    compactExpected = compactString(expected);       	    compactActual = compactString(actual);
       	    compactActual = compactString(actual);           }
       }
                                                             private void findCommonPrefixAndSuffix() {
       private int findCommonSuffix(int prefixIndex) {       	    findCommonPrefix();
       	    int expectedSuffix = expected.length() - 1;      	    int expectedSuffix = expected.length() - 1;
       	    int actualSuffix = actual.length() - 1;          	    int actualSuffix = actual.length() - 1;
       	    for(; actualSuffix >= prefixIndex                	    for(; actualSuffix >= prefixIndex
       	    	    	    && expectedSuffix >= prefixIndex;      	    	    	    && expectedSuffix >= prefixIndex;
       	    	    	    actualSuffix--, expectedSuffix--) {    	    	    	    actualSuffix--, expectedSuffix--) {
       	    	    if( expected.charAt(expectedSuffix)         	    	    if( expected.charAt(expectedSuffix)
       	    	    	    	    != actual.charAt(actualSuffix))   	    	    	    	    != actual.charAt(actualSuffix))
       	    	    	    break;                                 	    	    	    break;
       	    }                                                	    }
       	    return expected.length() - expectedSuffix;       	    return expected.length() - expectedSuffix;
       }                                                     }

                                                             private void findCommonPrefix() {
                                                             	    prefixIndex = 0;
                                                             	    int end = Math.min(expected.length(),
                                                             	    	    	    actual.length());

                            시간 결합을                           	
                                                             	
                                                             	
                                                                  for(; prefix < end; prefix++) {
                                                                  	
                                                                  	
                                                                       if(expected.charAt(prefix)
                                                                       	    	    != actual.charAt(prefix))

                          하나의 함수에 표현                         	
                                                             	
                                                             }
                                                                  	
                                                                  }
                                                                       	    break;




12년 9월 3일 월요일
Clean Code 적용

     • 지저분해진 findCommonPrefixAndSuffix를 개선
                                                             private void findCommonPrefixAndSuffix() {
       private void findCommonPrefixAndSuffix() {            	    findCommonPrefix();
       	    findCommonPrefix();                              	    int suffixLength = 1;
       	    int expectedSuffix = expected.length() - 1;      	   for(; !suffixOverlapsPerfix(suffixLength);
       	    int actualSuffix = actual.length() - 1;          	   	    	    suffixLength++) {
       	    for(; actualSuffix >= prefixIndex                	   	    if( charFromEnd(expected, suffixLength)
       	    	    	    && expectedSuffix >= prefixIndex;
                                                             	   	    	    	    != charFromEnd(actual, suffixLength))
       	    	    	    actualSuffix--, expectedSuffix--) {
                                                             	   	    	    break;
       	    	    if( expected.charAt(expectedSuffix)
                                                             	   }
       	    	    	    	    != actual.charAt(actualSuffix))
                                                             	   suffixIndex = suffixLength
       	    	    	    break;
                                                             }
       	    }
       	    return expected.length() - expectedSuffix;
                                                             private char charFromEnd(String s, int i) {
       }
                                                             	    return s.charAt(s.length() - i);
                                                             }

                                                             private boolean suffixOverlapsPerfix(int suffixLength) {
                                                             	    return actual.length() - suffixLength < prefixLength ||
                                                             	    	    expected.length() - suffixLength < prefixLength;
                                                             }




                                                suffixIndex가 실제로는
                                                    접미어의 길이
12년 9월 3일 월요일
Clean Code 적용

     • suffixIndex를 suffixLength로 변경
                                                                     private int suffixLength = 0;
        private String compactString(String source) {
                                                                     private String compactString(String source) {
        	    String result = DELTA_START + source.substring(
                                                                     	    String result = DELTA_START + source.substring(
        	    	    prefixIndex, source.length() - suffixIndex + 1 )
                                                                     	    	    prefixLength, source.length() - suffixLength ) +
        	    	    + DELTA_END;
                                                                     	    	    DELTA_END;
        	
                                                                     	
        	    if(prefixIndex > 0) {
                                                                     	    if(prefixLength > 0) {
        	    	    result = computeCommonPrefix() + result;
                                                                     	    	    result = computeCommonPrefix() + result;
        	    }
                                                                     	    }
        	
                                                                     	
        	    if(suffixIndex > 0) {
                                                                     	    if(suffixLength > 0) {
        	    	    result = result + computeCommonSuffix();
                                                                     	    	    result = result + computeCommonSuffix();
        	    }
                                                                     	    }
        	    return result;
                                                                     	    return result;
        }
                                                                     }

     • suffixLength로 인한 이슈 발생 (suffixLength > 0)
      private int suffixLength = 0;
      private String compactString(String source) {
      	    String result = DELTA_START + source.substring(
      	    	    prefixLength, source.length() - suffixLength )
                                                                      private String compactString(String source) {
      	    	    + DELTA_END;
      	
                                                                      	    return computeCommonPrefix() + DELTA_START
      	    if(prefixLength > 0) {
                                                                      	    	    + source.subString source.substring(prefixLength,
      	    	    result = computeCommonPrefix() + result;
                                                                      	    	    source.length() - suffixLength ) + DELTA_END
      	    }
                                                                      	    	    + computeCommonSuffix();
      	
                                                                      }
      	    if(suffixLength > 0) {
      	    	    result = result + computeCommonSuffix();
      	    }
      	    return result;
      }


12년 9월 3일 월요일

Mais conteúdo relacionado

Mais procurados

FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Mario Fusco
 

Mais procurados (19)

Oop 1
Oop 1Oop 1
Oop 1
 
The Ring programming language version 1.9 book - Part 20 of 210
The Ring programming language version 1.9 book - Part 20 of 210The Ring programming language version 1.9 book - Part 20 of 210
The Ring programming language version 1.9 book - Part 20 of 210
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
 
Link list
Link listLink list
Link list
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Groovy intro for OUDL
Groovy intro for OUDLGroovy intro for OUDL
Groovy intro for OUDL
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
C++ Chapter I
C++ Chapter IC++ Chapter I
C++ Chapter I
 
The Ring programming language version 1.8 book - Part 82 of 202
The Ring programming language version 1.8 book - Part 82 of 202The Ring programming language version 1.8 book - Part 82 of 202
The Ring programming language version 1.8 book - Part 82 of 202
 
C reference card
C reference cardC reference card
C reference card
 
Combining Text and Graphics in Eclipse-based Modeling Tools
Combining Text and Graphics in Eclipse-based Modeling ToolsCombining Text and Graphics in Eclipse-based Modeling Tools
Combining Text and Graphics in Eclipse-based Modeling Tools
 
Lecture 12: Classes and Files
Lecture 12: Classes and FilesLecture 12: Classes and Files
Lecture 12: Classes and Files
 
C++ Chapter IV
C++ Chapter IVC++ Chapter IV
C++ Chapter IV
 
Jersey Guice AOP
Jersey Guice AOPJersey Guice AOP
Jersey Guice AOP
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
Operator Overloading In Scala
Operator Overloading In ScalaOperator Overloading In Scala
Operator Overloading In Scala
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядом
 

Destaque

Api design for c++ 6장
Api design for c++ 6장Api design for c++ 6장
Api design for c++ 6장
Ji Hun Kim
 
To become Open Source Contributor
To become Open Source ContributorTo become Open Source Contributor
To become Open Source Contributor
DaeMyung Kang
 
프로그래머로 사는 법 Ch6
프로그래머로 사는 법 Ch6프로그래머로 사는 법 Ch6
프로그래머로 사는 법 Ch6
HyeonSeok Choi
 
프로그래머로사는법 Ch10
프로그래머로사는법 Ch10프로그래머로사는법 Ch10
프로그래머로사는법 Ch10
HyeonSeok Choi
 
프로그래머로 사는 법 Ch1
프로그래머로 사는 법 Ch1프로그래머로 사는 법 Ch1
프로그래머로 사는 법 Ch1
HyeonSeok Choi
 
Abstract factory petterns
Abstract factory petternsAbstract factory petterns
Abstract factory petterns
HyeonSeok Choi
 

Destaque (18)

Api design for c++ 6장
Api design for c++ 6장Api design for c++ 6장
Api design for c++ 6장
 
C++api디자인 1장
C++api디자인 1장C++api디자인 1장
C++api디자인 1장
 
Ooa&d
Ooa&dOoa&d
Ooa&d
 
To become Open Source Contributor
To become Open Source ContributorTo become Open Source Contributor
To become Open Source Contributor
 
프로그래머로 사는 법 Ch6
프로그래머로 사는 법 Ch6프로그래머로 사는 법 Ch6
프로그래머로 사는 법 Ch6
 
프로그래머로사는법 Ch10
프로그래머로사는법 Ch10프로그래머로사는법 Ch10
프로그래머로사는법 Ch10
 
프로그래머로 사는 법 Ch1
프로그래머로 사는 법 Ch1프로그래머로 사는 법 Ch1
프로그래머로 사는 법 Ch1
 
Abstract factory petterns
Abstract factory petternsAbstract factory petterns
Abstract factory petterns
 
MutiCore 19-20
MutiCore 19-20MutiCore 19-20
MutiCore 19-20
 
Mining the social web ch1
Mining the social web ch1Mining the social web ch1
Mining the social web ch1
 
Elastic search 클러스터관리
Elastic search 클러스터관리Elastic search 클러스터관리
Elastic search 클러스터관리
 
7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성
 
Clean code Chapter.2
Clean code Chapter.2Clean code Chapter.2
Clean code Chapter.2
 
Chean code chapter 1
Chean code chapter 1Chean code chapter 1
Chean code chapter 1
 
HTTP 완벽가이드 1장.
HTTP 완벽가이드 1장.HTTP 완벽가이드 1장.
HTTP 완벽가이드 1장.
 
함수적 사고 2장
함수적 사고 2장함수적 사고 2장
함수적 사고 2장
 
엘라스틱서치 분석 이해하기 20160623
엘라스틱서치 분석 이해하기 20160623엘라스틱서치 분석 이해하기 20160623
엘라스틱서치 분석 이해하기 20160623
 
엘라스틱서치, 로그스태시, 키바나
엘라스틱서치, 로그스태시, 키바나엘라스틱서치, 로그스태시, 키바나
엘라스틱서치, 로그스태시, 키바나
 

Semelhante a Clean code ch15

Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
arjuncorner565
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
Anung Ariwibowo
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
HamletDRC
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
julien.ponge
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
julien.ponge
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnit
ferca_sl
 
Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02
Tarun Kumar
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
arshiartpalace
 

Semelhante a Clean code ch15 (20)

Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
JAVA SE 7
JAVA SE 7JAVA SE 7
JAVA SE 7
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnit
 
Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
Test string and array
Test string and arrayTest string and array
Test string and array
 
Inheritance
InheritanceInheritance
Inheritance
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 

Mais de HyeonSeok Choi

Mais de HyeonSeok Choi (20)

밑바닥부터시작하는딥러닝 Ch05
밑바닥부터시작하는딥러닝 Ch05밑바닥부터시작하는딥러닝 Ch05
밑바닥부터시작하는딥러닝 Ch05
 
밑바닥부터시작하는딥러닝 Ch2
밑바닥부터시작하는딥러닝 Ch2밑바닥부터시작하는딥러닝 Ch2
밑바닥부터시작하는딥러닝 Ch2
 
프로그래머를위한선형대수학1.2
프로그래머를위한선형대수학1.2프로그래머를위한선형대수학1.2
프로그래머를위한선형대수학1.2
 
알고리즘 중심의 머신러닝 가이드 Ch04
알고리즘 중심의 머신러닝 가이드 Ch04알고리즘 중심의 머신러닝 가이드 Ch04
알고리즘 중심의 머신러닝 가이드 Ch04
 
딥러닝 제대로시작하기 Ch04
딥러닝 제대로시작하기 Ch04딥러닝 제대로시작하기 Ch04
딥러닝 제대로시작하기 Ch04
 
밑바닥부터시작하는딥러닝 Ch05
밑바닥부터시작하는딥러닝 Ch05밑바닥부터시작하는딥러닝 Ch05
밑바닥부터시작하는딥러닝 Ch05
 
7가지 동시성 모델 4장
7가지 동시성 모델 4장7가지 동시성 모델 4장
7가지 동시성 모델 4장
 
Bounded Context
Bounded ContextBounded Context
Bounded Context
 
DDD Repository
DDD RepositoryDDD Repository
DDD Repository
 
DDD Start Ch#3
DDD Start Ch#3DDD Start Ch#3
DDD Start Ch#3
 
실무로 배우는 시스템 성능 최적화 Ch8
실무로 배우는 시스템 성능 최적화 Ch8실무로 배우는 시스템 성능 최적화 Ch8
실무로 배우는 시스템 성능 최적화 Ch8
 
실무로 배우는 시스템 성능 최적화 Ch7
실무로 배우는 시스템 성능 최적화 Ch7실무로 배우는 시스템 성능 최적화 Ch7
실무로 배우는 시스템 성능 최적화 Ch7
 
실무로 배우는 시스템 성능 최적화 Ch6
실무로 배우는 시스템 성능 최적화 Ch6실무로 배우는 시스템 성능 최적화 Ch6
실무로 배우는 시스템 성능 최적화 Ch6
 
Logstash, ElasticSearch, Kibana
Logstash, ElasticSearch, KibanaLogstash, ElasticSearch, Kibana
Logstash, ElasticSearch, Kibana
 
실무로배우는시스템성능최적화 Ch1
실무로배우는시스템성능최적화 Ch1실무로배우는시스템성능최적화 Ch1
실무로배우는시스템성능최적화 Ch1
 
HTTP 완벽가이드 21장
HTTP 완벽가이드 21장HTTP 완벽가이드 21장
HTTP 완벽가이드 21장
 
HTTP 완벽가이드 16장
HTTP 완벽가이드 16장HTTP 완벽가이드 16장
HTTP 완벽가이드 16장
 
HTTPS
HTTPSHTTPS
HTTPS
 
HTTP 완벽가이드 6장.
HTTP 완벽가이드 6장.HTTP 완벽가이드 6장.
HTTP 완벽가이드 6장.
 
Cluster - spark
Cluster - sparkCluster - spark
Cluster - spark
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Clean code ch15

  • 1. Clean Code Ch.15 JUnit chois79 12년 9월 3일 월요일
  • 2. JUnit 프레임워크 • JUnit 소개 • Java 언어용 테스트 프레임워크 • 저자: 켄트벡, 에릭감마 등 • v3.x 구조 • 모든 테스트 클래스는 testCase를 상속 받음 • 테스트 메소드의 이름은 test로 시작해야 함 import junit.framework.TestCase; public class ComparisoncompactorTest extends TestCase{ public void testMessage() { String failure = new ComparisonCompactor(0, "b", "c").compact("a"); assertTrue("a expected:<[b]> but was:<[c]>".equals(failure)); } } • But, 이 장에서는 JUnit에서 가져온 예제 코드 ComparisonCompactor.java 를 평가 12년 9월 3일 월요일
  • 3. ComparisonCompactor Class • 두 문자열을 받아 차이를 반환 • ex) ABCDE, ABXDE => ...B[X]D... public class ComparisonCompactor { private static final String ELLIPSIS = "..."; private static final String DELTA_END = "]"; private static final String DELTA_START= "["; private int fContextLength; private String fExpected; private String fActual; private int fPrefix; private int fSuffix; public ComparisonCompactor(int contextLength, String expected, String actual) { fContextLength = contextLength; fExpected = expected; fActual = actual; } public String compact(String message) { if(fExpected == null || fActual == null || areStringEqual()) return assertFormat(message, fExpected, fActual); findCommonPrefix(); findCommonSuffix(); String expected = compactString(fExpected); String actual = compactString(fActual); return assertFormat(message, expected, actual); } 12년 9월 3일 월요일
  • 4. ComparisonCompactor Class private String compactString(String source) { String result = DELTA_START + source.substring(fPrefix, source.length() - fSuffix + 1) + DELTA_END; if(fPrefix > 0) { result = computeCommonPrefix() + result; } if(fSuffix > 0) { result = result + computeCommonSuffix(); } return result; } private void findCommonSuffix() { int expectedSuffix = fExpected.length() - 1; int actualSuffix = fActual.length() - 1; for(; actualSuffix >= fPrefix && expectedSuffix >= fPrefix; actualSuffix--, expectedSuffix--) { if(fExpected.charAt(expectedSuffix) != fActual.charAt(actualSuffix)) break; } fSuffix = fExpected.length() - expectedSuffix; } private void findCommonPrefix() { fPrefix = 0; int end = Math.min(fExpected.length(), fActual.length()); for(; fPrefix < end; fPrefix++) { if(fExpected.charAt(fPrefix) != fActual.charAt(fPrefix)) break; } } 12년 9월 3일 월요일
  • 5. ComparisonCompactor Class private String computeCommonPrefix() { return (fPrefix > fContextLength? ELLIPSIS: "") + fExpected.substring(Math.max(0, fPrefix - fContextLength), fPrefix); } private String computeCommonSuffix() { int end = Math.min(fExpected.length() - fSuffix + 1 + fContextLength, fExpected.length()); return fExpected.substring(fExpected.length() - fSuffix + 1, end) + (fExpected.length() - fSuffix + 1 < fExpected.length() - fContextLength? ELLIPSIS: ""); } private boolean areStringEqual() { return fExpected.equals(fActual); } private String assertFormat(String message, String fExpected, String fActual) { return message + “expected: <” + fExpected + “> but was: <” + fActual + “>”; } } 12년 9월 3일 월요일
  • 6. Clean Code 적용 • 접두어 제거 private static final String ELLIPSIS = "..."; private static final String ELLIPSIS = "..."; private static final String DELTA_END = "]"; private static final String DELTA_END = "]"; private static final String DELTA_START= "["; private static final String DELTA_START= "["; private int fContextLength; private int contextLength; private String fExpected; private String expected; private String fActual; private String actual; private int fPrefix; private int prefix; private int fSuffix; private int suffix; • 접두어 제거로 인한 충돌 public String compact(String message) { public String compact(String message) { if(expected == null || actual == null || areStringEqual()) if(expected == null || actual == null || areStringEqual()) return assertFormat(message, expected, actual); return assertFormat(message, expected, actual); findCommonPrefix(); findCommonPrefix(); findCommonSuffix(); findCommonSuffix(); String compactExpected = compactString(expected); String expected = compactString(expected); String compactActual = compactString(actual); String actual = compactString(actual); return assertFormat(message, compactExpected, return assertFormat(message, expected, actual); compactActual);; } } 12년 9월 3일 월요일
  • 7. Clean Code 적용 • 조건문 캡슐화 public String compact(String message) { if(shouldNotCompact()) public String compact(String message) { return assertFormat(message, expected, actual); if(expected == null || actual == null || areStringEqual()) findCommonPrefix(); return assertFormat(message, expected, actual); findCommonSuffix(); findCommonPrefix(); compactExpected = compactString(expected); findCommonSuffix(); compactActual = compactString(actual); compactExpected = compactString(expected); return assertFormat(message, compactExpected, compactActual = compactString(actual); compactActual); return assertFormat(message, compactExpected, } compactActual); private boolean shouldNotCompact() { } return expected == null || actual == null || areStringEqual(); } public String compact(String message) { • 긍정 표현으로 변경 if(canBeCompacted()) { findCommonPrefix(); public String compact(String message) { findCommonSuffix(); if(shouldNotCompact()) compactExpected = compactString(expected); return assertFormat(message, expected, actual); compactActual = compactString(actual); findCommonPrefix(); return assertFormat(message, compactExpected, findCommonSuffix(); compactActual); compactExpected = compactString(expected); } else { compactActual = compactString(actual); return assertFormat(message, expected, actual); return assertFormat(message, compactExpected, } compactActual); } } private boolean canBeCompacted() { private boolean shouldNotCompact() { return expected != null && actual != null && return expected == null || actual == null || areStringEqual(); areStringEqual(); } } 12년 9월 3일 월요일
  • 8. Clean Code 적용 • 함수의 의미를 명확하게 변경, Extract Method 적용 public String compact(String message) { private String compactExpected; if(canBeCompacted()) { private String compactActual; findCommonPrefix(); findCommonSuffix(); public String formatCompactedComparison(String message) { compactExpected = compactString(expected); if(canBeCompacted()) { compactActual = compactString(actual); compactExpectedAndActual(); return assertFormat(message, compactExpected, return assertFormat(message, compactExpected, compactActual); compactActual); } else { } return assertFormat(message, expected, actual); return assertFormat(message, expected, actual); } } } private void compactExpectedAndActual() { findCommonPrefix(); findCommonSuffix(); compactExpected = compactString(expected); compactActual = compactString(actual); } 12년 9월 3일 월요일
  • 9. Clean Code 적용 • 함수 내부의 사용 방식 통일 private void compactExpectedAndActual() { private void compactExpectedAndActual() { prefixIndex = findCommonPrefix(); findCommonPrefix(); suffixIndex = findCommonSuffix(); findCommonSuffix(); compactExpected = compactString(expected); compactExpected = compactString(expected); compactActual = compactString(actual); compactActual = compactString(actual); } } private int findCommonPrefix() { private void findCommonPrefix() { int prefixIndex = 0; prefix = 0; int end = Math.min(expected.length(), actual.length()); int end = Math.min(expected.length(), actual.length()); for(; prefix < end; prefix++) { for(; prefixIndex < end; prefixIndex ++) { if(expected.charAt(prefix) if(expected.charAt(prefixIndex) != actual.charAt(prefix)) != actual.charAt(prefixIndex)) break; break; } } } return prefixIndex; } private void findCommonSuffix() { int expectedSuffix = expected.length() - 1; private int findCommonSuffix() { int actualSuffix = actual.length() - 1; int expectedSuffix = expected.length() - 1; for(; actualSuffix >= prefix int actualSuffix = actual.length() - 1; && expectedSuffix >= prefix; for(; actualSuffix >= prefixIndex actualSuffix--, expectedSuffix--) { && expectedSuffix >= prefixIndex; if( expected.charAt(expectedSuffix) actualSuffix--, expectedSuffix--) { != actual.charAt(actualSuffix)) if( expected.charAt(expectedSuffix) break; != actual.charAt(actualSuffix)) } break; suffix = expected.length() - expectedSuffix; } } return expected.length() - expectedSuffix; } 12년 9월 3일 월요일
  • 10. Clean Code 적용 • 시간 결합 제거 private void compactExpectedAndActual() { private void compactExpectedAndActual() { prefixIndex = findCommonPrefix(); prefixIndex = findCommonPrefix(); suffixIndex = findCommonSuffix(); suffixIndex = findCommonSuffix(prefixIndex); compactExpected = compactString(expected); compactExpected = compactString(expected); compactActual = compactString(actual); compactActual = compactString(actual); } } private int findCommonSuffix() { private int findCommonSuffix(int prefixIndex) { int expectedSuffix = expected.length() - 1; int expectedSuffix = expected.length() - 1; int actualSuffix = actual.length() - 1; int actualSuffix = actual.length() - 1; for(; actualSuffix >= prefixIndex for(; actualSuffix >= prefixIndex && expectedSuffix >= prefixIndex; && expectedSuffix >= prefixIndex; actualSuffix--, expectedSuffix--) { actualSuffix--, expectedSuffix--) { if( expected.charAt(expectedSuffix) if( expected.charAt(expectedSuffix) != actual.charAt(actualSuffix)) != actual.charAt(actualSuffix)) break; break; } } return expected.length() - expectedSuffix; return expected.length() - expectedSuffix; } } 적절하지 못하다 12년 9월 3일 월요일
  • 11. Clean Code 적용 • 시간 결합 제거 ver2 private void compactExpectedAndActual() { private void compactExpectedAndActual() { prefixIndex = findCommonPrefix(); findCommonPrefixAndSuffix(); suffixIndex = findCommonSuffix(prefixIndex); compactExpected = compactString(expected); compactExpected = compactString(expected); compactActual = compactString(actual); compactActual = compactString(actual); } } private void findCommonPrefixAndSuffix() { private int findCommonSuffix(int prefixIndex) { findCommonPrefix(); int expectedSuffix = expected.length() - 1; int expectedSuffix = expected.length() - 1; int actualSuffix = actual.length() - 1; int actualSuffix = actual.length() - 1; for(; actualSuffix >= prefixIndex for(; actualSuffix >= prefixIndex && expectedSuffix >= prefixIndex; && expectedSuffix >= prefixIndex; actualSuffix--, expectedSuffix--) { actualSuffix--, expectedSuffix--) { if( expected.charAt(expectedSuffix) if( expected.charAt(expectedSuffix) != actual.charAt(actualSuffix)) != actual.charAt(actualSuffix)) break; break; } } return expected.length() - expectedSuffix; return expected.length() - expectedSuffix; } } private void findCommonPrefix() { prefixIndex = 0; int end = Math.min(expected.length(), actual.length()); 시간 결합을 for(; prefix < end; prefix++) { if(expected.charAt(prefix) != actual.charAt(prefix)) 하나의 함수에 표현 } } break; 12년 9월 3일 월요일
  • 12. Clean Code 적용 • 지저분해진 findCommonPrefixAndSuffix를 개선 private void findCommonPrefixAndSuffix() { private void findCommonPrefixAndSuffix() { findCommonPrefix(); findCommonPrefix(); int suffixLength = 1; int expectedSuffix = expected.length() - 1; for(; !suffixOverlapsPerfix(suffixLength); int actualSuffix = actual.length() - 1; suffixLength++) { for(; actualSuffix >= prefixIndex if( charFromEnd(expected, suffixLength) && expectedSuffix >= prefixIndex; != charFromEnd(actual, suffixLength)) actualSuffix--, expectedSuffix--) { break; if( expected.charAt(expectedSuffix) } != actual.charAt(actualSuffix)) suffixIndex = suffixLength break; } } return expected.length() - expectedSuffix; private char charFromEnd(String s, int i) { } return s.charAt(s.length() - i); } private boolean suffixOverlapsPerfix(int suffixLength) { return actual.length() - suffixLength < prefixLength || expected.length() - suffixLength < prefixLength; } suffixIndex가 실제로는 접미어의 길이 12년 9월 3일 월요일
  • 13. Clean Code 적용 • suffixIndex를 suffixLength로 변경 private int suffixLength = 0; private String compactString(String source) { private String compactString(String source) { String result = DELTA_START + source.substring( String result = DELTA_START + source.substring( prefixIndex, source.length() - suffixIndex + 1 ) prefixLength, source.length() - suffixLength ) + + DELTA_END; DELTA_END; if(prefixIndex > 0) { if(prefixLength > 0) { result = computeCommonPrefix() + result; result = computeCommonPrefix() + result; } } if(suffixIndex > 0) { if(suffixLength > 0) { result = result + computeCommonSuffix(); result = result + computeCommonSuffix(); } } return result; return result; } } • suffixLength로 인한 이슈 발생 (suffixLength > 0) private int suffixLength = 0; private String compactString(String source) { String result = DELTA_START + source.substring( prefixLength, source.length() - suffixLength ) private String compactString(String source) { + DELTA_END; return computeCommonPrefix() + DELTA_START if(prefixLength > 0) { + source.subString source.substring(prefixLength, result = computeCommonPrefix() + result; source.length() - suffixLength ) + DELTA_END } + computeCommonSuffix(); } if(suffixLength > 0) { result = result + computeCommonSuffix(); } return result; } 12년 9월 3일 월요일