ITEM 16: Use Accessor methods

class Point {
    public double x;
    public double y;
}

์œ„ ํด๋ž˜์Šค๋Š” ์•„๋ž˜ ๋ฌธ์ œ์ ๋“ค์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค.

  • ์บก์Šํ™” ์ด์  ์ œ๊ณตํ•˜์ง€ ๋ชปํ•จ(๋ฐ์ดํ„ฐ ํ•„๋“œ์— ์ง์ ‘ ์ ‘๊ทผ ๊ฐ€๋Šฅ)

  • ๋‚ด๋ถ€ ํ‘œํ˜„ ๋ณ€๊ฒฝ์‹œ API ์ˆ˜์ • ํ•„์š”

  • ๋ถˆ๋ณ€์‹ ๋ณด์žฅ ๋ถˆ๊ฐ€๋Šฅ

  • ์™ธ๋ถ€์—์„œ ํ•„๋“œ์— ์ ‘๊ทผํ•  ๋•Œ ๋ถ€์ˆ˜ ์ž‘์—… ์ˆ˜ํ–‰ ๋ถˆ๊ฐ€๋Šฅ

์ด๋Ÿฌํ•œ ๋ฌธ์ œ์ ๋“ค์ด ์‹ซ์–ด ๋ณดํ†ต ์•„๋ž˜์™€ ๊ฐ™์ด private ํ•„๋“œ๋ฅผ public ์ ‘๊ทผ์ž๋กœ ์ ‘๊ทผํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๊ตฌํ˜„ํ•œ๋‹ค.

์ ‘๊ทผ์ž ๋ฐฉ์‹

class Point{
    private double x;
    private double y;

    public Point(double x, double y){
        this.x = x;
        this.y = y;
    }

    public double getX(){
        return x;
    }
    public double getY(){
        return y;
    }
    public void setX(double x){
        return this.x = x;
    }
    public void setY(double y){
        return this.y = y;
    }
}

ํŒจํ‚ค์ง€ ๋ฐ”๊นฅ์—์„œ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ํด๋ž˜์Šค๋ผ๋ฉด ์ ‘๊ทผ์ž๋ฅผ ์ œ๊ณตํ•˜์—ฌ ํด๋ž˜์Šค ๋‚ด๋ถ€ ํ‘œํ˜„ ๋ฐฉ์‹์„ ์–ธ์ œ๋“  ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋Š” ์œ ์—ฐ์„ฑ์ด ์žˆ๋‹ค. ๊ทธ๋Ÿฌ๋ฏ€๋กœ public ํด๋ž˜์Šค์—์„œ ์ด ๋ฐฉ์‹์€ ํ™•์‹คํžˆ ๋งž๋‹ค.

ํ•˜์ง€๋งŒ, package-private, private ์ค‘์ฒฉ ํด๋ž˜์Šค์˜ ๊ฒฝ์šฐ ๋ฐ์ดํ„ฐ ํ•„๋“œ๋ฅผ ๋…ธ์ถœํ•œ๋‹ค๊ณ  ํ•ด๋„ ๊ทธ ํด๋ž˜์Šค๊ฐ€ ํ‘œํ˜„ํ•˜๋ ค๋Š” ์ถ”์ƒ ๊ฐœ๋…๋งŒ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ํ‘œํ˜„ํ•œ๋‹ค๋ฉด ๋ฌธ์ œ๊ฐ€ ์—†๋‹ค. ์ ‘๊ทผ์ž ๋ฐฉ์‹๋ณด๋‹ค ํ›จ์”ฌ ๊น”๋”ํ•˜๋ฉฐ, ํŒจํ‚ค์ง€ ๋ฐ”๊นฅ ์ฝ”๋“œ ์‹ ๊ฒฝ์“ฐ์ง€ ์•Š๊ณ  ๋ฐ์ดํ„ฐ ํ‘œํ˜„ ๋ฐฉ์‹์„ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋‹ค.

๋ถˆ๋ณ€ ํ•„๋“œ

public final class Time {
    private static final int HOURS_PER_DAY = 24;
    private static final int MINUTES_PER_DAY = 60;

    public final int hour;
    public final int minute;

    public Time(int hour, int minute){
        if(hour < 0 || hour >= HOURS_PER_DAY){
            throw new IllegalArgumentException("์‹œ๊ฐ„ : "+ hour);
        }
        if(minute < 0 || minute >= MINUTES_PER_DAY){
            throw new IllegalArgumentException("๋ถ„ : "+ hour);
        }
        this.hour = hour;
        this.minute = minute;
    }
}

๋‹ค์Œ๊ณผ ๊ฐ™์ด public ํด๋ž˜์Šค์˜ ํ•„๋“œ๊ฐ€ ๋ถˆ๋ณ€์ด๋ผ๋ฉด ๋ถˆ๋ณ€์‹์€ ๋ณด์žฅํ•  ์ˆ˜ ์žˆ๊ฒŒ๋˜์–ด ์ง์ ‘ ๋…ธ์ถœํ•  ๋•Œ์˜ ๋‹จ์ ์€ ์ค„์ง€๋งŒ, ์—ฌ์ „ํžˆ ๋‹จ์ ์ด ์กด์žฌํ•œ๋‹ค.

  • ๋‚ด๋ถ€ ํ‘œํ˜„ ๋ณ€๊ฒฝ์‹œ API ์ˆ˜์ • ํ•„์š”

  • ํ•„๋“œ๋ฅผ ์ฝ์„ ๋•Œ ๋ถ€์ˆ˜ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์—†๋‹ค.

Last updated