Monday, October 17, 2011

Conditions and Dictionaries

Last week I was involved in some new employee code reviews and pairing interviews. Since most people that apply to ThoughtWorks do our Mars Rover problem, I decided that I should probably give the problem a try. The solution is pretty simple, which is probably why most people select this problem. I happened to be in a programming mood at the time, so I decided to make the problem a little more difficult.

Could I write a solution without an IF statement?

It turns out that I can and the results were very interesting. Here is the first cut of my spin left method before the change over.



Here is another deviation with if statements, because you know... switches are smelly.



Then here is what I came up with when trying to remove all my conditions.



Personally, I find it much more readable than the other two. This is something I would not have expected given an arbitrary challenge. Maybe those anti-if people are onto something.

Saturday, October 01, 2011

Tackling Business Complexity

This week at a client site, one of our stories came back from the dead because some condition wasn't handled. As we were implementing the story, our understanding increased and along with understanding came new questions. After asking these new questions, it became clear that there was a lack of holistic understanding for the both the developers and the business. The developers wanted a rationalized set of conditions, the business wanted things to be displayed in different ways when certain conditions were met. Basically, we wanted the same thing, but could not meet on a common language.

The thing we could agree on was what parts were important, so I came up with the idea of producing a truth table to hash out the different combinations. It looked a lot like the image below.




After creating the table, it was a matter of going through each combination and recording what expected result should be displayed. This produced five potential outcomes that turned out to be relatively simple to handle.



Looks almost too easy right? I'll assure you that the vernacular of the story did not cover the problem in such logical terms. The distillation of these guard statements (each condition returned) was a direct result of the truth table. Had we gone with a more classical approach, it would have likely resulted in a fair bit of cyclomatic complexity or the introduction of more classes to tackle this problem through polymorphism.

As it turned out, we wrote some tests, wired everything up and it worked just like the BA wanted, but could not logically define.

Monday, March 28, 2011

What is NuGet

After spending some time with Ruby on Rails and the wonderful package management tool RubyGems, I was very excited to hear about NuGet, a .NET package manager that comes bundled with ASP.NET MVC 3. Finally, the .NET community gets a Microsoft supported package manager. The NuGet page has a pretty good description of what it is and why you should care...

NuGet is a Visual Studio extension that makes it easy to install and update open source libraries and tools in Visual Studio.
When you use NuGet to install a package, it copies the library files to your solution and automatically updates your project (add references, change config files, etc). If you remove a package, NuGet reverses whatever changes it made so that no clutter is left.
You can think of it as a much more convenient way to include third party libraries if you haven't used something like ruby gems before. As a package manager, NuGet will do many things for you to make your life easier.

First, it makes it simple to find and include a library. You don't have to google for the library, find the project page, find the download page, find the right version, etc... You can easily install the package the way you would a local library (almost).

It will pull in dependencies for that library. Want to use Fluent-NHibernate? Just grab the NuGet package and it will include NHibernate, along with NHibernates own dependencies.

It can also allow the injection of useful template code into your project to help get you started. MVCMailer does just this to help get you started with sample views and mailers.

If this sounds worthwhile, head over to Justin Etheredge's blog and follow his tutorial, which is really good.

Also be sure to check out some of the available packages in the NuGet Gallery.

Wednesday, May 26, 2010

PURE HTML Templates

I’ve been pressured into writing about PURE templates by a couple of my colleagues at ThoughtWorks. My blogging has died down after rolling off my previous iPhone project, but while doing some work in ASP.NET MVC I came across something useful. A very nice HTML templating engine.

My biggest complaint when looking at HTML templating engines is that they are very similar to PHP or ASP code, littering my HTML with different forms of placeholders. They are very simple and quick to pick up, but very limited once you need to do something more than map A onto B without creating a lot of one off functions that will fit in one line.

<script type="text/html" id="item_tmpl">
  <div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>">
    <div class="grid_1 alpha right">
      <img class="righted" src="<%=profile_image_url%>"/>
    </div>
    <div class="grid_6 omega contents">
      <p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>
    </div>
  </div>
</script>

Introducing PURE Templates

Have a look at this fully functional example (view source) using PURE. There is some HTML and a small script block. In the block is a javascript object literal representing the data and a single call to PURE giving the root of the HTML template and the data to render. Clean HTML, very little code and no dirty template placeholders. This shows that, in the happy day scenario, PURE is very simple and easy to use, like most other templating engines.

