Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coding to interfaces? [duplicate]

Tags:

java

oop

I want to solidify my understanding of the "coding to interface" concept. As I understand it, one creates interfaces to delineate expected functionality, and then implements these "contracts" in concrete classes. To use the interface one can simply call the methods on an instance of the concrete class.

The obvious benefit is knowing of the functionality provided by the concrete class, irrespective of its specific implementation.

Based on the above:

  1. Are there any fallacies in my understanding of "coding to interfaces"?
  2. Are there any benefits of coding to interfaces that I missed?

Thanks.

like image 985
Ari Avatar asked Dec 28 '09 18:12

Ari


People also ask

How do you avoid code duplication?

Don't Repeat Yourself (DRY): Using DRY or Do not Repeat Yourself principle, you make sure that you stay away from duplicate code as often as you can. Rather you replace the duplicate code with abstractions or use data normalization. To reduce duplicity in a function, one can use loops and trees.

Why is code duplication not recommended?

It's safe to say that duplicate code makes your code awfully hard to maintain. It makes your codebase unnecessary large and adds extra technical debt. On top of that, writing duplicate code is a waste of time that could have been better spent.

What is duplicate code in C#?

In computer programming, duplicate code is a sequence of source code that occurs more than once, either within a program or across different programs owned or maintained by the same entity. Duplicate code is generally considered undesirable for a number of reasons.

How do I ignore duplicate codes in Intellij?

Ignore names and values while searching for duplicates Press Ctrl+Alt+S to open the IDE settings and select Editor | Duplicates. Select file types to which the analysis should apply and select the checkboxes next to the constructs that you want to anonymize. Apply the changes and close the dialog.


1 Answers

Just one possible correction:

To use the interface one can simply call the methods on an instance of the concrete class.

One would call the methods on a reference of the type interface, which happens to use the concrete class as implementation:

List<String> l = new ArrayList<String>();
l.add("foo");
l.add("bar");

If you decided to switch to another List implementation, the client code works without change:

List<String> l = new LinkedList<String>();

This is especially useful for hiding implementation details, auto generating proxies, etc.

You'll find that frameworks like spring and guice encourage programming to an interface. It's the basis for ideas like aspect-oriented programming, auto generated proxies for transaction management, etc.

like image 52
duffymo Avatar answered Oct 24 '22 09:10

duffymo