Exception Handling Best Practices in .NET

0

Category :


Contents

Introduction


Having a bug in your software is forgivable, and even expected. What's unforgivable is having a recurring bug you can't fix because you don't have enough information.

Plan for the worst

Check it early

Strong type checking and validation are powerful tools to prevent unexpected exceptions and to document and test code. The earlier in execution you detect a problem, the easier is to fix.

Don't trust external data

External data is not reliable. It must be extensively checked. It doesn't matter if the data is coming from the registry, database, from a disk, from a socket, from a file you just wrote or from the keyboard. All external data should be checked and only then you can rely on it.

The only reliable devices are: the video, the mouse and keyboard.

Anytime you need external data, you can have the following situations:
  • Not enough security privileges
  • The information is not there
  • The information is incomplete
  • The information is complete, but invalid
It really doesn't matter if it's a registry key, a file, a socket, a database, a web service or a serial port. All external data sources will fail, sooner or later. Plan for a safe failure and minimize damage.

Writes can fail, too

Unreliable data sources are also unreliable data repositories. When you're saving data, similar situations can happen:
  • Not enough security privileges
  • The device isn't there
  • There's not enough space
  • The device has a physical fault

Code Safely

A friend of mine often says: "A good programmer is someone who never introduce bad code in his projects". I don't believe that this is all that it's needed to be a good programmer, but surely it will put you almost there. Below, I compiled a list of the most common "bad code" that you can introduce in your projects, when it comes to exception handling.

Don't throw new Exception()

Please, don't do it. Exception is a too broad class, and it's hard to catch without side-effects. Derive your own exception class, but derive it from ApplicationException. This way you could set a specialized exception handler for exceptions thrown by the framework and another for exceptions thrown by yourself.

Revision note: David Levitt wrote me, in the comments section below, that although Microsoft still touts using System.ApplicationException as a base class in MSDN docs, this is no longer considered a good practice, as noted by Brad Adams, as you can see in his blog. The idea is creating exception class hierarchies that are as shallow and wide as possible, as you often do with class hierarchies. The reason I didn't change the article immediately was because I needed to do more research before I introduced it here. After all this research, I could not decide yet whether shallow class hierarchies are a good idea in Exception handling or not, so I decided to leave both opinions here. But, no matter what you do, don't throw new Exception() and derive your own Exception class when needed.

Don't put important exception information on the Message field

Exceptions are classes. When you return the exception information, create fields to store data. If you fail on doing it, people will need to parse the Message field to get the information they need. Now, think what will happen to the calling code if you need to localize or even just correct a spelling error in error messages. You may never know how much code you'll break by doing it.

Put a single catch (Exception ex) per thread

Generic exception handling should be done in a central point in your application. Each thread needs a separate try/catch block, or you'll lose exceptions and you'll have problems hard to understand. When an application starts several threads to do some background processing, often you create a class for storing processing results. Don't forget to add a field for storing an exception that could happen or you won't be able to communicate it to the main thread. In "fire and forget" situations, you probably will need to duplicate the main application exception handler on the thread handler.

Generic Exceptions caught should be published

It really doesn't matter what you use for logging - log4net, EIF, Event Log, TraceListeners, text files, etc. What's really important is: if you caught a generic Exception, log it somewhere. But log it only once - often code is ridden with catch blocks that log exceptions and you end up with a huge log, with too much repeated information to be useful.

Log Exception.ToString(); never log only Exception.Message!

As we're talking about logging, don't forget that you should always log Exception.ToString(), and never Exception.Message. Exception.ToString() will give you a stack trace, the inner exception and the message. Often, this information is priceless and if you only log Exception.Message, you'll only have something like "Object reference not set to an instance of an object".

Don't catch (Exception) more than once per thread

There are rare exceptions (no pun intended) to this rule. If you need to catch an exception, always use the most specific exception for the code you're writing.
I always see beginners thinking that good code is code that doesn't throw exceptions. This is not true. Good code throws exceptions as needed, and handles only the exceptions it knows how to handle.
As a sample of this rule, look at the following code. I bet that the guy who wrote it will kill me when he read this, but it was taken from a real-world example. Actually, the real-world code was a bit more complicated - I simplified it a lot for didactic reasons.
The first class (MyClass) is on an assembly, and the second class (GenericLibrary) is on another assembly, a library full of generic code. On the development machine the code ran right, but on the QA machines, the code always returned "Invalid number", even if the entered number was valid.
Can you say why this was happening?

public class MyClass
{
    public static string ValidateNumber(string userInput)
    {
        try
        {
            int val = GenericLibrary.ConvertToInt(userInput);
            return "Valid number";
        }
        catch (Exception)
        {
            return "Invalid number";
        }
    }
}

public class GenericLibrary
{
    public static int ConvertToInt(string userInput)
    {
        return Convert.ToInt32(userInput);
    }
}

The problem was the too generic exception handler. According to the MSDN documentation, Convert.ToInt32 only throws ArgumentException, FormatException and OverflowException. So, those are the only exceptions that should be handled.
The problem was on our setup, which didn't include the second assembly (GenericLibrary). Now, we had a FileNotFoundException when the ConvertToInt was called, and the code assumed that it was because the number was invalid.
The next time you write "catch (Exception ex)", try to describe how your code would behave when an OutOfMemoryException is thrown.

Don't ever swallow exceptions

The worst thing you can do is catch (Exception) and put an empty code block on it. Never do this.

Cleanup code should be put in finally blocks

Ideally, since you're not handling a lot of generic exceptions and have a central exception handler, your code should have a lot more finally blocks than catch blocks. Never do cleanup code, e.g., closing streams, restoring state (as the mouse cursor), outside of a finally block. Make it a habit.
One thing that people often overlook is how a try/finally block can make your code both more readable and more robust. It's a great tool for cleanup code.
As a sample, suppose you need to read some temporary information from a file and return it as a string. No matter what happens, you need to delete this file, because it's temporary. This kind of return & cleanup begs for a try/finally block.
Let's see the simplest possible code without using try/finally:
string ReadTempFile(string FileName)
{
    string fileContents;
    using (StreamReader sr = new StreamReader(FileName))
    {
        fileContents = sr.ReadToEnd();
    }
    File.Delete(FileName);
    return fileContents;
}
This code also has a problem when an exception is thrown on, e.g., the ReadToEnd method: it leaves a temporary file on the disk. So, I've actually saw some people trying to solve it coding as this:
string ReadTempFile(string FileName)
{
    try
    {
        string fileContents;
        using (StreamReader sr = new StreamReader(FileName))
        {
            fileContents = sr.ReadToEnd();
        }
        File.Delete(FileName);
        return fileContents;
    }
    catch (Exception)
    {
        File.Delete(FileName);
        throw;
    }
}
The code is becoming complex and it's starting to duplicate code.
Now, see how much cleaner and robust is the try/finally solution:
string ReadTempFile(string FileName)
{
    try
    {
        using (StreamReader sr = new StreamReader(FileName))
        {
            return sr.ReadToEnd();
        }
    }
    finally
    {
        File.Delete(FileName);
    }
}
Where did the fileContents variable go? It's not necessary anymore, because we can return the contents and the cleanup code executes after the return point. This is one of the advantages of having code that can run after the function returns: you can clean resources that may be needed for the return statement.

Use "using" everywhere

Simply calling Dispose() on an object is not enough. The using keyword will prevent resource leaks even on the presence of an exception.

Don't return special values on error conditions

There are lots of problems with special values:
  • Exceptions makes the common case faster, because when you return special values from methods, each method return needs to be checked and this consumes at least one processor register more, leading to slower code
  • Special values can, and will be ignored
  • Special values don't carry stack traces, and rich error details
  • All too often there's no suitable value to return from a function that can represent an error condition. What value would you return from the following function to represent a "division by zero" error?
public int divide(int x, int y)
{
    return x / y;
}

Don't use exceptions to indicate absence of a resource

Microsoft recommends that you should use return special values on extremely common situations. I know I just wrote the opposite and I also don't like it, but life is easier when most APIs are consistent, so I recommend you to adhere to this style with caution.
I looked at the .NET framework, and I noticed that the almost only APIs that use this style are the APIs that return some resource (e.g., Assembly.GetManifestStream method). All those APIs return null in case of the absence of some resource.

