Java

[Effective Java] ์•„์ดํ…œ 52. ๋‹ค์ค‘์ •์˜๋Š” ์‹ ์ค‘ํžˆ ์‚ฌ์šฉํ•˜๋ผ.

quedevel 2023. 3. 24. 19:42
728x90
๋ฐ˜์‘ํ˜•

๐ŸŽฏ ์•„์ดํ…œ 52. ๋‹ค์ค‘์ •์˜๋Š” ์‹ ์ค‘ํžˆ ์‚ฌ์šฉํ•˜๋ผ.

  • ์ปฌ๋ ‰์…˜ ๋ถ„๋ฅ˜๊ธฐ - ์˜ค๋ฅ˜! ์ด ํ”„๋กœ๊ทธ๋žจ์€ ๋ฌด์—‡์„ ์ถœ๋ ฅํ• ๊นŒ?
public class CollectionClassifier {
    public static String classify(Set<?> s) {
        return "์ง‘ํ•ฉ";
    }

    public static String classify(List<?> lst) {
        return "๋ฆฌ์ŠคํŠธ";
    }

    public static String classify(Collection<?> c) {
        return "๊ทธ ์™ธ";
    }

    public static void main(String[] args) {
        Collection<?>[] collections = {
                new HashSet<String>(),
                new ArrayList<BigInteger>(),
                new HashMap<String, String>().values()
        };

        for (Collection<?> c : collections)
            System.out.println(classify(c));
    }
}

"์ง‘ํ•ฉ","๋ฆฌ์ŠคํŠธ","๊ทธ ์™ธ"๋ฅผ ์ฐจ๋ก€๋กœ ์ถœ๋ ฅํ•  ๊ฒƒ ๊ฐ™์ง€๋งŒ, ์‹ค์ œ๋กœ ์ˆ˜ํ–‰ํ•ด๋ณด๋ฉด "๊ทธ ์™ธ"๋งŒ ์„ธ ๋ฒˆ ์—ฐ๋‹ฌ์•„ ์ถœ๋ ฅํ•œ๋‹ค. ๊ทธ ์ด์œ ๋Š” ๋‹ค์ค‘์ •์˜(overloading, ์˜ค๋ฒ„๋กœ๋”ฉ)๋œ ์„ธ classify ์ค‘ ์–ด๋Š ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ• ์ง€๊ฐ€ ์ปดํŒŒ์ผํƒ€์ž…์— ์ •ํ•ด์ง€๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋”ฐ๋ผ์„œ, ์ปดํŒŒ์ผํƒ€์ž…์˜ ๋งค๊ฐœ๋ณ€์ˆ˜ ํƒ€์ž…์„ ๊ธฐ์ค€์œผ๋กœ ํ•ญ์ƒ ์„ธ ๋ฒˆ์งธ ๋ฉ”์„œ๋“œ๋งŒ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ์ด๋‹ค.


์ด๋Ÿฌํ•œ ๋ฌธ์ œ๋Š” CollectionClassifier์˜ ๋ชจ๋“  classify ๋ฉ”์„œ๋“œ๋ฅผ ํ•˜๋‚˜๋กœ ํ•ฉ์นœ ํ›„ instanceof๋กœ ๋ช…์‹œ์ ์œผ๋กœ ๊ฒ€์‚ฌํ•˜๋ฉด ๋ง๋”ํžˆ ํ•ด๊ฒฐ๋œ๋‹ค.

public class FixedCollectionClassifier {
    public static String classify(Collection<?> c) {
        return c instanceof Set ? "์ง‘ํ•ฉ" :
                c instanceof List ? "๋ฆฌ์ŠคํŠธ" : "๊ทธ ์™ธ";
    }

    public static void main(String[] args) {
        Collection<?>[] collections = {
                new HashSet<String>(),
                new ArrayList<BigInteger>(),
                new HashMap<String, String>().values()
        };

        for (Collection<?> c : collections)
            System.out.println(classify(c));
    }
}

ํ”„๋กœ๊ทธ๋งค์ด ์–ธ์–ด๊ฐ€ ๋‹ค์ค‘์ •์˜๋ฅผ ํ—ˆ์šฉํ•œ๋‹ค๊ณ  ํ•ด์„œ ๋‹ค์ค‘์ •์˜๋ฅผ ๊ผญ ํ™œ์šฉํ•˜๋ž€ ๋œป์€ ์•„๋‹ˆ๋‹ค. ์ผ๋ฐ˜์ ์œผ๋กœ ๋งค๊ฐœ๋ณ€์ˆ˜ ์ˆ˜๊ฐ€ ๊ฐ™์€ ๋•Œ๋Š” ๋‹ค์ค‘์ •์˜๋ฅผ ํ”ผํ•˜๋Š” ๊ฒŒ ์ข‹๋‹ค. ์ƒํ™ฉ์— ๋”ฐ๋ผ, ํŠนํžˆ ์ƒ์„ฑ์ž๋ผ๋ฉด ์ด ์กฐ์–ธ์„ ๋”ฐ๋ฅด๊ธฐ๊ฐ€ ๋ถˆ๊ฐ€๋Šฅํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ทธ๋Ÿด ๋•Œ๋Š” ํ—ท๊ฐˆ๋ฆด ๋งŒํ•œ ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” ํ˜•๋ณ€ํ™˜ํ•˜์—ฌ ์ •ํ™•ํ•œ ๋‹ค์ค‘์ •์˜ ๋ฉ”์„œ๋“œ๊ฐ€ ์„ ํƒ๋˜๋„๋ก ํ•ด์•ผ ํ•œ๋‹ค.


์ฐธ๊ณ  ์ž๋ฃŒ

Joshua Bloch, ใ€ŽEffective Java 3/Eใ€, ๊ฐœ์•ž๋งต์‹œ ์˜ฎ๊น€, ํ”„๋กœ๊ทธ๋ž˜๋ฐ์ธ์‚ฌ์ดํŠธ(2018)
http://www.kyobobook.co.kr/product/detailViewKor.laf?ejkGb=KOR&mallGb=KOR&barcode=9788966262281&orderClick=LEa&Kc=

728x90
๋ฐ˜์‘ํ˜•