오브젝트 - 10장 상속과 코드 재사용

Seyeon_CHOI·2022년 11월 21일
1
post-thumbnail

중복 코드는 우리를 주저하게 만들뿐만 아니라 동료들을 의심하게 만든다.

01. 상속과 중복 코드

DRY 원칙

동일한 지식을 중복하지 말라는 것

한 번, 단 한번(Once and Only Once) 원칙 또는 단일 지점 제어(Single-Point Control) 원칙
핵심은 코드 안에 중복이 존재해서는 안 된다는 것이다.

  • 중복 코드는 변경을 방해한다.
  • 새로운 코드를 추가하고 나면 언젠가는 변경될 것이라고 생각해야 한다.

중복 코드가 가지는 가장 큰 문제는 코드를 수정하는 데 필요한 노력을 몇 배로 증가시킨다는 것이다.

중복 여부를 판단하는 기준은 변경

요구사향이 변경됐을 때 두 코드를 한번에 수정해야 한다면 이 코드는 중복이다.

중복 여부를 결정하는 기준은 코드의 모양이 아닌, 코드가 변경에 반응하는 방식이다.

중복과 변경

중복 코드 살펴보기

가입자별로 전화 요금을 계산하는 간단한 애플리케이션을 개발

전화 요금을 계산하는 규칙: 10초당 5원

public class Call {
    private LocalDateTime from;
    private LocalDateTime to;

    public Call(LocalDateTime from, LocalDateTime to) {
        this.from = from;
        this.to = to;
    }

    public Duration getDuration() {
        return Duration.between(from, to);
    }

    public LocalDateTime getFrom() {
        return from;
    }
}
public class Phone {
	private Money amount;
	private Duration seconds;
	private List<Call> calls = new ArrayList<>();

	public Phone(Money amount, Duration seconds) {
		this.amount = amount;
		this.seconds = seconds;
	}

	public void call(Call call) {
		calls.add(call);
	}
	
	public List<Call> getCalls() {
		return calls;
	}

	public Money getAmount() {
		return amount;
	}

	public Duration getSeconds() {
		return seconds;
	}

	public Money calculateFee() {
		Money result = Money.ZERO;

		for (Call call : calls) {
			result = result.plus(amount.times(call.getDuration().getSeconds() / seconds.getSeconds()));
		}

		return result;
	}
}
Phone phone = new Phone(Money.wons(5), Duration.ofSeconds(10));
phone.call(new Call(LocalDateTiem.of(2018, 1, 1, 12, 10, 0),  // 1분간 통화(=60초=30원)
		 LocalDateTime.of(2018, 1, 1, 12, 11, 0)));
phone.call(new Call(LocalDateTiem.of(2018, 1, 2, 12, 10, 0),  // 1분간 통화(=60초=30원)
		 LocalDateTime.of(2018, 1, 2, 12, 11, 0)));

phone.calculateFee(); // 총 2분간 통화 => Money.wons(60)

심야 할인 요금제 라는 새로운 요금 방식을 추가한다고 가정한다.

