Hugoware

The product of a web developer with a little too much caffeine

Posts Tagged ‘Best Practices

Stop, Think, Fix Errors… (Repeat!)

with 2 comments

“Don’t change your code unless you know how it will fix your problem”. If I had to pick a quote to put a ‘squiggly line and my name’ next to, then this would be it.

I’ve seen developers stare blankly at an exception message, comment out a line of code or two and then try and run their code again hoping for the best.

This, of course, rarely fixes anything. Quite often the line of the error message has little to do with the actual problem. Instead, this introduces new errors into your code and causes the problem to take longer to resolve.

Even if you guess and make an exception message go away you still don’t know what caused the error to begin with. Instead, you have a new error that is quietly causing problems and is now much harder to find. They might be ugly, but exception messages are the easiest errors to fix… well, after compiler errors that is…

So, how can you “know” your change will fix the problem? Here are some of the recommendations I make to other developers.

Stop and Think… Carefully

The bug isn’t going anywhere and each time you guess incorrectly you add a new error to your code.

It seems like such a silly thing to even mention, but I’ve seen plenty of developers take a cursory glance at an exception message and then just start changing stuff. It doesn’t even matter if you’re in a “break-fix” situation – you should always carefully consider the problem before changing your code.

Read the error, start following up the stack and think about what could cause this result. Think about the conditions that would cause the error or how you could force the error to happen again.

If you don’t know why your change will fix the code then you aren’t fixing anything.

Understand the Debugger

You don’t need to know what a memory dump is for or how read binary manually to use debugger. Just simply understanding how to set break points and stepping into, over and out of code will probably cover 99% of the problems you encounter.

It might seem daunting at first but don’t ignore the debugger because logging or message boxes are easier to write. Once you get a hang of it, the debugger will most likely become the greatest tool in your future bug squashing adventures.

Isolate and Resolve the Specific Problem

It can be difficult at times to figure out why a section of code doesn’t work when it sits in the middle of a larger application. Sometimes its better to create an empty project and work with a smaller section of the program by itself.

For example, if you don’t understand how a part of your framework is supposed to behave, pull it into a separate program, for example a console application, and work with it until you are comfortable with the results. Then when you integrate your changes back into the main project you can be confident that any remaining errors aren’t part of the newly introduced code.

Look At Open Source Code

If you’ve written some code that is consistently causing problems then consider looking for a framework or open source project instead.

This isn’t a matter of being a good or bad developer. It certainly has nothing to do with being unable to figure out the problem for yourself. Quite simply, code that consistently has errors is probably a difficult problem.

Public frameworks and open source projects are typically owned by other developers that understand the problem better than others. They have taken the time to abstract away the specifics of a problem and build a clean API for other developers to use.

These developers are also typically eager to improve their code and will listen to feedback. Even if you don’t use their project there’s a good chance that you will learn something by simply reading their code.

To sum it up, don’t just change code and hope for the best. Stop, think, ask yourself how does this fix the problem?.

How do you approach fixing problems in your code?

Written by hugoware

June 23, 2010 at 12:02 am

Avoiding Confirmation Boxes

with one comment

One thing I try to avoid in interface design is unnecessary user interaction – Basically, asking the user for feedback when it isn’t needed. The area that probably bothers me the most are “confirmation boxes” – Especially those that block the entire application until you’ve clicked ‘OK’?

I’m not really sure why you see them so often in applications since I’m pretty sure that users and developers alike probably get tired of seeing them. Not only that, studies have shown that they are mostly ineffective, normally only earning a cursory glance before being dismissed.

So what can you do instead?

Don’t Confirm Success, Notify On Failure

Probably the easiest and quickest improvement to an application is to stop confirming when your application worked. How many times have you seen this pointless little window pop up?

Uh, yeah…

For the most part, a user should be able to assume that their “request completed successfully.” — Otherwise, why the heck did they buy your software to begin with?

Instead, pop up a modal dialog box if something goes wrong and their request didn’t work. This is a much better time to interfere with user work flow.

Allow Permanent Dismissal

New users of an application don’t mind confirmation boxes as much since they are still poking around and trying to figure out what everything does. But after the 10th or 15th time the ‘your request has been completed!’ message is starting to wear on them.

