Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface without any members - bad practice? [duplicate]

Tags:

Possible Duplicate:
What is the purpose of a marker interface?

Is it bad practice to create a completely empty interface such as:

public interface ISomething { } 

There is a case where I would like to treat certain objects differently than others, but I don't require any new behavior.

like image 488
Erix Avatar asked Jul 22 '10 16:07

Erix


People also ask

Can you create an interface without any members?

Interfaces are meant to describe behavioral contracts. An empty interface doesn't describe any behavior - you're not defining any form of contract here. The design guidelines for interfaces specifically says: Avoid using marker interfaces (interfaces with no members).

Are empty interfaces bad practice?

Generally, yes. By definition, empty interfaces provide you nothing. They can be marker interfaces (generally evil), or aliases for another type (occasionally useful due to legacy code when renaming something).

Should I create an interface for every class?

In most cases, a final class is the best thing you can create. If a user doesn't like your class, they can simply choose not to use it. However, if you're building up a hierarchy of objects you should introduce an interface for every class.

CAN interface have no methods?

Yes, you can write an interface without any methods. These are known as marking interfaces or, tagging interfaces. A marker interface i.e. it does not contain any methods or fields by implementing these interfaces a class will exhibit a special behavior with respect to the interface implemented.


2 Answers

I personally think that empty interfaces are not a good thing.

Interfaces are meant to describe behavioral contracts. An empty interface doesn't describe any behavior - you're not defining any form of contract here.

The design guidelines for interfaces specifically says:

Avoid using marker interfaces (interfaces with no members).

Custom attributes provide a way to mark a type. For more information about custom attributes, see Writing Custom Attributes. Custom attributes are preferred when you can defer checking for the attribute until the code is executing. If your scenario requires compile-time checking, you cannot comply with this guideline.

like image 104
Reed Copsey Avatar answered Oct 14 '22 23:10

Reed Copsey


Have you considered using an attribute instead of an interface? That would usually be my approach. Admittedly it's slightly harder to test for the presence of an attribute than whether an object implements an interface, but it feels like a better fit in general.

like image 23
Jon Skeet Avatar answered Oct 14 '22 21:10

Jon Skeet