Don't use exception handling as means of returning information from a method

This is a bad design. Not only exceptions are slow (as the name implies, they're meant only to be used on exceptional cases), but a lot of try/catch blocks in your code makes the code harder to follow. Proper class design can accommodate common return values. If you're really in need to return data as an exception, probably your method is doing too much and needs to be split.

Use exceptions for errors that should not be ignored

I'll use a real world example for this. When developing an API so people could access Crivo (my product), the first thing that you should do is calling the Login method. If Login fails, or is not called, every other method call will fail. I chose to throw an exception from the Login method if it fails, instead of simply returning false, so the calling program cannot ignore it.

Don't clear the stack trace when re-throwing an exception

The stack trace is one of the most useful information that an exception carries. Often, we need to put some exception handling on catch blocks (e.g., to rollback a transaction) and re-throw the exception. See the right (and the wrong) way of doing it: The wrong way:
try
{
    // Some code that throws an exception

}
catch (Exception ex)
{
    // some code that handles the exception

    throw ex;
}

Why is this wrong? Because, when you examine the stack trace, the point of the exception will be the line of the "throw ex;", hiding the real error location. Try it.
try
{
    // Some code that throws an exception

}
catch (Exception ex)
{
    // some code that handles the exception

    throw;
}

What has changed? Instead of "throw ex;", which will throw a new exception and clear the stack trace, we have simply "throw;". If you don't specify the exception, the throw statement will simply rethrow the very same exception the catch statement caught. This will keep your stack trace intact, but still allows you to put code in your catch blocks.

Avoid changing exceptions without adding semantic value

Only change an exception if you need to add some semantic value to it - e.g., you're doing a DBMS connection driver, so the user doesn't care about the specific socket error and wants only to know that the connection failed.
If you ever need to do it, please, keep the original exception on the InnerException member. Don't forget that your exception handling code may have a bug too, and if you have InnerException, you may be able to find it easier.

Exceptions should be marked [Serializable]

A lot of scenarios needs that exceptions are serializable. When deriving from another exception class, don't forget to add that attribute. You'll never know when your method will be called from Remoting components or Web Services.

When in doubt, don't Assert, throw an Exception

Don't forget that Debug.Assert is removed from release code. When checking and doing validation, it's often better to throw an Exception than to put an assertion in your code.
Save assertions for unit tests, for internal loop invariants, and for checks that should never fail due to runtime conditions (a very rare situation, if you think about it).

Each exception class should have at least the three original constructors

Doing it is easy (just copy & paste the definitions from other exception classes) and failing to do that won't allow users of your classes to follow some of these guidelines.
Which constructors I am referring to? The last three constructors described on this page.

Be careful when using the AppDomain.UnhandledException event

Revision note: I was pointed by Phillip Haack in my blog of this important omission. Other common source of mistakes is the Application.ThreadException event. There are lots of caveats when using them:
  • The exception notification occurs too late: when you receive the notification your application will not be able to respond to the exception anymore.
  • The application will finish if the exception occurred on the main thread (actually, any thread that started from unmanaged code).
  • It's hard to create generic code that works consistently. Quoting MSDN: "This event occurs only for the application domain that is created by the system when an application is started. If an application creates additional application domains, specifying a delegate for this event in those applications domains has no effect."
  • When the code is running those events, you won't have access to any useful information other than the exception itself. You won't be able to close database connections, rollback transactions, nor anything useful. For beginners, the temptation of using global variables will be huge.
    Indeed, you should never base your whole exception handling strategy on those events. Think of them as "safety nets", and log the exception for further examination. Later, be sure to correct the code that is not handling properly the exception.

Don't reinvent the wheel

There are lots of good frameworks and libraries to deal with exceptions. Two of them are provided by Microsoft and I mention here:
Notice, though, that if you don't follow strict design guidelines, like those I showed here, those libraries will be nearly useless.

Conclusion

I hope that this article helps someone to code better. More than a closed list of practices, I hope that this article be a starting point for a discussion of how to deal with exceptions in our code, and how to make our programs more robust.
I can't believe that I wrote all of this without any mistake or controversial opinion. I'd love to hear your opinion and suggestions about this topic.

History

  • 9 Feb 2005 - Initial version
  • 21 Feb 2005 - Added information about ApplicationException, AppDomain.UnhandledException and Application.ThreadException

my thanks to:
http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx

Responsive Web Design: What It Is and How To Use It

0

Category :

Responsive Web Design: What It Is and How To Use It


In the field of Web design and development, we’re quickly getting to the point of being unable to keep up with the endless new resolutions and devices.

Responsive Web design is the approach that suggests that design and development should respond to the user’s behavior and environment based on screen size, platform and orientation. The practice consists of a mix of flexible grids and layouts, images and an intelligent use of CSS media queries. As the user switches from their laptop to iPad, the website should automatically switch to accommodate for resolution, image size and scripting abilities. In other words, the website should have the technology to automatically respond to the user’s preferences. This would eliminate the need for a different design and development phase for each new gadget on the market.

The Concept Of Responsive Web Design

some ideas are already being practiced: fluid layouts, media queries and scripts that can reformat Web pages and mark-up effortlessly (or automatically).
But responsive Web design is not only about adjustable screen resolutions and automatically resizable images, but rather about a whole new way of thinking about design.

Adjusting Screen Resolution

With more devices come varying screen resolutions, definitions and orientations. Many new devices(being developed every day) are able to switch from portrait to landscape at the user’s whim. How is one to design for these situations?

Part of the Solution: Flexible Everything

Now we can make things more flexible. Images can be automatically adjusted, and we have workarounds so that layouts never break (although they may become squished and illegible in the process). While it’s not a complete fix, the solution gives us far more options. It’s perfect for devices that switch from portrait orientation to landscape in an instant or for when users switch from a large computer screen to an iPad.

Ethan Marcotte wrote an introductory article about the approach
http://www.alistapart.com/articles/responsive-web-design/

Flexible Images

One major problem that needs to be solved with responsive Web design is working with images. There are a number of techniques to resize images proportionately, and many are easily done. The most popular option, noted in Ethan Marcotte’s article on fluid images but first experimented with by Richard Rutter, is to use CSS’s max-width for an easy fix.

Note that max-width is not supported in IE, but a good use of width: 100% would solve the problem neatly in an IE-specific style sheet.

img { max-width: 100%; }

While resizing an image for mobile devices can be very simple, if the original image size is meant for large devices, it could significantly slow download times and take up space unnecessarily.

Filament Group’s Responsive Images

This technique, presented by the Filament Group, takes this issue into consideration and not only resizes images proportionately, but shrinks image resolution on smaller devices, so very large images don’t waste space unnecessarily on small screens.
http://filamentgroup.com/examples/responsive-images/



For any screen that is wider than 480 pixels, the larger-resolution image (largeRes.jpg) will load; smaller screens wouldn’t need to load the bigger image, and so the smaller image (smallRes.jpg) will load.

This technique is fully supported in modern browsers, such as IE8+, Safari, Chrome and Opera, as well as mobile devices that use these same browsers (iPad, iPhone, etc.). Older browsers and Firefox degrade nicely

Stop iPhone Simulator Image Resizing

One nice thing about the iPhone and iPod Touch is that Web designs automatically rescale to fit the tiny screen. A full-sized design, unless specified otherwise, would just shrink proportionally for the tiny browser, however many noticed that images were still changing proportionally with the page even if they were specifically made for (or could otherwise fit) the tiny screen

Because this works only with Apple’s simulator, we can use an Apple-specific meta tag to fix the problem

meta name="viewport" content="width=device-width; initial-scale=1.0"

Custom Layout Structure

For extreme size changes, we may want to change the layout altogether, either through a separate style sheet or, more efficiently, through a CSS media query. This does not have to be troublesome; most of the styles can remain the same, while specific style sheets can inherit these styles and move elements around with floats, widths, heights and so on.

For example, we could have one main style sheet (which would also be the default) that would define all of the main structural elements, such as #wrapper, #content, #sidebar, #nav, along with colors, backgrounds and typography. Default flexible widths and floats could also be defined.

If a style sheet made the layout too narrow, short, wide or tall, we could then detect that and switch to a new style sheet. This new child style sheet would adopt everything from the default style sheet and then just redefine the layout’s structure.

Media Queries

CSS3 supports all of the same media types as CSS 2.1, such as screen, print and handheld, but has added dozens of new media features, including max-width, device-width, orientation and color, they will be ignored if accessed by an older computer browser that does not support CSS3.


This media query is fairly self-explanatory: if the browser displays this page on a screen (rather than print, etc.), and if the width of the screen (not necessarily the viewport) is 480 pixels or less, then load shetland.css.

Multiple media queries can also be dropped right into a single style sheet, which is the most efficient option when used:

/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}

