Archive | August 2013

Understanding delegates, events and event handler.

This is the first post in a series of posts focussing on event, delegates and event handlers. In the series we will discuss what each and what its role in event driven programming. The first post will be theory where we bring into focus what each is and we will try to explain using a simple example.

In this post we are going to look at delegates, events and event handler and understand how each of them depend on the other to work. A delegate in C# is more like a function pointer in C++. By function pointer, means that, it means that the delegate points to a function , and so it will know which function to call at runtime. Basically, a delegate is a specialized .NET class.  So at runtime, a class is generated for every delagate you declare. This generated class inherit from MultiCastDelegate class which tracks the subscribers.

Delegates, plays a major role in event driven programming, as it acts as the glue/pipeline through which the event sends or communicates with the event handler. Its through the delegates that you pass the events arguements to event handlers.

Event arguments encapsulate the actual data from the event to the event handler. For example, in windows application, we have useful event like mouse click, which passes lot of data including x and y co-ordinates of the clicked point. We have others like button click event which has minimal data to pass.

Event Handler, is a method that gets data from a delegate, and process it appropriately. The difference with other methods is that its signature is dictated by the delegates itself. But most of the event handlers and delegates takes two parameter, sender and EventArgs. The sender represents whoever raised the event or who owns the event. e.g OnClick, the sender is the button as its the one to be clicked. EventsArgs is extra data which the handler of the event might find useful.

Event are a way of notification and are used every in .net framework. They provide a way to trigger notification and alert from the interaction of the program either by a user or other programs. In short they signal an occurence of an action. Once an event is raised, it passes data (EventArgs) which is very important to the method responding to it. And so between an event and event handler there is a delegate, otherwise you are just calling a function just like any other. You can raise an event in two ways

  1. calling the event like methods
  2. access the events delegate and invoke it directly

The best way to explain is a hospital set up, we have a doctor, patient and the receptionist. Once a new patient arrives he provides information to a receptionist. We can have more than one receptionist, doctor and patient as well. The receptionist takes paperwork containing patient information as well as his (Receptionist) name so that the doctor can know who attended the patient. The hospital protocal is that a patient should not go straight to the doctor.  So medium to pass information to the doctor is the receptionist. With reference to the explanation we have so far we can deduce the following:

-Patient: Is the event raiser/he will own the event.

-Doctor: Event handler. He knows how to treat the patient

-Receptionisht: Delegate. He knows the doctor who will treat the patient given a patient.

-Patient information: Event args.

We can define our event like PatientArrived. So when the doctor arrives in the hospital he prepares himself and alerts the receptionist that he can now attend to patient who arrives. So this means he can handle PatientArrived event.

Hope this makes it easier to understand the concept behind Events, Delegates and Event handler.

In the next blog we will now present this information using code and you will see how each will come into play.

Happy coding ūüôā

Strategy design pattern demystified

By definition from wikipedia, strategy pattern also called as policy pattern is a software design pattern whereby an algorithm behaviour can be selected at runtime. Using the pattern you define a family of algorithms and making them interchangeable.

With strategy pattern the specific behaviors should not be inherited and to avoid this you use interfaces to abstract the behavior with which each of the strategy implementation should implement. And this should be in harmony with the open/closed principle which states that classes should be open to extensibility and closed to modifications.

The pattern is really simple, nice pattern to get started on design patterns and very applicable as implement algorithms on a daily basis.

The purpose for this design pattern includes but not limited to the following:

  • ¬†Encapsulates a family of related algorithms
  • ¬†It allows various algorithm to vary and evolve separately from the context (Context being the class using them)
  • ¬†Allowing a class to maintain a single purpose

Some of the red flag to know that you need to implement this pattern in you code might include:

  • Switch statement in code
  • Adding a new way of implementation of a certain algorithm will include adding a new file for that specific implementation.

In this post we are going to consider, a situation where we are required to calculate both weighted and simple average mean of some given rating e.g could game rating, restaurant rating etc,etc. Just from the requirement you can easily see that we will probably need some different ways of implementing each of them, since hardly can you get one from the other. And this now will prompt to us to use strategy pattern to implement the different algorithms.

Assuming we have the following Review class which will contain a rating property:

public class Review
{
public int Rating { get; set; }
}

For us to be in harmoney with Open/Closed principle, since the two algorithm are involved in computing then we will have an interface with one function, simple as:

internal interface IRatingAlgorithm
{
int Compute(IList<Review> reviews);
}

