-
Notifications
You must be signed in to change notification settings - Fork 5
☑️Java Convention
Sungwon edited this page Mar 9, 2025
·
2 revisions
- 클래스 내 순서 상수 → 인스턴스 필드 → 생성자 → 기능
- 줄 바꿈도 컨벤션이다.
- 클래스 선언부와 필드 사이에 공백 한 줄 추가한다.
- 인스턴스 변수 사이에 개행을 한다.
- 메소드 사이에 개행을 한다.
- 클래스 마지막에 개행을 하지 않는다.
- 파일 마지막에 개행한다.
- 네이밍
- 상수(static final)는 대문자, 스네이크 기법으로 작성한다.
- 변수(인스턴스 변수, 메서드 파라미터, 메서드 변수)는 소문자 카멜 기법으로 작성한다.
- 어노테이션은 대상(클래스 혹은 메소드)의 정체성과 가장 가까운 순으로 선언부에 가깝게 한다.
- 객체 필드, 메소드 파라미터, 메서드 변수에 가능하면 final 을 붙인다.
- 패키지명은 단수, 소문자로 한다.
- 생성자 선언 순서는 파라미터가 적은 순서대로 작성한다.
package com.naaga.domain; // (5)
@EntityListeners(AuditingEntityListener.class)
@Entity // (3)
public class Example {
// (2)
private static final Example FIXED_EXAMPLE = new Example(1L, "나아가", 20);
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id // (3)
private Long id;
private String name;
private int age;
public Example() {...} // (8)
public Example(final String name) {...} // (8)
public Example(final String name, final int age) {...} // (8)
public Example(final Long id, final String name, final int age) {...} // (8)
public void doSomething(final String a, final int b) {...} // (4)
public Long getId() {...}
public void setId(final Long id) {...}
public boolean equals(final Object o) {...}
public int hashCode() {...}
public String toString() {...}
}객체지향 생활 체조 원칙 중 아래의 원칙을 기본으로 한다.
- 한 메소드에 오직 한 단계의 들여쓰기(indent)만 한다.
- else & switch예약어를 사용하지 않는다.
- 줄여쓰지 않는다(축약 금지).
- record는 DTO와 VO에서 사용한다.
네이밍 규칙
-
테스트 메서드명을 한글로 작성한다.
-
예외케이스에 대한 테스트 메서드 네이밍은 ~ 하면 예외가 발생한다.로을 통일한다.
-
생성로직에 대한 테스트 메서드 명은 ~ 생성한다.로 통일한다.
-
테스트 클래스의 빈 주입은 필드 주입을 사용한다.
-
given, when, then 주석을 명시적으로 붙인다. 생략하지 않는다. given, when, then 절을 나누기 곤란한 경우 given, when & then 과 같이 & 으로 합쳐 작성한다.
// given & when
// when & then
// given & when & then
@Test
void 없는_장소를_조회하면_예외가_발생한다() {
// given
final Place place = new Place(...);
placeRepository.save(place);
// when & then
assertThatThrownBy(() -> placeRepository.findById(-1L))
.isInstanceOf(PlaceException.class);
}
@Test
void 장소를_아이디로_조회한다() {
// given
final Place expected = new Place(...);
placeRepository.save(place);
// when
final Place actual = placeRepository.findById(place.getId());
// then
assertThat(actual).isEqualTo(expected);
}- @Entity 클래스의 이름을 단수로 한다. 만약 MySQL 예약어와 겹치면 다른 단어를 선택한다.
- @Entity 클래스의 기본 생성자는 protected 로 지정한다.
##예외처리 도메인 단위로 예외를 클래스를 생성한다. 그 도메인 예외에 대한 enum Type을 나눠 상황을 정의한다.
조회 요청 : find~() 쓰기 요청 : create~() 삭제 요청 : delete~() 수정 요청 : update~()
요청 DTO : ~Request 응답 DTO : ~Response
조회 메서드는 맨 아래에 위치한다. 조회 요청 : find~() 쓰기 요청 : create~() 삭제 요청 : delete~() 수정 요청 : update~()
- Fetch Join은 fetch
- 조회 주체의 이름이나 자료형, 컬렉션 안쓰기 <- All 사용하기
findAllByPassed (O)
findListByPassed (X)
findBlueprintsByPassed (X)
- 핵심 구분 필드가 사용되는 경우, By 붙이기
public Page<Blueprint> findAllByPassed(Pageable pageable) {
if (pageable == null) {
throw new ApiException(BlueprintErrorCode.NULL_POINT_ERROR,"pageable이 NULL입니다.");
}
return blueprintRepository.findByInspectionStatus(InspectionStatus.PASSED, pageable);
}- `By` 뒤에는 복수형일 경우 자료형이나 콜렉션 대신 `S` 붙이기
- 같이 조회되는 데이터가 있는 경우, With 붙이기
public List<Blueprint> fetchAllWithCartBlueprints(List<Blueprint> blueprints) {
if (blueprints == null) {
throw new ApiException(BlueprintErrorCode.NULL_POINT_ERROR,"blueprints가 NULL입니다.");
}
return blueprintRepository.findWithCartBlueprints(blueprints);
}- 하나를 반환할 때는 One 붙이기
public Blueprint findOne(Long id) {
return blueprintRepository.findById(id)
.orElseThrow(() -> new ApiException(BlueprintErrorCode.NOT_FOUND_ERROR,"blueprintId : "+id));
}Spring Data JPA 쿼리 메소드 명명을 따른다.