Use ViewModels to manage data & organize code in ASP.NET MVC applications

The concept of the ViewModel isn’t just for ASP.NET MVC, as you’ll see references to ViewModels throughout the web in articles and blog posts about the MVC, MVP, and MVVM patterns. Those posts and articles can center around any number of technologies such as ASP.NET, Silverlight, WPF, or MVC… This post will investigate ViewModels as they apply to the world of ASP.NET MVC.

What is an ASP.NET MVC ViewModel?

In ASP.NET MVC, ViewModels allow you to shape multiple entities from one or more data models or sources into a single object, optimized for consumption and rendering by the view. The below image illustrates the concept of a ViewModel:

 

image_16

The purpose of a ViewModel is for the view to have a single object to render, alleviating the need for UI logic code in the view that would otherwise be necessary. This means the only responsibility, or concern, of the view is to render that single ViewModel object, aiding in a cleaner separation of concerns (SoC). Concerns are distinct aspects of the application that have a particular purpose (i.e., concern), and keeping these aspects apart means your application is more organized, and the code more focused. Putting data manipulation code in its own location away from the view and controller, enforces SoC.

Using ViewModels in MVC for finer granularity and better SoC leads to more easily maintainable and testable code. Remember, unit testing is about testing small units.

Along with better coding practices, there are many business reasons demonstrating why you might consider using ViewModels:

  • Incorporating dropdown lists of lookup data into a related entity
  • Master-detail records view
  • Pagination: combining actual data and paging information
  • Components like a shopping cart or user profile widget
  • Dashboards, with multiple sources of disparate data
  • Reports, often with aggregate data

The above scenarios are common to a wide variety of applications, and deal with more complex data than basic CRUD forms-over-data page (e.g., a simple 1:1 mapping to the db table). For example, providing a list of states, and ensuring that the state that matches the state of current customer, means that you need to either provide two sets of data or a single set of customer/state data combined, as shown in the image below.

 

image_6

Some scenarios such as a lookup table representing states in the USA, could easily work with either ViewModels or a ViewBag/ViewData object, so there is some potential overlap at times. It’s up to the application architects and developers to decide what works best with their exact use case.

Creating a ViewModel

Although a ViewModel consists of multiple entities, at its core a ViewModel is still just a class – and one that doesn’t even inherit from anything special, as many MVC classes do.

Physically, ViewModels can exist in different locations, listed below:

  • In a folder called ViewModels that resides in the root of the project. (small apps)
  • As a .dll referenced from the MVC project (any size app)
  • In a separate project(s) as a service layer, for large applications that generate view/content specific data. (enterprise apps)

Since a ViewModel is just a class, the easiest way to get started using one is to create a new folder named ViewModels and add a new code file to it.

To create the CustomerViewModel ViewModel, add the Customer and StatesDictionary types as properties to form one CustomerViewModel class. In the example below, the CustomerViewModel class contains the newly defined properties.

public class CustomerViewModel 

{

    public Customer Customer { get; set; }

    public StatesDictionary States { get; set; }

    public CustomerViewModel(Customer customer)

    {

        Customer = customer;

        States = new StatesDictionary();

    }

}

Generally, ViewModels contain the word “ViewModel” as part of its name; however, the conventions at work here are for consistency in code readability, since other classes in MVC state their intents in their names as well (e.g., names of controllers, action methods, etc…use conventions in their names).

The StatesDictionary class is a simple Dictionary object containing two type parameters of type string. The class also contains the definitions for all the members in the Dictionary (i.e., the state data). The only property in the StatesDictionary class is the StateSelectList, which is an object that Html Helpers use with to render an HTML <select> element that displays a listing of states. The type Dictionary<string, string> in the StateSelectList property maps to the state abbreviation then state name, respectively.

public class StatesDictionary

{

    public static SelectList StateSelectList

    {

        get { return new SelectList(StateDictionary, "Value", "Key"); }

    } 

