티스토리 뷰

일급 객체 first-class object)란 다른 객체들에 일반적으로 적용 가능한 연산을 모두 지원하는 객체를 가리킨다. 보통 함수에 인자로 넘기기, 수정하기, 변수에 대입하기와 같은 연산을 지원할 때 일급 객체라고 한다 즉 다음과 같은 조건을 만족해야 합니다,

  1. 변수나 데이타에 할당할 수 있어야 한다.
  2. 객체의 인자로 넘길 수 있어야 한다.
  3. 객체의 리턴값으로 리턴할 수 있어야 한다

자바 프로그밍 언어는 사용하는 메서드, 클래스는 전달할 수 없는 구조체로 일급 객체가 아니다, 이것을 해결하고자 자바 1.8에서 메서드 참조(Method Reference)를 사용해서 일급 객체로 사용합니다,

자바에서 메서드를 어떤 방법으로 전달할 수 있을까? 자바 1.8 이전은 다음과 같이 작성하였습니다..

public static void beforeJava8() {
    List<Car> cars = new ArrayList<>();
    cars.add(new Car("소나타", "검정", "현대"));
    cars.add(new Car("SM5", "검정", "삼성"));
    cars.add(new Car("SM5", "흰색", "삼성"));

    List<Car> blackCars = filterCarColor(cars);
    System.out.println(blackCars.toString());
    List<Car> companyCars = filterCarColor(cars);
    System.out.println(companyCars.toString());
  }

  public static List<Car> filterCarColor(List<Car> cars) {
    // 반환 값을 위한 반환 값
    List<Car> rnCars = new ArrayList<>();

    for ( Car car : cars) {
      if (COLOR_BLACK.equals(car.getColor())) {
        rnCars.add(car);
      }
    }

    return rnCars;
  }

  public static List<Car> filterCarCompany(List<Car> cars) {
    // 반환 값을 위한 반환 값
    List<Car> rnCars = new ArrayList<>();

    for ( Car car : cars) {
      if (COMPANY_SAMSUNG.equals(car.getCompany())) {
        rnCars.add(car);
      }
    }

    return rnCars;
  }

소스 : 자바 1.8 이전

 

GitHub - hyomee/code

Contribute to hyomee/code development by creating an account on GitHub.

github.com

filterCarColor, filterCarComapy는 if 조건문의 조건식을 제외하고 동일 코드로 되어 있음을 확인할 수 있다, 이 예제를 다음과 같이 리펙토링을 한다.

1. 조건식 함수화 

  public static boolean isColorBlack(Car car) {
    return COLOR_BLACK.equals(car.getColor());
  }

  public static boolean isCompanySamsung(Car car) {
    return COMPANY_SAMSUNG.equals(car.getCompany());
  }

2. Interfacce 함수 생성 

함수를 메서드의 파라미터로 전달하기 위해서 인터페이스를 생성한다,

interface Condition<T> {
  boolean isCondition(T t);
}

3. 함수를 받아서 처리하는 메서드 생성 

자바에서 메서드는 파라미터로 전달할 수 없으므로 인터페이스를 만들어서 사용해야 합니다.

  public static List<Car> filterCar(List<Car> cars, Condition<Car> carCondition) {
    // 반환 값을 위한 반환 값
    List<Car> rnCars = new ArrayList<>();

    for ( Car car : cars) {
      // 파라메터러 받은 
      if (carCondition.isCondition(car)) {
        rnCars.add(car);
      }
    }

    return rnCars;
  }

4. 사용

  public  void runAfterJava8() {
    List<Car> cars = new ArrayList<>();
    cars.add(new Car("소나타", "검정", "현대"));
    cars.add(new Car("SM5", "검정", "삼성"));
    cars.add(new Car("SM5", "흰색", "삼성"));

    List<Car> blackCars = filterCar(cars, Car :: isColorBlack);
    System.out.println(blackCars.toString());
    List<Car> companyCars = filterCar(cars, Car :: isCompanySamsung);
    System.out.println(companyCars.toString());
  }

람다를 사용해서 함수를 파라미터로 연결한다. ( Car :: isColorBlack )

5. 람다를 이용하면 더 편하게 사용할 수 있다.

List<Car> blackCars = filterCar(cars, (Car car) -> Constant.COLOR_BLACK.equals(car.getColor()));

(Car car) -> Constant.COLOR_BLACK.equals(car.getColor()) 를 사용해서 직접 호출할 수 있다.

소스 : 자바 1.8 이후 

 

GitHub - hyomee/code

Contribute to hyomee/code development by creating an account on GitHub.

github.com