Generics constraints


It has been a long time since the generics are around and most of developers are using them in their code. In this post, I would like to talk about how to use generics more effectively by using constraints.

 What are constraints?

Constraints are conditions applied on the parameter type that are checked at compile time.

Why constraints?

We use constraints to avoid runtime errors when we create generic types.

For instance, if we write a generic class that calculates an employee salary. We want this class to be generic because we may have different types of employee classes (this is for illustration only):

 

public class Employee
    {
        public string Name
        {
            get;
            set;
        }

        public doubleHourlyRate { get;
            set;
        }

        public double NumberOfWorkedHours
        {
            get;
            set;
        }
    }

    class PayCalculator<T>
    {
        public double CalculateEmployeeSalary(T employee)
        {
            //We need an employee from the T type
            Employeeemp = employee as Employee;
            returnemp.HourlyRate * emp.NumberOfWorkedHours; 
         } 
       }    

What’s wrong with this code?

At runtime, there is no guarantee that the type passed to PayCalculator is an Employee type. If it is not an Employee, the ’emp’ variable will have a null value which will make the last line of the CalculateEmployeeSalary method raise a null value exception. We can add a test to check whether or not the ’emp’ variable is null before we calculate the salary. This will fix a runtime error but still, a developer could instantiate our PayCalculator with a non valid type which will lead to an unexpected result.

To avoid this situation, we must add a constraint to our generic class. which will look like:

class PayCalculator<T> : where T:Employee
    {
        public double CalculateEmployeeSalary(T employee)
        {
            //We need an employee from the T type
            Employeeemp = employee as Employee;
            returnemp.HourlyRate * emp.NumberOfWorkedHours;
        }
    }

This means that whenever we instantiate a PayCalculator with a type, the compiler will check whether the passed type is an Employee type or not (actually, it can be a derivative of Employee). If it is not the case, it won’t compile at all.

Types of constraints:

There are 6 types of constraints:

  1. where T : <base class> this is the one we just have seen.
  2. where T: <interface> the type must implement a certain interface.
  3. where T: new() the type must have a parmeterless constructor
  4. where T: U in this case our generic has two parameters and the T one must inherit from type U.
  5. where T: struct T must be a value type
  6. where T:class T must be a reference type.

Note that constraints can be combined: you can have more than one constraints for a class. In this case, the ‘struct’ and ‘class’ constraints (respectively 5 and 6) must be the first constraints. The ‘new()’ constraint, on the other hand,  is always the last one to be specified.

You can find more details on MSDN: http://msdn.microsoft.com/en-us/library/d5x73970(VS.80).aspx

There is also good examples in the book “More effective C#”

 

The S in SOLID – The hell of Helper classes and helper namespaces and helper…


I recently came across a very interesting podcast about SOLID principles and wanted to write a very brief blog entry regarding one particular principe. The Single Responsibility principle which is the S of SOLID.

Sometimes, even experienced developers seem to forget about some OOP basics and one of the most common behavior I have seen is the lazyness (or something else… don’t know) to correctly name a class, a namespace or a project. Have you ever seen someone adding an Utilities project? Or another developer creating a “Helpers” namespace that contains “Helper” classes…

Well, if you look at these classes, they usually contain everything and their opposites. While I agree that finding good names is not always straightforward, I admit that my hair stand when I come across such classes or, worse,  whole projects because it is the starting point for the mess… “I could not find a container for my method, I put it in the XYZHelper class. After all, it helps achieving a goal, so it pertains to a helper class. I never came across a HELPER namesace or class in the whole .NET framework even though, there are helper methods which are not isolated in a helper class).” 🙂

The Single Responsibility principle helps to solve this common issue. Simply, check your class and find out what are the reasons that can make it change. If you found more than one reason, then, you should split it into two or more classes. And once split, the name of the new classes is more obvious because you have split the methods into subsets based on their responsibilities which makes them have something in common (which is generally a good starting point for naming a class).

That’s the S principle (very simplified).

For more information, check out the podcast on this link: http://www.hanselminutes.com/default.aspx?showID=163

ASP.NET AJAX Collapsible form section


There are many cases where we may need to implement complex forms that contain multiple sections that can be hidden or shown depending on the user’s entries. The issue we encounter in such scenarios is that the section we want to hide or show may contain validators that must be disabled in order to let the form to post back. This can be easily achieved using a server side code, but it involves a round trip to the server which we would like to avoid for performance reasons.

I have written a generic AJAX enabled control that will help you, very easily, to hide or show a form section with client side code (Javascript) so that you no longer have to worry about all the plumbing in JS that manages validators.

You can find the article that describes the solution along with the source code on the following link: http://www.codeproject.com/KB/ajax/AJAX_Collapsible_form.aspx

How SCRUM helped our team


In 2008, I began work with a client on a new project. The client was a airline and travel agency that needed to rewrite, from scratch, their online travel booking application. The new website had the following primary requirements:

  • Improve end user experience, including performance and security issues;
  • Offer new set of products on the website (Hotel booking, car hiring and insurance purchase); and
  • The new application had to connect to a brand new back-end system.

