Profile Picture

Sirwan Afifi

Stories from a web developer.

© 2015. Sirwan Afifi All rights reserved.

Explicit Interface Implementation

Let’s imagine that you have a class with two methods:

public class VendingMachine
{
    public bool InsertCoin(float amount)
    {
        if (amount < 500)
        {
            return false;
        }
        return true;
    }

    public string Buy()
    {
        return "Buy";
    }
}

Now when we want to create an instance of this class and call one of those methods, it executes as expected:

VendingMachine machine = new VendingMachine();
machine.InsertCoin(5); // false
machine.Buy();         // "Buy"

Now suppose that we have an interface called IVendingMachine that has two methods:

public interface IVendingMachine 
{
    bool InsertCoin(float amount);
    string Buy();
}

We want our class to implements this interface:

public class VendingMachine : IVendingMachine
{
    public bool InsertCoin(float amount)
    {
        if (amount < 500)
        {
            return false;
        }
        return true;
    }

    public string Buy()
    {
        return "Buy";
    }
}

Our class satisfied the interface because it has the methods with the same names. So Visual Studio doesn’t give you a compiler error. Now let’s imagine that we also want to add interface’s methods to this class, So, in this case, we must explicitly prefix the methods with IVendingMachine.:

public class VendingMachine : IVendingMachine
{
    public bool InsertCoin(float amount)
    {
        if (amount < 500)
        {
            return false;
        }
        return true;
    }

    bool IVendingMachine.InsertCoin(float amount)
    {
        if (amount < 300)
        {
            return true;
        }
        return false;
    }

    public string Buy()
    {
        return "Buy";
    }

    string IVendingMachine.Buy()
    {
        return "IVendingMachine Buy";
    }
}

Note that Visual Studio can help you to implement interface explicitly by pressing Ctrl + . on the name of the interface and select Implement interface explicitly:

Now, what happens when we call the InsertCoin and Buy methods? In this case, we should consider two different situations when we create the object:

  • Concrete Type
  • Interface Variable

If we want the methods of VendingMachine we should create the object with concrete type:

VendingMachine machine = new VendingMachine();
machine.InsertCoin(5); // false
machine.Buy();         // "Buy"

If we want the methods of IVendingMachine we should create the object with interface variable:

IVendingMachine machine = new VendingMachine();
machine.InsertCoin(5); // true
machine.Buy();         // "IVendingMachine Buy"

Delegates in C#

Lately I have been studying some topics in C# in order to improve myself. I think Delegate is one of those topics which is kinda difficult for beginners to initiate with. So, in order to make it clear how it works, I’m going to make some explanations in this post.

What are Delegates?

Delegate was introduced in C# 1. Think of it as a simply being a placeholder for functions that’ll be called at some point in time. Assume you want to declare a variable that is a reference to a specific method. In this case, the variable encapsulates some executable code and you can invoke the variable just like an actual method. In doing so, we need to create a delegate

Defining a Delegate

Delegates are created using delegate keyword along with the function signature:

delegate int Sum(int a, int b);

As you can see we are defining a delegate called Sum that is compatible with any method with an int return type with two parameters. Actually we defined a type that we can use to create variables and point those variables to methods that have the same signature and same return type. The type defenition for a delegate describes the method that we want to call:

int Add(int a, int b) => a + b;

Now we can assign a method to the delegate variable. This assignment creates a delegate instance:

Sum s = Add;

Now we can invoke the delegate instance in the same way as a method:

int result = s(5, 6);

Advantages of Delegate

  • Delegates are type safe, It means that the C# compiler checks the function signatures of a Delegate when you use them at runtime.
  • Can be used to define callback functions.
  • Can be dynamically switched at runtime.

Real World example

Suppose that you want to implement something like a Repeater control in your ASP.NET MVC application, As you probably know a Repeater is(was) server side databound control in ASP.NET WebForm for displaying information, It had a lot of flexability becuase you had complete control over the your markup.

public static class Helpers
{
	public delegate HelperResult ItemTemplate<T>(T input);

	public static HelperResult Repeater<T>(this HtmlHelper html,
	  IEnumerable<T> items,
	  ItemTemplate<T> itemTemplate,
	  ItemTemplate<T> alternatingitemTemplate = null)
	{
		return new HelperResult(writer =>
		{
			int i = 0;
			foreach (var item in items)
			{
				var func = i % 2 == 0 ? itemTemplate : alternatingitemTemplate;
				func(item).WriteTo(writer);
				i++;
			}
		});
	}
}

As you can see we emulated the ItemTemplate and AlternatingItemTemplate using a delegate. In this case user can pass the data and the data will be rendered inside the view. In this case the delegates act like callback.
The ItemTemplate delegate in our example can be replaced with Func delegate:

Func<T, HelperResult> itemTemplate,
Func<T, HelperResult> alternatingitemTemplate = null

Now we can use our helper inside any view:

<table>
    <tr>
        <td>Id</td>
        <td>Name</td>
    </tr>
    @Html.Repeater(Model, @<tr>
	    <td>@item.Title</td>
	    <td>@item.Price</td>
	</tr>, 
	@<tr class="alert-info">
	    <td>@item.Title</td>
	    <td>@item.Price</td>
    </tr>)
</table>

If you run the application you can see the result:

You can check out the GitHub repository for this post.


Thinking out of the box to become a better programmer

Image courtesy of http://goo.gl/iu68gq

Today I was talking with a friend of mine about thinking, The topic is interesting and I wanted to share it with you because as a programmer we are always thinking and trying to find solutions. Actually it’s a good habit when you want to learn something new, instead of taking action and delve into the details, you should think about that and break it down into several pieces then construct it as a big picture. Once you get familiar to it you can start trying to figure out each individual piece, By doing so you will become great in your field.

Image courtesy of http://goo.gl/Xi2Cn4

On the other hand, thinking isn’t the only thing for being an expert in programming. Suppose that you are given a challenging feature to implement in a team you’re working with, you might spend days and days trying to implement this feature and each time you fail and stuck in it then you try to find a solution on the net or asking questions on Stackoverflow. I’m not saying you shouldn’t google about your problem, What I’m saying is that you should understand the problem, This is where a Thinking out of the box’s metaphor comes into play.

This is very helpful because when you ran into a problem you should first think about it in a new or a different prespective, For example you can put yourself in end user’s place and try to figure it out. Once you understand it, you can start coding the feature. By doing so you can help yourself and believe me it works like a charm and you don’t need to post off-topic questions every single day on Stackoverflow anymore, Instead when you run into a serious problem, you can post your question and get extra votes :)

So thinking out of the box helps us to think like a programmer, It also helps you to approach problems in new ways.


Why AngularJS?

I wanted to share a few thoughts about AngularJS

Introduction

AngularJS is a MV* framework for writing manageable, clean, full-featured applications in the browser with JavaScript , It’s also incredibly easy to learn for those who already have HTML and JavaScript experience. Angular’s goal was to create a way for designers to be able to do HTML design using components. One thing that I like about Angular is that, it’s an opinionated MV* framework, It means that it tells you what are the certain ways of doing things, Some people might argue that it’s somehow a limitation for a framework such as Angular because it solves fewer problems, but I think at least it assures to not having spaghetti code.

How I got into AngularJS

I have been sitting on the fence for far too long to chose a great JavaScript framework. Finally a couple of years ago I decided to use AngularJS and it caught my attention. It actually made me cursious to learn more about it. I started to use AngularJS for some parts of my application. At the time Angular team were working on the next version of the framework So I stopped using it because I heard that the next version is a different framework. Now I have come to conclusion that it’s better to stick with Angular 1.x, then I can switch to Angular 2 in a right time.

AngularJS Benefites

Angular has lots of great features from testability and two-way binding, to more vague concepts. For me the best thing about Angular is that it has a flat learning curve So you can get the most of it. All being said here are the some of my favorite features and benefits of Angular:

  • Code Reduction: Angular reduces the amount of code that developers write.
  • Two Way Binding
  • Beautiful syntax and higher level APIs

