포스트

람다가 필요한 이유

람다가 필요한 이유

값 매개변수화(Value Parameterization)

  • 문자값, 숫자값 처럼 구체적인 값을 매개변수를 통해 외부에서 전달 받고록 해서, 메서드의 동작을 달리하고 재사용성을 높이는 방법
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Ex0Main {

  public static void helloJava() {
    System.out.println("프로그램 시작");
    System.out.println("Hello Java");
    System.out.println("프로그램 종료");
  }

  public static void helloSpring() {
    System.out.println("프로그램 시작");
    System.out.println("Hello Spring");
    System.out.println("프로그램 종료");
  }

  public static void main(String[] args) {
    helloJava();
    helloSpring();
  }
}
  • 값 매개변수화 리팩토링
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Ex0RefMain {

  public static void hello(String str) {
    System.out.println("프로그램 시작"); // 변하지 않는 부분

    // 변하는 부분 시작
    System.out.println(str);
    // 변하는 부분 종료

    System.out.println("프로그램 종료"); // 변하지 않는 부분
  }

  public static void main(String[] args) {
    hello("hello Java");
    hello("hello Spring");
  }
}

동작 매개변수화

  • 코드 조각을 메서드 안에 두는 것이 아니라, 매개변수를 통해서 외부에서 전달 받도록 해서 메서드의 동작을 달리하고 재사용성을 높이는 방법
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Ex1Main {

  public static void helloDice() {
    long startNs = System.nanoTime();

    //코드 조각 시작
    int randomValue = new Random().nextInt(6) + 1;
    System.out.println("주사위 = " + randomValue);
    //코드 조각 종료

    long endNs = System.nanoTime();
    System.out.println("실행 시간: " + (endNs - startNs) + "ns");
  }

  public static void helloSum() {
    long startNs = System.nanoTime();

    //코드 조각 시작
    for (int i = 1; i <= 3; i++) {
      System.out.println("i = " + i);
    }
    //코드 조각 종료

    long endNs = System.nanoTime();
    System.out.println("실행 시간: " + (endNs - startNs) + "ns");
  }

  public static void main(String[] args) {
    helloDice();
    helloSum();
  }
}
  • 동작 파라미터화 리팩토링
1
2
3
public interface Procedure {
  void run();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Ex1RefMainV3 {

  public static void hello(Procedure procedure) {
    long startNs = System.nanoTime();

    //코드 조각 시작
    procedure.run();
    //코드 조각 종료

    long endNs = System.nanoTime();
    System.out.println("실행 시간: " + (endNs - startNs) + "ns");
  }

  public static void main(String[] args) {
    hello(new Procedure() {
      @Override
      public void run() {
        int randomValue = new Random().nextInt(6) + 1;
        System.out.println("주사위 = " + randomValue);
      }
    });

    hello(new Procedure() {
      @Override
      public void run() {
        for (int i = 1; i <= 3; i++) {
          System.out.println("i = " + i);
        }
      }
    });
  }

익명 클래스를 더욱 간결하게 만들기

람다를 사용하면 코드 조각을 전달하기 위해 클래스를 정의하고 메서드를 만들고 인스턴까지 생성하는 복잡한 과정을 생략할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Ex1RefMainV4 {

  public static void hello(Procedure procedure) {
    long startNs = System.nanoTime();

    //코드 조각 시작
    procedure.run();
    //코드 조각 종료

    long endNs = System.nanoTime();
    System.out.println("실행 시간: " + (endNs - startNs) + "ns");
  }

  public static void main(String[] args) {
    hello(() -> {
      int randomValue = new Random().nextInt(6) + 1;
      System.out.println("주사위 = " + randomValue);
    });

    hello(() -> {
      for (int i = 1; i <= 3; i++) {
        System.out.println("i = " + i);
      }
    });
  }
}

함수 VS 메서드

클래스(객체)와의 관계

  • 함수
    • 독립적으로 존재하며, 클래스(객체)와 직접적인 연관이 없음
  • 메서드
    • 클래스(객체)에 속해 있는 함수
    • 객체의 상태에 직접 접근하거나, 객체가 제공해야 할 기능을 구현할 수 있음

호출 방식과 스코프

  • 함수
    • 호출시에 객체 인스턴스가 필요 없음
    • 보통 이름(매개변수) 형태로 호출
    • 지역 변수, 전역 변수 등과 함께 동작하며, 클래스나 객체 특우의 속성은 다루지 못함
  • 메서드
    • 보통 객체(인스턴스).메서드이름(매개변수) 형태로 호출
    • 호출 될 때, 해당 객체의 필드(속성)나 다른 메서드에 접근 가능
    • 인스턴스 메서드, 클래스(정적) 메서드, 추상 메서드 등 다양한 형태가 있을 수 있음

참고

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.