Tutorial :interface good practices


is it a good practice to have an interface that has no methods but just properties?


Imagine that we have two different classes that don't derive from the same base: Users and Businesses. At some point in our project, we decide that Users and Businesses both need to have a reference to elements of an address, such as Street1, Street2, City, State, and Zip. We also have a proxy class of some sort that needs to be able to manipulate these values directly, regardless of the class they are defined in.

One way to accomplish this would be to create an interface like so (example in c#):

public interface IHasAddress {    public string Street1 { get; set; }    public string Street2 { get; set; }    public string City { get; set; }    public string State { get; set; }    public string Zip { get; set; }  }  

Now, we can have a method in another class that does the following:

public static class Test {    public static void CheckZip(IHasAddress addressContainer) {      if (addressContainer == null) return;      if (addressContainer.Zip == "33314") addressContainer.State = "FL";    }  }  

As long as both User and Business implement the IHasAddress interface, the following code will compile and work as expected:

User user = new User();  Business business = new Business();  Test.CheckZip(user);  Test.CheckZip(business);  

This is a purely theoretical problem/solution, but it does prove a perfectly good need for this kind of structure.


It does not matter whether or not an interface has methods or not. The members that an interface exposes should be driven by the requirements of that interface's client.


This would make sense if you were intending to have a set of data objects with a similar base structure.


Don't forget that properties are nothing more than methods typically named get_PropertyName or set_PropertyName.

So no, I see no issue with an interface that has only properties in it. They're still methods.


This was a common way in Java to define a bunch of related constants before it got proper Enums.


I don't see anything wrong with it. If your application requires a contract to implement a bunch of properties, then so be it.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »