fooberry

Sweetness without context.

Can you be too lexical in your syntax

April 16th 2010

Anyone whom has read any of my recent code knows I love lexical syntax. I really love it when anyone, even our HTML designers, can read our code and understand exactly what is going on. Im not the only one either.

@MarkBorcherding amen, fellow believer in functionNamesShouldSayWhatTheyDo(AndParameterNamesShouldReflectWhyTheyAreNeededByTheFunction)!

@noelweichbrodt

A great example is the terrible Selenium API. It is confusing to even me, at firstonly for a second. Take a look at the following example.

_selenium.Open("some.url");
_selenium.Type("css=id$=_username","homer");
_selenium.Type("css=id$=_password","beer.is.yummy");
_selenium.Click("css=id$=_submit","LoginButton");
_selenium.WaitForPageToLoad("30000") 
Assert.Equal("Homer Simpson",_selenium.GetText("css=id$=_userFullName")); 

 

Now that's not terrible. I would even lean to say anyone would know what that does, but what is the css=id$=_username? That looks goofy.  Why do we do that? Take a look at our extensions on top of the Selenium API.

_theBrowser.Types("Homer").IntoAspNetControl("username");
_theBrowser.Types("beer.is.yummy").IntoAspNetControl("password");
_theBrowser.ClicksOnAspNetControl("LoginButton");
_theBrowser.WaitsForThePageToLoad();
"userFullName".AspNetControl().TextIn(_theBrowser).ShouldBe("Homer Simpson");

 

It wouldn't be hard to argue the second example is not much more clear. You dont have to remember that CSS selector or why we did the $=_ instead of just =. Overall, Im pretty happy with our API. There is a valid argument that this syntax will take time to learn since any developer reading it will have zero experience with it or know what calls are available, but over time, I think the benefit of its readability out weight its learning curve.

So here is where I am today. I dont like the following code.

<input 
    type="text" 
    id="<%=Html.IdFor(x=>x.CustomDomainName) %>"
    style='<%= !Model.HasCustomDomainName ? string.Empty : "display:none" %>'
    />

 

Its a pretty typical ternary operator. In this case though, I have to explain to our designers what that actually means and how to read it. Im really tempted to create the extension methods I need to have this syntax.

<input 
    type="text" 
    id="<%=Html.IdFor(x=>x.CustomDomainName) %>"
    style='<%= Model.HasCustomDomainName.IsFalse().Then(()=>"display:none") %>'
    />

 

Again, much more clear, but it feels like Im starting to abuse the extension methods and making a mess of the languagebut it reads so much nicer.

blog comments powered by Disqus