ublic class NightlyDiscountPhone {
    private static final int LATE_NIGHT_HOUR = 22;  // 22시부터 시작

    private Money nightlyAmount;  // 심야 요금
    private Money regularAmount; // 원래 요금
    private Duration seconds;  // 단위 시간
    private List<Call> calls = new ArrayList<>(); // 통화 목록

    public NightlyDiscountPhone(Money nightlyAmount, Money regularAmount, Duration seconds) {
        this.nightlyAmount = nightlyAmount;
        this.regularAmount = regularAmount;
        this.seconds = seconds;
    }

    public Money calculateFee() { // phone과 중복되는 코드가 있음(일반 요금)
        Money result = Money.ZERO;

        for(Call call : calls) {
            if (call.getFrom().getHour() >= LATE_NIGHT_HOUR) { // 심야 요금
                result = result.plus(nightlyAmount.times(call.getDuration().getSeconds() / seconds.getSeconds()));
            } else { // 일반 요금
                result = result.plus(regularAmount.times(call.getDuration().getSeconds() / seconds.getSeconds()));
            }
        }

        return result;
    }
  • Phone과 NightlyDiscountPhone 사이에는 중복코드가 존재
    • 언제 터질 지 모르는 시한폭탄을 안고 있는 것과 같다.

중복 코드 수정하기

Phone과 NightDiscountPhone 양쪽 모두에 통화 요금을 계산하는 로직이 들어있기 때문에
두 클래스를 함께 수정해야 한다.

public class Phone {
	...
	private double taxRate;

	public Phone (Money amount, Duration seconds, double taxRate) {
		...
		this.taxRate = taxRate;
	}

	public Money calculateFee() {
		Money result = Money.ZERO;

		for (Call call : calls) {
			result = result.plus(amount.times(call.getDuration().getSeconds() / seconds.getSeconds()));
		}

		return result.plus(result.times(taxRate));
	}
}

NightlyDiscountPhone도 동일한 방식으로 수정

public class NightlyDiscountPhone {
	...
	private double taxRate;

	public NightlyDiscountPhone(Money nightlyAmount, Money regularAmount, 
			Duration seconds, double taxRate) {
		...
		this.taxRate = taxRate;
	}

	public Money calculateFee() {
		Money result = Money.ZERO;

		for (Call call : calls) {
			if (call.getForm().getHour() >= LATE_NIGHT_HOUR) {
				result = result.plus(
					nightlyAmount.times(call.getDuration().getSeconds() / seconds.getSeconds()));
			} else {
				result = result.plus(
					regularAmount.times(call.getDuration().getSeconds() / seconds.getSeconds()));
			}
		}

		return result.minus(result.times(taxRate));
	}
}

중복 코드의 양이 많아질수록 버그의 수는 증가하며 그에 비례해 코드를 변경하는 속도는 점점 더 느려진다.

타입 코드 사용하기

클래스를 하나로 합치는 것

public class Phone {
	private static final int LATE_NIGHT_HOUT = 22;
	enum PhoneType { REGULAR, NIGHTLY } 

	private PhoneType type;

	private Money amount;
	private Money regularAmount;
	private Money nightlyAmount;
	private Duration seconds;
	private List<Call> calls = new ArrayList<>();

	public Phone(Money amount, Duration seconds) {
		this(PhoneType.REGULAR, amount, Money.ZERO, Money.ZERO, seconds);
	}

	public Phone(Money nightlyAmount, Money regularAmount, Duration seconds) {
		this(PhoneType.NIGHTLY, Money.ZERO, nightlyAmount, regularAmount, seconds);
	}

	public Phone(PhoneType type, Money amount, Money nightlyAmount,
		Money regularAmount, Duration seconds) {
		this.type = type;
		this.amount = amount;
		this.regularAmount = regularAmount;
		this.nightlyAmount = nightlyAmount;
		this.seconds = seconds;
	}

	public Money calculateFee() {
		Money result = Money.ZERO;
	
		for (Call call : calls) {
			if (type == PhoneType.REGULAR) {
				result = result.plus(
					amount.times(call.getDuration().getSeconds() / seconds.getSeconds()));
			} else {
				if (call.getFrom().getHour() >= LATE_NIGHT_HOUR) {
					result = result.plus(
						nightlyAmount.times(call.getDuration().getSeconds() / seconds.getSeconds()));
				} else {
					result = result.plus(
						regularAMount.times(call.getDuration().getSeconds() / seconds.getSeconds()));
				}
			}
		}
		return result;
	}
}
  • 타입 코드를 사용하면 낮은 응집도와 높은 결합도에 시달리게된다.

상속을 이용해서 중복 코드 제거하기

public class NightlyDiscountPhone extends Phone {
	private static final int LATE_NIGHT_HOUR = 22;

	private Money nightlyAmount;

	public NightlyDiscountPhone(Money nightlyAmount, Money regularAmount, Duration seconds) {
		super(regularAmount, seconds);
		this.nightlyAmount = nightlyAmount;
	}

	@Override
	public Money calculateFee() {
		Money result. =super.claculateFee();

		Money nightlyFee = Money.ZERO;
		for (Call call : getCalls()) {
			if (call.getFrom().getHour() >= LATE_NIGHT_HOUR) {
				nightlyFee = nightlyFee.plus(
					getAmount().minus(nightlyAmount).times(
						call.getDuration().getSeconds() / getSeconds().getSeconds()));
			}
		}
		return result.minus(nightlyFee);
	}
}
  • 상속을 이용하기 위해서는 부모 클래스의 개발자가 세웠던 가정이나 추론 과정을 정확하게 이해해야 한다.

상속은 결합도를 높인다.

상속이 초래하는 부모 클래스와 자식 클래스 사이의 강한 결합이 코드를 수정하기 어렵게 만든다.

**강하게 결합된 Phone과 NightlyDiscountPhone**

  • 요구사항 추가
    • Phone은 세율을 인스턴스 변수로 포함
    • calulateFee 메서드에서 값을 반환할 때 taxRate를 이용해 세금 부과
public class Phone {
	...
	private double taxRate;

	public Phone(Money amount, Duration seconds, double taxRate) {
		...
		this.taxRate = taxRate;
	}

	public Money calculateFee() {
		...
		return result.plus(result.times(taxRate));
	}

	public double getTaxRate() {
		return taxRate;
	}
}
public class NightlyDiscountPhone extends Phone {
	public NightlyDiscountPhone(Money nightlyAmount, Money regularAmount, 
		Duration seconds, double taxRate) {
		super(regularAmount, seconds, taxRate);
		...
	}

	@Override
	public Money calculateFee() {
		...
		return result.minus(nightlyFee.plus(nightlyFee.times(getTaxRate())));
	}
}

Phone에 taxRate를 추가함으로써, Phone과 유사한 코드를 NightlyDiscountPhone에도 추가해야 했다.

자식 클래스의 메서드 안에서 super 참조를 이용해 부모 클래스의 메서드를 직접 호출할 경우
→ 두 클래스는 강하게 결합된다. super 호출을 제거할 수 있는 방법을 찾아 결합도를 제거하라.

02. 취약한 기반 클래스 문제

상속 관계로 연결된 자식 클래스가 부모 클래스의 변경에 취약해지는 현상 → 취약 기반 클래스 문제

이 문제는 상속을 사용한다면 피할 수 없는 객체지향 프로그래밍의 근본적인 취약성 이다.

  • 취약한 기반 클래스 문제는 캡슐화를 약화시키고 결합도를 높인다.
  • 자식 클래스가 부모의 구현 세부사항에 의존하도록 만들기 때문에 캡슐화를 약화시킨다.

객체를 사용하는 이유?

구현과 관련된 세부사항을 퍼블릭 인터페이스 뒤로 캡슐화할 수 있기 때문이다.

안타깝게도 상속을 사용하면 부모 클래스의 퍼블릭 인터페이스가 아닌 구현을 변경하더라도 자식 클래스가 영향을 받기 쉬워진다. 상속 계층의 상위에 위치한 클래스에 가해지는 작은 변경만으로도 상속 계층에 속한 모든 자손들이 급격하게 요동칠 수 있다.

객체지향의 기반은 캡슐화를 통한 변경의 통제다.

상속은 코드의 재사용을 위해 캡슐화의 장점을 희석시키고 구현에 대한 결합도를 높임으로써

객체지향이 가진 강력함을 반감시킨다.

불필요한 인터페이스 상속 문제

Stack은 Vector의 퍼블릭 인터페이스를 상속받기 때문에 add, remove를 통해서 임의의 위치에서 요소를 추가하거나 삭제할 수 있다. 이는 Stack의 규칙을 쉽게 위반할 수 있다.

상속받은 부모 클래스의 메서드가 자식 클래스의 내부 구조에 대한 규칙을 깨트릴 수 있다.

메서드 오버라이딩의 오작용 문제

public class InstrumentedhashSet<E> extends HashSet<E> {
		private int addCount = 0;

		@Override
		public boolean add(E e) {
				addCount++;
				return super.add(e);
		}
		
		@Override
		public boolean addAll(Collection<? extends E> c) {
				addCount += c.size();
				return super.addAll(c);
		}
}
InstrumentedHashsSet<String> languages = new InstrumentedHashSet<>();
languages.addAll(Arrays.asList("Java", "Ruby", "Scala"));

위의 코드를 실행시켜보면 addCount가 3이 된다고 예상하지만, 값은 6이다.

부모 클래스인 HashSet의 addAll() 메서드 안에서 add 메서드를 호출하기 때문이다.

기존보다 더 좋은 해결책은 InstrumentdhashSet의 addAll 메서드를 오버라이딩하고 추가되는 각 요소에 대해 한 번씩 add 메시지를 호출하는 것이다.

public class InstrumentedHashSet<E> extends HashSet<E> {
	@Override
	public boolean add(E e) {
		addCount++;
		return super.add(e);
	}

	@Override
	public boolean addAll(Collection<? extends E> c) {
		boolean modified = false;
		for (E e : c) 
			if (add(e))
				modified = true;
		return modified;
	}
}

자식 클래스가 부모 클래스의 메서드를 오버라이딩할 경우 부모 클래스가 자신의 메서드를 사용하는 방법에 자식 클래스가 결합될 수 있다.

부모 클래스와 자식 클래스의 동시 수정 문제

음악 목록을 추가할 수 있는 플레이리스트

public class Playlist {
		private List<Song> tracks = new ArrayList<>();
		
		public void append(Song song) {
				getTracks().add(song);
		}

		public List<Song> getTracks() {
				return tracks;
		}
}
public class PersonalPlaylist extends Playlist {
		public void remove(Song song) {
				getTracks().remove(song);
		}
}

이제 플레이리스트에서 노래를 삭제할 수 있는 기능이 추가된 PersonalPlaylist가 필요하다고 가정해보자.

  • PersonalPlaylist를 구현하는 가장 빠른 방법은 상속을 통해 Playlist의 코드를 재사용하는 것이다.
public class PersonalPlaylist extends Playlist {
		public void remove(Song song) {
				getTracks().remove(song);
		}
}

요구사항

  • Playlist에서 노래의 목록뿐만 아니라 가수별 노래의 제목도 함께 관리해야 한다고 가정
public class Playlist {
	private List<Song> tracks = new ArrayList<>();
	private Map<String, String> singers = new HashMap<>();

	public void append(Song song) {
		tracks.add(song);
		singers.put(song.getSinger(), song.getTitle());
	}

	public List<Song> getTracks() {
		return tracks;
	}

	public Map<String, String> getSingers() {
		return singers;
	}
}

위 수정 내용이 정상적으로 동작하려면 PersonalPlaylist의 remove 메서드도 함께 수정해야한다.

public class PersonalPlaylist extends Playlist {
	public void remove(Song song) {
		getTracks().remove(song);
		getSingers().remove(song.getSinger());
	}
}

자식 클래스가 부모 클래스의 메서드를 오버라이딩하거나 불필요한 인터페이스를 상속받지 않았어도 함께 수정해야한다는 사실을 보여준다.

상속을 사용하면 자식 클래스가 부모 클래스의 구현에 강하게 결합되기 때문에 이 문제를 피하기는 어렵다.

클래스를 상속하면 결합도로 인해 자식 클래스와 부모 클래스의 구현을 영원히 변경하지 않거나, 자식 클래스와 부모 클래스를 동시에 변경하거나 둘 중 하나를 선택할 수 밖에 없다.

03. Phone 다시 살펴보기

추상화에 의존하자

자식 클래스가 부모 클래스의 구현이 아닌 추상화에 의존하도록 수정

  • 두 메서드가 유사하게 보인다면 차이점을 메서드로 추출하라. 메서드 추출을 통해 두 메서드를 동일한 형태로 보이도록 만들 수 있다.
  • 부모 클래스의 코드를 하위로 내리지 말고 자식 클래스의 코드를 상위로 올려라. 부모 클래스의 구체적인 메서드를 자식 클래스로 내리는 것보다 자식 클래스의 추상적인 메서드를 부모 클래스로 올리는 것이 재사용성과 응집도 측면에서 더 뛰어난 결과를 얻을 수 있다.

차이를 메서드로 추출하라

중복 코드 안에서 차이점은 별도의 메서드로 추출

  • ‘변하는 것으로부터 변하지 않는 것을 분리하라’, ‘변하는 부분을 찾고 이를 캡슐화하라’ 라는 조언을
    메서드 수준에서 적용한 것

중복 코드를 부모 클래스로 올려라

  • Phone과 NightlyDiscountPhone의 공통 부분을 부모 클래스로 이동시킨다.
    • 동일한 메서드인 calculateFee는 추상 클래스로 이동하고, calculateCallFee만 자식클래스에서 각자 구현한다.

추상화가 핵심이다

공통 코드를 상위클래스로 이동시킨 후에 각 클래스는 서로 다른 이유로 변경된다는것에 주목

의도를 드러내는 이름 선택하기

ex)

  • AbstractPhone → phone
  • Phone → RegularPhone

04. 차이에 의한 프로그래밍

기존 코드와 다른 부분만을 추가함으로써 애플리케이션의 기능을 확장하는 방법

profile
오물쪼물 코딩생활 ๑•‿•๑

0개의 댓글