:::: MENU ::::

Tuesday, March 17, 2009

It seems like such a trivial thing to be talking about but not knowing the difference between the two operators can make a huge difference between working code and code that only seems to work.

Let me illustrate:

        bool b = false;

        bool c = true;

        if(b & c)

            // do something

 

        if(b && c)

            // do something

In the code above, both b & c and b && c evaluate to false, so  we are safe.  No problems.  But this leads us to believe that the following code is also safe:

        string s = null;

        if(s != null & s.Length > 0)

            // do something

 

        if(s != null && s.Length > 0)

            // do something

and this is what would get you in trouble.

The single ampersand and single pipe are knows as “bit wise operators.”  What this means in practical terms is that they will take whatever they find on BOTH sides of the operator and AND (&) or OR(|) them together.

So in the case of:

if(s != null & s.Length > 0)

s.Length > 0 will still get evaluated even if s is null.  Not exactly what we had in mind.

There is another side effect of bitwise operators that gets used very infrequently.  Because they are bitwise, I can use them on integers as well as boolean values.

int i= 5 & 6;

is a perfectly legal construct in CSharp.  It will AND all the bits that make up 5  (101) and all the bits that make up 4 (100) and store the result in i (4 or 100).

On the other hand, && and || are strictly used for boolean expressions and will evaluate as little of the expression as it can get away with.

This is why we can write:

        if(s != null && s.Length > 0)
            // do something

If s is null, we already know that the expression will fail, so there is no need to evaluate the string’s length.

And now for one of my favorite binary statements.

There are 10 types of people in the world.  Those who understand binary and those who don’t.

 

Friday, March 13, 2009

Rather than using Copy[Ctrl C] and paste [Ctrl V] in pairs, developers can  store multiple cut/copy segments in the memory and use Ctrl+Shift+V to cycle through them.

To try this, simply select texts in editor and continue to copy your selections using Ctrl C. You can copy up to 20 selections at a time.

Now point your cursor where you want to insert these selections and select Ctrl+Shift+V. Keep hitting ‘V’ key to cycle through the list of all the selections you have.Hit enter and your selected selection will be pasted where cursor is located.

 

Tuesday, March 10, 2009

From my recent engagements I collected few performance anti-patterns that make ASP.NET web application to perform the way that is less than optimal. Many related to architecture and design.
Below is the list of the anti-patterns and related materials on how to identify, analyze, and fix it.
Have fun - if you feel like sharing your own experiences - that would rock my world!

Why My ASP.NET Application Slow?

 

Thursday, March 5, 2009

Introduction

JQuery is a powerful JavaScript library that enables the developer to do more in less code, a point which I hope to show you in this article. Rather than give a brief overview, let's learn in this article by example.

To start, JQuery uses the $ notation to target the HTML elements for retrieval or manipulation purposes. As an example, take a look at some of the ways you can access HTML elements.

Listing 1: Accessing a single or array of elements

  1. $("p") //accesses all p elements  
  2. $("#pid") //accesses an element by its ID  
  3. $(".p") //accesses elements using a class name  

The notation you see above, using an identifier within the $() notation, is a common approach across most JavaScript libraries. Not all libraries provide all three of these features as simple as JQuery does. Whether it's a single element or an array, JQuery makes working with elements easy. Let's take a look at what can be done with JQuery.

Selectors

As we saw above, JQuery makes it easy to access elements by an id, css class, or tag name. JQuery goes beyond this by providing a wide array of selectors all in one statement. The first selector I will demo provides the capability to drill down through a hierarchical structure, such as a table in Listing 2.

Listing 2: Parsing tables

  1. $("table > tbody > tr") //processes all table rows in a table  
  2. $("#t1 > tbody > tr") //processes all table roes in one specific table  
  3. $(".table > tbody > tr") // processes tables with the table class  

The greater than notation specifies the hierarchy of elements that must exist to match all TR elements; these patterns will not match TR elements within the header or footer of a table, nor would it match a table without a body element. Note that the id or class matching can be used anywhere in the selector. For instance, replacing the tr tag with a css class called "tablerow" would also work, but limits the results (which may be a more desired result).

Selectors can target one or multiple elements using a variety of patterns. Targeting multiple elements can be done by matching all elements of a specific tag type [$("p")], ore match multiple elements simultaneously using a comma separated list like: p, span, div. Selectors can also use filters that restrict the results returned, as shown in Listing 3.

Listing 3: Some of the available filters

  1. $(p:first)  //first in range  
  2. $(p:last)  //last in range  
  3. $(table > tbody > tr:even)  //even rows  
  4. $(table > tbody > tr:odd) //odd rows  
  5. $(p:eq(1)) //at index 1  
  6. $(p:gt(2)) //greater than 2, elements 3 and beyond  
  7. $(p:lt(10)) //less than 10, 0-9  
  8. $(p:empty) //where p has no children  
  9. $(p:parent) //where p is a parent  

Some of these filters are handy; for instance, when styling tables, using the :even and :odd filters work very well to create an alternating pattern. Using the :lt filter is good when you want to get the top 10 of something within a specific list. Accessing elements using an index (:eq) or getting the :first or :last in a list is always handy. Attributes can also be used to filter the results returned. For instance, take a look at using attributes to filter data.

Listing 4: Accessing text control values

  1. $("input[type='text']").css("color", "red");  

This is by no means a complete list; you can find more selectors at: http://docs.jquery.com/Selectors.

Accessing Content

JQuery provides access to the content of elements that expose a value and those that do not. Depending on the type of elements being accessed, these methods can extract this information. For instance, take a look at some of the assignments below.

Listing 5: Accessing content

  1. $("#span").html();  
  2. $(:input).val();  
  3. $("#name").text();  

In the examples above, some methods are used to extract information out of the underlying result set. The html() method allows the developer to extract the inner HTML information from the target element. The result-set must be singular in nature; this means that the results returned via $() has to be a single element; otherwise, the first element's value is returned. The val() method works differently; it can return a single result of the first element in the result. Notice the :input notation; this targets all text input controls. There are a couple of these filters available, which you can find out more at jquery.com.

When using these values, know that val() method looks for elements that have a value property associated with them. The html() method looks for the inner HTML contents of an element. The text() method gets the text of an element; this is the only multi-range method, as it concatenates the values into a single string.

Each of these methods works in a get and set mode; the get mode is the empty method call; passing in no value to the method performs a get call. When passing in a value, this performs a set operation, overriding the inner content.

There are other methods that can be used to manipulate HTML markup I didn't mention. One of the more common options is the css() method. This method takes two parameters: the name of the css value to modify, and the new value to apply. It can also take a collection of name value pairs in a class (noted by the {}). This makes it easy to apply css rules to a single or multiple elements.

Another popular method is the attr() method; this method reads or writes attributes of an element. To write an attribute, provide the name and value of the attribute to the method. Or, to set more than one attribute at a time, use the {} notation to set properties in bulk.

Take a look at some of the following examples.

Listing 6: Using css() and attr()

  1. $("p").css("background-color", "blue");  
  2. $("p").css({ "background-color" : "navy", "color", "white" });  
  3. $("button").attr("disabled", "disabled");  

These are by no means the only methods; there are other methods for modifying content; there are plenty of other methods that can modify the markup, such as wrapping content with HTML markup or replacing content with a substitute. You can find more documentation at: http://docs.jquery.com/Manipulation

Traversing Content

JQuery includes helpful methods that traverse the result set, or affect the results in a variety of ways. For instance, JQuery can navigate up or down the stack using the parent() or children() methods. These methods assume a single result of course, but these options are available.

In addition, other methods like the filter() method can trim down a larger result set; for instance, suppose that a JQuery result returns a collection of paragraph elements. The filter method can apply an expression that reduces the total number of results that will have a chained response applied to it. There are plenty of other methods for accessing the previous, next, sibling, and other related elements too.

Let's take a look at some of these methods in use:

Listing 7: Using the parent(), children(), and filter() methods

  1. alert($("#pid").parent().tagName);  
  2. $("#pid").children().hide();  
  3. $("#pid").children("[type='hidden']:first").val();  
  4. $("p").filter(".highlighting").show();  

There are plenty of other methods used for traversing content available at: http://docs.jquery.com/Traversing.

Events

JQuery can listen to object events. The most notable and frequently used event is the ready event, an event that fires when the browser has loaded. To attach to the ready event, do the following.

Listing 8: Attaching to the ready event

  1. $(document).ready(function() { .. });  

The ready event is where most of the code processing is placed, but this isn't required. If using ASP.NET AJAX, the page's client-side init or load event handler is another opportune place to put initialization code in. JQuery isn't limited to the ready event; it can also listen to other events like:

Listing 9: Handling a button click

  1. $("#buttonid").click(function() { alert("BUTTON CLICK"); }  

Handling events is a pretty standard process, as shown above. In the event definition, the this pointer actually refers to the object that raised the event (the button that was clicked, in the case of listing 7).

There are some other options to attaching events, but that is out of scope for this article. You can find more about events at: http://docs.jquery.com/Events.

 

1. The Byzantine Generals Problem (1982) by Leslie Lamport, Robert Shostak and Marshall Pease - The problem with distributed consensus
2. Go To statements considered harmfull (1968) - by Edsger W. Dijkstra - Didn't you always want to know why ? :)
3. A Note on Distributed Computing (1994) - by Samuel C. Kendall, Jim Waldo, Ann Wollrath and Geoff Wyant - Also on Michael's list but it is one of the foundation papers on distributed computing
4. Big Ball of Mud (1999) - Brian Foote and Joseph Yoder - patterns or anti-patterns?
5. No Silver Bullet Essence and Accidents of Software Engineering (1987) - Frederick P. Brooks - On the limitations of Technology and Technological innovations.
6. The Open Closed Principle (1996) - Robert C. Martin (Uncle Bob) - The first in a series of articles on Object Oriented Principles (you remember the debate on SOLID...)
7. IEEE1471-2000 A recommended practice for architectural description of software intensive systems (2000) various- It is a standard and not a paper but it is the best foundation for describing a software architecture I know.
8. Harvest, Yield, and Scalable Tolerant Systems (1999) Armando Fox, Eric A. Brewer - That's where the CAP theorem was first defined
9. An Introduction to Software Architecture (1993) - David Garlan and Mary Shaw - one of the foundation articles of software architecture field (although based on earlier work by the two)
10. Who Needs an Architect? (2003) Martin Fowler - Do we or don't we?

 

More

  1. On the criteria to be used in decomposing systems into modules – David Parnas
  2. A Note On Distributed Computing – Jim Waldo, Geoff Wyant, Ann Wollrath, Sam Kendall
  3. The Next 700 Programming Languages – P. J. Landin
  4. Can Programming Be Liberated from the von Neumann Style? – John Backus
  5. Reflections on Trusting Trust – Ken Thompson
  6. Lisp: Good News, Bad News, How to Win Big – Richard Gabriel
  7. An experimental evaluation of the assumption of independence in multiversion programming – John Knight and Nancy Leveson
  8. Arguments and Results – James Noble
  9. A Laboratory For Teaching Object-Oriented Thinking – Kent Beck, Ward Cunningham
  10. Programming as an Experience: the inspiration for Self – David Ungar, Randall B. Smith

On the criteria to be used in decomposing systems into modules – Parnas

This is a very old paper, but it is more than a classic. In in it, Parnas introduces a forerunner to the Single Responsibility Principle. He introduces the idea that we should use modularity to hide design decisions – things which could change. People still don’t consider this as often as they should.

Another thing I really like in the paper is his comment on the KWIC system which he used as an example. He mentioned that it would take a good programmer a week or two to code. Today, it would take practically no time at all. Thumbs up for improved skills and better tools. We have made progress.

A Note On Distributed Computing – Waldo, Wyant, Wollrath, Kendall

Abstraction is great but it can only go so far. In this paper, the authors lay to rest what was once a pervasive myth – that we could design a distributed system and make distribution transparent. Ever wonder why you had to implement specific interfaces to do remoting in Java? This is why.

In the aftermath it might seem hard to believe that people thought this was possible. I think we can we partially thank this paper for that.

The Next 700 Programming Languages – Landin

Most of us have spent a lot of time working in traditional programming languages, but functional programming languages are slowly seeing an uptick and many OO languages are gaining functional features. This paper (which reads like a tutorial) makes an argument for an expression-oriented style of programming. It also lays the foundation for lazy evaluation.

One of the other neat things about this paper, from a historical point of view, is that there is a discussion section at the end in which there a number of questions and comments about whether making indentation significant in a language is a good idea. I was thrown to see people asking whether or not this would be a problem for functions which span over several pages(!).

Can Programming Be Liberated from the von Neumann Style? – Backus

John Backus is known for a number of achievements in computer science. He received the ACM Turing Award for his work on Fortran. This paper, which he presented at the award ceremony was rather shocking at the time because it said, in essence, “we got it wrong.” Backus took the opportunity to make a plea for pure functional programming. His arguments were convincing and they helped to set a research agenda which is just now starting to make some waves in the mainstream.

Reflections on Trusting Trust – Thompson

I once heard that when this paper was presented, people in attendance rushed back to de-compile their C compilers and look for, er, problems. This paper unveiled a hard problem at the heart of computer security. If you’ve spent any time at all thinking about security, you need to read it.

Lisp: Good News, Bad News, How to Win Big – Gabriel

This paper is a bit atypical in this list. It’s aimed at the Lisp community and it comes off as a bit of a lament. But, hidden deep within it is the Gabriel’s description of the ‘Worse is Better’ philosophy – an idea with profound implications for the acceptance and spread of technology.

An experimental evaluation of the assumption of independence in multiversion programming – John Knight and Nancy Leveson

Behind this dry title lies something very interesting. I first heard about this paper from Ralph Johnson in a newsgroup discussion about program correctness. It turns out that one of the avenues that engineers in other disciplines take to make their products stronger – redundancy – doesn’t really work in software. Multi-version programming was the idea that you could decrease faults in critical systems by handing the spec to several teams, having them develop the software independently, and then having the systems run in parallel. A monitoring process verifies their results and if there is any discrepancy it picks the most common result. Sounds like it should work, right? Well..

Arguments and Results – Noble

I think that all of the other papers in this list are rather well known in some circles. This one isn’t, or if it is, I just haven’t found that circle yet. What I like about this paper is that it takes something which we deal with every day – the set of arguments and results of functions – and it works them through a series of variations which just don’t occur to many people. The fact is, every function that you work with has a number of possible directions if could evolve in. Not all of them are appropriate, but if you know the possible directions, you’re richer for it.

A Laboratory For Teaching Object-Oriented Thinking – Beck, Cunningham

There are an incredible number of papers about there about object orientation. The thing which makes this one great is its directness. OO went through a number of stages. It was once fresh and novel, then it was ornate, and then it became matter-of-fact. This paper hits upon key ideas which many people don’t talk about much any more: anthropomorphism and dropping the top/down perspective. It also shows you how you can design with index cards. It may not sound cool but it is incredibly effective.

Programming as an Experience: the inspiration for Self – Ungar, Smith

How many people know about the Self Project? Not enough in my opinion. Self was an attempt to take two ideas in computing and push them as far as humanly possible. The first was minimalism: the Self programming language was thoroughly in the Lisp and Smalltalk vein – everything was defined in terms of the smallest number of primitives possible. The other idea was direct manipulation – the idea that the object metaphor could be pushed all the way in the user interface – the programmer and user sit with a mouse in a sea of directly clickable objects and use them for everything. If they could’ve gotten away with dropping the keyboard, I think they would’ve.

The amount of technology which the Self project threw off is terrifying also. Self broke ground in dynamic language optimization and VM design. Chances are, your VM uses technology it pioneered. It’s also one of the more perverse ironies that the most widely distributed programming language today (JavaScript) is a prototype-based programming language which borrowed ideas from the hyper-research-y Self.

More

Tuesday, March 3, 2009

In your applications there may be times when you want to give the user the ability to override a setting or configuration value.  Often times you want to provide sensible defaults so that every single configuration option does not have to be specified, only those you which to override.  I want to show a very simple way to make your applications a bit smarter when creating classes with overridable default values.

Example 1:

   1: public class DemoObejct

   2: {

   3:     private string DEFAULT_MESSAGE = "Thank you for your order";

   4:    

   5:     private string message = DEFAULT_MESSAGE;

   6:    

   7:     public string Message

   8:     {

   9:         get { return message; }

  10:         set { message = value; }

  11:     }

  12: }

Example 2:

   1: public class DemoObejct

   2: {

   3:     private string DEFAULT_MESSAGE = "Thank you for your order";

   4:    

   5:     private string message;

   6:    

   7:     public string Message

   8:     {

   9:         get { return message ?? DEFAULT_MESSAGE; }

  10:         set { message = value; }

  11:     }

  12: }

So what's the difference?  The difference IS subtle but I consider the following code snippet:

   1: var obj = new DemoObject();

   2: 

   3: Console.WriteLine(obj.Message);

   4: 

   5: obj.Message = null;

   6: 

   7: Console.WriteLine(obj.Message);

Setting the Message property to null in line 5 results in different behavior between the two examples.  I find the second example to be preferable, setting the property to null invokes the default message again.  It's a very simple thing you can do to provide a more robust object

Here are two more examples where I use this strategy often:

Integers and Default Values:

   1: public class DemoObject

   2: {

   3:     private int? attemptThreshold;

   4:     private const int DEFAULT_ATTEMPTTHRESHOLD = 3;        

   5:        

   6:     public int AttemptThreshold

   7:     {

   8:         get { return attemptThreshold.HasValue ? attemptThreshold.Value : DEFAULT_ATTEMPTTHRESHOLD; }

   9:         set { attemptThreshold = value; }

  10:     }

  11: }

Logging Component:

   1: public class DemoObject

   2: {

   3:     private ILogger logger;

   4: 

   5:     public ILogger Logger

   6:     {

   7:         get { return logger ?? NullLogger.Instance; }

   8:         set { logger = value; }

   9:     }

  10: }

The above logging example is where this type of strategy really shines.  It prevents NullReferenceExceptions in your code if by chance your logger gets a null value at some point, again providing for a more robust object and application.