Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle uninitialized local variables

Tags:

c#

clr

After reading this Eric Lippert Article, I understand that the C# compiler doesn't like it if we leave local variables uninitialized.

As I encounter this 'problem' from time to time, I looked at some of my old code and was able to weed out most of the situation where actually don't need uninitialized (SomeClass obj = null) local variables.

But I came up with a situation where I don't know how to refactor the code.

public void DoSomething(string foo) {   

    SomeClass obj; // = null; 

    try {
        obj = SomeClass.CreateItem(target);
    } catch(CustomException ex) {
        // notify UI of error
    }

    if (obj != null) {
        // do something with `obj`
    }
}

SomeClass.CreateItem may fail due to external factors. If it does, I want to notify the user, if not I want to perform an Action.

The C# compiler doesn't want me to leave obj uninitialized, so I usually assign null to it.

This feels like a 'hack' now and my question is:

Is there a design flaw in the code above?

And if there is, how should I deal with references at compile time, when I can't determine if they are going to point to an existing object at run time?

like image 798
MrPaulch Avatar asked Jul 08 '15 18:07

MrPaulch


1 Answers

I would refactor the code like this:

private SomeClass TryToCreateItem()
{
    try 
    {
        return SomeClass.CreateItem(target);
    } 
    catch(CustomException ex) 
    {
        // notify UI of error
    }
    return null;
}

public void DoSomething(string foo) 
{ 
    SomeClass obj = TryToCreateItem(); 
    if (obj != null) {
      // do something with `obj`
    }

"Extract method" is my favourite refactoring.

like image 161
Eric Lippert Avatar answered Oct 10 '22 23:10

Eric Lippert