    public static readonly IDictionary<string, string> 

        StateDictionary = new Dictionary<string, string> { 

      {"Choose...",""}

    , { "Alabama", "AL" }

    , { "Alaska", "AK" }

    , { "Arizona", "AZ" }

    , { "Arkansas", "AR" }

    , { "California", "CA" }

    // code continues to add states...

    }; 

}

Data that lives in small lists and infrequently changes, like the StatesDictionary class, exists in all types of applications. In real world applications, you’ll find a variety of methods for dealing with lookup data such as a list of states – often XML files and SQL tables. You can replace the code in the StateDictionary method to use entities from Entity Framework, read data from files, or any data access code that you require.

After creating the ViewModel, the next steps are to instantiate it in a controller and return it to the view.

Getting the ViewModel to the view

Starts with the controller…

Sending a ViewModel to the view for rendering will work the same as when dealing with a model. Since it’s just a class, the view doesn’t know, and doesn’t care, where the model or ViewModel came from. You can create the instance of the ViewModel class in the controller, or resolve it if using an IoC container. Remember that just as you would do with views, you should keep controllers clean of unnecessary code, meaning that only code that fetches the model or ViewModel belongs here, and little more.

public ActionResult Edit(int id)

{

    Customer customer = context.Customers.Single(x => x.Id == id);

    var customerViewModel = new CustomerViewModel(customer);

    return View(customerViewModel);

}

Then the view renders the ViewModel…

In order for the view to know what object to use, set the @model keyword to point to the ViewModel, just like you already would with a regular model.

@model FourthCoffee.Web.ViewModels.CustomerViewModel

Because the Customer object is a property of the ViewModel, you’ll see the model.Class.Property syntax to access the ViewModel data, similar to the following line of code.

<div class="editor-label">

    @Html.LabelFor(model => model.Customer.FirstName)

</div>

<div class="editor-field">

    @Html.EditorFor(model => model.Customer.FirstName)

    @Html.ValidationMessageFor(model => model.Customer.FirstName)

</div>

@* ...View code continues rendering properties... *@

Additionally, you can edit the Edit/Create views so that the DropDownList containing a list of the states will display, and display the correct state matching that of the customer.

<div class="editor-field">    

    @Html.DropDownList("state", new SelectList(StatesDictionary.StateSelectList, 

                       "Value", "Text", Model.Customer == null ? "" : Model.Customer.State))

    @Html.ValidationMessageFor(model => model.Customer.State)

</div>

As you might have noticed, using a ViewModel is just as easy as using the ViewBag or ViewData objects. ViewModels, however, provide those extra benefits like being easier to test and optimize.

Checking the results

After a user navigates to the /Customers/Edit/1 URL in the browser, the Razor view engine renders the CustomerViewModel similarly to the following screen shot.

image_4

The State DropDownList displays the states and the current state for that customer, as expected.

Digging Further into ViewModels

Because ViewModels render pre-manipulated data that no longer have those 1:1 mappings between model classes and database tables, you’ll need to do create mappings yourself. You can manually map small ViewModels, but this will quickly become burdensome when mapping larger classes, especially when working with parent-child-grandchild, multi-level, or complex data. This is where a tool such as AutoMapper comes into play. AutoMapper will let you fluently setup mappings between ViewModels and models more easily than doing so manually, or writing your own mapper.

Here are some tips for using ViewModels:

  • Put only data that you’ll render in the ViewModel.
  • The view should direct the properties of the ViewModel, this way it fits better for rendering and maintenance.
  • Use a mapper when ViewModels become complex.

Some tools that can help assist you in generating POCOs (Plain Old CLR Objects) for models and ViewModels are:

POCO Generator

EF POCO Templates

In addition to these tools, you can use MvcScaffolding to create actions and views based on ViewModels. MvcScaffolding, invention of ASP.NET team member Steve Sanderson, gives you more power in creating CRUD, repository, unit test and other templates quickly and painlessly. Check out Steve’s Multi-part series on MvcScaffolding here. MvcScaffolding works with ViewModels as well as models.

You should always prefer using a ViewModel rather than instantiating multiple models and putting that manipulation code in the controller.

Summary

ViewModels help you organize and manage data in MVC applications when you need to work with more complex data than the other objects allow. Using ViewModels gives you the flexibility to use data as you see fit. ViewModels area generally a more flexible way to access multiple data sources than models + ViewBag/ViewData objects.

Further reading: Comparing the MVC and MVVM patterns along with their respective ViewModels

Download the code!

A 30 year sorting algorithm saga: from 250k to 14GB in one minute

Microsoft Research busted through the world record for sorting an unprecedented amount of data in under one minute, with a new sorting technique called MinuteSort (with flat datacenter storage). The Microsoft Research team sorted the equivalent of two 100-byte data records for every human being on the planet.

That’s a rough equivalent of a short email message, for example, this series of 1’s represents 200 bytes:

1111111111111111111111111111111111111111111111111111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111111111111111111111111111111

This is 200 bytes of a plain text message you might send in an email.

How much wood could a woodchuck chuck if a woodchuck could chuck wood?
Good woodchucks chuck much.

Multiply that by the population of planet Earth, currently at around 7 BILLION, and the result is 1,400,000,000,000 bytes, or over 14GB in one minute.

That’s a lot of data to wade through, and sorting hasn’t always been so fast and sexy. Take a look at this scan of an ancient TI-99 programming magazine article from 1983 on five popular sorting algorithms, some still used today.

  • Bubble Sort
  • Shell Sort
  • Selection Sort
  • Heap Sort
  • Quick Sort

Here’s a sampling of the article, page 1 & 2 (Download the complete 5 pages)

 

Ti-1_2ti-1a_2

 

Turn to the last page or the article and you can see that in 1983 the Quick Sort, wins the honor of sorting roughly 250k in about 1 minute and the Bubble sort can run equivalent of the 200 byte sample sample above in about 6 minutes (ouch).

image_12

How times have changed.

Sorting basics from Carnegie Mellon http://www.cs.cmu.edu/~adityaa/211/Lecture12AG.pdf [pdf]

Download the complete article

Big congrats to the awesome team at Microsoft Research! 100 points and a Geritol if you are old enough to have used a TI-99 or have read this magazine.

Partial views in ASP.NET MVC

What is a partial view and when should I use it?

As developers become familiar with the ASP.NET MVC model, they’ll naturally want to create reusable components filled with content & code. In Web Forms, we could do this by creating a web user control or a web server control, but in MVC, we will use partial views. You’ll notice that conceptually, all of the scenarios below would work for either technology.

  • A stock ticker that’s displayed on each page in an application.
  • A calendar widget that’s displayed on multiple pages in application.
  • A login box.
  • A social networking component used on multiple pages, such as a Facebook Like button.

While ASP.NET MVC partial views may behave similarly in theory to web user controls, syntactically and functionally, the two behave differently. Web user controls found in web forms uses ViewState, PostBacks, and Events while MVC partial views do not use any of the preceding techniques for managing state. Just as ASP.NET web user controls do, partial views can tap into the models contained in your application as well as share data between other application components.

Rendering partial views

Partial views in ASP.NET MVC 3 allow the developer to create reusable content with the very precise and clean Razor syntax (or ASPX). The syntax that renders the partial view is implemented as an Html helper. The Html.Partial helper renders the partial view named “_FeaturedProduct” inline. The first argument of all overloaded methods in the call the @Html.Partial expect the view/partial’s file name, without the file extension. Adhering to convention, the @Html.Partial helper assumes the view resides in the \Views\Shared\ folder. Additional overloads in the @Html.Partial method allow you to pass ViewData/ViewBag objects between views/partials (see below under Sharing data…).

The code below demonstrates the call to render the featured product partial view.

<div>
  @Html.Partial("_FeaturedProduct")
</div
>

Partial views can be rendered inside a Layout Page (or if using MVC 2/3 w/ASPX, the Master Page) as well as regular views.

There are some cases where you might like to step aside and write directly to the HTTP Response stream rather than having a partial view render the results (partials/views use MvcHtmlString/StringWriter). To do so, use the Html.RenderPartial helper.

<div>
  @Html.RenderPartial(“_FeaturedProduct”)
</div
>

Use Html.RenderPartial for streaming images or other elements that are media-centric or where faster download times are highly important.

Creating a partial view

Both partial views and regular views are .cshtml files, with the difference being the folder where the partial views reside: \Views\Shared\. Use the Add New View dialog by accessing the context menu from the \Views\Shared node in Solution Explorer. The Add New View template dialog offers choices for creating your partial views, including the option for strongly typing views. Don’t forget to check off  “Create as a partial view” or you’ll end up with a lot of code to delete.

SNAGHTML44dfac8

Once you’ve created the view you can get started customizing it by simply editing the file. There’s no problem in deleting or modifying the view’s code, as there’s no designer tied to it. The code shown below (_FeaturedProduct.cshtml) is the same code the default view template creates, but modified to display the featured product differently:

<style type=“text/css”>
    .featuredProduct {border: solid 1px #000}
</style
>
<
div>
    <div>
        <h2>
            Our Featured product:<br />
            @ViewBag.FeaturedProduct.Name
        </h2>
    </div>    <div>
        <h3>
            Now discounted to $@String.Format(“{0:F}”, ((decimal)ViewBag.FeaturedProduct.Price)-100)
        </h3>
    </div>  
    <div>
        @Html.ActionLink(“Featured Product Details”, “Details”, new { id = ViewBag.FeaturedProduct.ProductId })
    </div> 
    <div>
        <img class=“featuredProduct” src=@Href(“~/Content/Images”)/@ViewBag.FeaturedProduct.ImageName” alt=Featured Product”/>
    </div
>
</
div
>

As with strongly typed views, strongly typed partial views also support dot notation syntax and access to the model, ViewBag, ViewData and other classes specifically designed for sharing data.

It should be clear when reading through the above code that the syntax of partial view looks the same as a regular view. The important take-away is not about the syntax but how the partial view is used. However, a syntactic benefit to developers is the consistency between both partial and full views, particularly when we need to share data between them.

Sharing Data between views and partial views

It’s a common occurrence to pass data between components of an application, and in this case those components are MVC partials, views & controllers. As previously noted, you should use the ViewBag or ViewData classes to share data across views and controllers. First, a few notes on ViewBag and ViewData:

  • ViewData was available in previous versions; ViewBag was released with MVC 3.
  • ViewData can contain any type of data in a name-value pair format. I.e., ViewData[“Message”] = “Welcome”;
  • ViewBag objects are just wrappers around ViewData objects, and allow developers to code to them using strongly typed syntax.
  • ViewBag objects can be extended by simply setting properties in a more fluent syntax. I.e.,  ViewBag.Customer = new Customer(1,”Smith”);

If code in a controller uses either the ViewBag or ViewData classes, those classes will be available throughout the view’s lifecycle, and that includes its partial views.

The preferable object is the ViewBag. Because of its more fluent and dynamic syntax, there’s more complex objects that can be shared quite easily between components. The sample below demonstrates setting up the ViewBag object in the controller so it will be available to all necessary components:

ProductModel productModel = new ProductModel();        
public ActionResult Index()
{
    ViewBag.FeaturedProduct = new FeaturedProduct(105, "The Most Awesome Bike Ever!", 1000.00M, "bike4.png");          
    return View(productModel.Products);           
}

The ViewBag is accessed inside the view or partial using the follows syntax:

@ViewBag.FeaturedProduct.Name

Summary

Partial views are a great way to reuse fragments of HTML and Razor syntax together, with the ability to easily share data.

Resources:

Introducing Razor

Introducing MVC Development w/the Razor View Engine

Razor View Syntax

How to Connect to SQL Azure through SQL Server Management Studio 2008 (SSMS 2008)

Most developers on the Microsoft stack that use SQL Server, and who are migrating their databases to SQL Azure, likely work in SQL Server Management Studio 2008 (SSMS 2008), Visual Studio, or a mixture of both, for DBA and data management tasks. Fortunately, SQL Azure has two options for those who need to administer, create, maintain, and develop using SQL Azure: The SQL Azure Management Portal and SSMS 2008.

Before you start — If you want to try out the online tools or see take SQL Azure for a spin with SSMS 2008, sign up for a 90 day free trial.

Connect to SQL Azure from SSMS 2008

You can use SQL Server Management Studio (including, and especially, SQL Express) to connect to SQL Azure, but you first need to have some information handy that you can find in the SQL Azure Online Management Portal. Once there, you can view your subscription information including the information you need to connect to a SQL Azure server or database.

image3

Here is the information you need:

  1. The fully qualified server name. See the blocked out, red, parts of above image, as to where you can locate your server info.
  2. Valid credentials that you have already setup via the online SQL Azure Management Portal (of course, the password is not available for viewing, as it should be memorized anyway)

Enter this information into the SQL Server 2008 Connect to Server dialog, and click the Connect button to authenticate. Don’t forget you must choose SQL Server Authentication before you may enter credentials.

image16

Upon successful authentication, SQL Server Management Studio opens. This is the exact same SSMS you are familiar with, with the only difference being that you have connected to SQL Azure instead of a SQL Server on your LAN.

SNAGHTMLa64d4e1

From here you can run queries, manage tables, and do all the SQL administrative tasks you need to. Note there is a SQL Azure Database node in the Template Explorer that you can access from the View menu. Of course if you are using SQL Azure you’ll want the SQL Azure SDK for Visual Studio 2010.

Connect to SQL Azure from Visual Studio

The same credentials and authentication happen in both tools, SSMS and Visual Studio. This means all that you need to do is open the SQL Server Object explorer and connect exactly as you would any SQL Server in your LAN. Once connected, you can enjoy administering and working with SQL Azure inside of Visual Studio.

SNAGHTMLcf0cc28_1

Troubleshooting SQL Azure Connectivity

The Firewall check failed error is very common, as you need to enter an IP Address range to connect to SQL Azure from various client programs (i.e., SSMS). Here’s the error text:

Firewall check failed. Cannot open server ‘SERVERNAME’ requested by the login. Client with IP address XXX.XXX.XXX.XXX is not allowed to access the server. To enable access, use the SQL Azure Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range. It may take up to five minutes for this change to take effect.

If you get this error you can reset it from the Windows Azure Mgmt Portal. Just navigate to the server you need access to, then add in the IP Range, as shown in the image below:

image_4

Alternatively, you can use SQLCMD in the Windows command prompt which will look something like this:

C:\>SQLCMD –U<user>@<server> -P<password> -S<server>.database.windows.net

exec sp_set_firewall_rule N’Allow Windows Azure’,’0.0.0.0′,’0.0.0.0′

SQLCMD Azure commands: http://msdn.microsoft.com/en-us/library/windowsazure/ee621783.aspx

NOTE: Only the server-level principal login (this is the primary/master login that you use to connect to the Windows Azure Portal online, a Windows Live Id), while connected to the master database, can configure firewall settings for your SQL Azure server. Also, check out the SQL Azure troubleshooting for other common errors, troubleshooting, and help.

Common JavaScript mistakes and pitfalls you can avoid

Having solid JavaScript skills is more important than ever in today’s web applications, and will continue to grow in importance as more browsers, IDEs, etc…, boast of HTML5 feature support. New HTML5 elements such as <canvas> , and features like Web Storage, Web Sockets, or Geolocation depend heavily on JavaScript. Despite tons of freely available, open source, or 3rd party libraries such as jQuery, Prototype, or Script.aculo.us, we still need to keep in mind that they’re just JavaScript layered on top of JavaScript – a level of abstraction. Knowing the under the hood workings and “gotchas” of JavaScript will certainly give you a boost with writing better code.

Developers that use strongly typed languages tend to treat JavaScript as a restricted rather than an expressive language, as they’re used to working with many compiler restrictions. On top of that, JavaScript’s reputation as a “toy, browser-only, language” precedes itself; many developers don’t bother to look deeply at some of its powerful features, as well as some language quirks that can really cause trouble.

The truth is out there: Dealing with truthy/falsy values

Dealing with comparisons and equality is usually straightforward, but JavaScript has a few caveats. Because of the way JavaScript deals with expressions, it has two sets of equality operators and some complicated rules around one of them (==/!==). The first set…

The “Equals” operator  ( = = )  and The “Does-not-equal” Operator ( ! = )

And the second set…

The “Strict Equals” operator ( = = = ) and The “Strict Does-not-equal” Operator ( ! = = )

If you’re wondering why JavaScript has two sets of equality(ish) operators, it’s because JavaScript works on the premise of truthy and falsy values.  The == / != operators will work as you might expect if the operands are of the same type (boolean), but if they are not, the == and != operators try to coerce the values, using a rather large and drawn out ritual to determine the result. Truthy/falsy values are a means for JavaScript to deal with non-Boolean expressions, by pretending as if they are Boolean anyway.

As a rule of thumb, JavaScript evaluates the values in the list below as false, and everything else as true:

  • false
  • null
  • empty string (“”)
  • 0
  • NaN

Since values like null, “”, and NaN, aren’t boolean values but are still treated as such, that makes them falsy. In short, when you compare expressions that aren’t actual boolean values, JavaScript can produce results that are inconsistent with what you might expect. For example, if you compare the value 0 to false, this is what you get:

(0 == false)  // true 
(0 === false) // false (correct)

When expressions accept anything, including NaN, undefined, etc…, there’s a lot of room for mistakes, even by experienced developers. Amplify that with the many rules involved to mentally juggle, and it too easy to see how == and != disrupt your thought processes while coding.

The take-away: the strict === and !== operators are the best way to go, but don’t shrug off the equals operator just yet, as you’ll likely run across them daily in the JavaScript world, making this valuable information for the maintenance coder.

What exactly is an isNaN(NaN); anyway?

NaN, or Not-A-Number, is a construct of JavaScript that’s useful only in very specific edge cases. Why then, is this important to know? Being a mischievous little code gremlin, NaN pops up everywhere. It’s a property of the Number object, (Number.NaN), and default value of NaN is NaN, yet it’s a falsy value. When trying use NaN in an expression, NaN returns a false every time. Since NaN is no help in determining what is actually non-numeric, you’ll need an alternative. Fortunately there is a very reliable isNaN() function you can use. Notice when the isNaN() function evaluates an alphanumeric string, the result is true, and a false for numeric values. To further investigate how isNaN() behaves, enter a few of the following statements in the Console tab of any browser’s dev tools and browse the results. (IE F12 dev tools featured below).

SNAGHTML6fc7755

isNaN() works as expected with numbers and alphanumerical data.

The conculsion: use isNaN().

Is eval() evil or just misunderstood?

eval()is the little function that wants to do everything for you, including dynamically creating and executing JavaScript.  Want to parse JSON? eval(). Want to clump a bunch of stuff together? eval(). Want to make up code to run on the fly? eval(). eval() finds ways to do something, anything, with what you give it, making it easy for developers to do both awesome and horrible things with it.

In an attempt to keep eval() innocent, many suggest limiting eval() usage to the following scenarios:

1) You need to allow script to run dynamically.

This opens up your page to potential security issues, so only use this when it’s necessary, as there are a few different ways to execute code dynamically in JavaScript (a quick Bing search shows many different techniques). That leaves…

2) Parsing JSON

You can use eval() for JSON parsing; however, you are still going to run into the same security issues. On top of that, the JSON.parse() method works much better as it’s meant just for JSON handling.

In general, stay away from eval() where you can, it has the potential to get evil quickly, and there’s usually a decent alternative.

Avoid function faux pas.

Functions live a first class life In JavaScript, so they’re not just functions, they’re objects too. It all depends very much on how you them. Take, for example, the following simple function to calculate two numbers:

var result = function (a, b) { return a + b;};

In many languages, the result passed back from the function will contain the sum of the values of the arguments, a, and b. In JavaScript; however, there is more to the story. Opening any browser’s developer tools and inspecting the code, shows the type as an “Object (Function)” and its value as the function itself.

SNAGHTML45e09f_1

You don’t need to, but you can, define and name functions. If you don’t provide a name when creating an inline function, it’s an anonymous function.

Having the knowledge that functions are objects allows you to better understand and work with Open Source or 3rd Party libraries, such as jQuery or Script.aculo.us. Consider jQuery’s chaining feature, that allows you to “tack on”, i.e., chain, other methods to the end of the previous method, in a single statement. Since the function is also an object, you can expect to call methods on it using dot notation, as the following simple jQuery chaining example demonstrates:

$("#inputBox").removeClass("normal").addClass("error");

In addition to function behavior, it’s necessary to know how to write good, clean, functions. Since JavaScript throws everything into a global namespace, you’ll want to encapsulate your functions into namespaces with classes and members (see below). And watch out for globals…

A variable of global proportions.

The authors of JavaScript intended it to be a language with a very low barrier for entry for the internet pioneers circa 1995. Because of this, they made the decision to allow, and even encourage, globally scoped variables. One or two global variables in a very small program can be useful, even manageable, and was certainly not a big issue at the time since HTML had only a few tags and the DOM a handful of nodes. However, JavaScript has grown into arguably the most popular language in the world, and has powered a spectrum of applications from the smallest to the largest. Anything other than the simplest of sites can contain nasty bugs because of the global space.

When possible, avoid global variables, and here’s why:

  • It’s too easy to have variable naming clashes in large applications.
  • It’s too easy to overwrite the wrong variable, or the right variable at the wrong time, when there are many variables accessible from anywhere.
  • Not needing to declare variables means there are often “floaters” hanging around in globally-scoped memory, but doing nothing.

A good workaround to this language gotcha is to create your own namespace and classes in it, and store any would-be global variables as properties of that object instead. Though they’re not real namespaces, they are objects that can behave like namespaces, making it easier for you to organize your code. The code below provides an outline of how you can create and access your own namespace:

var SampleNamespace = new function () { };
SampleNamespace.SampleGlobalObject = new function () {
 
    // Private function 
    var privateFunction = function ()
    { }
 
    // Public function
    this.publicFunction = function ()
    { }
}
// Calling the public function 
var publicFunctionTest = function () {
    SampleNamespace.SampleGlobalObject.publicFunction();
}

Global variables aren’t the only problematic variables in JavaScript. JavaScript doesn’t perform block scope, so variables you define can inadvertently become as error prone as global variables. The only scope smaller than the global scope is function scope. This means that you can access variables where you might expect otherwise, such as outside an if/else or for loop.

Although JavaScript is a dynamic, expressive, language, you need to organize it into namespaces, classes, and other units for a solid maintenance experience.

Summary

Watch out for some of the most common pitfalls that developers encounter, even while using Open Source libraries such as jQuery. There are, of course, many more language quirks and features that can also cause trouble, as with any language. If you want to go deeper into JavaScript, here are two highly recommended books.

JavaScript: The Good Parts by

JavaScript Patterns by Stoyan Stefanov