For example take a look this piece of code written in raw JavaScript:

document.getElementById('btn')
.addEventListener('click', function(el) {
    alert('clicked!');
});

Whereas with Angular you can simple achieve same goal this way:

<button id="btn" ng-click="handleClick()">Click Me</button>

$scope.handleClick = function() {
    console.log('clicked!');
}

As you can see the Angular code is less complex.

  • Popularity
  • Testability
    Angular was designed with testing in mind. So you can test any components of your application easily through both unit testing and end to end testing. For unit testing you can use a component called ngMock and for e2e testing you can use Protractor. It is worthwhile to mention that for both cases you can run your tests using a tool called Karma.

AngularJS gotchas

Although Angular is a great framework but it has some problems that you can run into trouble with it. Here are some of them:

  • SEO
    For dealing with this issue we can use server side rendering or use a prerenderer,
  • Performance
    One thing that causes performance problem in Angular is having too many bindings. If performance is important you can consider using a different rendering engine.
  • External Events and Digest Cycle

Conclusion

Even though Angular 2 is coming, But Angular 1 is still a thing and I think Angular 1 will be supported for a long time to come.


Asynchronous Execution in JavaScript

As you know browsers are typically single threaded, It means that the browser can only be doing either update the UI or executing JavaScript at any given time. It actually incapable of doing theme simultaneously.

As I mentioned when JavaScript is executing code, the UI is unable to respond to the user. So, our goal as a developer is to build a highly responsive UI. For doing that you could create smaller unit of work and use JavaScript timers to return execution to the next event in the queue:

function buffer(items, iterFn, callback) {
    var i = 0, len = items.length;
    setTimeout(function () {
        var result;

        for (var start = +new Date; i < len && result  
                    !== false && ((+new Date) 
                     - start < 50) ; i++) {
            result = iterFn.call(items[i], items[i], i);
        }

        if (i < len && result !== false) {
            setTimeout(arguments.callee, 20);
        } else {
            callback(items);
        }
    }, 20);
}

Assume that we want to pull down some data from the server, Then the data is going to be processed through an array loop, And we are going to build some DOM elements:

@{
    ViewBag.Title = "Home Page";
}
<ul></ul>
@section scripts
{
    <script>
        $(document).ready(function () {
            $.get('@Url.Action("Date")', function (result) {
                var html = '';

                buffer(result, function (item) {
                    html += '<li>' + item + '</li>';
                }, function () {
                    $('ul').append(html);
                });
            });
        });
    </script>
}

Also the action method is like this:

public JsonResult Date()
{
    var data = Enumerable.Range(0, 50000);

    return Json(data, JsonRequestBehavior.AllowGet);
}

The buffer method works like a charm but using setTimeout is considered to be a bad practice. So that’s where the Web Workers come into play.

Web Workers

MDN:

Web Workers provide a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. In addition, they can perform I/O using XMLHttpRequest (although the responseXML and channel attributes are always null). Once created, a worker can send messages to the JavaScript code that created it by posting messages to an event handler specified by that code (and vice versa.) This article provides a detailed introduction to using web workers.

Well, Web Wrokers bring background threading to browsers. It is a best option if you have intense processing that needs to happen in your browser. Since Workers run in another global context so there’s a few restrictions that you have to keep in mind, Here you can see the list of functions and classes available to Web Workers. So your favorite JavaScript library may not work with workers.

So let’s rewrite our example with Web Workers:

<ul id="result">Hello</ul>
@section scripts
{
    <script>
        $(function () {
            var _worker;

            _worker = new Worker('@Url.Content("~/Scripts/getData.js")');
            _worker.addEventListener("message", messageHander, false);
            _worker.postMessage("fetch");

            function messageHander(e) {
                $("#result").html(e.data);
            }

        });
    </script>
}

As you can see I instantiated a worker, Then I setup an event listener for message, So when data comes in from the AJAX call, we will inject the result into html of a container called result.
Here you see the worker:

function messageHandler(e) {
    if (e.data === "fetch") {
        fetch();
    }
}

