Archive | OTHERS RSS for this section

Abstract classes or interfaces?

Many of the times, I have seen the question of what factors should one consider either to implement a functionality in terms of abstraction, and this narrows down to if one should employ abstract class or interfaces.  A few days ago I was surprised when reviewing some code and just to brainstorm the developer,  I asked him a simple question, why did you choose to use abstract class rather than an interface?  Guess the response.. I just thought its good to use abstract class rather than interfaces. I didn’t have any other question for him but found it useful to demisfy this here for him, and others who would have the same kind of response to such a question.

I do agree that the choice of using any of them can be a daunting task.I will try to summarize what I have and wha I have found useful on the internet on this post. But  lets start at looking at the definitions of each:

An abstract class is a class that cannot be instantiated but must be inherited. The class can contain some default implementation for the child classes to use, and this methods should be non abstract methods. If an abstract method need exist, then it should be modified with abstract keyword and does not contain a body.

An interface on the hand is a type definition similar to class except that it purely represent a contract between an object and its user. And so its just a collection of members definitions e.g method, properties, events etc without any implementation.

So this brings to the question of who support or does what? Here are do’s and don’ts for each of them.

  1. Instantiation: Abstract classes cannot be instantiated away from their derived classes, meaning that there constructor are called only by their derived classes. Interfaces on the hand cannot be instantiated.
  2. Abstract classes can provide abstract members which base class MUST implement while all interfaces members MUST be implemented in the base class. So you can not implement partial interface, if you don’t need an implementation or you will not use some interface members you may need to leave stubs. e.g ConvertBack method for IValueConverter is usually not implemented but most implementation of the interface leave a stub, and this bring to the Interface Segragation Principle
  3. Extensibility: Abstract classes are more extensible than interface. You can alter an abstract classes without breaking any version compatibility. And note this extensibility is for non-abstract members. Interfaces on the other hand, if you have to extend you will have to create a new interface, otherwise you break the existing clients. Consider a situation where you are employed and after sometime you get a pay rise, you actually and should sign a new contract which looks the same as the previous with with the new  salary figures appear.
  4. Virtual members: Abstract classes allows for virtual members with default implementation for the deriving classes while for interfaces all members are automatically virtual and cannot contain any implementation.
  5. Accessibility modifiers: You can control accessibility of some members in abstract classes while all members of an interface are public by default.
  6. Inheritance: Being a rule in C# specification multiple class inheritance is not supported meaning that a class cannot inherit from more than one classes. On the contrary multiple inheritance is supported with interfaces

With that in place there are some guideline you should follow when deciding which one to use and when to use it.

  1. If you anticipate to create multiple versions of a component you may use abstract classes reason being it’s easy to create and version your components. For example by changing or updating the base class all inheriting classes are automatically updated whilst in interfaces they do not support versioning. Once an interface is created it cannot be changed you will have to create a new one. The analogy being once you sign a contract with your employer, and happens you get a pay rise you sign a new contract, you don’t manipulate the previous.
  1. If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
  2. If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
  3. If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

So too much of theory lets dive and see how we can establish some, if not all of the aforementioned points. So we are going to use an aspect of polygons. Basically we have a number of polygons which have different ways of calculating their areas. So we will employ both, interface and abstract class concepts.

 public interface IRegularPolygon
 {
 int NumberOfSides { get; set; }
 int SideLength { get; set; }

double GetArea();
 }
 public class Octagon : IRegularPolygon
 {
 public int NumberOfSides { get; set; }
 public int SideLength { get; set; }

public Octagon(int length)
 {
 NumberOfSides = 8;
 SideLength = length;
 }

public double GetArea()
 {
 return SideLength * SideLength * (2 + 2 * Math.Sqrt(2));
 }
 }

We also have an abstract class approach of the same.

 public abstract class AbstractRegularPolygon
 {
 public int NumberOfSides { get; set; }
 public int SideLength { get; set; }

public AbstractRegularPolygon(int sides, int length)
 {
 NumberOfSides = sides;
 SideLength = length;
 }

public abstract double GetArea();
 }
 public class Triangle : AbstractRegularPolygon
 {
 public Triangle(int length) :
 base(3, length) { }

public override double GetArea()
 {
 return SideLength * SideLength * Math.Sqrt(3) / 4;
 }
 }

Assuming that  you have implemented you get a requirement that you need to add a way to calculate the perimeter of the polygons. And knowing that, to calculate the perimeter of a polygon is just multiplying the number of sides with the length of one side.  With the abstract class implementation it really straight forward all you need to do is as below:

 public double GetPerimeter()
 {
 return NumberOfSides * SideLength;
 }

With the interface implementation you cannot just add the function declaration since this will break the existing clients. An easier way is to have a new interface with all the previous declaration or rather employ interface inheritance where you create a new interface with the new perimeter function inheriting from the IRegularPolygon. I would go with the latter.

Just to keep the post short, we end by looking what is in the framework which employs abstract classes and intefaces. In the BCL we have System.IO.Stream class, which is an abstract class. It contains some implementation of various methods as well as abstract and virtual methods which deriving classes implements. Some of the deriving classes include:

  • MemoryStream
  • FileStream
  • BufferedStream

With the interface, we have List<T> class which implements a list of interfaces which also show interface inheritance and best application of Interface Segregation Principle. Some of the interface it implements are

IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable

So we end the post to make sure its not too long,  having demonstrated a couple of points I leave it to you to try the rest and poke me if any issue arises or if you need some clarity or some of technical engagement.

Its my hope you will consider the above mentioned points next time you find yourself in a dillema of which one to use, abstract or interfaces.

Again happy coding  and bye for now 🙂

Advertisements

Subversion Post-Commit Hooks

I came across this and I find it in order to share with my readers.

The “Hello World!” of Subversion post-commit hooks is the use of SVNnotify to send e-mails out to a project team every time a new revision is committed to the repository.

This is easier than it sounds:

Make sure svnnotify is installed on your system. I’ll leave that as an exercise for the reader.

Navigate to your repository’s hooks directory. This is almost always a directory cleverly named “hooks” right inside the top level of your repository:

cd /Users/mwest/svn/my_repository/hooks/

Create a new file called post-commit, and make it executable by the www user.


touch ./post-commit

chmod 755 ./post-commit

Open up the file you just created, and add the following bit of code:


#!/bin/sh

REPOS="$1"

REV="$2"

/usr/local/bin/svnnotify \

--repos-path "$REPOS" \

--revision "$REV" \

--subject-cx \

--with-diff \

--handler HTML::ColorDiff \

--to \

--from

It’s all pretty straightforward, so let’s take it line by line:

The first line is the so-called shebang that tells the system that the file is a shell script that ought be executed.

Next, we set two variables based on the information that Subversion passes into the script when it’s called. The post-commit hook gets two bits of data: the path to the repository, and the new revision number that the commit created.

Finally, we call svnnotify to actually generate and send a nicely formatted e-mail using the repository path and revision number that we gathered earlier. Make sure to put your e-mail address (or list’s address) in the last two lines!

Do some work, and commit it. Go check your email

Happy coding 🙂

Ola Nerdimingos

Watch this space for information on new and cool stuff on .net framework stack!!!

Keep watching!!

%d bloggers like this: