Sunday, December 30, 2007

Time to learn grammar (Predicate Delegates)

I was in seventh that time, our Maths teacher entered into the class. He ordered, "Students, who have not completed their assignments, stand outside the class". Unlucky me, like always I went outside the class.

If you noticed after this, we are a group of students standing outside the class; poor we :(. Question to my readers, lets represent this in my favourite subject Mathematics:

{students standing outside the class poor we is a group of students (who have not completed their assignments)}

By this, we want to seperate some specific students (who have not completed their assignments) from the group of students. Means, we create a criteria = who have not completed their assignments and equate this criteria for each of the student in the group, when a student satisfies this criteria he comes into the group of "students standing outside the class" which is our resultset.

This phenomenon in Mathematics is known as Predicate or a Propositional function - which represents the choice of student which returns a proposition which can be either true or false i.e. he has completed his assignment or not.

Few points of our interest:

  • Predicate always applies to a collection, in our case it is "a group of students"
  • Predicate works against a condition/criteria, in our case it is "who have not completed their assignments"
  • Predicate always returns a boolean value (true/false), this is because predicate evaluates against a criteria which can only return true (if a set element satisfies the criteria) or return false (if a set element doesn't satisfies the criteria)

Now we know what is a Predicate ? isn't it :) - similarly we have a special delegate which we call "Predicate Delegate".

What you think a "Predicate Delegate" will be?

This is a a special delegate which will

  1. Always apply to a set (i.e. collection of a specific type of object, in our case it is a group of students)
  2. Always evaluate for each member in the set (i.e. every object in the collection, in our case it is every student)
  3. Always return a boolean value (i.e true or false, in our case when a criteria is met by a student it will return true and vice-versa)

I cannot resist myself from giving a example:

  1. Here is our criteria -
    //A simple criteria which applies only to a student
    public static bool HasDoneAssignment(Student studentToBeEvaluated)
    {
    bool result = false;

    result = studentToBeEvaluate.Assignment.IsComplete;

    return result;
    }
  2. How do we evaluate to this criteria?
    //Evaluate students one by one
    HasDoneAssignment(student1);
    HasDoneAssignment(student2);
    HasDoneAssignment(student3);
  3. What could be a delegate for the same? (hint - its delegate will just be "delegate" keyword suffixed with Method Signature)
    //A simple delegate which accepts student
    public delegate bool HasDoneAssignmentDelegate(student studentToBeEvaluated);
  4. How do we consume this delegate?
    //Instantiate the delegate and point it to our criteria function
    HasDoneAssignmentDelegate evaluateStudentCriteria = HasDoneAssignment;

    //Evaluate studens
    evaluateStudentCriteria(student1);
    evaluateStudentCriteria(student2);
    evaluateStudentCriteria(student3);
  5. Wanna try it using a Predicate Delegate, seems like you want it :)
    //Instantiate Predicate delegate of type <int> and point it to our function
    Predicate<student> evaluateStudentCriteriaUsingPredicateDelegate = HasDoneAssignment;

    //Evaluate numbers
    evaluateStudentCriteriaUsingPredicateDelegate(student1);
    evaluateStudentCriteriaUsingPredicateDelegate(student2);
    evaluateStudentCriteriaUsingPredicateDelegate(student3);

Wow, Can you notice how Predicate delegate is helping us? See the old and the new code:

<Old> HasDoneAssignmentDelegate evaluateStudentCriteria = HasDoneAssignment;

Vs

<New> Predicate<student> evaluateStudentCriteriaUsingPredicateDelegate = HasDoneAssignment;

Conclusion

We can always use a Predicate delegate in lieu of a delegate(function pointer) which takes only one argument and returns a boolean value. That means, any function which accepts a single argument and returns a boolean value can be pointed using Predicate delegates.

Predicate delegate uses another good feature of .NET framework - Generics to facilitate strongly typed input to that particular function.

In real world scenarios, predicate delegates can be used for anything which requires any kind of filtering i.e. AnyCollection>.Find(), <AnyCollection>.FindAll(), etc. I know you can always use for more innovative functionalities across our business applications. :) Clever you..

Quiz for you guys

How do we pass the criteria within the predicate delegate? because you know what predicate delegate doesn't accepts any criteria; since predicate delegates can only have one parameter pointing to the object to which we want to apply the criteria.

For hints you can see my one of the earlier post. In my version of implementation of LINQ like design you will discover how I harness the power of Predicate delegate to implement the Where<> functionality. Can you recall this ?

employees.Where<int>("Salary", 20000);
Hope you enjoyed reading this post, please share your views by giving comments :)

Rushes of Tale about a young guy known as "LINQ"

I started working on my next story about the new and young guy “LINQ”.

Here are some bits:

LinqList<Employee> employees = Utility.CreateLinqEmployeesList();
//How to implement LINQ like feature in VS 2005
employees.Where<string>("Name", "S").OrderBy<string>("Name");

This story is based on our previous kitchen story, gear yourself to experience the real code in my next post.

Saturday, December 29, 2007

Benefits of cooking food at home (Anonymous Methods)

10:30 PM - Late, very late to think , think and think. You know what I am planning to eat something. Very recently, my office work had kept me busy full day. So.....

Finally, I decide on to get some "Jamie Oliver" - The easiest sexiest salad in the world. I had two choices:

  1. Either, I can create this receipe in my dinning room, where I can bring all the ingredients required to prepare this. Though, the chances may be me forgotting to bring some ingredients in the dinning room.
  2. Or, I can go to kitchen and prepare this receipe there. So, that I need not to bring specific ingredients to dinning room and will save myself from shuffling between dinning room and kitchen. This may save my time too. :)

