본문으로 건너뛰기

Boilerplate code 란? 개념 정리 및 예시

Boilerplate 란

  • Boilerplate 는 신문사에서 사용하는 금속판을 의미합니다.
  • 신문사에서는 금속판에 이미 만들어진 틀을 사용하여 동일한 내용을 반복적으로 인쇄합니다.

Boilerplate code 개념

  • Boilerplate code 는 매번 새로운 프로젝트를 시작할 때마다 반복적으로 작성해야 하는 코드를 말합니다. Boilerplate code 는 여러 곳에서 비슷한 형태로 반복되는 코드입니다.
  • 예를 들어 프로젝트의 구조를 만들거나, 설정을 초기화하거나, 라이브러리를 불러오는 등의 작업을 포함합니다. 또는, Getter & Setter Method 같은 특정 기능을 구현할 때 반복적으로 작성해야 하는 코드를 말합니다.

Boilerplate code 예시

  • Boilerplate code 는 다양한 언어에서 발생할 수 있습니다.
  • Java에서 Boilerplate로 사용되는 코드의 예시로는 다음과 같습니다.
    • Getter & Setter Method
    • equals() and hashCode() Method
    • toString() Method
    • Constructor Method
  • 위 코드들은 매번 새로운 클래스를 만들 때마다 반복적으로 작성해야 하는 코드입니다.
// 1. Getter & Setter Method
public class Person {
private String name;
private int age;

// Getter Method
public String getName() {
return name;
}

// Setter Method
public void setName(String name) {
this.name = name;
}

// Getter Method
public int getAge() {
return age;
}

// Setter Method
public void setAge(int age) {
this.age = age;
}
}

// 2. equals() and hashCode() Method
public class Person {
private String name;
private int age;

// equals() Method
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}

// hashCode() Method
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}

// 3. toString() Method
public class Person {
private String name;
private int age;

// toString() Method
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

// 4. Constructor Method
public class Person {
private String name;
private int age;

// Constructor Method
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}

Boilerplate code 를 줄이는 방법

  • Boilerplate code 는 반복적으로 작성해야 하는 코드이기 때문에, 코드의 양이 많아지면 코드의 가독성이 떨어질 수 있습니다.
  • Java 에서는 Boilerplate code 를 줄이기 위해 다음과 같은 방법을 사용할 수 있습니다.
    • IDE(Integrated Development Environment) 사용: IDE 에서 제공하는 기능을 사용하여 Boilerplate code 를 자동으로 생성할 수 있습니다.
    • Lombok 라이브러리 사용: Lombok 라이브러리를 사용하여 Getter & Setter Method, equals() and hashCode() Method, toString() Method, Constructor Method 등을 자동으로 생성할 수 있습니다.
    • Annotation Processor 사용: Annotation Processor 를 사용하여 Boilerplate code 를 자동으로 생성할 수 있습니다.
    • Template Engine 사용: Template Engine 을 사용하여 Boilerplate code 를 자동으로 생성할 수 있습니다.
  • Java 에서는 Lombok 라이브러리를 사용하여 아래와 같이 Boilerplate code 를 줄일 수 있습니다.
    • @Data Annotation 을 사용하여 Getter & Setter Method, equals() and hashCode() Method, toString() Method, Constructor Method 를 자동으로 생성할 수 있습니다.
    • 아래와 같이 @Data Annotation 을 사용하는 것만으로 코드 작성을 줄일 수 있습니다.
import lombok.Data;

@Data
public class Person {
private String name;
private int age;
}
  • 언어나 프레임워크에 따라 Boilerplate code 를 줄이는 방법이 다를 수 있습니다. 현재 사용하고 있는 언어나 프레임워크에서 제공하는 기능을 사용하여 Boilerplate code 를 줄이는 방법을 찾아보세요.