0

So I've been working on my largest project yet, and I've found that a lot of my objects have fields that can be null. Because of this, I'm having to do something like this for every single instance:

if(box1 != null)
     box1.draw();

This doesn't seem too bad, but when you have to do that like 8 times, it makes the code seem cluttered. I feel like there could be a simpler way to do this.

grey00
  • 469
  • 2
  • 13
  • 1
    That's the only way to test for null that I know of. But if you have to do this a lot, it makes me wonder if there may be design problems with your code. – Hovercraft Full Of Eels Nov 02 '14 at 00:22
  • yes, there are times when things should and could be null and some when they should never be null. You need to learn to trust your own applications object state and if something is null then it is a fatal exception and the program should crash and you need to fix the bug. – ug_ Nov 02 '14 at 00:22
  • Read this question http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java?rq=1 and awnsers. Its a great question about this exact problem – ug_ Nov 02 '14 at 00:24

1 Answers1

1

Yes, there is another way. You can use the Null Object design pattern.

  • Define a new class EmptyBox that has an empty body for the draw method
  • Add just one check if box1 is null then set it to a new instance of EmptyBox

thanks to this you will no longer need the not-null checks.

Adam Siemion
  • 15,569
  • 7
  • 58
  • 92