function fetch() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            var html = "";
            var res = JSON.parse(xmlhttp.responseText);
            for (var i = 0; i < res.length; i++) {
                html += '<li>' + res[i] + '</li>';
            }
            postMessage(html);
        }
    }

    xmlhttp.open('GET', '/Home/Date', false);
    xmlhttp.send();
}
addEventListener("message", messageHandler, true);

Inside the fetch content we used typical AJAX call because in Web Workers you can not use a third-party library it means that there’s no access to non-thread safe components, So you have to use a native XMLHttpRequest in your worker. Now if you run the code you will see that now that’s pretty fast even quite a bit faster than before.

You can see the sample code in the GitHub repository


Object Oriented JavaScript Part 2

###Classes In many programming languages a class is a standard unit of work, which means that you normally create all of your code inside classes and these classes contain data, behaviour, events and those sort of things that you are going to use in developing your solutions. for example in C# we can create a class this way:

public class Person
{
    // Field
    public string firstName;
	// Constructor that takes no arguments.
    public Person(string firstName, string lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    // Method
    public string Greet(string name)
    {
        return $"Hello, { name }. My name is { this.firstName }"
    }
}

In this case we have a class along with properties, constructor. So a class in C# contains data as well as operation as well as events. It will be useful to create same sort of structure in JavaScript. Prior to ES6 there was no such thing as a class in JavaScript, we could simply do everything with functions, we could create classes by using some of the language semantics to create things that look and feels like classes. But they were not classes in the classical sense. for example we used function to do this:

function Person(firstName, lastName){
	this.firstName = firstName;
	this.lastName = lastName;
}
Person.prototype.greet = function (name) {
	return "Hello, " + name + ". My name is " + this.firstName;
};

So what this function does is use the this keyword to define new property that represents a person object in this case. And what’s interesting here this is what’s called a constructor syntax. So this function when called will return an object. By doing this, we can create a new person:

var person = new Person("Sirwan", "Afifi");

In this case, we can see that it is using the new keyword. this keyword is used to find a function with a name, after the new, return an object that contained the shape that is defined in the function. Once we have an instance of that, we can get any of the properties that are specified in the constructor syntax function:

var firstName = person.firstName;

ES6 introduces language support for classes with class keyword. So the ES6 equivalent of the Person function would be the following:

class Person {
	constructor(firstName, lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}
	
	greet(name) {
		return `Hello, ${name}. My name is ${this.firstName}`;
	}
}	

So we have essentially recreated the same Person data type but with much better syntax. behind the scene the runtime is doing the exactly what we used to do. But now the syntax is clean and expressive. As you can see there is constructor in the class definition. the constructor is one of the class members that we can list in the body of a class, just like the other members it is a function, it is a function that automatically invoked when we say new and use the class name as a function call:

var person = new Person("Sirwan", "Afifi");

###Getters and Setters In a class we can also use getter and setter, they are created using get and set keyword. get and set allows us to run code on the reading or writing of a property:

// ES6 get and set
class Person {
    constructor(firstName, lastName) {
        this._firstName = firstName;
        this._lastName = lastName;
    }
  
    get fullName() {
      var result  = this._firstName + ", " + this._lastName;
        return result.toUpperCase();
    }
  