CSS3 Media Queries

@media screen and (min-width: 600px) {
     .hereIsMyClass {
          width: 30%;
          float: right;
     }
}
this media query will run only if the minimum width is 600 pixels (therefore, 600 pixels or wider).

@media screen and (max-width: 600px) {
     .aClassforSmallScreens {
          clear: both;
   font-size: 1.3em;
     }
}
this media query will apply only to browser or screen widths with a maximum width of 600 pixels or narrower.

@media screen and (max-device-width: 480px) {
     .classForiPhoneDisplay {
          font-size: 1.2em;
     }
}

@media screen and (min-device-width: 768px) {
     .minimumiPadWidth {
          clear: both;
    margin-bottom: 2px solid #ccc;
     }
}
The min-device-width and max-device-width media query properties are great for targeting certain devices with set dimensions, without applying the same styles to other screen sizes in a browser that mimics the device’s size.

Media queries can also be defined in a standard HTML link tag:




JavaScript

Another method that can be used is JavaScript, especially as a back-up to devices that don’t support all of the CSS3 media query options.Fortunately, there is already a pre-made JavaScript library that makes older browsers (IE 5+, Firefox 1+, Safari 2) support CSS3 media queries. If you’re already using these queries, just grab a copy of the library, and include it in the mark-up: http://code.google.com/p/css3-mediaqueries-js/

