์ด ๋ด์ฉ์ ์ฝ๋ ๋ฆฌ๋ทฐ ์คํฐ๋๋ฅผ ํ๋ ๋น์ ๋ฒจ๋ก๊ทธ์ ์์ฑํ์๋ ๋ด์ฉ์ ๋๋ค.
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) ๋ณ์๊ฐ ๋์ค๋ฉฐ, ์ด์ด์ ๋น๊ณต๊ฐ ์ธ์คํด์ค ๋ณ์๊ฐ ๋์จ๋ค. ๊ณต๊ฐ ๋ณ์๊ฐ ํ์ํ ๊ฒฝ์ฐ๋ ๊ฑฐ์ ์๋ค.
๋ณ์ ๋ชฉ๋ก ๋ค์์๋ ๊ณต๊ฐ ํจ์๊ฐ ๋์จ๋ค. ๋น๊ณต๊ฐ ํจ์๋ ์์ ์ ํธ์ถํ๋ ๊ณต๊ฐ ํจ์ ์งํ์ ๋ฃ๋๋ค. ์ฆ, ์ถ์ํ ๋จ๊ณ๊ฐ ์์ฐจ์ ์ผ๋ก ๋ด๋ ค๊ฐ๋ค. ๊ทธ๋์ ํ๋ก๊ทธ๋จ์ ์ ๋ฌธ ๊ธฐ์ฌ์ฒ๋ผ ์ฝํ๋ค.
๋น๊ณต๊ฐ ํจ์์์ ์์น ์ถฉ๋์ ํผํ๊ธฐ ์ํด, ์ ๊ทผ ์ ์ด์ ํจ์๋ ๋งจ ์๋์ ์์นํ๊ณ ๊ทธ ์ด์ธ์ ๊ณต๊ฐ ํจ์๋ ๋ชจ๋ ๊ทธ ์์ ์์ฑํ๋๋ก ํด์ผ๊ฒ ๋ค๋ ์๊ฐ์ ํ๊ฒ ๋์์ต๋๋ค.
๋ถ์กฑํ๊ฑฐ๋ ๋ณด์ํ ์ ์ด ์๋ค๋ฉด ์ธ์ ๋ ์ง ๋๊ธ ๋ถํ๋๋ฆฝ๋๋ค!
'๐ค ๊ณ ๋ฏผ์ ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Spring] Repository์ ๋ฐํ ํ์ ์ผ๋ก๋ ์ด๋ค ๊ฒ์ ์จ์ผ ํ ๊น? (Entity vs void) (2) | 2024.02.06 |
---|