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?

4
  • 1
    Its called a marker interface, however this is all sorts of duplicate Commented Jan 11, 2019 at 9:36
  • I know how it called, its about null object pattern. So that maby exception from marker as far as null object itself breaks some rules already. Thats why im asking. Commented Jan 11, 2019 at 9:49
  • "null object" doesn't mean "empty interface", however. It just means "an object value that is semantically equivalent to nothing". Commented Jan 11, 2019 at 9:59
  • Have you thought about Optional? Does it make sense to your problem? Commented Jan 11, 2019 at 10:25

1 Answer 1

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!");
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Well, you simply implement it properly as wiki suggest. 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.