반응형

자바에서 람다 표현식은 익명 함수를 간결하게 표현할 수 있는 기능입니다. 람다 표현식을 사용하면 코드가 더 직관적이고 간결해지며, 특히 함수형 인터페이스를 사용할 때 유용합니다.

1. 람다 표현식 기본 구조

(매개변수들) -> { 실행할 코드 }
    
  • 매개변수들: 람다식에 전달되는 입력 값들.
  • 실행할 코드: 람다식이 실행할 코드 블록.

2. 예시

1) 매개변수가 없는 람다

() -> System.out.println("Hello, World!");
    

이 예시는 매개변수가 없고, "Hello, World!"를 출력하는 람다식입니다.

2) 매개변수가 하나인 람다

x -> x * x
    

매개변수 x를 받아서 x의 제곱을 반환하는 람다식입니다.

3) 매개변수가 여러 개인 람다

(x, y) -> x + y
    

매개변수 x와 y를 받아서 두 값을 더하는 람다식입니다.

3. 람다 표현식 사용 예시

람다 표현식은 주로 함수형 인터페이스에서 사용됩니다. 예를 들어, Runnable 인터페이스를 사용한 예시는 다음과 같습니다:

Runnable task = () -> System.out.println("Hello from a thread!");
task.run();
    

4. 람다 표현식의 장점

  • 간결한 코드: 익명 클래스를 사용하는 것보다 코드가 훨씬 간결해집니다.
  • 가독성 향상: 불필요한 boilerplate 코드가 줄어들어 가독성이 향상됩니다.
  • 함수형 프로그래밍: 자바에서 함수형 프로그래밍 스타일을 사용할 수 있습니다.

5. 함수형 인터페이스

람다 표현식은 함수형 인터페이스와 함께 사용됩니다. 함수형 인터페이스는 하나의 추상 메서드만을 가지는 인터페이스를 말합니다. 예시로 Runnable, Callable, Comparator 등이 있습니다.

@FunctionalInterface
public interface MyFunction {
    void apply();
}
    

위 예시에서 MyFunction 인터페이스는 하나의 추상 메서드를 가지고 있으며, 람다로 구현할 수 있습니다.

MyFunction myFunc = () -> System.out.println("Hello from MyFunction!");
myFunc.apply();
    

6. 람다 표현식의 제한 사항

  • final 또는 effectively final 변수만 사용 가능: 람다식 내에서 참조되는 변수는 반드시 final이거나 사실상 final이어야 합니다.
  • 상태 변경이 어려움: 람다식 내부에서 외부 변수를 변경할 수 없으므로 상태 관리에 제한이 있을 수 있습니다.

7. 결론

람다 표현식은 자바에서 함수형 프로그래밍을 보다 쉽게 구현할 수 있게 해 주는 강력한 도구입니다. 간결한 코드 작성, 가독성 향상 및 함수형 프로그래밍 스타일을 지원하는 데 큰 장점이 있습니다.

728x90
반응형

toString을 항상 재정의하라

Object의 기본 toString 메서드가 우리가 작성한 클래스에 적합한 문자열을 반환하는 경우는 거의 없음

toString을 잘 구현한 클래스는 사용하기에 훨씬 즐겁고, 그 클래스를 사용한 시스템은 디버깅하기 쉬음

실전에서 toString은 그 객체가 가진 주요 정보 모두를 반환하는 게 좋음

포맷을 명시하든 아니든 여러분의 의도는 명확히 밝혀야 함

class sample(){

    @Override public String toString(){
        return String.format("%03d-%03d-%04d", areaCode, prefix, lineNum);
    }

}
class sample(){

    @Override public String toString(){
        ...
    }

}

포맷 명시 여부와 상관없이 toString이 반환한 값에 포함된 정보를 얻어올 수 있는 API를 제공하자
PhoneNumber 클래스는 지역 코드, 프리픽스, 가입자 번호용 접근자를 제공해야함
그렇지 않으면 이 정보가 필요한 프로그래머는 toString의 반환값을 파싱할 수 밖에 없음

정적 유틸리티 클래스, 대부분의 열거 타입 이미 toString을 제공함

하지만 하위 클래스들이 공유해야 할 문자열 표현이 있는 추상 클래스라면 toString을 재정의해줘야 함
대다수의 컬렉션 구현체는 추상 컬렉션 클래스들의 toString 메서드를 상속해 씀

구글의 AutoValue 프레임워크는 toString도 생성해줌

정리

모든 구체 클래스에서 Object의 toString을 재정의하자.

toString은 해당 객체에 관한 명확하고 유용한 정보를 읽기 좋은 형태로 반환해야함

