본문 바로가기

PMD

[한글화 시리즈-05] Clone Implementation Rules

Clone Implementation Rules

이 룰셋은 clone() 메소드를 사용할 경우 고려해볼만한 룰로 구성되어 있다.



ProperCloneImplementation

객체의 clone() 메소드는 단순히 생성자로 객체를 생성하지 말고 super.clone()을 이용하여 implements해야 한다.

//나쁜 예
class Foo implements Cloneable{
    public Object clone() throws CloneNotSupportedException{
        return new Foo(); // 단순히 new를 이용해서 생성하면 안된다. 
    }
}

//좋은 예
class Foo implements Cloneable{
    private String type;
    private String value;
    public Object clone() throws CloneNotSupportedException{
        //super.clone을 이용하여 implements한다.
        Foo f =  (Foo)super.clone();
        //각 맴버변수를 복사한한다.
        f.type = type;
        f.value = value;
        return f;
    }
}


CloneThrowsCloneNotSupportedException

clone() 메소드는 cloneable 인터페이스를 구현하지 않으면 CloneNotSupportedException을 발생함으로 throws CloneNotSupportedException를 사용해야 한다.

class Foo implements Cloneable{
    private String type;
    private String value;
    //무조건 throws CloneNotSupportedException을 정의해야 한다.
    public Object clone() throws CloneNotSupportedException{
        Foo f =  (Foo)super.clone();
        f.type = type;
        f.value = value;
        return f;
    }
}

CloneMethodMustImplementCloneable

clone() 메소드를 구현할 때는 java.lang.Cloneable 인터페이스를 implements해야 한다. Cloneable에는 아무런 메소드들이 정의되어 있지 않지만 cloneable을 구현하지 않으면 clone() 메소드를 호출할 시에 CloneNotSupportedException을 발생시킨다.

//무조건 Cloneable을 implements해야 한다.
class Foo implements Cloneable{
    private String type;
    private String value;
    public Object clone() throws CloneNotSupportedException{
        Foo f =  (Foo)super.clone();
        f.type = type;
        f.value = value;
        return f;
    }
}


해당 URL: http://pmd.sourceforge.net/pmd-4.2.6/rules/clone.html