Null object pattern java

Null object pattern java

Null object design pattern is one of the behavioral patterns. In the null object design pattern, an object is defined, which has no value or zero value, hence, a null object. The uses of such object along with their behavior are described by the null object design pattern. The ‘Pattern Languages of Program Design’ book series were the first to publish this pattern.

Null Object Pattern

The intent of a Null Object is to encapsulate the absence of an object by providing a substitutable alternative that offers suitable default do nothing behavior. In short, a design where “nothing will come of nothing.

The pattern is implemented in object-oriented programming languages, for example, Java or C#. The implementation in these languages is such that the references may be null. Before implementing any methods, these references need to be checked in order to ensure that they are not null because the methods cannot be implemented on null references. To forward the message of the absence of a particular object, for example, a client who does not exist, programmers do not use null references, instead of that, they use an object that serves the expected interface but its method body is empty. This approach has an advantage over the working default implementation, which is the predictability of the null objects. Also, it is not capable of doing anything and therefore, it has no side effects.

Sample Implementation of Null Object Pattern

For example, consider a function that retrieves a list of the files, present in a folder and performs an operation on each file. In case, it comes across a folder that is empty, it has to return a response which could be merely a null reference instead of a list. The design can get complicated when the code expects a list and it has to verify that it, in fact, has a list. If a null object is returned, there is no need for the verification of the return value, whether it is a list or not. The object can be iterated as normal, without having to do anything, by the calling function. But, the return value still can be checked, that whether it is a null object or not. The null object design pattern can also be used a tool for testing.

Читайте также:  Encoding utf8 getbytes java

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Pattern“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.

Spring-5-Design-Pattern

For example, to test the availability of a certain feature such as a database. The structure of the null object design pattern is such that it contains, Abstract Class, Real Class, Null Class, and Client. The abstract class has to define the abstract primitive operations which are defined by the concrete implementations. The Real Class is responsible for implementing the Abstract class, performing some real operations. The Null class implements the abstract class, which do nothing. It does that so that a non-null object is passed to the client. The client receives the implementation of the abstract class and uses it. The fact that the received object is a null object or a real object, does not matter to the client because both of them are used the same way. The null object design pattern removes the old functionality and replaces it with null objects. The null object has a ‘do nothing’ code put in them, this is to avoid the blocks for do-nothing code. The advantage of doing it is that the present code does not need to be changed or altered.

UML Diagram of the Null Object Design Pattern

Null Object Pattern

Let’s see the following UML diagram about this design pattern and it’s components classes.

Client

AbstractObject

It declares the interface for Client’s collaborator and its implements default behavior for the interface common to all classes, as appropriate.

RealObject

It defines a concrete subclass of AbstractObject whose instances provide useful behavior that Client expects.

NullObject

It provides an interface identical to AbstractObject’s so that a null object can be substituted for a real object.

Example for Null Object Design Pattern

Step 1: Create an interface.
Animal.java

/** * */ package com.doj.patterns.behavior.nullobject; /** * @author Dinesh.Rajput * */ public interface Animal

Step 2: Create concrete classes implementing the above interface.
Dog.java

package com.doj.patterns.behavior.nullobject; /** * @author Dinesh.Rajput * */ public class Dog implements Animal < String name; public Dog(String name) < this.name = name; >@Override public void makeSound() < System.out.println("woof!"); >@Override public boolean doNilSound() < return false; >>

NullAnimal.java

/** * */ package com.doj.patterns.behavior.nullobject; /** * @author Dinesh.Rajput * */ public class NullAnimal implements Animal < @Override public void makeSound() < System.out.println("No Sound. "); >@Override public boolean doNilSound() < return true; >>

Step 3: Create AnimalFactory Class.

AnimalFactory.java

/** * */ package com.doj.patterns.behavior.nullobject; /** * @author Dinesh.Rajput * */ public class AnimalFactory < public static final String[] names = ; public static Animal getAnimal(String name) < for (int i = 0; i < names.length; i++) < if (names[i].equalsIgnoreCase(name))< return new Dog(name); >> return new NullAnimal(); > >

Step 4: Use the AnimalFactory to get either Dog or NullAnimal objects based on the name of animal passed to it.
NullPatternDemo.java

/** * */ package com.doj.patterns.behavior.nullobject; /** * @author Dinesh.Rajput * */ public class NullPatternDemo < /** * @param args */ public static void main(String[] args) < Animal dog = AnimalFactory.getAnimal("Tommy"); Animal cat = AnimalFactory.getAnimal("NULL"); System.out.println("Animal's Sound"); dog.makeSound(); cat.makeSound(); >>

