开发者

Creating null reference

class A{

A(int i){
}
}

A obj=new A(1);
开发者_运维问答

while creating Object if i pass positive numbers object must be created. A obj=new A(-1); If negetive numbers are passed it object must not be created.

How to adjsut the constructor to do this


If you don't want an object to be created, don't call new. Calling new always creates an object, even if it then gets thrown away due to an exception. If you just want to avoid the caller from receiving an object as a result of the constructor call, you could make your constructor throw an exception. If you want them just to receive a null reference, you can't do that in a constructor.

However, you could have a static method instead, which then conditionally calls new or returns null:

public class A
{
    public static A createIfNonNegative(int i)
    {
        return i < 0 ? null : new A();
    }
}


You can use Null Object pattern. In that case object will be created but with logic null state.


As an alternative to Jon Skeet (obviously) excellent answer, you can also throw an exception from constructor :

class A{

    A(int i){
        if(i<0) {
            throw new NumberBelowZeroException(i); // implementation of this exception is left as an exercise
        }
    }
}

A obj=new A(1);

This way, the object will be constructed (as constructor, by having been called, ensures object exists), but it will indicate clearly that it is not usable.


There are several approaches:

  1. The logic depending of the value of i encapsulated in the same level. In this case condition checking is needed, even if it returns null:
    A a = createAInstance(i);
    if(a == null) { // do something }
    else { // do something else }
    
    so depending on the algorithm you can check the condition at the level where you use A a:
    if(i >= 0) { A a = new A(i); // do something }
    else { // do something else }
    
  2. The logic is implemented in A only: use Null Object to implement a null stub for A, and the code dealing with A instance shouldn't feel the difference;
  3. the logic is mixed: use Null Object as in 2.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