3

Lets say I have an abstract object which can be implemented by multiple, separate plugin authors. (For instance, a bug database connection) I don't want consumers of my bits to have to deal with each specific plugin type.

I also want to separate the process of parsing a configuration file from the process of actually initializing database plugins and other such things.

To that end, I came up with something like this:

public interface IConfiguration
{
    // No members
}

public interface IConnection
{
    // Members go in here
    void Create();
    void Update();
    void Delete();
}

public interface IConnectionProvider
{
    // Try to interpret file as a configuration, otherwise return null
    IConfiguration ParseConfiguration(Stream configurationContents);
    IConnection Connect(IConfiguration settings);
}

public class ThingyRepository
{
    // Lets say there is a constructor that initializes this with something
    List<IConnectionProvider> providers;

    // Insulates people from the actual connection provider
    KeyValuePair<IConfiguration, IConnectionProvider> Parse(string filename)
    {
        IConnection result = null;
        IConnectionProvider resultProvider = null;
        foreach (var provider in this.providers)
        {
            using (Stream fs = OpenTheFileReadonly(filename))
            {
                IConnection curResult = provider.ParseConfiguration(fs);
                if (curResult == null)
                {
                    continue;
                }
                else
                {
                    if (result == null)
                    {
                        result = curResult;
                        resultProvider = provider;
                    }
                    else
                    {
                        throw new Exception ("ambguity!");
                    }
                }
            }
        }

        if (result == null)
        {
            throw new Exception ("can't parse!");
        }

        return new KeyValuePair<IConfiguration, IConnectionProvider>(
            result, resultProvider);
    }
}

My question is, I've got this empty interface which is supposed to serve as an opaque handle to whatever settings were loaded from the indicated file. The specific implementer of IConnectionProvider knows what bits it needs in its configuration that it would load from a file, but users of this library should be insulated from that information.

But having an empty interface seems strange to me. Does this sort of thing make sense or have I done something horribly wrong?

6
  • 2
    It is an old Java hack. There's no point to it in C# when you got attributes. Jan 22, 2013 at 1:16
  • 1
    Except that an attribute can't be used as a GTP, such as the key type of a Dictionary or the element type of a List. I think they have their place, if used sparingly and for good reason. Code smell, maybe, but not bad practice out-of-hand.
    – KeithS
    Jan 22, 2013 at 1:29
  • @Hans: What value would using an attribute give here? Jan 22, 2013 at 1:40
  • I think IConnection curResult = provider.ParseConfiguration(fs); Should be IConfiguration curResult = provider.ParseConfiguration(fs); and there should be a call to the Connect method to convert Iconfiguration to IConnection. As such it's hard for me to see the idea behind this code. What are the consumers? Are they going to consume the KeyValuePair<IConfiguration, IConnectionProvider> collection? How are they going to use IConfiguration interface that it provides? It looks that the code sample is a bit out of wack. Jan 22, 2013 at 2:35
  • @zespri: I threw together a minimal example that would demonstrate the point; not something which necessarily matches the code I was working on when I came up with the question. Jan 22, 2013 at 5:41

2 Answers 2

2

The basic concept of an interface with no members, that simply identifies implementors as being something instead of the interface's normal job of identifying what an object has or does, is known as a "flag interface". It has its uses, but use them sparingly. I, for instance, typically use them in a hierarchical format to identify domain objects that should be persisted to a particular data store:

//no direct implementors; unfortunately an "abstract interface" is kind of redundant
//and there's no way to tell the compiler that a class inheriting from this base 
//interface is wrong,
public interface IDomainObject
{
   int Id {get;}
}

public interface IDatabaseDomainObject:IDomainObject { }

public interface ICloudDomainObject:IDomainObject { }

public class SomeDatabaseEntity:IDatabaseDomainObject
{
    public int Id{get;set;}

    ... //more properties/logic
}

public class SomeCloudEntity:ICloudDomainObject
{
    public int Id{get;set;}

    ... //more properties/logic
}

The derived interfaces tell me nothing new about the structure of an implementing object, except that the object belongs to that specific sub-domain, allowing me to further control what can be passed where:

//I can set up a basic Repository pattern handling any IDomainObject...
//(no direct concrete implementors, though I happen to have an abstract)
public interface IRepository<T> where T:IDomainObject
{
    public TDom Retrieve<TDom>(int id) where TDom:T;
}

//... Then create an interface specific to a sub-domain for implementations of
//a Repository for that specific persistence mechanism...
public interface IDatabaseRepository:IRepository<IDatabaseDomainObject>
{
    //... which will only accept objects of the sub-domain.
    public TDom Retrieve<TDom>(int id) where TDom:IDatabaseDomainObject;
}

The resulting implementations and their usages can be checked at compile-time to prove that an ICloudDomainObject isn't being passed to an IDatabaseRepository, and at no time can a String or byte[] be passed into the repository for storage. This compile-time security isn't possible with attributes or properties, which are the other primary ways to "flag" a class as having some special significance.

So in short, it's not bad practice per se, but definitely ask yourself what you want out of the flag interface, and ask yourself if any state or logical data that would commonly be implemented on an IConfiguration (perhaps the name or other identifier of said configuration, or methods to load or persist it to the chosen data store) could do with some enforced standardization.

3
  • In this case it isn't even that -- I could just as easily replace "IConfiguration" with "object" and everything would still work. Jan 22, 2013 at 1:40
  • Your "tag interface" example looks like it would be better served by adding a property to the interface returning an enum, and the enum have values "Cloud" and "Database". (This allows someone to inherit from "IDomainObject" directly which presumably would break your invariants) Jan 22, 2013 at 1:42
  • If a programmer inherits directly from IDomainObject, they couldn't use any existing code to persist the object; there are no direct implementations of IRepository<IDomainObject> so it should be pretty obvious they screwed up. In addition, an interface property can't be checked at compile-time like a GTP can; the enum would have to be checked, and errors thrown and tested for, at runtime, where here I know before the application ever starts that I'm passing an object to the wrong Repository.
    – KeithS
    Jan 22, 2013 at 2:04
0

I think this is entirely valid. I'm designing an API where the caller has to first get an opaque "session" object and then pass it in to subsequent calls.

Different implementations of the API will use totally different implementations of the session object, so the session object clearly isn't an abstract class with different subclasses; it's an interface. Since the session object has no behavior visible to the caller, it seems to me the only logical model for this is an interface with no members.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.