    set firstName(newName) {
        this._firstName = newName; 
    }
   set lastName(newName) {
        this._lastName = newName; 
    }
   greet(name) {
     return `Hello, ${name}. My name is ${this._firstName}`;
   }
}    
let sirwan = new Person('Sirwan', 'Afifi');
console.log(sirwan.fullName);  // Outputs 'SIRWAN, AFIFI'
let omid = new Person('Daryoush', 'Zandi');
omid.firstName = "Omid";
omid.lastName = "Kamangar";
console.log(omid.fullName);  // Outputs 'OMID, KAMANGAR'

###Inheritance ES6 also gives us an easy syntax to specify and inheritance for relationship. Which is a way we say a class inherits from another class. Now assume that we need another class for modling an Employee, since every employee is a person, maybe we will have the Employee inherit from a Person. In ES6 inheritance is specified using extends keyword:

class Employee extends Person{
  // more features
  getWork() {
    return `${ this._firstName } is working.`;
  }
}

let emp = new Employee('Sirwan', 'Afifi');
console.log(emp.getWork()); // Outputs 'Sirwan is working.'

The only thing is that a lot of features in ES2015 are not supported in the browsers. For example classes are not supported by any browser, now there might be a nightly built of Firefox that supports classes. So instead we have to use a transpiler and there are many transpilers such as TypeScript, Bable and variety of others. I recommend you to use Bable because it has the best support for all of ES2015 features.


Object Oriented JavaScript Part 1

Recently I’ve started to improve my JavaScript skill, So I decided to keep notes about new things I learn from now on. Since I’m a C# developer, I’m trying to use my existing knowledge in C# to learn JavaScript.
As you know in C# we have something called Object and collection initializer. For example we can use object initializer to create name and value pairs for different properties of the object, in this case car object:

var car = new Car()
{ 
    Name = "Chevrolet Corvette", 
    Color = "Red", 
    Manufacturer = new CarManufacturer() 
    { 
        Name = "Chevrolet", 
        Country = "USA" 
    } 
};

As you can see we used object initializer for those embedded objects too. Although object initializers can be used for anonymous types. So here’s the same example which we build with anonymous object:

var car = new { 
    Name = "Chevrolet Corvette", 
    Color = "Red", 
    Manufacturer = new { 
        Name = "Chevrolet", 
        Country = "USA" 
    } 
};

This is very similar the way dynamic objects work in JavaScript. So in JavaScript object creation is going to follow this pattern:

var car = { 
    name: "Chevrolet Corvette", 
    color: "Red", 
    manufacturer: { 
        name: "Chevrolet", 
        country: "USA" 
    },
    "towing capacity": "5,952 lbs" 
};

As you can see we use key/value pairs. Actually it’s a little different from C# for instance we used colons (:) instead of equals (=) but generally the syntaxes are similar. In some case you may see the name is embedded in quotes, it’s optional but if you’re using any reserved characters like space, in this case, you need to surround the name with quotes (like towing capacity).

These dynamic objects that you have defined with this name value pairs allows you to take these objects you are creating and access each the properties you have defined in that name value pair by the name using a simple dot syntax. For example here in JavaScript you can just access the name using dot name convention:

var name = car.name;

You can also use a bracket syntax, that’s why objects are sometimes called associative arrays:

var name = car["name"];

This way we can retrieve or set the property values. There are other ways for accessing and retrieving property value that are as follows:

car.color                = "Dot syntax";
car["towing capacity"]   = "String with space";
car[str]                 = "String value";
car[rand]                = "Random Number";
car[obj]                 = "Object";
car[""]                  = "Even an empty string"; 

We can also get embedded objects that are the properties of those dynamic objects as well and retrive properties from them:

var manufacturer = car.manufacturer;
var name = manufacturer.name;
var country = manufacturer.country;

###Malleability As you probably know, One of the key features of JavaScript is that the language is loosely typed it means that variables are declared without a type. So the objects that you are creating in this way are very malleable. In C# ExpandoObject gives you this behavior.

ExpandoObject Represents an object whose members can be dynamically added and removed at run time.

For example in this code we are creating a new object and marking it as dynamic so that we can add members to this ExpandoObject as we want:

dynamic car  = new ExpandoObject();
car.Name = "Chevrolet Corvette";
car.Color = "Red";

These are being added on-the-fly. It means that these aren’t defining the shape ahead of time. We are just saying we are going to add properties to the car object. In fact this is pretty much the same way in JavaScript:

var car = { 
    name: "Chevrolet Corvette", 
    color: "Red"
};

We can still add another property or function on-the-fly:

car["towing capacity"] = "5,952 lbs";
car.model = function () {
    var s = this.name;
};

Resourses:


My first blog post!

Here’s my first blog post :) In this blog I’m going to share thing that I learn, hope you enjoy reading my blog :)


subscribe via RSS