The Basics: Conditional Inversion

Conditional inversion is a simple but powerful technique that makes your code easier to read. I’ve noticed that not a lot of people in the Sitecore community seem to know about it, so I thought I’d blog about it.

Inverting your ifs

Deeply nested code is pretty hard to read. Let’s take this example:

public class Class1
{
    private static object Lock = new object();
    private static string Value = false;

    public string GetValue()
    {
        if (Value == null)
        {
            lock (Lock)
            {
                if (Value == null)
                {
                    Value = ExpensiveCreateValueMethod();
                }
            }
        }

        return Value;
    }
}

This is a very common pattern in multithreaded code, the double-check lock. It ensures that the Value is not initialized more than once at the same time by different threads. It’s also fairly hard to follow the code: it has a lot of nested blocks, and the information density is not very high.

Let’s take a different approach to the same code.

invert.jpg

Let’s invert our if statements so we can get out of our method as quickly as possible.

public class Class1
{
    private static object Lock = new object();
    private static string Value = false;

    public string GetValue()
    {
        if (Value != null) return Value;

        lock (Lock)
        {
            if (Value != null) return Value;

            return Value = ExpensiveCreateValueMethod();
        }
    }
}

With inverted if statements we check not for success but for failure. This method has two fewer nesting levels, is four lines shorter, and is significantly more readable because you don’t have to traverse a long if block to see what code will be executed next on success. Imagine outside a contrived example like this one, where your if might be 50 lines long.

So next time you’re writing conditionals, think about handling the failure before the success. Instead of:

public string Foo(string bar) 
{
    if(bar != null) {
        // do
        // stuff
        return something;
    }

    return null;
}

Do this:

public string Foo(string bar) 
{
    if(bar == null) return null;

    // do
    // stuff
    return something;
}

Nicer, right?

Feeling loopy?

loop.gif

The same inversion technique is also lovely for loop control. Have you ever written a loop like this?

foreach (var foo in bar)
{
    if (foo != null)
    {
        // do
        // stuff
    }
}

When inverting loop control you make use of the continue statement. This is an underused gem that skips the current loop iteration just like return skips the rest of a method. We can rewrite the loop above for better readability like so:

foreach (var foo in bar)
{
    if (foo == null) continue;

    // do
    // stuff
}

Now if foo is null, we just skip the rest of the loop body and go to the next item. Handy, right?

Bonus points: asserting reference types

A special case of this kind of inversion is the use of the Sitecore.Diagnostics.Assert class. When you’re designing a method, any reference type parameters to that method are allowed to be null. I’ll bet you didn’t expect someone to pass null, right? (I’ll bet I didn’t either!)

public void DoStuff()
{
    // null is usually not overtly passed, e.g. looping over dynamic data
    var stuffFromRestService = new[] { "foo", null, "bar" };
    foreach (var attribute in stuffFromRestService)
    {
        DoAThing(attribute);
    }
}

public void DoAThing(string attribute)
{
    // boom
    attribute.ToLowerInvariant();
}

Then you get this most favourite error, with a ‘helpful’ stack trace in the middle of the offending method:
ysod.png

Not helpful, right? Well we can handle this more gracefully if we assert that our parameters that are reference types are not null - then we get an exception at the top of the method that is useful and tells us what really happened:

// using Sitecore.Diagnostics;
public void DoAThing(string attribute) 
{
    Assert.ArgumentNotNull(attribute, nameof(attribute));

    // do stuff
    attribute.ToLowerInvariant();
}

And we get a better error message that tells us the argument name and what happened:
arg.png

Pretty handy, right? Now go forth and code!

C#4: Defining optional parameters in interfaces is very unreliable

See this example

In short, when the object is treated as the interface the default value from the interface applies. If it’s treated as the implementation, the implementation’s default applies. But the implementation isn’t required to have a default for it at all - in which case the call will fail, unless it’s treated as the interface.

It’s all very unreliable, and while I’m sure it works this way for good technical reasons under the hood, realistically it doesn’t present a very coherent interface.

Making asp:TextBox do HTML5 input types

I was watching a presentation on HTML5 from one of my coworkers a few weeks ago and we were talking about the new input types in HTML5, like numbers and dates. They’re backward compatible with non-HTML5 browsers (which render them as text boxes), but provide very useful UI features particularly to smartphones where the on screen keyboard can change to be more appropriate.


