Choosing: Interface vs. Abstract Class(kirillosenkov.blogspot.com)

submitted by KirillOsenkovKirillOsenkov(570) 4 years, 8 months ago

When to use which? Where's the difference? What are the best practices recommended by .NET architects? This and some personal experiences in a blog posting by Kirill Osenkov

2 comments |category: |Views: 60

tags: another

new Add a live kick counter to your blog >> liveImage

You can even customize the image by choosing your own colors, and then clicking the button below to update the preview and the html code:

  • "Kick It" text
  • "Kick It" background
  • kick count text
  • kick count background
  • border

Simply copy and paste this HTML into your blog post.


Users who kicked this story:
Comments:

posted by senfosenfo(881) 4 years, 8 months ago 0

I'd actually argue that this article takes the wrong approach at deciding when to choose an interface versus an abstract class because it assumes that a default implementation can be assumed for any new functionality. For me, the question to determine which to use is simple. Do I have a default implementation that I would like to apply to any part of the contract? If the answer to that question is "yes", I have little choice to use anything other than an abstract class. Otherwise, I will always choose an interface. The reason is that classes can extend any number of interfaces, whereas a class can extend only a single abstract class.

The only situation in which new functionality can be added to an abstract class without breaking client code is when a default implementation can be designed. The idea of interfaces and abstract classes is to ensure that clients implement their classes to the specifications of the contract. That said, the only way to keep from breaking client code by adding new functionality to an abstract class would be to provide some level of implementation to the new functionality. If no default implementation can be assumed, a stub would have to be created, which could lead to undesirable and confusing affects. For example, during maintenance, a developer might mistakingly assume that the functionality has already developed in the base class, when in reality, it was not. In this situation, I would argue that it's better to break the client code to make it clear that further implementation is required.

Reply

posted by ksuhksuh(0) 4 years, 8 months ago 0

No.

You can still create an interface. You can then create a concrete class that implements that interface. That would be your default implementation. Of course, if all you can come up with is one implementation of the interface, then creating the interface probably isn't all that useful.

Clients should then use composition to use the concrete class, rather than inheriting from it.

IDataReader is the classic example in the .NET framework.

Reply

information Login or create an account to comment on this story