Step 5: Let’s run the above demo class and verify the output.

Animal's Sound woof! No Sound.

Источник

Читайте также:  Php сделать zip архив

Null Object

In most object-oriented languages, such as Java or C#, references may be null. These references need to be checked to ensure they are not null before invoking any methods, because methods typically cannot be invoked on null references. Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), one uses an object which implements the expected interface, but whose method body is empty. The advantage of this approach over a working default implementation is that a Null Object is very predictable and has no side effects: it does nothing.

# Explanation

We are building a binary tree from nodes. There are ordinary nodes and «empty» nodes. Traversing the tree normally should not cause errors, so we use null object pattern where necessary.

Null Object pattern handles «empty» objects gracefully.

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral («null») behavior. The null object design pattern describes the uses of such objects and their behavior (or lack thereof).

Programmatic Example

Here’s the definition of Node interface.

public interface Node  String getName(); int getTreeSize(); Node getLeft(); Node getRight(); void walk(); > 

We have two implementations of Node . The normal implementation NodeImpl and NullNode for empty nodes.

@Slf4j public class NodeImpl implements Node  private final String name; private final Node left; private final Node right; /** * Constructor. */ public NodeImpl(String name, Node left, Node right)  this.name = name; this.left = left; this.right = right; > @Override public int getTreeSize()  return 1 + left.getTreeSize() + right.getTreeSize(); > @Override public Node getLeft()  return left; > @Override public Node getRight()  return right; > @Override public String getName()  return name; > @Override public void walk()  LOGGER.info(name); if (left.getTreeSize() > 0)  left.walk(); > if (right.getTreeSize() > 0)  right.walk(); > > > public final class NullNode implements Node  private static final NullNode instance = new NullNode(); private NullNode()  > public static NullNode getInstance()  return instance; > @Override public int getTreeSize()  return 0; > @Override public Node getLeft()  return null; > @Override public Node getRight()  return null; > @Override public String getName()  return null; > @Override public void walk()  // Do nothing > > 

Источник

How to create Null Object Pattern in Java

How to create Null Object Pattern in Java - images/logos/oopjava.jpg

In Null Object Pattern a null object replaces the check of NULL object instance. This is useful when you don’t want to have null objects, but instead you need an object with default values.

Implementation

  • one class will define the real objects
  • the second class will define the Null Object used in case a real object is not define.

Will pick the example with a simple model interface.

package com.admfactory.pattern; public interface Model

The implementation for the real object.

package com.admfactory.pattern; public class User implements Model < private int id; private String name; public User(int id, String name) < this.id = id; this.name = name; >@Override public int getId() < return id; >@Override public String getName() < return name; >@Override public String toString() < return String.format("[id:%d,name:%s]", getId(), getName()); >> 

The implementation for the Null Object.

package com.admfactory.pattern; public class NullUser implements Model < @Override public int getId() < return 0; >@Override public String getName() < return "Null User"; >@Override public String toString() < return String.format("[id:%d,name:%s]", getId(), getName()); >> 

Also a factory class is needed to return the object if exists or instead to return a Null object.

To be more easier the factory class will create all the users and will store it in a local Hashtable. In real world this class will handle the database reading.

package com.admfactory.pattern; import java.util.Hashtable; public class UserFactory < private static Hashtableusers = new Hashtable(); static < Model u1 = new User(1, "John"); users.put(String.valueOf(u1.getId()), u1); Model u2 = new User(2, "Jan"); users.put(String.valueOf(u2.getId()), u2); Model u3 = new User(3, "Jose"); users.put(String.valueOf(u3.getId()), u3); >public static Model getUser(int id) < String key = String.valueOf(id); Model user = users.get(key); if (user == null) user = new NullUser(); return user; >> 

Example

Simple example using the Null Design Pattern implementation.

package com.admfactory.pattern; public class NullPatternExample < public static void main(String[] args) < Model u1 = UserFactory.getUser(1); Model u2 = UserFactory.getUser(2); Model u3 = UserFactory.getUser(3); Model u4 = UserFactory.getUser(4); Model u5 = UserFactory.getUser(5); System.out.println("Java Null Design Pattern Example"); System.out.println(); System.out.println(u1.toString()); System.out.println(u2.toString()); System.out.println(u3.toString()); System.out.println(u4.toString()); System.out.println(u5.toString()); >> 

Output

Java Null Design Pattern Example [id:1,name:John] [id:2,name:Jan] [id:3,name:Jose] [id:0,name:Null User] [id:0,name:Null User] 

You can notice that the u4 and u5 object are not present in the hashtable and an instantiation of Null object is return for these.

Источник

Оцените статью