NMP-Study / EffectiveJava2022

Effective Java Study 2022
5 stars 0 forks source link

아이템 17. 변경 가능성을 최소화하라 #17

Closed okhee closed 2 years ago

luckyDaveKim commented 2 years ago

클래스를 불변으로 만드는 5가지 규칙

Tip : 불변 클래스의 메서드는 동사(add) 대신 전치사(plus)를 사용
이는 해당 메서드가 객체의 값을 변경하지 않는다는 사실을 강조

불변 클래스

ex: String, BigInteger, BigDecimal 등...

public final class Complex {
    private final double re;
    private final double im;

    public Complex(double re, double im) {
        this.re = re;
        this.im = im;
    }

    public double realPart() {
        return re;
    }

    public double ImaginaryPart() {
        return im;
    }

    // 1. 동사(add) 가 아닌, 전치사(plus) 사용하여, 이 메서드가 객체의 값을 변환하지 않음을 강조
    // 2. 객체 자신을 수정하지 않고, 새로운 Complex 인스턴스를 만들어 반환
    public Complex plus(Complex o) {
        return new Complex(re + o.re, im + o.im);
    }

    public Complex minus(Complex o) {
        return new Complex(re - o.re, im - o.im);
    }

    public Complex times(Complex o) {
        return new Complex(re * o.re - im * o.im, re * o.im + im * o.re);

    }

    public Complex dividedBy(Complex o) {
        double tmp = o.re * o.re + o.im + o.im;
        return new Complex((re * o.re + im * o.im) / tmp, (im * o.re - re * o.im) / tmp);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        Complex complex = (Complex)o;
        return Double.compare(complex.re, re) == 0 && Double.compare(complex.im, im) == 0;
    }

    @Override
    public int hashCode() {
        return Objects.hash(re, im);
    }

    @Override
    public String toString() {
        return String.format("(%f + %fi)", re, im);
    }
}

장점

단점

단점 극복 : 가변 동반 클래스 제공 ex: StringBuilder 등...

불변 클래스 만드는법

직렬화 주의점 Serializable을 구현하는 불변 클래스의 내부에 가변 객체를 참조하는 필드가 있다면, readObject, readResolve 메서드를 정의해야한다 참고 : https://github.com/NMP-Study/EffectiveJava2022/blob/4be6aa4df8e807ee7814eeb7c84d83aa417aedb5/src/main/java/org/effectivejava/item17/MutableAttack.java#L5

마무리