Monday, September 1, 2014

Providers that make your life easy (Part II)

Chapter – VI
Providers that make your life easy (Part II)

Okay, in the previous post I've shown you how to create an object using JavaScript factory functions. So far so good. Now let me show you another way of creating an object in JavaScript. This work around includes creating an object using constructor functions. Following this pattern you would create an object like below,

var Actor = function (firstName, lastName, catchPhrase) {
                this.firstName = firstName;
                this.lastName = lastName;
                this.catchPhrase = catchPhrase;
                this.sayCatchPhrase = function() {
                    return this.firstName + " " + this.lastName + " says " + this.catchPhrase;
                };
            }

var clint = new Actor("Client", "Eastwood", "Go ahead. Make my day");

Except for some minor changes everything is almost same as before. As you can see when we create an object using the constructor function we always keep the variable’s [variable to which the constructor function holds its reference] first letter capitalized. Also we have used this. and then the property name of the object. Rather than using a colon (:) to assign a property value to one of the passed in parameter, here we simply assign it using an equal (=) sign. Last but not the least we called that constructor function by creating a new instance of it [see the new keyword at the start of the constructor function call]. Now if we write

clint.sayCatchPhrase();

The output is same as before

"Clint Eastwood says Go ahead. Make my day”

So what is the main difference between these two patterns for creating a JavaScript object? If we create an object with constructor function, the object is born with a type. Means our clint is an Actor type. You can check it in browser’s developer console by simply writing

clint instanceof Actor

Which will return true. But creating an object with a factory function doesn't have a type. Also you would use the constructor function pattern when creating an object of a type is too frequent.


In my next post we will take a deep dive into the wonderful world of Angular.js providers. Till then stay tuned!

Sunday, August 31, 2014

Providers that make your life easy (Part I)

Chapter – VI
Providers that make your life easy (Part I)

In the previous post I've shown you how you can implement business logics in your controllers and use them in different parts of your application just by calling them. But as we all know too much code in one place is never a good idea. And it is considered to be a good habit not to write a whole amount of business logics in a controller cause you may have to use those same logics again in another controller. So doing the same thing over and over again is an overkill and also error prone.

So in this chapter I’m going to show you how Angular.js providers can make your coding life cycle easier by separating these business logics from your controllers and prevent from injecting bugs in your application.

Ok sounds fine, but there is a catch! Before I make your head spin with those topics of Angular, let’s take a step back to some object oriented JavaScript. You may ask yourself why? The answer is be patient my friend!

So let’s start by creating a simple object in JavaScript. There are many ways of creating an object in JavaScript but I’m going to show you the easiest and most granted way. And that is known as creating an object by object literals. First of all I want to create an arnoldSchwarzenegger (A Hollywood Actor) object. The object will have a property for holding the first name of the actor, a property for the last name, a property for the catch phrase and last of all a property which will make a string with all of those previous properties and show it to the application users.

Creating an object literal is as easy as pie. It is just some key value pair. All you have to do is to define a key [a string representing the property name] and a value associated with it. So from that concept our Arnold Schwarzenegger object literal will look like this,

var arnoldSchwarzenegger = {
            firstName: "Arnold",
            lastName: "Schwarzenegger",
            catchPhrase: "Hasta la vista, baby",
            sayCatchPhrase: function () {
                return this.firstName + " " + this.lastName + " says " + this.catchPhrase;
            }
};

Now if you call the sayCatchPhrase property like this

arnoldSchwarzenegger.sayCatchPhrase();

You will get the string given below

"Arnold Schwarzenegger says Hasta la vista, baby"

Remember to add those first brackets when you call sayCatchPhrase. Since JavaScript don’t have methods for an object, you can bypass this rule by encapsulating a function within a property.

Now it’s time to create the clintEastwood object. All is same as before.

var clintEastwood = {
            firstName: "Clint",
            lastName: "Eastwood",
            catchPhrase: "Go ahead. Make my day",
            sayCatchPhrase: function () {
                return this.firstName + " " + this.lastName + " says " + this.catchPhrase;
            }
};

clintEastwood.sayCatchPhrase();

"Clint Eastwood says Go ahead. Make my day”

Now let’s create another one. Wait a sec!!! You may ask yourself why am I doing the same thing over and over again. Why don’t I just define a class and declare those properties in that class. Then when the time comes I just instantiate an object of that class and use those properties. Well you are right about the fact that we are doing the same thing over and over again but to our utter luck we don’t have the concept of class in JavaScript.

But don’t worry because where there is a will there is a way. Functions are like the first class citizen in JavaScript language. We can do almost anything with functions. And we can also create an object within a function and return that object. Functions like these are called factory functions.
So creating and returning an actor object with a factory function looks like this,

var actor = function (firstName, lastName, catchPhrase) {
            return {
                firstName: firstName,
                lastName: lastName,
                catchPhrase: catchPhrase,
                sayCatchPhrase: function () {
                    return this.firstName + " " + this.lastName + " says " + this.catchPhrase;
                }
            };
};

var clint = actor("Client", "Eastwood", "Go ahead. Make my day");

clint.sayCatchPhrase();

"Clint Eastwood says Go ahead. Make my day”

As you can see I've declared a function with some parameters. In that function we set the passed in parameters in an object literal and then return that to hold the reference into actor variable. Then all we did is called the actor function with some parameters.

I hope you likethe way I create an object with factory function to restrict myself from doing the same thing again and again. There is another way by which we can create an object. But that will be discussed in the next part. 

Thursday, August 28, 2014

Alarming Delegates (Advanced)

Alarming Delegates (Advanced)

Creating an alarm system using delegates


So here goes a post about c# delegates, which is considered to be one of the hardest concept in c#. So I decided to show you a simple example which I guess will clear the concept of delegates for you.

Delegates are like function pointers in C++ and callback functions in JavaScript. Functions can be encapsulated using delegates. As you already know that c# is an event based programming language, you will be happy to know that behind the scene all events are basically delegates. So sooner or later you will find yourself learning delegates.

‘Nuff said! Let’s talk about the example which we are going to build. Our example is very simple one. All we are going to build is a simple console app, which will work like a clock. It will only count the seconds, so you can call it a second’s clock. In this simple app you will have to set an alarm for an upcoming second. The app will continuously check the current second against the second set at compile time and will show an alarming message if the condition is matched.

Now let’s talk about how we are going to build it using delegates. For simplicity let’s create a Clock class first. For now the class only contains a single DateTime property named Alarm.

public class Clock
{
public DateTime Alarm { get; set; }
}

We will use this auto property to set an alarm time in seconds in near future.


We all know that Class and Struct are some ways of creating user defined types. Likewise delegates can be used to define a type which can only encapsulate functions. Signature of a delegate type is more like a function declaration. To declare a delegate, you simply have to follow the signature given below,

access_modifier delegate_keyword reurn_type delegate_name(type parameter1,……);

So, let’s go and create our own delegate as

public delegate void ClockAlarm(Clock clock, string name);

As you can see our newly created delegate, ClockAlarm can take a Clock object and a string as parameters and can return a void type. Everything is set.

So I successfully declared a delegate but there is no use of it. Let’s go to our Main method in  Program class and write some magical code. Let’s start by creating an instance of our Clock class and assign a seconds value of a near future for the Alarm property.

var clock = new Clock();
clock.Alarm =  DateTime.Now.AddSeconds(5);

Now it’s time to encapsulate a function with our ClockAlarm delegate. You may be thinking now that ok so I have a delegate to which I can attach a function. But what will be the signature and definition of the attaching function? I know you are geek enough and figured out the attaching functions’ signature. Yes you are right!!! its signature is same as our  ClockAlarm delegate. If we try to attach a function whose signature mismatches with our  ClockAlarm delegate signature, it will give you a compile time error.

Next let’s create our attaching or subscribing function with definition as below

private static void Wakeup(Clock clock)
{
while (true)
       {
       Thread.Sleep(1000);
              DateTime currentTime = DateTime.Now;
             
if (currentTime.Second == clock.Alarm.Second)
              {
                     Console.WriteLine("Please wake up!!!!");
                     break;
              }
             
Console.WriteLine("Clock is ticking!!!");
}
}

The code is very simple all we did is created a while loop which will first send the system to sleep for one second and wake it up. After that it will assign the current DateTime value to the currentTime variable. After that the if clause checks if the current second matches the Alarm property value which was passed in the function object. If the clause is true then it prints the message "Please wake up!!!!" and breaks out of the loop otherwise it will continuously prints "Clock is ticking!!!" message. 

Now its time to create an instance of our delegate and then attach the subscribing function to it.

ClockAlarm clockAlarm;
clockAlarm = Wakeup;
  
Last of all we will have to invoke the delegate with the required parameters. To do that we will simply have to write

clockAlarm(clock,"Fiyaz");

So I guess you got the point. With the help of a delegate we are making a function subscribing to an event which is basically for now is simply an alarm notification. Now if you run the program you’ll something like this,



We can attach more than one subscribing functions to our delegate which is a process of multicasting delegates. More about delegate multicasting in the next post.