However, as the web becomes more and more about creating and interacting with services. Consuming third party sources becomes necessity and those sources will not be providing data in the human readable format your require, nor will their names be exactly what you need.

For these situations, we need something more powerful than all these happy day templates can provide (assuming you don’t just want to remap everything you consume). In PURE, they accommodate this by way of a Directive. At a basic level, a directive is a javascript object literal defining how to map your data onto your HTML. The keys are CSS Selectors and the values are Actions, where Actions can be strings, objects or functions.

  <!-- HTML template -->
  <ul>
    <li></li>
  </ul>

  <script>
    var data = {
      legs:4,
      animals:[
        {name:'dog', legs:4},
        {name:'cat', legs:4},
        {name:'bird', legs:2},
        {name:'mouse', legs:4}
      ]
    };

    //declaration of the actions PURE has to do
    var directive = {
      'li':{
        'animal<-animals':{
          '.':'animal.name'
        },
        sort:function(a, b){
          return a.name > b.name ? 1 : -1;
        },
        filter:function(a){
          return a.context.legs === a.item.legs;
        }
      }
    };

    // note the use of render instead of autoRender, and the 2nd argument
    $('ul').render(data, directive);
</script>

source

The above example  shows what a directive looks like while consuming data that must be iterated over. It also shows how the directive can accommodate sorting and filtering, which can come in handy at times. If you like what you see, check out the rest of the demos or the tutorials.

Monday, March 29, 2010

Objective-c Inheritance & Message Passing

Came across an interesting result while overriding a base class last week. Assume we have a class with two methods, one overloading the other as follows.









Assume both methods are defined within the interface (intentionally public). Now when we inherit from this class and override the first method (create:id), where does the "create:int" message in the second method get passed too? It is calling "self" from the context of the parent, but we just overrode the method in the child.





Given the above, where does the message go? Will it call create:id on the child or the parent?

Turns out, it is all in what you declare within your interface for the child. Define




in the child interface and it will pass the message to the child (using your override). Don't and the message will instead go to the parent. Thought it was very curious behavior as a C# guy.

Saturday, March 06, 2010

Objective-C Libraries and Tools

There are quite a few open source cocoa touch libraries and frameworks.

OCMock, the winner by default when it comes to mocking in objective-c. It is actually a really decent mocking framework with all the elements you would come to expect (mocks, stubs and partial mocks). Setting it up can be a bit of a pain, fortunately Colin Barret has figured that out for us already.

Google Toolbox, augments the SenTestingKit (OCUnit) providing more assertions, log tracking, binding testing and more. A very visual tutorial on setting up Google Toolbox.

GHUnit, I am still spending time with this one. Seems promising so far. Key features are running individual tests, running tests from the command line (easier) and testing macros.

UISpec is a test automation tool. It’s key feature is that it can run automation tests within the simulator (OCUnit must deploy to the iPhone). Documentation is pretty sparse.

ASIHTTPRequest is a library that wraps the CFNetwork API, handling quite a bit of the grunt work for you. Great for working with RESTful services.

json-framework, another key element of working with RESTful services. JSON is lighter weight and uses key-value pairs to represent data. This plays very nicely with the KVC techniques you should be using in Cocoa.

SpeedLimit, this is a great utility for simulating the network speeds you are likely to have on the iPhone.

Tuesday, March 02, 2010

IPhone Development Guide

Just a collection of information and useful advice that I have collected. Hope this helps you get started.

Start where I started doing something simple hello world type examples. All of the icodeblog tutorials are worth doing if you are starting out (though watch out for the SQLite ones as Core Data replaces that now). Try this one to get a feel for interface builder and this one next for tying the code into IB. It can take a little while to learn the name of the different controls you will be using. This tutorial is on one of the navigation controls, the UITabBarController, which visually rests on the bottom of the window and will be one of your staples.

Cocoa has a learning curve of its own, get up to speed on Key-Value Coding (further reading), the framework makes use of many dictionaries. There is also a good post (with even more links) on the MVC Model used on the iPhone. It differs slightly from other representations of the Model View Controller pattern.

Model-View-Controller design patternsource

The primary difference is in the behavior between the different flows back to the view. On the iPhone, only your controller should be interacting with the UIView where as traditionally it is acceptable for the Model to have some interactions (Notifications or checking state).

Matt Gallagher’s blog is probably something that you want to subscribe to. A few of my favorites: