Monday, June 30, 2014

Interfaces: Better Design, How & When to Use

An interface contains only the signatures of methods, properties, events or indexers = like a list of WHAT needs to be done by everything that implements (claims) the interface. The interface itself is only allowed to list them! Not use, define, or implement them on its own!

A class or struct that implements the interface must implement the members of the interface = takes that list of WHAT and shows you exactly HOW by defining the actual methods, properties, events or indexers. Showing is doing!

The typical naming convention is to put the letter "I" before the name of the interface. Let's say I have an interface for recipes! I will call on what it is, define a name with the letter "I" before.. and have it return void (return void means don't return anything). This is a sample of where I have a set of recipes that should be findable and listable on a website! Note how the two things I want it to do will be split into the interface and class files. First is the interface:

Here is the class:

We use interfaces in order to make things easy to edit and change in the future! It makes less work for us now, less work for us later.. and the only thing it requires is a little planning ahead! You want to always keep all of your pieces separate from one another.. individual working parts that can be interchanged. We would be quite upset if for example someone fused your engine to your gas tank and your steering wheel.. and you had to take apart all of those if one went out or was upgraded. So the same applies here, you keep the parts neat and within the bounds of their function and then use interfaces to link the pieces together. A class can have none, one, or many interfaces. Interfaces are an integral part of good design for architecture that is easy to use and modify for the future (be nice to fellow future selves and other developers!).