sample jQuery snippet that detects browser width and changes the style sheet accordingly — if one prefers a more hands-on approach:


There are many solutions for pairing up JavaScript with CSS media queries. Remember that media queries are not an absolute answer, but rather are fantastic options for responsive Web design when it comes to pure CSS-based solutions.

Designing for Touchscreen

http://www.whatcreative.co.uk/blog/tips/designing-for-touch-screen/

Conclusion

We are indeed entering a new age of Web design and development. Far too many options are available now, and there will be far too many in the future to continue adjusting and creating custom solutions for each screen size, device and advancement in technology. We should rather start a new era today: creating websites that are future-ready right now. Understanding how to make a design responsive to the user doesn’t require too much learning, and it can definitely be a lot less stressful and more productive than learning how to design and code properly for every single device available.


my thanks to:
http://www.smashingmagazine.com/2011/01/12/guidelines-for-responsive-web-design/
http://blogs.sitepoint.com/responsive-web-design-with-html5-and-the-less-framework-3/

Javascript Functions v Methods

0

Category :

Functions

A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).

All data that is passed to a function is explicitly passed.


Let's say a function is a block of code (usually with its own scope, and sometimes with its own closure) that may receive some arguments and may also return a result.


Methods

A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.

1. It is implicitly passed the object for which it was called
2. It is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data)


A method is a function that is owned by an object (in some object oriented systems, it is more correct to say it is owned by a class). Being "owned" by a object/class means that you refer to the method through the object/class; for example, in Java if you want to invoke a method "open()" owned by an object "door" you need to write "door.open()".

The way objects have to expose their behavior are called methods. Methods thus are the artifact object have to "do" something.

In many object oriented languages, all "functions" belong to some object (or class) and so in these languages there are no functions that are not methods.

Functional vs. Object-Oriented JavaScript Development

0

Category :

JavaScript is such a flexible language that it can be used to write code that follows two radically different programming paradigms—functional programming and object-oriented programming (OOP).