Anyway, let’s just say they’re a good idea. A good idea that, much as I like ASP.NET, are not likely to make an appearance any time soon in the core framework. So, I looked around to see if I could figure out a way to patch a standard to render these new HTML5 types. Yes, you MVC types already can do this easily. For the rest of us that are using third party CMS tools, WebForms is still the way of life :)


I came across a post by Phil Haack about a sneaky method of overriding HtmlTextWriter to change the attributes output by WebControls, and repurposed it to accomplish the HTML5-ization. Basically you override the AddAttribute() method and make it ignore the attribute you want to manually handle - in this case, the type attribute of the TextBox. Then I made a new TextMode-style enum that encompasses the HTML5 types and wrote a bit of logic that manually creates the right type attribute. The new enum is exposed in the Html5TextMode property, and the value is proxied back into the default TextMode property if it’s compatible with it.


So how do you use it? It’s pretty simple:

<prefix:Html5TextBox runat="server" Html5TextMode="Tel" ID="telephone" />

And the code for the control itself:

public class Html5TextBox : TextBox
{
 /// <summary>
 /// When using non-HTML5 constructs this mode will be accurate. If using HTML5, it will return SingleLine.
 /// </summary>
 public override TextBoxMode TextMode
 {
  get
  {
   try
   {
    return (TextBoxMode)Enum.Parse(typeof(TextBoxMode), Html5TextMode.ToString());
   }
   catch(ArgumentException) { return TextBoxMode.SingleLine; }
  }
  set
  {
   Html5TextMode = (Html5TextBoxMode)Enum.Parse(typeof(Html5TextBoxMode), value.ToString());
  }
 }

 /// <summary>
 /// Sets the text mode of the control including HTML5 text modes such as Num and DateTime
 /// </summary>
 public Html5TextBoxMode Html5TextMode
 {
  get
  {
   object textMode = this.ViewState["5Mode"];
   if (textMode != null)
   {
    return (Html5TextBoxMode)textMode;
   }
   return Html5TextBoxMode.SingleLine;
  }
  set
  {
   this.ViewState["5Mode"] = value;
  }
 }

 /// <remarks>
 /// Adds the normal attributes (since the writer is actually a PatchedHtmlTextWriter from Render() the type attribute won't be rendered),
 /// then explicitly adds the appropriate type attribute including the HTML5 extensions
 /// </remarks>
 protected override void AddAttributesToRender(HtmlTextWriter writer)
 {
  base.AddAttributesToRender(writer);

  string type = null;
  if (Html5TextMode == Html5TextBoxMode.SingleLine)
   type = "text";
  else if (Html5TextMode == Html5TextBoxMode.DateTimeLocal)
   type = "datetime-local";
  else type = Html5TextMode.ToString().ToLowerInvariant();

  if (type != null)
   (writer as PatchedHtmlTextWriter).AddTypeAttribute(type);
 }

 /// <remarks>
 /// Patches the type of HtmlTextWriter that the control renders to
 /// </remarks>
 protected override void Render(HtmlTextWriter writer)
 {
  base.Render(new PatchedHtmlTextWriter(writer));
 }

 /// <summary>
 /// A version of HtmlTextWriter that intentionally ignores the "type" attribute when it is added.
 /// </summary>
 /// <remarks>
 /// Technique courtesy of Phil Haack
 /// http://haacked.com/archive/2006/01/18/UsingaDecoratortoHookIntoAWebControlsRenderingforBetterXHTMLCompliance.aspx
 /// </remarks>
 private class PatchedHtmlTextWriter : HtmlTextWriter
 {
  internal PatchedHtmlTextWriter(HtmlTextWriter basis) : base(basis) { }

  public override void AddAttribute(HtmlTextWriterAttribute key, string value)
  {
   if(key != HtmlTextWriterAttribute.Type)
    base.AddAttribute(key, value);
  }

  public override void AddAttribute(string name, string value)
  {
   if(name != "type")
    base.AddAttribute(name, value);
  }

  /// <summary>
  /// Manually adds a type attribute
  /// </summary>
  public void AddTypeAttribute(string value)
  {
   base.AddAttribute(HtmlTextWriterAttribute.Type, value);
  }
 }
}

/// <summary>
/// Extends the TextMode enum with additional HTML5 types
/// </summary>
public enum Html5TextBoxMode { MultiLine, SingleLine, Password, DateTime, DateTimeLocal, Date, Month, Time, Week, Number, Range, Email, Url, Search, Tel, Color }

