Hugoware

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

Posts Tagged ‘Opinion

Autocomplete? Yeah, But How?

leave a comment »

Unless you’re really hardcore you probably use an IDE with some sort of autocomplete feature. It doesn’t have to be the super charged intellisense you find in Visual Studio – It could be as simple as the autocomplete feature in Notepad++ (which I love by the way…)

In any case, I got to wondering today – How do other people use their autocomplete features?

Best I could figure there was probably about 4 different ways you could approach using autocomplete…

  1. Type just long enough to see the item you want and then use the arrow keys to correct item.
  2. Keep typing, regardless of when it appears on the list, until it becomes the selected item.
  3. Use both pretty much equally.
  4. Auto complete is for noobs

Yeah, it isn’t a very deep, through provoking sort of question but it is somewhat interesting to think about. Maybe there is some sort of deeper psychological meaning behind our choices… or not…

[Poll] : So, how do you use your autocomplete feature?

Written by hugoware

June 24, 2010 at 9:40 pm

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?

Goodbye Courier, Goodbye Innovation…

with 3 comments

The Courier project was canceled today. Despite all the excitement and buzz that a handful of concept art was able to generate, the Courier was abandoned without anything more than this short and uninformative explanation…

At any given time, we’re looking at new ideas, investigating, testing, incubating them. It’s in our DNA to develop new form factors and natural user interfaces to foster productivity and creativity. The Courier project is an example of this type of effort. It will be evaluated for use in future offerings, but we have no plans to build such a device at this time.

Really? Is that really how the Courier dies? Dismissed as quietly as it was introduced?

In my opinion, Microsoft really needed this to shake things up. The had simultaneously gotten the interest of students, graphic designers, businessmen and Inspector Gadget fans all with the same device!

More importantly, this showed that Microsoft could innovate truly unique experiences that were both functional and “magical”. Sure, Windows Phone 7 is cool, but it’s still Microsoft playing catch up. This was something completely different which is why I think it created the buzz that it did… not like their other recent innovations which aren’t even registering as a blip on the radar.

Recently, or more specifically today, conducted a highly scientific poll (of 4 family members) to see how the whole “brand recognition” thing was going for Apple vs. Microsoft.

I started with “Tell me everything that you know Apple makes” which they breezed through easily. The 8 and 4 year old for the most part nailed it — iPhone, iPods (Apple-Pods) and laptops. These kids don’t even own these things.

Then I asked “Tell me everything that you know Microsoft makes”. Neither of the kids could name anything. The adults stumbled through it as well but they did at least name off a few versions of Windows and a couple of the Office products – but from their perspective that was it.

Keep in mind that I’m a Microsoft developer – I own a Zune, I use Windows, I search with Bing… okay, that last one is a lie… but these people see Microsoft stuff all the time.

Of course, my family and in-laws are hardly representative of a larger, growing consumer base, right?

Oh…

To be clear, I’m a big fan of Microsoft, in fact some day I hope I’ll be working for them… but today I’m dumbfounded by their decision. Microsoft needed this…

Goodbye Courier, goodbye innovation…

Written by hugoware

April 29, 2010 at 10:20 pm

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

Spelling It Out With Booleans

with 4 comments

Code complexity has been a big issue for me lately. I’ve been realizing that the quality of my code has degraded over the years to the point that I’m finding I cram large chunks of code into a vaguely named method like Load() or Render(). It wasn’t until I got an assistant and I likened programming to ‘painting by number’ that I realized that I wasn’t following my own instructions anymore.

It wasn’t that I was intentionally writing complex code but rather that a large complex function wasn’t hard to read anymore — my definition of complexity has changed.

The last time that I discussed code complexity I explained that writing short, clear methods was an ideal way to decrease code complexity. This post continues the discussion by looking at using booleans to improve the readability of code.

Clarity With Booleans

Maybe you’ve seen a snippet of code like this before…

if (value % 2 == 0) { 
    //do something
}
else {
    //do something else
}

Most programmers are going to immediately recognize what this code is going to do — but imagine for a second that you don’t know what that code does. How is a less seasoned programmer going to have any clue what just happened there? Try Googling ‘value % 2 == 0’? I don’t think that is going to work out so well.

This is a good example where a boolean can be used to create clarity in a program. A boolean is used to determine the flow of a program — so why not use well named booleans to further clarify your intent?

bool isEvenNumber = (value % 2 == 0);
if (isEvenNumber) { 
    //do something
}
else {
    //do something else
}

This is a simple example but it applies everywhere. What stops you from spelling it out with a boolean?

Describe Intent Without A Comment

MVC is a good example of where well named booleans can improve the readability of code. How much harder is the first snippet to read compared to the second.

Logic Performed Inline

<div class="<% if (allItems.IndexOf(entry) % 2 == 0) { %>alt-item %<% } %><% if (entry.DatePosted.Date < DateTime.Now.Date.AddDays(-7)) { %>old-post<% } %>" >
<div class="subject" ><% =entry.Subject %></div>
<% if (string.IsNullOrEmpty((entry.Location ?? string.Empty).Trim())) { %><div class="location" ><% =entry.Location %><% } %>
<% if (string.IsNullOrEmpty((entry.Description ?? string.Empty).Trim())) { %><div class="desc" ><% =entry.Description%><% } %>
</div>

Logic Performed In Advance

