How to Write Interfaces for Static Classes in C#

cinterfacesstatic

I'm writing a postcode validation library, so that I can call a helper method

var result = Postcode.IsValid(postcode, country)

To that end I need to have 'classes' that represent supported countries and know how to validate each. At present I have an interface thus:

public interface IPostcode {
    bool IsValid(string postcode);
}

and I have to have classes for each country, e.g.

public class USA : IPostcode {
  public bool IsValid(string postcode) {
     // ... validate here
  }

The helper method selects the relevant IPostcode based on the country code.

The issue is that it feels wrong to have to instantiate classes that have no state or properties, just methods which would be far better if they were static. But of course static classes can't have interfaces. Is there a better pattern for this?

Best Answer

I don't think there is anything wrong with having classes without state. As long as the classes have different behavior (different postcode validation logic) they are justified.

You could kind-of achieve the same thing with static methods and using a delegate signature rather than an interface (since the interface is only a single function signature anyway) but I think using classes are more natural and straightforward.

Related Topic