Natively, the JavaScript language allows you to treat functions in just the same fashion as values. You can assign a function to a variable and also pass it around to other functions. Abstractly speaking, we can say that a JavaScript function is a value of a very special type: the value is the behavior provided and the type is something we can just call “function.”

Natively, the JavaScript language also offers objects. In JavaScript, objects are seen as plain bags of properties and methods. They look more like simple dictionaries of data and behavior than fully-fledged objects as you will find in a qualified OOP language such as C#, Java, or C++. In classic OOP, a class represents the layout of what will actually become an object once an instance of that class is created through the new operator. In JavaScript, you have no classes that provide the blueprints for objects to create. In JavaScript, the “blueprint” for an object is an implicit concept and it looks a lot like a dictionary. So in JavaScript, you just create objects and store data into them. JavaScript objects, however, offer some degree of object-oriented capabilities such as encapsulation and inheritance.

For once, the quick answer to the question that this article addresses is not the classic “It depends.” It is, instead, a less compromising “whatever you ultimately like most”. But let’s elaborate a bit on it.

Functional Programming in Brief

In functional programming the building block of code is the “function”, as opposed to the class in object-oriented programming and the subroutine in procedural programming. A function is a unit of code that only describes the operations to be performed on the input. A function gets some input and returns some output; everything else is hidden from view.

As a functional programmer, you build your applications by pipelining function calls to create a super function that just gets the program’s input and returns the program’s output. There’s typically no layer where you process the input, store state, arrange a sequence of statements, update the state, and decide about the next step. A function is a like a value and can be used as an argument and be passed to other functions as well as used in any other context where values can be used.

Note, though, that real-world functional languages such as F# also mix concepts like functions and pipelining with variables and some simple notion of state. F#, for example, lets you store intermediate results in some local variable and use it as the input for successive function calls. The scope of such variables though is fairly limited and there’s anything like global or static members.

JavaScript and Functional Programming

JavaScript is not a truly functional language such as F#. JavaScript, however, does support some constructs that are typical of a functional language. By using these constructs extensively, you can do good functional programming in JavaScript. At the end of the day, this is largely what you do when you use the jQuery library.

In JavaScript, anonymous functions are the pillar of functional programming. An anonymous function is a direct offshoot of lambda calculus or, if you like it most, a language adaptation of old-fashioned function pointers.

The only difference between a regular function and an anonymous function is in the name. In a functional context, you don’t strictly need to name a function especially if you’re using it as a value that you pass around. Here’s an example that shows how to combine together various functions.

// Function to calculate a total
var CalcTotal = function(x, y) {
   return x + y;
};
 
// Function to add taxes
var AddTaxes = function(x) {
  return x * 1.2;
};
 
// Function that pipelines the other two
var CalcTotalPlusTaxes = function (fnCalcTotal, fnAddTaxes, x, y) {
    return fnAddTaxes(fnCalcTotal(x, y)); 
};
 
// Execution
var result = CalcTotalPlusTaxes(CalcTotal, AddTaxes, 40, 60);
alert(result);

Treating anonymous functions as plain values allows you to mix data and behavior in a quite effective way. This gives you a chance to apply some design principles to JavaScript code such as Dependency Inversion. When a higher level module (whether an object or a function) depends on capabilities provided by lower level modules, you can just inject the expected behavior as an argument. In many cases, this approach augments the readability and elegance of the code; for sure, it gives you more power to deal with complexity.

jQuery and the Consecration of Functional Programming

The jQuery library called more than ever the people’s attention on functional programming. The jQuery library is based on the jquery object or $. The $ is essentially a wrapper around DOM elements and DOM elements can be passed into the object through the type constructor—the popular $(…) expression. Furthermore, jQuery allows call chaining meaning that the $ object can pass its own wrapped values into other functions that return the same $ object.

These three facts about jQuery qualify the root object of the library as a monad; and monads are a fundamental concept in the theory of functional languages. jQuery takes you to reason in terms of chunks of behavior that you concatenate and pass around. This is extremely effective as long as the values you ultimately work with are just those that library manipulates natively. The jQuery library is effective because it allows you to enjoy the power (and to some extent the cleanness) of functional programming for the Web environment where all you do is manipulation of wrapped DOM elements.