I decided to go with the second approach and believe me I was quite at ease preparing the salad there. In kitchen, I need not to worry about finding every ingredient in the first place..now.. I can get each on-demand.

Can I think something of this sort:

  • Which provides me the freedom and ease to cook any functionality ?
  • Breaking the signature barrier of a function pointer (delegate1)
  • Decorating2 my existing functionality with extra functionality.
  • or, help me grab some biscuits/chips while I am preparing "Jamie Oliver" :)

Before we go into understanding the details, let me give a walkthrough over delegates:

1 Delegate: Originally, people call it function pointer. But for me delegate is a [placeholder] for a specific method signature.

  1. Let's create a simple method.
  2. public int AddMethod(int a, int b)
    {
    return a + b;
    }
  3. Create a simple delegate for the same "simple function".
  4. delegate int Add(int a, int b);
  5. Consume the delegate.
  6. public void TryDelegates()
    {
    //C# 1.x way of calling method - Named Methods
    Add addOld = AddMethod;
    //Output will be 45
    Console.WriteLine(addOld(20, 25));
    }

Till here, we have created a delegate and consumed the same, successfully. Now, how do we get some chips/biscuits in the middle of the method, that too without interfering the AddMethod()?

We can always go ahead and create a different method which will contain the biscuits/chips to act as some pre/post processing. Something like below:

//Modified AddMethod which will decorate the existing AddMethod
//with extra processing instructions
public int ModifiedAddMethod(int a, int b, int affectMe, Add addDelegate)
{
return addDelegate(a, b) + affectMe;
}

Here is how our consume method looks like:

public void TryDelegates()
{
//C# 1.x way of calling method - Named Methods
Add addOld = AddMethod;
//Output will be 45
Console.WriteLine(addOld(20, 25));

int affectMe = 10;
//Call the decorated method
Console.WriteLine(ModifiedAddMethod(20, 25, affectMe, addOld));
}

You can easily figure out, this looks like too much for us to do - that too just for a very simple method enhancement. One of the drawback of this method is to - pass whatever variable we need to process it in ModifiedAddMethod() , along with the delegate. Here is what C# 2.0 has for you, "Anonymous Methods - reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method" (as per MSDN).

What the heck is "Anonymous Method"?

For me, this is a mechanism which we can use to provide "CODE BLOCK" for direct execution and save ourself from mapping the expected delegate.

To understand this better, in our scenario creating a seperate method just for accomodating a "simple functionality change", we can write the ModifiedAddMethod() inline in the TryDelegates(). Here is how our code looks:

public void TryDelegates()
{
int affectMe = 10;
//C# 2.0 way of calling method - Anonymous Method
Add addNew = delegate(int a, int b)
{
return a + b + affectMe;
};
Console.WriteLine(addNew(20, 25));
}

As one benefit can be clearly seen that we have reduced lines of code + code has gained more readability + No hassles of passing variables.

Hey look, this quite matches to the natural style of my cooking. :) Voila, the we can program now using our natural instincts. This looks like a good time to introduce "Closures", to my readers.

What is a closure?

Is a block of code that can be passed as an argument to a function call. A cool feature borrowed from the world of functional programming language (Lisp, etc.) . To know more about closures, you would like to meet this gentleman - "Fowler"

Conclusion

In today's story, I introduced you to "Anonymous Methods" a.k.a. inline methods - inline delegate's implementation (again a method). Scenarios for using this would be, when we need to add some pre/post/additional processing for calling delegates, this specially applies to when we go for breaking limits with "System Delegates - delegates provided by .NET Framework".

My next story will target using an "Anonymous Method" to exploit one of the .NET Framework provided delegates. Please leave your comments, because they help me writing what you are looking for.

UPDATE:

One of my readers, "RAJEEV" had a tough time understanding why we would like to chain 2 delegates using anonymous method / delegate.

Reason #1 Anonymous Delegate exists specially to be used in conjunction of various Framework Delegates i.e. Predicate Delegate, Convertor Delegate, Action Delegate, etc.

Reason #2 Whenever, you require to access local method's variables without altering the specific delegate we can use Anonymous Method and then execute that specific delegate.

Sunday, December 23, 2007

Its too cold, out here

It’s a dark night here; wind is piercing my ears with chilling cold. There, I see a young guy shivering with cold towards the end of the lane. I walked at him and asked, “Seems like cold will kill us”. He replies in a down tone, “What can be done, see I have something which I can burn but I don’t know how to burn”.

This is our first guy. Suddenly, a tall guy emerges from the dark and tells him, there is another guy on the opposite side of the street, who already has a fireplace. This is our second guy. Now, I can see a clear smile on our first guy’s face. He was running towards the opposite side of the street towards the fireplace.

Walking further I saw another guy rubbing stones. I asked him, “Why are you rubbing stones?”. He answers with a rough throat, “I am trying to light the fire”. And here is what the curiosity was killing me, that in this hi-technology world; this guy was rubbing stones for lighting the fire. I fired my second question, “You already have a matchbox, with which you can lit the fire immediately and that too without any effort”, seems like I started acting as a cop.

He answered gently, “I am trying to do it myself and learn, so that in future I am not dependent on any box”. He is our third guy.

Now, I am in my cozy room writing this. Few minutes back, I introduced you to three guys:

1. Guy having something to burn, but didn’t knew how to burn.
2. Guy helping the first guy, to get something so that he can get some relief.
3. Trying to invent something on his own, so that he is not dependent on someone.

This was the story of three different kind of developers; one trying to find a solution, second guiding the first one to already existing solution and last one on inventing his own solution, so that he is not dependent on anyone.

Through this blog, I wish to walkthrough developers across the big ocean of design patterns, enterprise design, test driven development and the big word “AGILE”. I welcome everyone to contribute to this by sharing their own design experiences.