Visual Studio 2010 New Stuff

Visual Studio 2010 brings about a bunch of new “coder-centric” features, some of which I’m practically drooling over. Post based on a session with Jeff King, Program Manager of Visual Studio Web Tools. He’s a cool guy.

  • Improved CSS2.1 support, particularly in the designer view for attribute selectors and the like.

  • Multiple monitor enhancements: Grab a file’s tab in the editor and drag it somewhere else to have a mini window that can be moved to a different monitor

  • There’s already support for C# snippets, but now there’s also HTML/JS snippets. Default ones included for standard things eliminates typing runat=”server”s and <style type=”text/javascript”> or <a href=""></a> from being so boilerplate. Type tag (“a”, “requiredfieldvalidator”) or name of snippet and two tabs to insert. Supports sneaky things like when inserting a RequiredFieldValidator it will set the ControlToValidate to the last validatable control it finds automatically. Jeff literally wrote up a form with 2 fields, validation, and a radio button list in less than 1 minute and about 80 keystrokes including whitespace.
  • Neat trick that I think may exist in 2008 as well: make selection, right click, surround with… (update panel, div, etc)

  • Pretty darn good js intellisense based on a virtual evaluation engine - including intellisense for jquery with no vsdoc file, and intellisense on jquery extensions added with extend() that aren’t even obviously declared as a function even. Very impressive virtual DOM implementation.

  • Ability to “consume first” by referencing a nonexistant object, and have the object created based on the context of your mentions of it. Could prove quite useful to write tests prior to some code’s existence as the consume first model would create only the minimal set of required fields to work.

  • Ctrl-, opens a ‘quick find’ to find files in large projects - very much like jump to file in winamp - and set focus to them. I like this idea, even if you organize well the file lists just get too long in larger projects.

  • “call hierarchy,” a reflector-style analysis of who calls function x and what functions x calls

  • Application packaging, which includes files, databases (including merging schema changes), ssl certs, web.config transforms, etc into a single .zip package for deployment. Uses the MSDEPLOY tool that can be implemented on the server using a web service to eliminate the need for non-HTTP access as well as provide rsync-style synchronization. If you’ll excuse me being 12 years old for a minute, the rather amusing out of context phrase “you can take your package and give it to the community” was said while discussing this feature.

  • Web.config transformations allow automatic transformation of a web.config file based on project configurations (e.g. debug/release), transformations are diffs from the main web.config and use a XSLT-like (but less verbose) language. This looks like it would be a wonderful tool for development groups like mine (and @u2elan‘s as well) who have multiple developers doing local development, but each requiring a slightly different configuration per machine. The only problem is that it would require creating a build profile for every developer, and them to remember to switch to it before building on their machine. I suggested to Jeff King that some sort of provider model to programmatically select which transformation(s?) to load might be a good idea, so we could implement something like a switch based on machine name, or (@tvancil‘s idea) logged in username. He said he’d have some people call me to discuss it.

New Features in ASP.NET 4.0

ASP.NET 4.0 is going to introduce a lot of pain-point reducing features, particularly around the efficient delivery of content and standards compliance. Here are the main points as I saw them in Stephen Walther’s talk this morning.

  • FormView, as well as several other table-based controls: RenderTable=”false” disables table wrappers

  • ListView: no longer requires a , only an item template. Be careful with empty data sets though, as your wrap tags might be left exposed.

  • ViewState can be globally disabled and then selectively enabled on controls using the Control.ViewStateMode=”Disabled” (Enabled, Inherit) - it defaults to ‘inherit’. This is different than EnableViewState=false in that (1) it inherits and (2) you can re-enable it as needed on specific controls

  • Control.ClientIdMode property allows you greater control over the ID attribute emitted. Options include “Legacy,” [how it is now] “Static,” [use what you said] “Predictable,” [wasn’t defined] or “Inherit” allows overriding the ID value on a control. Can be set in the web.config element as well but that’s probably a bad idea to change except on an as-needed basis to avoid ID collisions in repeating controls. It was noted that the “Legacy” option would probably have its name changed before release.

  • New Response.RedirectPermanent() creates a 301 permanent redirect as opposed to Response.Redirect()’s 302 temporary redirect

  • ASP.NET “velocity” distributed caching, allows creating custom cache providers as well as caching on multiple machines

  • Web.config transforms allow multiple iterations of a web.config to be stored with the application. More about these later.