getterμ setterλ μ΄λμ λλ κ² μ’μκΉ?
μ΄ λ΄μ©μ μ½λ 리뷰 μ€ν°λλ₯Ό νλ λΉμ 벨λ‘κ·Έμ μμ±νμλ λ΄μ©μ λλ€.
Getterμ Setter
νν ν΄λμ€κ° κ°μ§κ³ μλ νλκ°λ€μ κ°μ Έμ€κ±°λ μ€μ ν λ μ°μ΄λ λ©μλλ€μ κ°κ° Getter, Setter λ©μλλΌ ν©λλ€. λλ μ κ·Ό μ μ΄μλΌκ³ νκΈ°λ ν©λλ€.
public class Car {
private static final int START_DISTANCE = 0;
private static final int ACCELERATE_MINIMUM_VALUE = 4;
private static final int ACCELERATE_MAXIMUM_VALUE = 9;
private final Name name;
private int distance;
private Car(final Name name, final int distance) {
this.name = name;
this.distance = distance;
}
public static Car createDefault(Name name) {
return new Car(name, START_DISTANCE);
}
// κΈ°ν λ©μλλ€
// μλμ°¨ κ²½μ£Ό λ―Έμ
μμλ getterλ§ μ¬μ©νμ΅λλ€.
public String getName() {
return name.getName();
}
public int getDistance() {
return this.distance;
}
// κΈ°ν λ©μλλ€: μ¦, getterκ° λ§¨ μλκ° μλμμ΅λλ€.
κ·Έλ°λ° getter λ©μλ (setter ν¬ν¨)λ ν΄λμ€μ 맨 μλμ λλΌλ 리뷰λ₯Ό λ°μμ΅λλ€. μ μ΄λ κ² λ§μνμ ¨λμ§ μμλ³΄κ² μ΅λλ€.
컨벀μ μΌλ‘ μ μλμ΄ μλκ°?
μ¬μ€ λ§μ΄ μ°Έκ³ νλ κ΅¬κΈ μλ° μ»¨λ²€μ μ΄λ, ν΄λ¦° μ½λ (Clean Code) μ± μλ getter, setterλ₯Ό 맨 μλμ λλΌλ λ΄μ©μ μμ΅λλ€.
컨벀μ μ μμ§λ§, κ΄λ‘μ μΌλ‘ μ¬μ©νλ€.
κ·Έλ°λ° μ€νμ€λ²νλ‘μ° κΈμ 보면, λ§μ μ¬λλ€μ΄ getterμ setterλ₯Ό κ΄λ‘μ μλμ λ μ μ μ μμ΅λλ€.
Not sure if there is universally accepted standard but my own preferences are;
- constructors first
- static methods next, if there is a main method, always before other static methods
- non static methods next, usually in order of the significance of the method followed by any methods that it calls. This means that public methods that call other class methods appear towards the top and private methods that call other class methods appear towards the top and private methods that call no ohter methods usually end up towards the bottom
- standard methods like toString, equals and hashcode next
- getters and setters have a special place reserved right at the bottom of the class
μ νν μ΄μ
컨벀μ μΌλ‘ μ΄λ£¨μ΄μ§ κ² μλλ° μ μ¬λλ€μ΄ 맨 μλμ λλ κ²μΈμ§ κΆκΈνμ¬ λ μ¬μ€λ΄€λλ, μλ μ΄μ λ₯Ό μ»μ μ μμμ΅λλ€.
- getter κ°μ λΆλΆμ μ°λ μΌμ΄ λ§κ³ μ μΈ μ μλ€λ©΄ μ§μνλ νΈμ΄ μ’κΈ° λλ¬Έμ λͺ μμ μΌλ‘ μλμ μμΉνλ€.
- λΆνμν getterλ μμ κΈ° μν΄μ μλμͺ½μμ μ¬μ©νλ κ²μ΄ μ’λ€.
μΆκ° μ°Έκ³ : ν΄λ¦° μ½λμμμ ν΄λμ€ μ²΄κ³ κΆμ₯μ
ν΄λ¦° μ½λμμ μμ±λ ν΄λμ€ μ²΄κ³λ₯Ό 보면, λ€μκ³Ό κ°μ΄ μ μλμ΄ μμ΅λλ€.
ν΄λμ€λ₯Ό μ μνλ νμ€ μλ° κ΄λ‘μ λ°λ₯΄λ©΄, κ°μ₯ λ¨Όμ λ³μ λͺ©λ‘μ΄ λμ¨λ€. μ μ (static) κ³΅κ° (public) μμκ° μλ€λ©΄ 맨 μ²μμ λμ¨λ€. λ€μμΌλ‘ μ μ λΉκ³΅κ° (private) λ³μκ° λμ€λ©°, μ΄μ΄μ λΉκ³΅κ° μΈμ€ν΄μ€ λ³μκ° λμ¨λ€. κ³΅κ° λ³μκ° νμν κ²½μ°λ κ±°μ μλ€.
λ³μ λͺ©λ‘ λ€μμλ κ³΅κ° ν¨μκ° λμ¨λ€. λΉκ³΅κ° ν¨μλ μμ μ νΈμΆνλ κ³΅κ° ν¨μ μ§νμ λ£λλ€. μ¦, μΆμν λ¨κ³κ° μμ°¨μ μΌλ‘ λ΄λ €κ°λ€. κ·Έλμ νλ‘κ·Έλ¨μ μ λ¬Έ κΈ°μ¬μ²λΌ μ½νλ€.
λΉκ³΅κ° ν¨μμμ μμΉ μΆ©λμ νΌνκΈ° μν΄, μ κ·Ό μ μ΄μ ν¨μλ 맨 μλμ μμΉνκ³ κ·Έ μ΄μΈμ κ³΅κ° ν¨μλ λͺ¨λ κ·Έ μμ μμ±νλλ‘ ν΄μΌκ² λ€λ μκ°μ νκ² λμμ΅λλ€.
λΆμ‘±νκ±°λ 보μν μ μ΄ μλ€λ©΄ μΈμ λ μ§ λκΈ λΆνλ립λλ€!