728x90
반응형

회사 코드에 EntityManager를 사용하여 try~catch~finally를 사용하여 finally에서 해당 EntityManager 인스턴스를 close()하고 자원을 반납하고 있었습니다. 

하지만 이펙티브 자바에서는 [아이템 9. try-finally 대신 try-with-resources를 사용하라.] 라는 내용이 존재합니다. 

그래서 EntityManager를 try-with-resources로 리팩터링을 하려고 했지만, AutoClosable이 지원하지 않는다고 IDE에서 말해주고 있었습니다. 관련 글을 찾던 중 블로그에 해당 이슈는 오픈소스에 fix issue로 등록이 되어 있고 특정 버전 이후에 추가가 되었다고 합니다.

제가 회사에서 쓰는 java persistence-api 라이브러리는 2.x로 AutoClosable을 지원하지 않았고, 3.x대로 올라가면서 Jakarta Persistence API -> 3.1.0 지원하게 된것을 알게되었습니다.

EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("default");
try(EntityManager entityManager = entityManagerFactory.createEntityManager()){

}

 

package jakarta.persistence;

import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.CriteriaUpdate;
import jakarta.persistence.metamodel.Metamodel;
import java.util.List;
import java.util.Map;

public interface EntityManager extends AutoCloseable {
    void persist(Object var1);

    <T> T merge(T var1);

    void remove(Object var1);

해당 Jakarta Persistence API의 EntityManager 인터페이스를 보면 알 수 있듯이 해당 클래스는 AutoCloseable을 상속하고 있는 것을 알 수 있습니다.

public interface AutoCloseable {
    /**
     * Closes this resource, relinquishing any underlying resources.
     * This method is invoked automatically on objects managed by the
     * {@code try}-with-resources statement.
     *
     * <p>While this interface method is declared to throw {@code
     * Exception}, implementers are <em>strongly</em> encouraged to
     * declare concrete implementations of the {@code close} method to
     * throw more specific exceptions, or to throw no exception at all
     * if the close operation cannot fail.
     *
     * <p> Cases where the close operation may fail require careful
     * attention by implementers. It is strongly advised to relinquish
     * the underlying resources and to internally <em>mark</em> the
     * resource as closed, prior to throwing the exception. The {@code
     * close} method is unlikely to be invoked more than once and so
     * this ensures that the resources are released in a timely manner.
     * Furthermore it reduces problems that could arise when the resource
     * wraps, or is wrapped, by another resource.
     *
     * <p><em>Implementers of this interface are also strongly advised
     * to not have the {@code close} method throw {@link
     * InterruptedException}.</em>
     *
     * This exception interacts with a thread's interrupted status,
     * and runtime misbehavior is likely to occur if an {@code
     * InterruptedException} is {@linkplain Throwable#addSuppressed
     * suppressed}.
     *
     * More generally, if it would cause problems for an
     * exception to be suppressed, the {@code AutoCloseable.close}
     * method should not throw it.
     *
     * <p>Note that unlike the {@link java.io.Closeable#close close}
     * method of {@link java.io.Closeable}, this {@code close} method
     * is <em>not</em> required to be idempotent.  In other words,
     * calling this {@code close} method more than once may have some
     * visible side effect, unlike {@code Closeable.close} which is
     * required to have no effect if called more than once.
     *
     * However, implementers of this interface are strongly encouraged
     * to make their {@code close} methods idempotent.
     *
     * @throws Exception if this resource cannot be closed
     */
    void close() throws Exception;
}

 

https://k3068.tistory.com/98

 

왜? EntityManager는 AutoCloseable 구현하고 있지 않은가?

EntityManager는 쓰레드 간에 공유를 하지 않고 사용 후 바로 정리해야 한다고 한다. public void run(ApplicationArguments args) throws Exception { EntityManager em = entityManagerFactory.createEntityManager(); EntityTransaction transa

k3068.tistory.com

 

https://www.inflearn.com/questions/231224/entitymanager-%EB%8A%94-%EC%99%9C-autocloseable-%EC%9D%84-%EC%A7%80%EC%9B%90%ED%95%98%EC%A7%80-%EC%95%8A%EB%82%98%EC%9A%94

 

EntityManager 는 왜 AutoCloseable 을 지원하지 않나요? - 인프런 | 질문 & 답변

안녕하세요문득 궁금한점이 생겨서 질문해봅니다.항상 사용하고 버려야 한다면 AutoCloseable지원하여 try-with-resource 문을 사용할 수 있도록 도움을 주면 좋을 것 같다고 생각이 들었지만시용해볼

www.inflearn.com

 

728x90

+ Recent posts