[모던 자바 인 액션] 동작 파라미터화 코드 전달하기

kims·2024년 1월 10일
0

자바

목록 보기
5/5

동작 파라미터화를 이용하면 자주 바뀌는 요구사항에 효과적으로 대응할 수 있다.

package ex;

public enum Color {
    RED,
    GREEN

    ;
}

package ex;

public class Apple {
    private Color color;

    public Apple(Color color) {
        this.color = color;
    }

    public Color getColor() {
        return color;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "color=" + color +
                '}';
    }
}

첫 번째 요구사항 : 녹색 사과만 필터링 해주세요.


package ex;

import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<Apple> apples = new Farm().filterGreenApples(List.of(new Apple(Color.GREEN), new Apple(Color.RED), new Apple(Color.GREEN)));

        apples.forEach(System.out::println);
    }
}

두 번째 요구사항 : 빨간색 사과만 필터링 해주세요.

  • 색을 파라미터화하자.

package ex;

import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<Apple> greenApples = new Farm().filterApplesByColor(List.of(new Apple(Color.GREEN), new Apple(Color.RED), new Apple(Color.GREEN)), Color.GREEN);
        List<Apple> redApples = new Farm().filterApplesByColor(List.of(new Apple(Color.GREEN), new Apple(Color.RED), new Apple(Color.GREEN)), Color.RED);

        greenApples.forEach(apple -> System.out.println("green : " + apple));
        System.out.println("---");
        redApples.forEach(apple -> System.out.println("red : " + apple));
    }
}

세 번째 요구사항 : 무게로 사과를 구분할 수 있게 해주세요.

  • Apple 클래스 weight 필드 추가
package ex;

public class Apple {
    private Color color;

    private int weight;

    public Apple(Color color, int weight) {
        this.color = color;
        this.weight = weight;
    }

    public Color getColor() {
        return color;
    }

    public int getWeight() {
        return weight;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "color=" + color +
                ", weight=" + weight +
                '}';
    }
}

  • 새로 추가한 무게 조건 필터링 코드가 기존의 색 조건 필터링 코드와 대부분 중복된다.
    이는 소프트웨어 공학의 DRY(Don't Repeat Yourself, 같은 것을 반복하지 말 것) 원칙을 어긴다.

참고

💡참고

profile
기술로 세상을 이롭게

0개의 댓글