You may be a huge fan of the jQuery library and appreciate the functional lifestyle it pushes. However, that has to be put into perspective and should not become a reason to push the functional programming paradigm over everything else. Let’s have a look at the following snippet from the source code of jQuery.

jQuery.fn = jQuery.prototype = {
    init: function( selector, context ) { ... },
       size: function() { return this.length; },
       each: function( callback, args ) {
        return jQuery.each( this, callback, args );  },
       ready: function( fn ) { ... }
       :
}

As you can see, the jQuery object has its own prototype featuring capabilities such as size and each. More interestingly, when you write a jQuery plugin you just extend the basic prototype adding a new function. At the end of the day, effective JavaScript programming is always a mix of functional and object-oriented style. With jQuery, though, you are mostly exposed to the functional part of it.

Objects in JavaScript

There’s a significant difference between objects in a qualified OOP language and JavaScript. In OOP languages, the class is a blueprint for actual objects you use. In JavaScript, you just have objects whose blueprint is that of a dictionary of data and functions. When you create a new object in JavaScript, you have an empty dictionary you can fill with anything you like.

Having said that, with a bit of work you can create (and reuse) custom objects and manage for them to inherit from existing objects and also behave polymorphically. This work is just what JavaScript object-oriented libraries do.

When it comes to adding layers to JavaScript to make it closer to a qualified OOP language and gain some more programming power and code reusability, you have to choose from two main approaches for extending the capabilities of the native JavaScript objects: closures and prototypes.

Before we get to that, however, a few words about the native Object type in JavaScript and it usage.

You can use the new keyword to create a new dictionary-like object in JavaScript. Next, you stuff data into it and you can add methods by wiring functions to property names. Here’s an example:

var person = new Object();
 person.Name = "Dino";
 person.LastName = "Esposito";
 person.BirthDate = new Date(1979,10,17)
 person.getAge = function() {
 var today = new Date();
 var thisDay = today.getDate();
 var thisMonth = today.getMonth();
 var thisYear = today.getFullYear();
 var age = thisYear-this.BirthDate.getFullYear()-1;
 if (thisMonth > this.BirthDate.getMonth())
   age = age +1;
 else 
 if (thisMonth == this.BirthDate.getMonth() &&
   thisDay >= this.BirthDate.getDate())
   age = age +1;
 return age;
}

What we have is an object modeled after a person; we don’t have a Person object. A possible way to define the layout of a type is creating a new, all-encompassing function that exposes just the members we like. In addition, in JavaScript all intrinsic objects have a read-only property named prototype. You can use the prototype property to provide a base set of functionality shared by any new instance of an object of that type. These two are the mechanisms to leverage for OOP in JavaScript.

Object-orientation through Closures

A closure is a general concept of programming languages. Applied to JavaScript, a closure is a function that can have variables and methods defined together within the same context. In this way, the outermost (anonymous or named) function “closes” the expression. Here’s an example of the closure model for a function that represents a Person type:

var Person = function(name, lastname, birthdate) 
{
   this.Name = name;
   this.LastName = lastname;
   this.BirthDate = birthdate;
 
   this.getAge = function() {
      var today = new Date();
      var thisDay = today.getDate();
      var thisMonth = today.getMonth();
      var thisYear = today.getFullYear();
      var age = thisYear-this.BirthDate.getFullYear()-1;
      if (thisMonth > this.BirthDate.getMonth())
          age = age +1;
      else 
         if (thisMonth == this.BirthDate.getMonth() &&
             thisDay >= this.BirthDate.getDate())
             age = age +1;
      return age;
   }
}

As you can see, the closure is nothing more than the constructor of the pseudo-class. In a closure model, the constructor contains the member declarations and members are truly encapsulated and private to the class. In addition, members are instance based, which increases the memory used by the class. Here’s how you use the object:

var p = new Person("Dino", "Esposito", new Date( ... );
alert(p.Name + " is " + p.getAge());

The closure model gives full encapsulation, but nothing more. To compose objects, you can only resort to aggregation.

Object-orientation through Prototypes

The prototype model entails that you define the public structure of the class through the JavaScript prototype object. The following code sample shows how to rewrite the preceding Person class to avoid a closure.

// Pseudo constructor
var Person = function(name, lastname, birthdate)
{
  if(name && lastname && birthdate) {
   this.initialize(name, lastname, birthdate);
  }
}
// Members
Person.prototype.initialize = function(name, lastname, birthdate)
{

 this.Name = name;
 this.LastName = lastname;
 this.BirthDate = birthdate;
}

Person.prototype.getAge = function()   
{
 var today = new Date();
 var thisDay = today.getDate();
 var thisMonth = today.getMonth();
 var thisYear = today.getFullYear();
 var age = thisYear-this.BirthDate.getFullYear()-1;
 if (thisMonth > this.BirthDate.getMonth())
  age = age +1;
 else 
    if (thisMonth == this.BirthDate.getMonth() &&
     thisDay >= this.BirthDate.getDate())
     age = age +1;
 return age;
}

In the prototype model, the constructor and members are clearly separated and a constructor is always required. As for private members, you just don’t have them. The var keyword which would keep them local in a closure doesn’t apply in the prototype model. So you can define getter/setter for what you intend to be properties, but the backing field will anyway remain accessible from the outside. You can resort to some internal (and documented) convention such as prefixing with an underscore the name of members you intend as private. It’s just a convention, however.

By using the prototype feature you can achieve inheritance by simply setting the prototype of a derived object to an instance of the “parent” object.

Developer = function Developer(name, lastname, birthdate) 
{ 
   this.initialize(name, lastname, birthdate);
}
Developer.prototype = new Person();

Note that you always need to use this to refer to members of the prototype from within any related member function.

Closure vs. Prototype

In the prototype model, members are shared by all instances as they are invoked on the shared prototype object. In this way, the amount of memory used by each instance is reduced which would also provide for faster object instantiation. Aside from syntax peculiarities, the prototype model makes defining classes much more similar to the classic OOP model than the closure model.

The choice between closure and prototype should also be guided by performance considerations and browser capabilities. Prototypes have a good load time in all browsers; and indeed, they have excellent performance in Firefox. (In contrast, closures have a better load time than prototypes in Internet Explorer.) Prototypes provide better support for IntelliSense, and allow for tool-based statement completion when used in tools that support this feature, such as Visual Studio. Prototypes can also help you obtain type information by simply using reflection. You won’t have to create an instance of the type in order to query for type information, which is unavoidable if closures are used. Finally, prototypes allow you to easily view private class members when debugging. Debugging objects derived using the closure model requires a number of additional steps.

As an example, consider that the Microsoft AJAX library is built using the prototype model (and the closure model was discarded along the way).


Conclusion

JavaScript is neither 100% functional or object-oriented. However, it lends itself to support to a good extent both paradigms, because in a way it borrows concepts from both qualified functional and object-oriented languages. This inevitably creates some noise around the programming techniques you can employ. As a developer, you must be ready to accept compromises that may not be acceptable in a fully-qualified functional or object-oriented scenario.

JavaScript is a must today for writing client-side code for Web and mobile applications. And the client-side code we are called to write is no longer plain scripting of the document object model as it was when the language was introduced. Today, we often use JavaScript for some client-side logic and input validation. To make the whole development process more sustainable, we resort to JavaScript libraries that abstract through functions or classes some of the most common tasks. The jQuery library is just the most illustrious example.

Because of the success of the jQuery library, functional programming is probably gaining momentum and overcoming object-oriented programming in JavaScript. But in the end, the final decision is left to you and attitude, skills, and ease are the key parameters for a decision. You don’t have to take it as a matter of religion and pick up option and stick to that forever. To use JavaScript at its best, you probably have to mix functional features with OO features.

Having said that, if I have to write client code for a Web front-end, I’d probably go with jQuery, use a lot of anonymous functions and don’t even bother about custom objects. Instead, if I have to write my own framework to support some server-side infrastructure, well, I’d probably opt for an object-oriented approach and consider closures or prototypes.

my thanks to:
http://msdn.microsoft.com/en-us/scriptjunkie/gg476048.aspx