Remus
Remus

Reputation: 1443

Is the use of blank interfaces a bad design?

I'm considering creating an interface and applying it to all objects in a certain namespace.

Scenario in which I would use this: I want to create a generic handler of those objects, and I'd like to enforce the generic parameter to only accept types that implement this particular interface.

Is this a bad design, or are blank interfaces acceptable?

Upvotes: 6

Views: 1669

Answers (6)

Chris Shaffer
Chris Shaffer

Reputation: 32575

What you are talking about doing is known as Marker Interfaces.

I've used this technique successfully in the past, but I would question whether the artificial limitation you are placing on your generic class is actually necessary. If so, then this is certainly a quick and compile checked method of accomplishing it.

Upvotes: 2

Ondrej Tucny
Ondrej Tucny

Reputation: 27974

No, it's not bad design. Providing reasonable constraints on generic arguments helps maintain code safety and readability. Furthermore, you can be quite sure the interface won't remain empty forever.

Upvotes: 2

Mike Caron
Mike Caron

Reputation: 14561

There's nothing... Wrong with using a blank interface, I guess. Just, the point of an interface is to define a common set of functionality that may vary in how its implemented.

It won't make coding any easier, since you're effectively working with a black-box (object, as some may call it).

Honestly, though, if I were implementing such an open ended architecture, I'd just go with regular old object.

Upvotes: 0

deanvmc
deanvmc

Reputation: 6095

My personal understanding of an interface is that it forms the public contract between one or more objects. The idea is simple, you can build your code base up using interfaces without worrying about implementation. Having said that it is an interesting question because you are technically trying to inforce a contract. I would say go ahead.

Upvotes: 1

Christian Mann
Christian Mann

Reputation: 8125

Why are you creating this interface if it's blank? What are the contents of each class? Is there any commonality between them? If the answer to that question is no, then why are you making an interface for each?

If you have a good reason for making a blank interface, it's probably alright. But think about it and see whether you can put anything into that interface that is common between the elements.

Upvotes: 0

Gerrie Schenck
Gerrie Schenck

Reputation: 22368

Nothing wrong with them in my opinion. A lot of their strength lies in combination with (generated) partial classes.

Upvotes: 1

Related Questions