First pattern, simple as can be: Null Object. Say you have some operation that returns a
Sprite
object that you then do something to. What if there is no sprite? You could return NULL
or nil
or None
or whatever your language of choice calls the thing. But then you have to check the returned value:If instead you return asprite = some_operation() if sprite: sprite.do_something()
Sprite
instance that simply doesn't do anything, your code becomes a little more straightforward:Not exactly a big deal, but of course it could add up to something more significant if you were using this in a more complicated way.sprite = some_operation() sprite.do_something()
It's certainly not a good idea to always ignore the fact that you didn't find the sprite in question, for example you don't want to keep inserting
NullSprite
objects into a list over and over. So when you do care, you need a way of telling that it's a real sprite. One way is to guarantee that only a single NullSprite
is ever created and to make that one globally accessible. Then, in places where you care, you can say this:Whether Null Object is particularly useful therefore depends on how often you care versus how often you don't care (but still have to check if you use the language's builtin version of "no such object"). As with all design patterns: Think before you apply the pattern!sprite = some_operation() if sprite is not Sprite.NULL: sprite.do_something()
No comments:
Post a Comment