And therefore any algorithm that needs to be in this family of algorithm, MUST implement this interface. And in case we need to introduce some other algorithms then we will just create a new class that implement the interface, and not modifying the existing ones (Hope now you can see the Open/Closed principle at work). Our first implementation is for simple average mean which uses LINQ average extension function

    internal class SimpleRatingAlgorithm : IRatingAlgorithm
{

public int Compute(IList<Review> reviews)
{
return (int)reviews.Average(r => r.Rating);
}
}

Easy huh? The weighted version go like this:

internal class WeightedRatingAlgorithm : IRatingAlgorithm
{

public int Compute(IList<Review> reviews)
{
var result = default(int);
var counter = 0;
var total = 0;

for (int i = 0; i < reviews.Count(); i++)
{
if (i < reviews.Count() / 2)
{
counter += 2;
total += reviews[i].Rating * 2;
}
else
{
counter += 1;
total += reviews[i].Rating;
}
}

result = total / counter;
return result;
}
}

And our context class is here:

internal class Rater
{
private readonly List<Review> _reviews;

public Rater(List<Review> reviews)
{
_reviews = reviews;
}

public int ComputeResult(IRatingAlgorithm algorithm)
{
return algorithm.Compute(_reviews);
}
}

Our client will now use the context class to call either of our algorithms. And here is how I am doing it, with a small static helper method to build some static review.

class Program
{
static void Main(string[] args)
{
var reviews = SampleReviews(new[] { 4, 8 });

var rater = new Rater(reviews);

var simpleresult = rater.ComputeResult(new SimpleRatingAlgorithm());

var weighted = rater.ComputeResult(new WeightedRatingAlgorithm());

Console.WriteLine("Simle average mean: {0} , Weighted mean {1}", simpleresult, weighted);
Console.ReadLine();
}

public static List<Review> SampleReviews(params  int[] rating)
{
return rating.Select(x => new Review { Rating = x }).ToList();
}
}

Advantages

  • Strategies may not use members of the containing class they will have to be self sustaining
  • Test may now be written for individual concrete strategies
  • Strategies may be mocked when testing the context class
  • Adding a new strategy does not break the Open/closed principle

Happy coding ūüôā

 

 

C# Virtual Keyword trap

What does virtual keyword stand for?

Virtual exists in different programming languages though with different names and rules of how it should be used. E.g in C# its “virtual”.¬†¬†With little experience of Java, I understand that all non-static methods are by default virtual functions, and therefore only methods modified with final keyword cannot be overridden as well as private methods which are not inherited.

So from the short and simple introduction, you can easily deduce that, by marking a method or a member virtual, you are giving authority to all child classes to  override and inject there own implementation. Override meaning that they can use their own implementation of the method/member instead of the base class implementation of the same method/member.

One thing to remember is that there is a hierarchy in derivation and execution of virtual members, since they can be overriden by many child classes. And so the rule  is that, only the most derived type will be executed depending on the object you are in.

So lets see what this might be bringing in our scenario.


class Shape
 {
 public Shape()
 {
 Draw();
 }
 public virtual void Draw()
 {
 Console.WriteLine(this.GetType().Name);
 }
 }

To note here is that the virtual method is called in the constructor, and remember the rules of the most derived takes precedence.

Another class that inherits from Shape as follows


class Circle : Shape
 {
private  int [] _coordinates;
 public Circle()
 {
_coordinates = new int[] { 1,2};
 }

public override void Draw()
 {
Console.WriteLine("{0} {1}", _coordinates[0], _coordinates[1]);
 }
 }

So in this class, we declared a array _coordinates and initialize it in the constructor. The is then used in the overridden method, just to see what happens. So in my calling class I set it up like so:


class Program
 {
 static void Main(string[] args)
 {

//Null exception
 Circle circle = new Circle();

//Null exception
 Shape shape = new Circle();
 Console.ReadLine();
 }
 }

When I run the above code so far, I get this screen

error2

I am creating a new instance of Circle class. The cause the constructor of Shape class to be called. In the Shape constructor we are calling Draw method. Our expectation here would be to see “Shape” printed on the console.

Which is not the case. The Draw method called in the base constructor, invokes the Draw method in the child (Circle) class since its the most derived, find an uninitialized int array, whence the null exception as we try to access first and second items in the array.

The consequences of this is that you can end using an object in unstable state. So you should be very careful when using virtual members in a constructor.

The Shape Draw method will only be called when you are creating a instance of Shape

Happy reading!

%d bloggers like this: