markhneedham/blog huggingface dataset:
ASP.NET MVC: Driving partials by convention
Date: 2009-02-21 10:39:49

I like to have conventions in the code I write - I find it makes the code i write much cleaner which still providing flexibility.

One of the conventions that Jeremy Miller coined for working with ASP.NET MVC applications is that of using one model per controller method aka http://codebetter.com/blogs/jeremy.miller/archive/2008/10/23/our-opinions-on-the-asp-net-mvc-introducing-the-thunderdome-principle.aspx["The Thunderdome principle"]. I think we can take this further by having one model per http://bradwilson.typepad.com/blog/2008/08/partial-renderi.html[partial] that we use inside our views.

The benefit of having a model especially for a partial is that we remove confusion about data available to populate our controls by restricting the amount of data we actually have. It also makes more sense from a conceptual point of view.

Given this approach it started to become quite annoying having to type the following code all the time.

[source,csharp]
----

<% Html.RenderPartial("_Foo", new FooModel()); %>
----

We realised that a neater approach would be if we could just pass in the model and it would work out which partial needed to be rendered, assuming the convention that each model is only used on one partial.

We are using strongly typed models on our views so the code behind in each of the partials extends ViewPage+++<T>+++, making it possible to work out the partial we want to load by looking up the model.+++</T>+++

[source,csharp]
----

public static class HtmlHelperExtensions
{
    public static void RenderPartialFrom(this HtmlHelper htmlHelper,  object model)
    {
        var thePartial = FindMeThePartial(model);
        htmlHelper.RenderPartial(thePartial, model);
    }

    private static string FindMeThePartial<T>(T model) where T : class
    {
        var projectAssembly = Assembly.Load("Project");
        var types = projectAssembly.GetTypes();

        foreach (var type in types)
        {
            if (type.BaseType == typeof(ViewPage<T>))
            {
                return type.Name;
            }
        }
        return string.Empty;
    }
}
----

You can then refer to this in views like so:

[source,csharp]
----

<% Html.RenderPartialFrom(new FooModel()); %>
----

Obviously it takes the first result it finds, so the convention we have is that each model should only be used on one partial which I think is a reasonable idea.
Refactoring: Comment it out vs small steps removal
Date: 2009-02-08 09:10:39

One refactoring I was doing last week was to try and remove the use of some getters/setters on one of our objects so that it was better encapsulated and all the behaviour related to it happened in one place.

The change involved introducing a constructor to initialise the object rather than doing so using the new object initialiser syntax and initalising it using the properties.

My initial approach was to *find all the usages of these properties and then remove each usage one by one*, running our suite of tests against the code after each change to ensure that nothing had broken as a result of the change.

While we were doing this my colleague pointed out that it would probably be quicker to just *comment out the properties code and then recompile the code* - the list of errors would then point out the areas which relied on the properties and we could then fix the code that way.

It's a technique I've used previously and it worked out reasonably well because there were only 10 or so usages, meaning we were able to make all those changes and run the tests in under ten minutes.

I think if there had been bigger changes to make - for example if the properties had been being used to expose the data all over the application (luckily we only had one case of this) then the smaller steps approach may have been preferable.

Getting the balance between taking small steps and getting rapid feedback was also a consideration here.

We were running our unit and javascript tests as we made the changes since we were uncertain exactly what impact the changes would have. It took around 70 seconds to run these tests, which I think encouraged slightly bigger steps so that we weren't sitting around waiting too often.

Both of these approaches are useful and it seems to me that maybe a combination of them, at different stages of our refactoring, would prove to be most useful.
Agile: Why do we integrate early?
Date: 2009-02-06 16:47:26

One of the inevitabilities of most projects is that at some stage there is going to need be some sort of integration.

The likes of Alistair Cockburn in http://www.markhneedham.com/blog/2008/11/05/crystal-clear-book-review/[Crystal Clear] and Andy Hunt/Dave Thomas in http://www.amazon.co.uk/Pragmatic-Programmer-Andrew-Hunt/dp/020161622X/ref=sr_1_1?ie=UTF8&s=books&qid=1233902988&sr=8-1[The Pragmatic Programmer] talk of the need to do integration early rather than letting it wait until later, but why?

== Get the pain out the way

To some degree every time we try to integrate there is going to be some level of pain - for me it therefore makes sense that we take this pain early on when we have the chance to do something about it rather than leaving it until later and being surprised at the problems it causes.

We never really know that the system actually works as expected until it is fully integrated, and *integration inevitably leads to situations which we didn't know existed previously*.

The potential problem we need to be careful about here is that we still deliver features with business value while doing our early integration otherwise we end up with the problem that we seem to be delivering absolutely nothing.

== Code can be more example driven

When we integrate later on one problem we face is that we have to try and assume what the integration will be like rather than actually knowing.

While it is possible to somewhat isolate ourselves from other systems, at some stage we need to integrate and this can typically lead to different data flowing through, in a different format than expected and we need to handle these differences.

*If we integrate late we are putting ourselves into a guessing game* of what we think we are going to integrate against and this leads us down the path of assumption driven development.

This inevitably leads to us coding for some situations which won't actually happen when we are integrated and missing out some situations which we didn't actually know could happen until we integrated.

== Less inventory

In lean terms inventory is a product or part of a product which is basically in a state of waiting - either waiting for something to be done to it or waiting for a customer to buy it.

I think we can find a similar analogy in terms of story cards where a part of that story is to integrate with another system for example.

When we do the integration work needed later on the additional problem we face is that we naturally *lose some knowledge* in the time that the story is sitting waiting.

In addition there is also *wasted time* as people regain the context of how the integration fits into the overall functionality of the story.
C#: Wrapping collections vs Extension methods
Date: 2009-02-23 20:24:26

Another interesting thing I've noticed in C# world is that there seems to be a trend towards using extension methods as much as possible. One area where this is particularly prevalent is when working with collections.

From reading http://www.markhneedham.com/blog/2008/11/06/object-calisthenics-first-thoughts/[Object Calisthenics] and working with http://pilchardfriendly.blogspot.com/[Nick] I have got used to wrapping collections and defining methods on the wrapped class for interacting with the underlying collection.

For example, given that we have a collection of Foos that we need to use in our system we might wrap that in an object Foos.

[source,csharp]
----

public class Foos
{
    private readonly IEnumerable<Foo> foos;

    public Foos(IEnumerable<Foo> foos)
    {
        this.foos = foos;
    }

    public Foo FindBy(string id)
    {
        return foos.Where(foo => foo.Id == id).First();
    }

    // some other methods to apply on the collection
}
----

Extension methods provide another way of achieving the same thing while not needing to wrap it.

[source,csharp]
----

public static class FooExtensions
{
    public static Foo FindBy(this IEnumerable<Foo> foos, string id)
    {
        return foos.Where(foo => foo.Id == id).First();
    }
}
----

It seems like there isn't much difference in wrapping the collection compared to just using an extension method to achieve the same outcome.

The benefit I see in wrapping is that we take away the ability to do anything to the collection that we don't want to happen. You only have the public API of the wrapper to interact with.

The benefit of the extension method approach is that we don't need to create the object Foos - we can just call a method on the collection.

I'm not sure which is a better approach - certainly languages which provide the ability to open classes seem to favour taking that approach over wrapping but I still think it's nice to have the wrapper as it means you don't have to be explicitly passing collections all around the code.

But maybe that's just me.
Encoding user entered data
Date: 2009-02-15 01:46:33

I previously wrote about http://www.markhneedham.com/blog/2009/02/12/aspnet-mvc-preventing-xss-attacks/[protecting websites from cross site scripting in the ASP.NET MVC framework] by encoding user input when we are going to display it in the browser.

We can either choose to encode data like this or we can encode it straight away when we get it.

There did not seem to be a consensus on the best approach in a http://forums.asp.net/t/1194407.aspx[discussion on the ASP.NET forums] but we believe it is far better to encode the data when it is outgoing rather than incoming.

If we encode the data when it comes in then we need to *remember which data was pre-encoded* and then *un-encode it when it is going to be displayed in a non-HTML format*.

If we had a user enter their name as "John O'Shea' for example then we would end up storing the ' in the name as its HTML representation and might accidentally end up sending them correspondence referring to them as the wrong name.

http://twitter.com/davcamer[Dave] suggested 'fixing it [encoding issue] as close to the problem as possible' as a useful guideline to follow.

In this case our problem is that when the data we received from the user is displayed there could be some potentially dangerous code in there and we don't want to allow it to be executed on our page.

We then work off the assumption that any web applications that use our data should know how to encode the data since that falls under their responsibility. Any other applications can use the data as is.

I drew this diagram to clear it up in my head:

image::{{<siteurl>}}/uploads/2009/02/dataencoding.gif[dataEncoding.gif,563]
Coding: Assertions in constructors
Date: 2009-02-14 01:32:10

While browsing through the http://www.codeplex.com/aspnet[ASP.NET MVC source] I noticed that they use an interesting pattern on the constructors to ensure that an exception will be thrown if an object is not instantiated correctly.

[source,csharp]
----

public ControllerContext(HttpContextBase httpContext, RouteData routeData, ControllerBase controller)
    : base(httpContext, routeData) {
    if (controller == null) {
        throw new ArgumentNullException("controller");
    }
    Controller = controller;
}
----

If you pass in a null Controller you shall go no further!

We have discussed the merits of putting assertions in constructors several times in our http://domaindrivendesign.org[Domain Driven Design] book club but without ever really coming to a conclusion with respect to whether or not it is a good pattern.

Spring is an example of a framework which does internal assertions on the values being passed to its objects and will throw assertions appropriately. There is even a custom http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/util/Assert.html[Assert] class to do so.

The benefit of this approach is that our *code will fail early* if there is a problem. The disadvantage is that we may end up putting *Asserts all over our code* to cater for every place where the input could be invalid. If we were to use the Spring Assert class we would then have a coupling to that in our production code.

The approach I am more familiar with is that we would *validate any input from the UI or from systems that we don't have control over*, but apart from these boundary cases we would assume that our classes are http://docs.codehaus.org/display/PICO/Good+Citizen[good citizens] and will call each other with valid data.

My understanding of the implicit contract of a constructor is that we should never be passing null values into them. If we are contemplating doing so then we are probably doing something wrong and either need to reconsider or create a new constructor and then default the value for the extra parameters in other constructors.

In a way I suppose this is a limitation of the Java/C# type system that you can't prevent null values being passed into a constructor or that you can even have a null value in the first place.
C#: Wrapping DateTime
Date: 2009-02-25 23:12:57

I think it was http://darrenhobbs.com/[Darren Hobbs] who first introduced me to the idea of wrapping dates in our system to describe what that date actually means in our context, and after suffering the pain of passing some unwrapped dates around our code I think I can safely say that wrapping them is the way to go.

The culprit was a date of birth which was sometimes being created from user input and sometimes being retrieved from another system.

The initial (incorrect) assumption was that we would be passing around the date in the same string format and there was no point wrapping the value as we were never doing anything with the data.

It proved to be a bit of a nightmare trying to work out which state the data of birth was in various parts of the application and we ended up doing conversions to the wrong format and then undoing those and losing the formatting in other places!

Step 1 here was clearly not to pass around the date as a string but instead to convert it to a DateTime as soon as possible.

This is much more expressive but we can take this one step further by wrapping that date time in a DateOfBirth class.

[source,csharp]
----

public class DateOfBirth
{
	private DateTime? dateOfBirth

	public DateOfBirth(DateTime? dateOfBirth)
	{
		this.dateOfBirth = dateofBirth;
	}

	public string ToDisplayFormat()
	{
		return dateOfBirth == null ? "" : dateOfBirth.Value.ToString("dd MMM yyyy");
	}
}
----

When we want to display this object on the page we just have to call the ToDisplayFormat() and if that date format needs to change then we have only one place to make that change. Creating this class removed at least 3 or 4 'DateTime.Parse(...)' and 'DateTime.ToString(...)' calls throughout the code.

Now we could achieve the same functionality using an extension method on DateTime? but it's not as expressive as this in my opinion. It is also really obvious when looking at the code to know what type we are dealing with and it is really obvious when reading this class which method we will use to get the format to display to the user.

I will certainly be looking to wrap any DateTimes I come across in future.
Clojure: A few things I've been tripping up on
Date: 2009-11-20 13:11:03

In my continued playing with Clojure I'm noticing a few things that I keep getting confused about.

== The meaning of parentheses

http://krbtech.wordpress.com/2009/03/16/same-temperature-converter-different-language-clojure/[Much like Keith Bennett] I'm not used to parentheses playing such an important role in the way that an expression gets evaluated.

As I understand it if an expression is enclosed in parentheses then that means it will be evaluated as a function.

For example I spent quite a while trying to work out why the following code kept throwing a class cast exception:

[source,lisp]
----

(if (true) 1 0)
----

If you run that code in the REPL you'll get the following exception because 'true' isn't a function and therefore can't be applied as such:

[source,text]
----

java.lang.ClassCastException: java.lang.Boolean cannot be cast to clojure.lang.IFn (NO_SOURCE_FILE:0)
----

If we don't want something to be treated this way then the parentheses need to disappear!

[source,lisp]
----

(if true 1 0)
----

== Truthyness

Somewhat related to the above is understanding which expressions evaluate to 'true' or 'false'.

I'm told there are some edge cases but that as a general rule everything except for 'false' and 'nil' evaluates to true.

I think that's an idea which is more common in languages like Ruby but I'm not yet used to the idea that we can something like this and have it execute:

[source,lisp]
----

(if "mark" 1 0)
----

In C# or Java I would except to have to compare "mark" to something in order for it to evaluate to a boolean result.

It seems like a really neat way to reduce the amount of code we have to write though so I like it so far.

== Character Literals

I've been working through http://java.ociweb.com/mark/clojure/article.html#Syntax[Mark Volkmann's Clojure tutorial] and in one example he defines the following function:

[source,lisp]
----

(def vowel? (set "aeiou"))
----

I wanted to try it out to see if a certain character was a vowel so I initially did this:

[source,lisp]
----

=>(vowel? "a")
nil
----

"a" is actually a string though which means it's an array of characters when what we really want is a single character.

I thought the following would be what I wanted:

[source,lisp]
----

(vowel? 'a')
----

Instead what I got was the following exception:

[source,text]
----

java.lang.Exception: Unmatched delimiter: )
----

This one just turned out to be a case of me not reading http://clojure.org/reader[the manual] very carefully and actually the following is what I wanted:

[source,lisp]
----

=> (vowel? \a)
\a
----
Clojure: A first look at recursive functions
Date: 2009-11-17 11:10:37

I'm working through Stuart Halloway's 'http://www.amazon.com/gp/product/1934356336?ie=UTF8&tag=marneesblo-20&linkCode=as2&camp=1789&creative=390957&creativeASIN=1934356336[Programming Clojure]' book and I just got to the section where it first mentions recursive functions.

It's a simple function to countdown from a given number to zero and then return that sequence.

This was one of the examples from the book:

[source,lisp]
----

(defn countdown [result x]
  (if (zero? x)
    result
    (recur (conj result x) (dec x))))
----

That function could then be called like this:

[source,lisp]
----

(countdown [] 5)
----

I wanted to see what the function would look if we didn't have the empty vector as a parameter.

From playing around with F# and Scala my first thought would be to write the function like this:

[source,lisp]
----

(defn count-down [from]
  (defn inner-count [so-far x]
    (if (zero? x)
      so-far
      (inner-count (conj so-far x) (dec x))))
  (inner-count [] from))
----

As the book points out a bit further on, Clojure doesn't perform automatic tail call optimisation so we end up with a stack overflow exception if we run the function with a big enough input value.

Clojure does optimise calls to 'recur' so it makes more sense to use that if we want to avoid that problem.

This is an example which makes use of that:

[source,lisp]
----

(defn count-down [from]
  (defn inner-count [so-far x]
    (if (zero? x)
      so-far
      (recur (conj so-far x) (dec x))))
  (inner-count [] from))
----

http://groups.google.com/group/clojure/browse_thread/thread/4e7a4bfb0d71a508?pli=1[Looking through the Clojure mailing list at a similar problem] I noticed that one of the suggestions was to arity overload the function to include an accumulator.

[source,lisp]
----

(defn count-down
  ([from]
    (count-down [] from))
  ([so-far from]
    (if (zero? from)
      so-far
      (recur (conj so-far from) (dec from)))))
----

Written this way it feels a little bit like Haskell or Erlang but probably not idiomatic Clojure.

Anyway on the next page Halloway shows a better way to do this with much less code!

[source,lisp]
----

(into [] (take 5 (iterate dec 5)))
----

I noticed that in Scala the idea of using 'take' and 'drop' on streams of values seems to be quite popular so I'm intrigued as to whether I'll find the same thing with Clojure.
The 'should' word
Date: 2009-11-17 23:52:42

I've been reading http://www.amazon.com/gp/product/1430219483?ie=UTF8&tag=marneesblo-20&linkCode=as2&camp=1789&creative=390957&creativeASIN=1430219483[Coders at Work] recently and one of my favourite answers from the first chapter interview with Jamie Zawinski is the following:

____
I think one thing that's really important is not to be afraid of your ignorance. If you don't understand how something works, ask someone who does. A lot of people are skittish about that. And that doesn't help anybody. Not knowing something doesn't mean you're dumb - it just means you don't know it yet.
____

A variation of this which I've noticed myself doing is internally telling myself that I 'should' know how to do certain things much better than I can.

This is most typically the case when I'm struggling with something on a new project that I'm working on and while it is indirectly useful for helping to identify areas that we can work I think the voice in itself is not that helpful to our learning.

When this happens I've started writing down whatever it is that I think I should know better and then taking some time to read more in that area.

Wherever possible I also try to speak to people who already have that skill and find out how they went about learning it.

For example, as I mentioned in my post about http://www.markhneedham.com/blog/category/reading-code/[reading the Unity source code], reading code is something I want to get better at and when I've worked with http://intwoplacesatonce.com/[Dave Cameron] he's able to understand how things fit together much more quickly than I am.

When we discussed this he pointed out that he'd spent a lot of time debugging through a lot of different code bases just for fun and working out how they fitted together by following the control flow.

It's pretty much always the case that others have spent quite a bit of time working on these skills so it's certainly something to keep in mind next time I come across something I 'should' know!