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?


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;

    //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;

    //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;


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() {

    //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;

    //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%><% } %>

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%><% } %>

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 {

    //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();


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.


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);

        else {



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

Is Encrypting Your Web.config A Waste Of Time?

with 2 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

Get Visitor Feedback – Without Asking For Their Help

leave a comment »

Do you track what visitors look at when they get to your site? Do you check things like the search phrase they used to get to your site? Do you track what gets downloaded the most? E-Mail comments sent directly to the administrator?

Most people I’ve ever met feel that feedback, like comments or e-mails, are the best/only way to gauge how your customer feels. They feel that unless you’re reading actual typed words from the customer, then you don’t know what they are looking for.

This last month, since jLinq and this blog came online, I’ve had about 620,000 hits. Want to take a guess how many e-mails with feedback I’ve gotten? 100? 200? 1000?

How about, 2…

Yep, just two e-mails with feedback. A little surprising since I know I’m not that good (if any good :)) at programming. Surely some people are at least a little confused on how jLinq works (or anything I’ve posted so far). I would have figured questions, suggestions and requests would come pouring in.

Feedback, Stealth Style

Despite the lack of “verbal” feedback, I’ve still managed to get interesting feedback from my site statistics, for example the pages that are viewed the most, the number of downloads for different versions and referrers to my site.

A good example of learning more about your website from site statistics alone is my own blog!

WordPress has quite a few awesome tracking features that tells you about your most viewed post, referrers to your site, search terms that led to your site and more. These stats tell you a lot of information about how people are finding your site. That’s really valuable information when you’re trying to figure out the best way to present your site when someone arrives.

On this blog I get my most traffic from a post that I did about changing HTML into a PDF. Definitely not my area of expertise, but a very hot topic for my blog. Knowing this it gives me incentive to work more on that project and make it better.

Another valuable piece of information has been seeing the search terms that help people make their way to this site. A great example of this was when I noticed people were getting to my site with the search terms of an exception that was found in jLinq. I realized that I didn’t have any documentation about the exceptions I had written and so the closest thing to help my visitors could find was this blog.

Are You Using Statistics?

It’s interesting that despite the ease that we can communicate over the web, feedback is still uncommon. I thought was always a great example of this. Anytime Jeff posts a blog entry he gets roughly 50 to 100 comments, and hot button issues around 300. That’s some really great numbers for feedback until you consider that he also has about 125K subscribed readers and who knows how many more that don’t use Feedburner (for example – myself).

My guess is that even on interesting topics, we’re in just too much of a hurry even to write a small comment. Maybe it’s that a large amount of feedback goes without a response. It could be that we’re constantly bombarded by websites telling us “your opinion matters” or “tell us what you think” that we just don’t even really care anymore unless it’s something we’re really passionate about.

But there is a great deal of knowledge to be harvested all without a single form. So, how are you using your website statistics?

Written by hugoware

June 1, 2009 at 1:51 am

Is ASP.NET And MVC Really A Good Fit?

with 8 comments

ASP.NET MVC is a new framework for building web applications. It’s geared to favor TDD and gives programmers more control over the the content that is sent down to the client. I’ve even defended ASP.NET MVC in other places for all of its great new features. I really do like ASP.NET MVC.

But the more I use it, the more I wonder if the pattern really works – or at least as well as WebForms did. Maybe I’m missing something, and I’d gladly take advice, but here are a few of my road blocks.

The Disconnect With RenderPartial

One of the cool things about WebControls was that you still had an awareness of other parts of the page. If you needed some client script to be attached to a page to make your control work, then…

  new LiteralControl("<script type='text/javascript' >alert('hello world');</script>"

No problem. Stylesheets can be added, scripts imported – great. But what about MVC, more specifically, inside of a “UserControl/PartialView”.

<% this.Header.Controls.Add(
  new LiteralControl("<script type='text/javascript' >alert('hello world');</script>"

What does this little code snippet create? Object reference not set to an instance of an object. exception. Uh oh. Nobody is home.

But even if you could pass some sort of reference to the header into your control – How do you plan to add anything anyways? Code between <% and %> is executed after your header has been rendered, or at the very least, is no longer checking for changes to itself (I’m not exactly certain if it is fully rendered but it doesn’t reflect any changes made to it).

Of course, you can always add script and link tags inline, but isn’t that a step backwards?

Knowing Everything Going Into A View

Once the controller finished handling a request it passes the information into the view. The view, as I understand it, isn’t supposed to do anything more than display the result. But is it really that simple? Do your views have a standard way of turning out every time? Do you really always know exactly everything you’re planning on displaying? Or the order your plan to show it?

I’m working on a project right now that allows people to type in a search term and then get results from all sorts of categories. Not only that, the results are order by most relevant to least relevant on the view as well as changes up the text and wording of your results depending on your query (like searching for locations near zipcode returns distances or searching for open stores returns hours, etc…).

So here’s the problem – I’ve got defined classes for each of the types of results so I can include a score for each of them (since I can’t use the generated LINQ object), I’ve got a container class for each of them to calculate the scores (since a generic list won’t do), I’ve got another class to represent the view (as the ‘generic type’). I just want to do a LINQ query and drop my results into a Databound control!!

Instead, I’ve got all these extra classes, which feels like clutter to me. Not only that, ordering the content on the page is a trick in itself. With WebForms you could reorder controls and that was the end of it. As of now, I haven’t found an easy way to do this with MVC.

Maybe I’m a little spoiled from using Javascript so much lately working on jLinq. I enjoy the flexibility you have. Want to add a score property? something.prop = "Assigned just like that!"; Need to add a function! something.generate = function() { ... }; If you read my previous post about passing Anonymous Types, you’ll understand where the inspiration came from.

Inline Code Just Doesn’t Replace WebControls

<% and %> just doesn’t work as well as a WebControl. Not only is it a little difficult to read, it’s also deceptive in how it works. For example, what is shown on the page when this view is run?

<%--In the <body> tag--%>
<asp:Content ContentPlaceHolderID="body" runat="server">
    <% this.ViewData&#91;"MyParam"&#93; = 5; %>

<%--In the <head> tag--%>
<asp:Content ContentPlaceHolderID="head" runat="server">
    <% =this.ViewData&#91;"MyParam"&#93; %>

It’s not 5, but I’m sure you knew that. But does everyone on your team know that? Were you able to say with certainly before you answered?

Now, that’s not to suggest that you can’t make the same mistake inside of a WebForm, but inline server side code is already hard enough to read to begin with; what happens when you start placing your code in the wrong order as well? Moving code between <script> tags doesn’t help that much either.

Exactly, What Are We Testing Again?

I won’t claim to know much of anything about TDD – I’m admittedly as beginner. I’ve noticed the claim that MVC makes great strides in improving TDD by using Controllers. This way you can generate tests using the Controller Actions – something was much more difficult with WebForms.

This might not really be directed at MVC as a fault, but do we really need to test Controller Actions? Or are we actually testing the functionality behind the scenes? For example, I keep seeing a lot of tests like this.

public void RouteDefaultsWork() {
    var app = new GlobalApplication();
    RouteCollection routes = new RouteCollection();
    var context = MvcMockHelpers.FakeHttpContext();

    var data = routes.GetRouteData(context);

Is that really a test? That proves something that we’re going to notice the second we run the app (which I’m hoping is done before you release your app 🙂 ) Aren’t we more concerned if our functions that pull, format and update information are accurate. A unit test makes sense for .CalculateRate() or .GetClosestLocationToZipcode(), but I haven’t quite figured out the purpose of testing a controller action.

With that said, are the Controllers really handling this kind of logic? Or haven’t we created separate, reuseable classes elsewhere that are handling this programming? If so, is making Controllers available for writing tests really all that helpful? I don’t really know.

I’m clearly not an authority on TDD with MVC, so any clarifications on what I’m doing wrong then I’m welcome to advice.


Don’t get me wrong – I love MVC. It’s bugged me for a long time being stuck using annoying parts of ASP.NET like using only a single form for a page or stupidly long control IDs for things that never needed an ID. It just seems that a lot is lost when you move away from WebForms.

I know that development is in full swing for MVC and I expect for things to only improve at this point. I look forward to the future of MVC since it will no doubt continue to improve.

Written by hugoware

May 25, 2009 at 1:02 am