After learning about their process and project, I suggested that we try a new approach: Scrum. My clients did not know much about Scrum. In fact, the only Scrum-like practice my client had tried was daily meetings. I insisted that using Scrum could help us build software more quickly and build it with higher quality. This was not easy to sell. The client had a number of questions, such as:

  • How can you accurately estimate a project with an iterative process?
  • How can you determine the delivery date of a project if you re-estimate it after every sprint?
  • How can your customer agree on an analysis and “sign it” if you do not have an analysis phase?
  • Isn’t Scrum just a cowboy development process since we do not have a detailed design phase?

I answered their questions or worked with them to find answers. At the same time, I did not pretend that Scrum could solve all of their problems. I did point out what they already knew:  their existing waterfall methodology, with its detailed estimates and phases, only gave the illusion that it could deliver a high quality product with all required features on budget and on time. Scrum, on the other hand, could mitigate some of these risks. After much debate, we decided to give Scrum a try.

Read more… (http://www.scrumalliance.org/articles/128-how-scrum-helped-ourteam)

Organizing classes in C#


I was doing a quick research on C# coding conventions and I found one rule that comes back in almost all coding conventions I came through: Always put fields (aka private members) at the top of the class definition.

I am not sure of the reasons to do this. Let me explain why I usually advocate the other way around: order properties and methods from the more accessible to the less accessible.

A class has two types of users:

  1. developers writing the code of the class (usually one or two developers max),
  2. developers who are ‘clients or users’ of the class (the rest of developers and other guys maintaining the software).

I consider that in the total lifecycle of a project, there might be much more developers of the 2nd type than of the first one.

When you use a class or try to maintain it (refactor it or try to find out about what it does to understand the code), you are not interested in private members. You rather focus on public methods and/or properties (concepts of black box that exposes services). Then, if you need to go further, you will probably have a look at the internals of the class. For this reason, I really prefere, when I open a class file, to directly have all interesting information ride away. Just right there and not have to scroll down.

For me this is a consequence of OOP programming and the encapsulation principle.

I would really appreciate comments… Am I the only one who advocates this? It is not a big deal and I gave up on this subject for the moment- however, I generally do not like the argument of ‘This is the standard!’ (which is the only one I got so far). I rather like the real reason underneath it but could not find anything explanation on this rule except a fellow who told me that this was a C++ programmers’ standard who did not have really the choice otherwise the compiler did not compile (I did not verify this argument yet).

Combining javascript files with Ajax toolkit library


One of the new features that came with .NET Framework SP1 is the ability to combine multiple js files in order to reduce the number of files downloaded by the browser.

In theory, you simply have to list all the JS files called by the page in a sub section of the script manager. You can get the list of files needed by your page by using the script reference profiler (third party control that lists all the files). You can find this control on http://weblogs.asp.net/bleroy/archive/2008/06/12/script-reference-profiler.aspx

Once the list is known, you just need to copy/paste it in the Script Manager control using the new ‘CompositeScript’ tag. This is an example from a real world application using Telerik and AJAX toolkit controls.

 <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
<CompositeScript ScriptMode=”Release”>
<Scripts>
<asp:ScriptReference name=”MicrosoftAjax.js”/>
<asp:ScriptReference name=”MicrosoftAjaxWebForms.js”/>
<asp:ScriptReference name=”AjaxControlToolkit.Common.Common.js” assembly=”AjaxControlToolkit, Version=3.0.20229.17016, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e”/>
<asp:ScriptReference name=”AjaxControlToolkit.ExtenderBase.BaseScripts.js” assembly=”AjaxControlToolkit, Version=3.0.20229.17016, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e”/>
<asp:ScriptReference name=”Telerik.Web.UI.Common.Core.js” assembly=”Telerik.Web.UI, Version=2008.2.826.35, Culture=neutral, PublicKeyToken=121fae78165ba3d4″/>
<asp:ScriptReference name=”Telerik.Web.UI.Common.Animation.AnimationScripts.js” assembly=”Telerik.Web.UI, Version=2008.2.826.35, Culture=neutral, PublicKeyToken=121fae78165ba3d4″/>
<asp:ScriptReference name=”Telerik.Web.UI.Common.Scrolling.ScrollingScripts.js” assembly=”Telerik.Web.UI, Version=2008.2.826.35, Culture=neutral, PublicKeyToken=121fae78165ba3d4″/>
<asp:ScriptReference name=”Telerik.Web.UI.Common.Navigation.NavigationScripts.js” assembly=”Telerik.Web.UI, Version=2008.2.826.35, Culture=neutral, PublicKeyToken=121fae78165ba3d4″/>
<asp:ScriptReference name=”Telerik.Web.UI.Menu.RadMenuScripts.js” assembly=”Telerik.Web.UI, Version=2008.2.826.35, Culture=neutral, PublicKeyToken=121fae78165ba3d4″/>
<asp:ScriptReference name=”Telerik.Web.UI.ComboBox.RadComboBoxScripts.js” assembly=”Telerik.Web.UI, Version=2008.2.826.35, Culture=neutral, PublicKeyToken=121fae78165ba3d4″/>
<asp:ScriptReference name=”Telerik.Web.UI.TabStrip.RadTabStripScripts.js” assembly=”Telerik.Web.UI, Version=2008.2.826.35, Culture=neutral, PublicKeyToken=121fae78165ba3d4″/>
</Scripts>
</CompositeScript>
</asp:ScriptManager>

Note that you can add references to your own JS files using the path to the Javascript:

i.e: <asp:ScriptReference Path=”~/js/MyJavascript.js” />

 However, this example won’t work properly. As you try to run a page that contains it, you will get the following error message:

The resource URL cannot be longer than 1024 characters. If using a CompositeScriptReference, reduce the number of ScriptReferences it contains, or combine them into a single static file and set the Path property to the location of it.

To fix this issue, you should split the list into smaller chuncks and add them in different Proxy Script Manager controls. Bear in mind that each of these controls will generate a separate JS file and therefore you may end up with as many JS files as the number of Script Manager/Proxy Script Manager controls.

<asp:ScriptManagerProxy ID=”ScriptManagerProxy1″ runat=”server”>
<CompositeScript ScriptMode=”Release”>
<Scripts>

…. SCRIPT References….(subset)
</Scripts>
</CompositeScript>
</asp:ScriptManagerProxy >

<asp:ScriptManagerProxy ID=”ScriptManagerProxy2″ runat=”server”>
<CompositeScript ScriptMode=”Release”>
<Scripts>

…. SCRIPT References….(another subset)
</Scripts>
</CompositeScript>
</asp:ScriptManagerProxy >

Another issue you should pay attention to is the order of your custom JS files. If you have any of your files that has Javascript code that executes at load (not in a function) and in which you use some Ajax functionality, ensure that you download it after the Ajax files. In other words, ensure that all Ajax library JS files are referenced before yours. I suggest that you put all your files in a separate Proxy Script Manager to isolate them and put this section as the last one in the list.

By combining files you create a new file with a URL that contains the references of all the JS included in the new resource (that’s the reason why it is limitted to 1024 characters in the URL). That’s said, you better have always the same sections with the same files in the same order so that the browser will download them only once and cache them for future use. I think that it is better to download a larger file than needed rather than redownloading many times the needed part only.

My suggestion is to put all references to common Ajax library files in multiple sections of the script manager and subsequent proxy script managers and put all this list in a/multiple user controls that you’ll add to your pages. Custom scripts should be added separately as needed or listed in one Proxy Script Manager and shared across all pages if you don’t have that many files.

As it is highly recommended to load javascripts at the end of the page, I suggest that you keep your ScriptManager empty of any JS reference and put all your references in ScriptManagerProxy controls placed at the end of the page.

Agile Design Artifacts


I recently got contracted by a company to be the technical lead for a web application development project. My first task was to come up with an architecture document for the application within 2 to 3 weeks. I rapidly realized that it was not realistic. I could eventually design the application, but I was convinced that it would not be efficient for the following reasons:

  • I was promised to get the full requirements a week after I started. I did not get them and still now, after 3 months,  there are still on going,
  • The web application was intended to connect to a back end bought from a third party provider. We did not know much about the API (actually, the API were planned to change – and still changing today after 3 months)

  • I always have been convinced that a too detailed architecture will be obsolete as soon as developers start to implement the functionality.

For these reasons, I told the team manager that I prefer not to spend my time drawing class diagrams or any sort of artifact that will be thrown away or, at best, be expensively kept up to date during the development process. What I suggested though was to:

  • Draw a high level design diagram; this diagram included all the providers and layers of the application.

  • Write few class stubs to give a direction to developers. The classes did not contain any implementation. They rather contained many “TODOs” with comments for developers; we also agreed with developers that the comments were there as a suggestion. They were allowed to go in another direction as long as they respect the overall design idea.

  • We focuse on only one type of artifact: the code itself. Well written code is the best artifact as it expresses the static view but also the dynamic view of the system (which is, from my point of view), the most important view to understand a system especially to support it.

  • We scheduled and took the necessary time to do few meetings with all developers to explain the design guidelines; this is far better than writing thick documents as developers came up with very interesting questions and suggestions from their past experiences. Once we agreed on the design, we started the development of what we called “the infrastructure” or the framework that will support the application.

During this phase, we decided to use SCRUM methodology; this was new to my client (they applied it partly in the past). I insisted on the fact that an iterative development process will help us to get things done and deliver high quality software.

We called this first phase the SPRINT 0; we did a lot of refactoring as the code was written and the application was growing in size. We decided that no interface (user interface) will be developed during this sprint; we wanted to focus only on the framework and the design.

Now, we are in the sprint 3. We delivered some functionality to the business and we had very positive comments so far. Even managers who first were skeptical regarding SCRUM methodology are now much more comfortable and confident that an iterative process can effectively help to deliver in time and with a high quality.