Sure, it was helpful at first but now that they know the expected behavior, the additional confirmation is an annoying extra click.

Ah, now that is better. I’m confident using this part of the program – stop bugging me!

Even Better – Don’t Confirm, Make It Easy To Undo

Remember the computer before the undo button? It was painful and frustrating, but then one day like magic we could fix our silly fat-finger mistakes – Genius!

What about the Internet before the undo button? Oh… wait. The ‘undo’ button is actually still pretty uncommon in web applications. Of course, web applications aren’t the only area that this applies – but it is still possible to make it happen. GMail is a great example of how this applies to any application – including the web.

The message explains what happened and gives immediate actions for the two most probably user responses – “What the heck did I just do?” and “Oh snap, I didn’t mean to delete that!”.

Use Visual Indicators As Confirmation

Visual indicators work well as additional confirmations. If you make it clear enough what a user is about to do then normally you can avoid a confirmation box.

Red highlights, short and clear sentences, explanation of the final result – All of these items act as an additional confirmation for the user to understand the result of their action. To take it a step further, the text on the button OK would be even clearer if it said Delete (see how easy this is!)

It doesn’t take much to reduce, and in many case eliminate, the dialog boxes we pop up in our applications. You’ll be happier, your users will be happier — Heck, I’ll even be happier even if I never use your application.

What are ways you can use to limit the number of dialog boxes you use in your applications?

Copyin’ and-a Pastin’

with 2 comments

How often do you use Copy and Paste in your code — because you really shouldn’t…

I’m not really a very opinionated person when it comes to software development but this is one point I tend to be adamant about with other developers. What you ought to be doing is Cutting and Pasting your code.

If I happen to catch a new developer copying some code I normally lead off with that sentence to which I get that raised eyebrow, “what is this dude talking about?” look but it is always a fun discussion.

You’re probably already realize the difference between the two, duplication as opposed to refactoring, but so far every new developer I’ve encountered hadn’t even heard the term before. Maybe it is just a matter of coincidence but I doubt it.

Normally, I show a simple example of how by refactoring you can limit errors and reduce how much work you have to do. A lot of you are going to see the problem with this right away…

//a user settings file
public class UserSettings {

    //holds the settings for the user
    public XDocument Settings { get; set; }

    //the users font color
    public string FontColor {
        get {
            if (this.Settings == null) {
                this.Setting = XDocument.Load(@"c:\settings.xml");
            }
            return this.Settings.Root.Element("fontColor").Value;
        }
        set {
            if (this.Settings == null) {
                this.Settings = XDocument.Load(@"c:\settings.xml");
            }
            this.Settings.Root.Element("fontColor").Value = value;
            this.Settings.Save(@"c:\settings.xml");
        }
    }

    //the size of the font
    public int FontSize {
        get {
            if (this.Settings == null) {
                this.Setting = XDocument.Load(@"c:\settings.xml");
            }
            int size = 0;
            int.TryParse(this.Settings.Root.Element("fontSize").Value, out size);
            return size;
        }
        set {
            if (this.Settings == null) {
                this.Settings = XDocument.Load(@"c:\settings.xml");
            }
            this.Settings.Root.Element("fontSize").Value = value;
            this.Settings.Save(@"c:\settings.xml");
        }
    }

    //the users font color
    public string FontFamily {
        get {
            if (this.Settings == null) {
                this.Setting = XDocument.Load("c:\\settings.xml");
            }
            return this.Settings.Root.Element("fontFamily").Value;
        }
        set {
            if (this.Settings == null) {
                this.Settings = XDocument.Load("c:\\settings.xml");
            }
            this.Settings.Root.Element("fontFamily").Value = value;
            this.Settings.Save("c:\\settings.xml");
        }
    }

}

A bit extreme? I doubt it – In fact, I’m willing to bet some devs have found code like this floating around in a project. So after discussing and refactoring we normally end up with something like this…

//a user settings file
public class UserSettings {

    private const string SETTINGS_PATH = @"c:\settings.xml";
    private const string SETTING_FONT_COLOR = "fontColor";
    private const string SETTING_FONT_SIZE = "fontSize";
    private const string SETTING_FONT_FAMILY = "fontFamily";

