Information Technology Reference
In-Depth Information
not be used with Arrays, ArrayLists, DataTables, Hashtables, ImageLists,
or many other collection classes. Coding the method using interfaces as
its parameter types is far more generic and far easier to reuse.
Using interfaces to define the APIs for a class also provides greater flexi-
bility. The WeatherDataStream class could implement a method that
returned a collection of WeatherData objects. That would look something
like this:
public List < WeatherData > DataSequence
{
get { return sequence; }
}
private List < WeatherData > sequence = new List < WeatherData >();
That leaves you vulnerable to future problems. At some point, you might
change from using a List<WeatherData> to exposing an array, a
SortedList<T>. Any of those changes will break the code. Sure, you can
change the parameter type, but that's changing the public interface to your
class. Changing the public interface to a class causes you to make many
more changes to a large system; you would need to change all the loca-
tions where the public property was accessed.
The second problem is more immediate and more troubling: The List<T>
class provides numerous methods to change the data it contains. Users of
your class could delete, modify, or even replace every object in the
sequence. That's almost certainly not your intent. Luckily, you can limit the
capabilities of the users of your class. Instead of returning a reference to
some internal object, you should return the interface you intend clients to
use. That would mean returning an IEnumerable<WeatherData>.
When your type exposes properties as class types, it exposes the entire
interface to that class. Using interfaces, you can choose to expose only the
methods and properties you want clients to use. The class used to imple-
ment the interface is an implementation detail that can change over time
(see Item 26).
Furthermore, unrelated types can implement the same interface. Suppose
you're building an application that manages employees, customers, and
vendors. Those are unrelated, at least in terms of the class hierarchy. But
they share some common functionality. They all have names, and you will
likely display those names in controls in your applications.
 
Search WWH ::




Custom Search