Skip to content

behavioral-pattern

Null Object

Null Object Design Pattern logo

Null Object is a behavioural design pattern based on inheritance which creates a valid representation of null objects in a system, in order to avoid returning null objects, on which respective null checks would be needed to prevent NullPointerException and unexpected behaviour of the application objects.

Introduction

It’s common to write methods that return null in situations where the requested information is not present or some conditions are not met in order to execute some chunk of code. However, sometimes this behaviour is poorly documented so it takes the developers using a given API by surprise, moreover, it can force that said developers to write lots of null checks to avoid runtime exceptions.

On either way, the application code might end up with a lack of cohesion and not clean at all, because now this chunk of code has to deal with a “null possible situation” and take decisions that would not be supposed to be taken by itself.

The Null Object design pattern comes to work on this problem, basically, instead of returning null where an object of class Foo was expected, one could return an object of a subclass of Foo in a basic valid state but at the same time, adhering to Foo‘s contract.

Read More »Null Object

Design Patterns

Design Patterns Logo Image


Design patterns are a collection of abstract solutions to recurrent problems in object-oriented software development. These solutions are presented like templates that can be applied in many situations and programming languages, but with similar structures, providing a design which contributes to system’s flexibility, extensibility, portability and code reuse.

Read More »Design Patterns