Empty interface for Null Object pattern

449 Views Asked by At

I have some DTO object for transfer data with WCF.

public class Foo
{
    //Many fields
}

WCF service method returns this object, and I have the valid case when this object should be null.

I want to use the null object pattern to return something instead of null to make this code more clear.

So, I implemented it as:

public interface IFoo
{
   //empty
}


public class NoFoo : IFoo
{
   //empty
}

public class Foo : IFoo
{
    public static IFoo NoFoo { get; } = new NoFoo();

    //Many fields
}

Usage of class Foo not require IFoo outside of null check. But i feel like empty interface is a code smell for sure. But if i will add all (or any) members of Foo to IFoo, these members will be never used. Because interface used only for null object pattern. So, I don't understand, what is the right way in this situation?

1

There are 1 best solutions below

1
nuclear sweet On

So i find out better way to achieve what i want. I put Foo inside IResult container that implement null object pattern.

public interface IResult
{
    Foo Foo { get; }
}

public class Result : IResult
{
    public static IResult NoResult = new NoResult();

    public Foo Foo { get; private set; }

    public Result(Foo foo)
    {
       Foo = foo;
    }

    private class NoResult : IResult
    {
        public Foo Foo => throw new NotImplementedException("Null object!");
    }
}