how-to-handle-null

#tip

null ์ž˜ ์“ฐ๋Š” ๋ฒ• 1

  • null์„ ํ†ตํ•ด ์œ ์—ฐํ•œ ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“ค์ง€ ๋ง๊ณ , ๋ช…์‹œ์ ์ธ ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“ค๋„๋ก.

  • null์„ ๋ฐ˜ํ™˜ํ•˜์ง€ ๋ง๋ผ

    • ๋ฐ˜ํ™˜ ๊ฐ’์ด ๊ผญ ์žˆ์–ด์•ผํ•˜๋Š”๋ฐ null์ด๋ฉด ์˜ˆ์™ธ๋ฅผ ๋˜์ง€๊ฒŒ ํ•˜๊ณ ,

    • ๋นˆ ๋ฐ˜ํ™˜๊ฐ’์€ ๋นˆ ์ปฌ๋ ‰์…˜์ด๋‚˜ ํ˜น์€ Null ๊ฐ์ฒด (๋นˆ ๊ฐ์ฒด์ง€๋งŒ Null ๋Œ€์šฉ์œผ๋กœ ์‚ฌ์šฉ๋˜๋Š”)

    • ๋ฐ˜ํ™˜ ๊ฐ’์ด ์—†์„ ์ˆ˜๋„ ์žˆ์œผ๋ฉด Optional์„ ๋ฐ˜ํ™˜.

null ์ž˜ ์“ฐ๋Š” ๋ฒ• 2

  • Design By Contract

    • require + __ + ensure

    • ๋ฉ”์„œ๋“œ๊ฐ€ ์‹คํ–‰๋˜๊ธฐ ์ „์— ๋งŒ์กฑ๋˜์–ด์•ผ ํ•˜๋Š” ๋ถ€๋ถ„ + ๋กœ์ง ์‹คํ–‰ + ๋กœ์ง ์‹คํ–‰ ํ›„์—, ๋งŒ์กฑ๋˜์–ด์•ผํ•˜๋Š” ๋ถ€๋ถ„

    • ์ด๋Ÿฐ ๋ฐฉ์‹์œผ๋กœ ๊ฐœ๋ฐœํ•˜๋ฉด, ํ’ˆ์งˆ์„ ๋ณด์žฅํ•  ์ˆ˜ ์žˆ์Œ.

  • ์ฆ‰ ์ด๊ฑธ null์— ๋Œ€์ž…ํ•ด๋ณด๋ฉด,

    • ๋ณดํ˜ธ์ ˆ์—๋Š” ๋‹จ์ •๋ฌธ, Objects์—์„œ ์ œ๊ณตํ•ด์ฃผ๋Š” ๋ฉ”์„œ๋“œ..๋“ฑ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Œ.

    • Assert, Preconditions.. ํด๋ž˜์Šค๋“ค๋„ ์‚ฌ์šฉํ•ด๋ณผ ์ˆ˜ ์žˆ๊ฒ ๋„ค.

  • ์ฆ‰ ์‚ฌ์ „ ์กฐ๊ฑด์„ ํ™•์‹คํžˆ ์ง€์ผœ๋ผ

null ์ž˜ ์“ฐ๋Š” ๋ฒ• 3

  • null์˜ ๋ฒ”์œ„๋ฅผ ์ขํ˜€๋ผ

  • ์ฆ‰ ํด๋ž˜์Šค๋‚˜ ๋ฉ”์„œ๋“œ ๋‚ด๋ถ€์—์„œ๋งŒ ์‚ฌ์šฉํ•˜๋„๋ก.

    • ๊ทธ๋ฆฌ๊ณ  ๊ทธ ํด๋ž˜์Šค๋‚˜ ๋ฉ”์„œ๋“œ๋ฅผ ์ž‘๊ฒŒ ๋งŒ๋“ค๋ฉด ๋จ.

JSR 308

  • @NonNull , @Nullable ๋“ฑ ์ปดํŒŒ์ผ ํƒ€์ž„์—์„œ ์ฒดํฌํ•  ์ˆ˜ ์žˆ๋„๋ก..

  • Automatic type refinement

    Console console = System.console();
    char[] password = nonNull(console) ? console.readPassword() : new char[0];

์ •๋ฆฌ

  • JSR 305, JSR 308 ์“ฐ์ž

  • Checker Framework

์ฐธ๊ณ 

  • https://www.youtube.com/watch?v=vX3yY_36Sk4&t=954

  • https://www.oracle.com/technical-resources/articles/java/ma14-architect-annotations.html

Last updated