<%
    bool isEvenItem = (allItems.IndexOf(entry) % 2 == 0);
    bool olderEntry = (entry.DatePosted.Date < DateTime.Now.Date.AddDays(-7)); 
    bool hasLocation = (string.IsNullOrEmpty((entry.Location ?? string.Empty).Trim()));
    bool hasDescription = (string.IsNullOrEmpty((entry.Description ?? string.Empty).Trim()));
%>

<div class="<% if (isEvenItem) { %>alt-item %<% } %><% if (olderEntry) { %>old-post<% } %>" >
<div class="subject" ><% =entry.Subject %></div>
<% if (hasLocation) { %><div class="location" ><% =entry.Location %><% } %>
<% if (hasDescription) { %><div class="desc" ><% =entry.Description%><% } %>
</div>

Snippet one is much shorter than snippet two — but does that really make it better? Or less complex?

You could argue that the logic shouldn’t be inline with MVC to begin with and you’d be correct. Instead those same comparisons would be well named boolean properties attached to the the model being used — which is exactly what I’m suggesting here.

It doesn’t matter where they are but using well-named booleans can improve and clarify the flow of logic in your application.

Written by hugoware

October 19, 2009 at 8:30 pm

Programming – AKA: Paint By Number

with 7 comments

This last week has been pretty busy for me. I’ve been working on several projects at work, deadlines coming due, trying to get personal projects done, jLinq bugs fixed — it’s been a rough week.

I was excited a few weeks ago when the new developer was going to start. I was finally going to be able to spread out some of this work and get a little more time on my hands… or so I thought. As it turns out, this guy isn’t exactly what I was expecting. Despite my best efforts, I still ended up hiring someone with pretty much no background in programming. I went from already being maxed out to now spending between 20% to 30% of my time teaching the basics of programming… yeah – this is my fault.

But as bad as it sounds it really has actually helped me rediscover a programming rule that I thought I was still using but apparently had forgotten.

So, one of the first projects the guy had to do involved checking a directory for new files, creating a record of the file if it was found and then processing existing files to transform file types from one to another. Really, probably an hour long job at most but was really causing this guy some grief.

An Alternate Approach — Simplicity

Naturally, as a developer, the first thing I started trying to explain was how the code would work like checking file dates or creating an XmlSerializer to load and save files — none of which actually helped him solve his problem. After several frustrating whiteboarding sessions I came up with a new route — make it so simple it was impossible to mess it up!

I took a second pass at trying to get the guy started in the right direction. Instead, I opened a new class file for him and wrote something like this.

public class FileRecordSync {
    //snip...

    //This is a list of the files that the program has already detected
    //this is also where to add new files that are discovered
    public List<FileRecordEntry> CurrentFiles { get; private set; }

    //determine if this file should be processed or not
    public bool IsValidFileType(string path) {
        throw new NotImplementedException();
    }

    //check and see if this file exists in CurrentFiles or not
    public bool IsExistingFileEntry(string path) {
        throw new NotImplementedException();
    }

    //check to see if the modified date is greater than the logged modified date
    public bool IsFileEntryModified(FileRecordEntry entry) {
        throw new NotImplementedException();
    }

    //find the matching file in the CurrentFiles or return null if nothing was found
    public FileRecordEntry FindExistingEntry(string path) {
        throw new NotImplementedException();
    }

    //create a new FileRecordEntry from the path and add it to CurrentFiles
    public void AddNewFileRecordEntry(string path) {
        throw new NotImplementedException();
    }

    //set the file as expired to 
    public void MarkFileAsModified(FileRecordEntry entry) {
        throw new NotImplementedException();
    }

    //snip...
}

Granted, an experienced developer could place all of those functions into a single loop and it would still be readable but isn’t the code above the kind of code we should all be writing anyways? Simple, clear, straight-forward functions each with a specific purpose and nothing more?

Code like this manages complexity – he didn’t have to worry about how each of the functions were going to fit into the master plan but instead how to complete each of the functions.

You know what coding like this makes me think of – Paint by number! And when it comes to code complexity – that’s a VERY good thing.

paint-by-number

It’s hard to tell what that is a picture of looking at it now — but if you remain diligent and fill in each of the blanks with the correct color then before long you’re staring at a masterpiece (or maybe not — this picture looks like someone holding a gun in FPS view — but you get the idea :))!

When it was all said and done with, the loop that had caused so much grief was much easier to read – not just for him but easier for me to read as well!


public void ProcessFiles() {

    foreach(string file in Directory.GetFiles(folder)) {

        if (!this.IsValidFileType(file)) { continue; }

        if (this.IsExistingFileEntry(file) &&
            this.IsFileModified(file)) {
            FileEntryRecord entry= this.FindExistingFile(file);
            this.MarkFileAsModified(entry);

        }
        else {
            this.AddNewFileRecordEntry(file);

        }
    }

}

Even without comments, you can most likely figure out what this code does with only a cursory glance over it.

A Personal Reevaluation

Its hard to say when a developer abandons simplicity. I think a lot of us start out writing gigantic functions that do much more than they need to and then slowly realize how much easier our lives are if we create functions for specific jobs.

Ironically though, I think the smarter and more skilled we become, we begin to lose sight of what a “simple” function really is. Some of us can write a single lambda expression to create a ham-n-cheese sandwich with our eyes closed — a 20 to 30 line for loop can’t possibly be that difficult for us anymore!

I can’t deny that I would have pushed all that code into a single loop, used a handful of well named variables with a couple clear and useful comments and called it a day. But looking back on the final result I can say without a doubt that I’d rather go back and make changes to the new, simpler class — wouldn’t you say the same?

Written by hugoware

September 17, 2009 at 10:17 pm