0

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?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
nuclear sweet
  • 1,079
  • 10
  • 27

1 Answers1

0

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!");
    }
}
nuclear sweet
  • 1,079
  • 10
  • 27
  • 1
    Well, you simply implement it [properly as wiki suggest](https://en.wikipedia.org/wiki/Null_object_pattern#C#). And otherwise nobody except you could guess about `IResult` wrapper (question was too abstract). Could you explain an advantage? I guess your solution should have some disadvantages, e.g. if you have `Foo` variable you have to set it in ugly way, while earlier you could have `IFoo` (but as you say, if interface is empty, then usability of such type is pretty low) without need to cast. – Sinatr Jan 11 '19 at 10:36