Object Reference .NET

ref this.Object

Web developers. You suck.

clock July 15, 2008 16:54 by author DaveTheKnave
Well, JavaScript developers, specifically.

In order to aid in development of my own websites, I enabled JavaScript debugging in Internet Explorer a few weeks back.

To my horror, I have quickly experienced what seems to be complete disregard for serving syntactically correct JavaScript on the open internet.

No, I’m not just talking about a few niche websites, run by amateur programmers. I am talking about industry-leading nerd-friendly powerhouse websites that should know better.

To list a few examples of websites coated with syntax errors (at the time of writing):

  1. http://slashdot.org/. Slashdot for god’s sake!! On the homepage!
  2. http://digg.com/. Try posting a new dig article with a thumbnail.
  3. http://www.computerworld.com/ come on.
  4. http://www.somethingawful.com/
  5. http://www.pcmag.com/
  6. http://www.washingtonpost.com

The list really does go on. With script debugging enabled, the internet becomes an almost unusable, frustrating place. Especially if you couple this with a delightful bug in Internet Explorer, that causes it to freeze if two of your open and loading tabs both have a modal JavaScript error box waiting for a response.

Anyone who writes production JavaScript should always have script debugging enabled. If not just to help catch your own mistakes - but also to see how infuriating it can be to simply use the internet while being forced to close millions of error dialogs.
This alone should convince you to write better JavaScript.

To enable script debugging:

Tools/Internet Options/Advanced/ - Un-check "Disable Script Debugging"



When disabled, this will cause a small error box to show if there is a syntax (or execution) error in any JavaScript code.


Slashdot: 15 July 2008

If you wish, you can click the “Debug” option, and this will offer you the option of opening visual studio, letting you step through the broken code.

I’m sure you’ll all agree that correct JavaScript should not be a lofty goal to aim for.

Dave

kick it on DotNetKicks.com


Object reference not set to an instance of an object

clock May 28, 2008 15:25 by author DaveTheKnave
This article is intended for amateur programmers, and/or people new to Object Oriented programming.

“Object reference not set to an instance of an object” is probably the most common run-time exception message spat-out by the .Net framework, and most programmers will probably encounter this more often than any other framework exception type.

This exception, or more specifically a “System.NullReferenceException” is always caused when code tries to access an instance of any object, when the object has not yet been created and/or returned via a constructor, or some method.

Back to basics.

Object oriented programming is a form of programming wherein things called “Objects” are given “responsibility” for data, and for various operations. Each Object has a kind of blueprint, called a “Class”, as shown in the following code:

public class Chair
{
    public Chair() { }
    public void Sit() { }
}  

In order to use this object, you must create an “instance” of it, so to do that with the above class:

Chair myChair;
myChair = new Chair();
myChair.Sit();

1) Memory Allocation

Chair myChair;
This line of code designates some memory to be used by your program for holding a “Chair” object. Think of this line, like setting aside some wood and nails to build a real chair.

2) Constructing your object

myChair = new Chair();
This line of code creates an “Instance” of a “Chair” class, and assigns it to the variable “myChair” so that we may use it. To continue the above analogy, this is akin to looking at the blueprints for a chair, and using the assigned resources of wood & nails (Memory, in the case of our program) and actually creating the Chair.

3) Using the Object

myChair.Sit();

Now that we have an actual chair object, we can sit on it. If, however, you forget to include the line:

myChair = new Chair();

Or, somehow your “myChair” object gets set to null before the myChair.Sit(); method-call, then a System.NullReferenceException will be thrown.

If your object is unassigned (or null) you’re essentially tying to “Sit()” on nothing, and your program will fall on its arse.

kick it on DotNetKicks.com


A C# Operator I would like to see.

clock April 30, 2008 19:14 by author DaveTheKnave
You could argue there are too many operators in C# as it is; however, I feel having an acute knowledge of the available operators is like knowing CTRL + B will bold the selected text in most word processing software.

To put it simply, it hurts no-one, whilst providing shortcuts to advanced users.

Consider the following:
if (MyObject != null)
{
    return MyObject;
}
else
{
    return SomeOtherObject;
}

In C# 2.0, the kind people at Microsoft provided the ?? operator to make this a much more sucinct:

return MyObject ?? SomeOtherObject;

One thing that I find ugly and boring in code is that of checking for nulls in nested object properties, so for a moderately extreme example:

Staff.Manager.PersonalDetails.Address.Location.Postcode

In order for me to be sure that I can access the “Postcode” part of this chain correctly (with the caviet that each of these proerty objects might be null) I’d have to write something like the following:

if (Staff != null && Staff.Manager != null && 
    Staff.Manager.PersonalDetails != null && 
    Staff.Manager.PersonalDetails.Address != null && .....
{

I’m sure you’ll agree the above is pretty ugly, especially if you don’t really care which property is null, just if any of them are.

So, I propose a new operator, the “Is anything in this chain null” operator, to be used something like so:

return ??{Staff.Manager.PersonalDetails.Address.Location.Postcode} : “No Postcode”

The actual syntax of this operator isn’t important, just the functionality.

I’d be interested to hear feedback on this.

Dave

kick it on DotNetKicks.com


Being a “nice” programmer

clock April 22, 2008 01:46 by author DaveTheKnave
Being a C# developer by trade, I naturally spend a lot of my working life programming computers. Whilst I by no-means profess to be a “guru” of any kind, I do notice that there is one aspect of software development that is often neglected from discussion, and most programmers will hopefully agree with me as I explain.

Programming is often described as an “art” – and whilst I agree with that statement, it is probably for different reasons than most programmers would assume. I believe one of the most important (and inherently artistic) elements of programming, to be that of simple document formatting.

With the majority of application development shifting to the ‘net, maintenance-programming is arguably becoming more important. As such, I myself would much rather attempt to maintain something complicated that was formatted and factored sensibly and aesthetically, than something programmatically simple, but with poor formatting, naming and structure.

Take the following made-up Page_Load example:

protected void Page_Load(object sender, EventArgs e)
{
    CreateDefaultWidgetProperties();
    if (WidgetProperties == null)
    {
          divMain.Visible = true;
     }
     
     HideWidgetTable(false, "customers", null);
     //The keyword Search Keyword = tbSearch.Text.Trim();
    lblMessage.Text = string.Empty;
    lblMessage.Visible = false;
    int PersonID = Int32.MinValue;
 
    if (!Page.IsPostBack)
    {
        if (Session[SessionKeys.ManageWidget.ContinueAction] != null 
                              && Person.Details.IsSomething == false)
        {
            string action = (string)Session[SessionKeys.ManageWidget.ContinueAction];
            ContinueAction(action, true);
        }
       
        SetupColumnHeaders();
       
        switch (ManageWidget.SearchType)
        {
            case ManageWidget.SearchTypes.DateSearch:
                LoadFromDateSearch();
                break;
            case ManageWidget.SearchTypes.RefSearch:
                LoadFromRefSearch();
               break;
            case ManageWidget.SearchTypes.StdSearch:
                LoadFromStandardSearch();
                break;
            default:
                SetupPage(WidgetProperties);
                BindRepeater(WidgetCollection);
                break;
             }
        }
       
        if (divOtherUsers.Visible == false || ddlPeople.SelectedValue == Person.ID.ToString())
            personId = Person.ID;
        else
            personId = int.Parse(ddlPeople.SelectedValue);
       
        if (personId > 0) Session.Add("CurrentPerson", personId);
}

As a rule of thumb, especially when dealing with program entry-points (such as .Net page-loads) I strongly believe that they should contain as little “code” as possible (if you have over a page in a method, you’re probably doing something wrong) – but more-so, they should contain an “code-index”.

When writing a page of code, consider you are writing it as you would an instruction manual, wherein having everything listed in one big chunk could potentially be hard to follow. Using the example of a VCR, if you only wanted to know how to fix a blinking VCR clock, you would go straight to the section in the instructions “How to set your VCR’s time”.

It should be the same with code. If I have to fix a bug in my imaginary “Widget Search”, I’ll know straight-off that it’s very likely to be in the ProcessWidgetSearch() method, meaning my maintainence will probably be faster, and my head will hurt less.

So, for example:

protected void Page_Load(object sender, EventArgs e)
{
    CreateDefaultWidgetProperties();
    divMain.Visible = WidgetProperties == null;
    HideWidgetTable(false, "customers", null);
    ProcessKeywordSearch();
 
    if (!Page.IsPostBack)
    {
        if (this.ContinueAction != null && !Person.Details.IsSomething)
        {
            ContinueAction(this.ContinueAction, true);
        }
        SetupColumnHeaders();
        ProcessWidgetSearchType();
    }
 
    SetCurrentPerson();
}

Another positive that should naturally fall-out of such an approach will be that of code re-use. If I wish to make a call to process my widget search-types again, I have already wrapped this logic in a method, meaning I’m less likley to copy / paste the same block of code (which would add to further maintainence).

The ‘art’ of this process is choosing which code-elemets are abstractly linked – however if you take the time to write code as if you were formatting it for someone else to read, not a computer, you will notice this will point your abstraction in the right direction, and everyone will say:

“What a nice programmer”

kick it on DotNetKicks.com



Search

Sign in