    //holds the settings for the user
    public XDocument Settings {
        get {
            if (this._Settings == null) {
                this._Setting = XDocument.Load(SETTINGS_PATH);
            }
            return this._Settings;
        }
    }
    private XDocument _Settings;

    //saves the settings file
    public void _SaveSettings() {
        this.Settings.Save(SETTINGS_PATH);
    }

    //gets the value for a setting
    private string _GetSettingValue(string name) {
        return this.Settings.Root.Element(name).Value;
    }

    //modifies a setting value
    private string _ChangeSetting(string name, object value) {
        this.Settings.Root.Element(name).Value = value;
        this._SaveSettings();
    }

    //the users font color
    public string FontColor {
        get { return this._GetSettingValue(SETTING_FONT_COLOR); }
        set { this._ChangeSetting(SETTING_FONT_COLOR, value);  }
    }

    //the size of the font
    public int FontSize {
        get {
            int size = 0;
            int.TryParse(this._GetSettingValue(SETTING_FONT_SIZE), out size);
            return size;
        }
        set { this._ChangeSetting(SETTING_FONT_SIZE, value); }
    }

    //the users font type
    public string FontFamily {
        get { return this._GetSettingValue(SETTING_FONT_FAMILY); }
        set { this._ChangeSetting(SETTING_FONT_FAMILY, value); }
    }

}

… And then the blank looks appear — two lines? We saved a measly two lines? However, this is the part where you ask them to make a change both of the code samples. Here are a couple samples I like to use…

  1. Add 5 more settings as properties
  2. Change the path of the settings file to ‘D:\settings\storage.xml’
  3. Change the location of the setting from the root of the document to ‘user/settings/personal’
  4. Adjust the code so that you don’t get an error if the element name isn’t found

Of course, the point isn’t that using copy and paste is bad – but duplicating a bunch of lines instead of focusing on the architecture of your code can quickly lead to unmaintainable code. It is always worth your time to review your code and look for the areas that are repeating themselves..

Anyways, just something I was thinking about today – Go out there and code!

Anyways, just something I was thinking about today – Go out there and code!

… just kidding…

Written by hugoware

March 12, 2010 at 12:21 am

Is Encrypting Your Web.config A Waste Of Time?

with 3 comments

In my last blog post I wrote about a utility has created to make it easier to encrypt web.config files hoping it would encourage more developers to protect their data. If you’ve ever tried doing it manually before, it isn’t really a very convenient process.

Additionally, I posted the blog entry on CodeProject — and received rather interesting response.

This article is pointless.
– Quote any high security site that uses an encrypted config file!
– If somebody has physical access to your config file/web server, you are as well doomed

Really? Is encrypting your web.config pointless. I don’t think so. In fact, I replied back with the following.

Encrypting a web.config file isn’t to defend against your server being compromised, but even if it were then I don’t think you understand exactly how aspnet_regiis works. The keys are written and locked down so that only members of the Administrators group can even read it, any lesser privileged accounts still can’t decrypt your web.config. Since typically website worker processes are running as NETWORK SERVICE, then unless you did something REALLY silly, your web.config should still be safe.

Even though that isn’t bullet-proof security, think about this scenario — You’ve have some junior developer right out of college working on a project that allows people to go out and download documents off your web server. He wants to send back the file as a download so he writes the bytes to the response stream and makes a change to the content-disposition and viola – freshly served documents all with a nice and neat little download dialog box.

But if your developer left a tiny little bug in the app and it was possible to download “../web.config” — What would you prefer to be served up? Encrypted or unencrypted?

In my opinion, an encrypted web.config file is 100% better than no encryption at all. Logging onto the server and running aspnet_regiis was very inconvenient way to get this done – this tool was made just try and help people get it done without needing to invest a lot of time into it.

But this really got me wondering, is this really a common opinion in the development community? Is encrypting your web.config really a waste of time? I don’t really think that encrypting your web.config file is the solution to all your problems – but it is some really cheap insurance that you can take out on sensitive file.

So what do you think? Is encrypting a web.config worth the time?

Written by hugoware

July 20, 2009 at 6:28 am