Java: Refactor Code by Introducing NULL Object
By admin on Oct 5, 2008 in Java, Programming, Refactoring
This is from the Refactoring book by Martin Fowler.
In our code we always need to check if a object is null, and depending on it, different actions are taken.
E.g. for the following code
1: if (subscriber == null) {
2: ratePlan = defaultRatePlan;
3: } else {
4: ratePlan = subscriber.getRatePlan();
5: }
The rationale is that if in our code we always need to check for NULL value for an object, it is good that we create a NULL object for the value object.
For the above code example, I can create a NullSubscriber object in this case.
1:
2: public class NullSubscriber extends Subscriber {
3:
4: ...
5:
6: public boolean isNull() {
7: return true;
8: }
9:
10: public RatePlan getRatePlan(){
11: return defaultRatePlan;
12: }
13: }
The NULL object extends Subscriber and implements the isNull method. Subscriber class also implements the isNull method and a static factory method to create the NULL object.
1: public class Subscriber {
2: private RatePlan ratePlan;
3:
4: protected Subscriber() {
5:
6: }
7: public RatePlan getRatePlan() {
8: return ratePlan;
9: }
10:
11: public void setRatePlan(RatePlan ratePlan) {
12: this.ratePlan = ratePlan;
13: }
14:
15: public boolean isNull() {
16: return false;
17: }
18:
19: static Subscriber newNull() {
20: return new NullSubscriber();
21: }
22:
23: }
In the class that return Subscriber object, I need to modify it to return the NULL subscriber if the object is null
1: public Subscriber getSubscriber() {
2: if (subscriber == null) return Subscriber.newNull();
3: return subscriber;
4: }
As you can see, the behavior is now moved to the NULL object. So the checking for null can now be removed.
1: if (subscriber == null) {
2: ratePlan = defaultRatePlan;
3: } else {
4: ratePlan = subscriber.getRatePlan();
5: }
6:
7: // For the above can be simplified to
8: ratePlan = subscriber.getRatePlan();
Now I can assign the rate plan directly.
Sorry, comments for this entry are closed at this time.