Originally posted by Tony Bateman:
Thanks for that too!
One question: on your web page you state:
"It is good practice to declare variables and parameter types with the interfaces and not the concrete classes".
Why is that?
Cheers,
Tony.
This paradigm is known as "coding to the interface not the implementation" (or something like that) and is a common way of thinking in any Object-Oriented programming language. I think Horatio's gives a good abstract explanation of the concepts, but I'd like to add a (perhaps) more concrete example.
Let's say you are working on a project where you need to index items with something other than an integer. Other languages provide this ability with some built-in type. After looking at the Collections framework in Java, you see that the
Map interface provides this functionality. You then need to choose a specific class that implements this. The typical choices are between
TreeMap, which can order the elements, or
HashMap, which does not preserve any specific order. Since ordering the elements adds some overhead and your particular project does not care about the order, you decide to use HashMap. Then you go about declaring variables, parameters, and return types with the HashMap class.
Now let's say that the requirements or design changes so that your application DOES care about ordering the elements. Now you have to go through all of your code and change HashMap to TreeMap. Obviously this will take some time and be a potential for errors.
If on the other hand, you originally declared all variables, parameters, and return types with the Map interface type, then you would only need to change a few places where you create the object! Think of the time savings this makes.
Admitedly, this example is somewhat contrived. However, I think it illustrates the benefites of using the interface instead of a particular concreate class. There are also other benefits, but I'll let you research it more if you are interested.
Keep Coding!
Layne