Information Technology Reference
In-Depth Information
Client code, written by you, never needs to know about the class Enumer-
ator<T>. All you need to know is that you get an object that implements
the IEnumerator<T> interface when you call the GetEnumerator func-
tion on a List<T> object. The specific type is an implementation detail.
The .NET Framework designers followed this same pattern with the other
collection classes: Dictionary<T> contains a private DictionaryEnumer-
ator<T>, Queue<T> contains a QueueEnumerator<T>, and so on. The
enumerator class being private gives many advantages. First, the List<T>
class can completely replace the type implementing IEnumerator<T>, and
you'd be none the wiser. Nothing breaks. Also, the enumerator class need
not be Common Language Specification (CLS) compliant. It's not public
(see Item 49). Its public interface is compliant. You can use the enumera-
tor without detailed knowledge about the class that implements it.
Creating internal classes is an often-overlooked method of limiting the
scope of types. By default, most programmers create public classes all the
time, without any thought to the alternatives. It's that VS .NET wizard
thing. Instead of unthinkingly accepting the default, you should give care-
ful thought to where your new type will be used. Is it useful to all clients,
or is it primarily used internally in this one assembly?
Exposing your functionality using interfaces enables you to more easily
create internal classes without limiting their usefulness outside the assem-
bly (see Item 26). Does the type need to be public, or is an aggregation of
interfaces a better way to describe its functionality? Internal classes allow
you to replace the class with a different version, as long as it implements
the same interfaces. As an example, consider a class that validates phone
numbers:
public class PhoneValidator
{
public bool ValidateNumber( PhoneNumber ph)
{
// perform validation.
// Check for valid area code, exchange.
return true ;
}
}
Months pass, and this class works fine. Then you get a request to handle
international phone numbers. The previous PhoneValidator fails. It was
coded to handle only U.S. phone numbers. You still need the U.S. Phone
 
Search WWH ::




Custom Search