Ayende @ Rahien

My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:


+972 52-548-6969

, @ Q c

Posts: 18 | Comments: 76

filter by tags archive

ChallengeWrite the check in comment

time to read 2 min | 291 words

In my code base, I have the following commit, which doesn’t have a checkin comment. This is the before:

private Entry GetEntryForSlug(string slug)
var entry = session.CreateCriteria(typeof(Entry))
.Add(Restrictions.Like("Slug", slug))

if(entry != null)
return entry;

//try load default document
return session.CreateCriteria(typeof (Entry))
.Add(Restrictions.Like("Slug", slug + "/default"))

And this is the after:

private Entry GetEntryForSlug(string slug)
var entries = session.CreateCriteria(typeof(Entry))
Restrictions.Like("Slug", slug) ||
Restrictions.Like("Slug", slug + "/default")

return entries
.OrderBy(x => x.Slug.Length)

What was the silent committer thinking about when he made the change? Can you write the check in comment?

More posts in "Challenge" series:

  1. (28 Apr 2015) What is the meaning of this change?
  2. (26 Sep 2013) Spot the bug
  3. (27 May 2013) The problem of locking down tasks…
  4. (17 Oct 2011) Minimum number of round trips
  5. (23 Aug 2011) Recent Comments with Future Posts
  6. (02 Aug 2011) Modifying execution approaches
  7. (29 Apr 2011) Stop the leaks
  8. (23 Dec 2010) This code should never hit production
  9. (17 Dec 2010) Your own ThreadLocal
  10. (03 Dec 2010) Querying relative information with RavenDB
  11. (29 Jun 2010) Find the bug
  12. (23 Jun 2010) Dynamically dynamic
  13. (28 Apr 2010) What killed the application?
  14. (19 Mar 2010) What does this code do?
  15. (04 Mar 2010) Robust enumeration over external code
  16. (16 Feb 2010) Premature optimization, and all of that…
  17. (12 Feb 2010) Efficient querying
  18. (10 Feb 2010) Find the resource leak
  19. (21 Oct 2009) Can you spot the bug?
  20. (18 Oct 2009) Why is this wrong?
  21. (17 Oct 2009) Write the check in comment
  22. (15 Sep 2009) NH Prof Exporting Reports
  23. (02 Sep 2009) The lazy loaded inheritance many to one association OR/M conundrum
  24. (01 Sep 2009) Why isn’t select broken?
  25. (06 Aug 2009) Find the bug fixes
  26. (26 May 2009) Find the bug
  27. (14 May 2009) multi threaded test failure
  28. (11 May 2009) The regex that doesn’t match
  29. (24 Mar 2009) probability based selection
  30. (13 Mar 2009) C# Rewriting
  31. (18 Feb 2009) write a self extracting program
  32. (04 Sep 2008) Don't stop with the first DSL abstraction
  33. (02 Aug 2008) What is the problem?
  34. (28 Jul 2008) What does this code do?
  35. (26 Jul 2008) Find the bug fix
  36. (05 Jul 2008) Find the deadlock
  37. (03 Jul 2008) Find the bug
  38. (02 Jul 2008) What is wrong with this code
  39. (05 Jun 2008) why did the tests fail?
  40. (27 May 2008) Striving for better syntax
  41. (13 Apr 2008) calling generics without the generic type
  42. (12 Apr 2008) The directory tree
  43. (24 Mar 2008) Find the version
  44. (21 Jan 2008) Strongly typing weakly typed code
  45. (28 Jun 2007) Windsor Null Object Dependency Facility



I assume the || operator is a bug. The committer was probably thinking about a LINQ-like optimization.

Incidentally I did a very similar thing yesterday using Criteria lambda extensions. Instead of writing code like

myCriteria.Add(p => p.FirstName == fname)

              .Add<Person>(p => p.LastName== lname)

I wrote

myCriteria.Add(p => p.FirstName == fname &&

                                                  p.LastName== lname)

and it took me a minute to realize why I was getting a runtime exception.


I'd guess that it was rewritten to perform a single database query instead of unnecessarily performing two.

Chris Airey

Maybe i'm wrong, but it doesn't like like neither of the queries are trying to archive the same result.


I've been bitten by this before.

UniqueResult will throw an exception if the query returns more than 1 row, which is quite possible when using LIKE.


He should use StringBuilder:

var sb = new StringBuilder().Append("slug").Append("/default") .ToString()

It would be faster.



why would that be faster? it would be slower.

comment: changed GetEntryForSlug to also return an entry for url with postfix "/default". first i try to find an entry that is an exact match for the slug. next i try it with a postfix. i ensured this by ordering by the length of the returned result list because the entry without postfix will be shorter and therefore first."

Steve Py

I get what the re-factor is doing, though I can't say I agree with it. The original code is pretty clear exactly what it's doing. return the item, if not found return the default, if not found, return #null. If anything, my only concern might be that the code is doing more than "one thing." For instance it might be a bit of a nuisance after the fact to determine if you actually retrieved an item or ended up with a default. But that's a digress.

The re-factor reduces the potential 2 queries to 1, however I'd say the readability of the intention of the code suffers. Get a list of the item an/or the item's default, then return the shortest one; assumed to be the item, if found, else the default, if found, else #null.

The thing is it took a couple careful passes looking at that to be sure it didn't have a "gotcha" or difference in behaviour. Frankly I favor readability over sheer optimization unless performance is a significant issue. Even so, in the ideal case where the "real" item is found, the extra query condition and LINQ sort & extraction is itself imparting an extra performance cost. I doubt the gain on average is more than negligible if anything at all.

Not sure what the actual choice in GIT comment ended up being, but I'd suggest that the following one should be an "Undo". ;)

Nick Aceves


While the code could certainly be more clear, it would be naive to suggest that the performance improvement is negligible. Surely you're not suggesting that an extra filter condition and a Linq OrderBy cost more than another round trip to the database...

To me, it really depends on how often we expect this code to load a default entry. If we are going to find real entry 90% of the time, I'd say leave the code as it was. If, instead, we're expecting to need a default entry around 50% of the time, and this code gets called frequently, then some kind of query optimization might make sense.


I don't know what this is from or for, but could it not have been written like:

private Entry GetEntryForSlug(string slug)


return session.CreateCriteria(typeof(Entry))


        Restrictions.Like("Slug", slug) ||

        Restrictions.Like("Slug", slug + "/default")


    .OrderBy(x => x.Slug.Length)



If so then that's far more read-able than both the original and committed... And it's not retrieving the result before deciding what to do with it...


Actually I just realized why the result was retrieved first, so that the orderby/firstordefault could be used against the resulted list...

Forget what I said I'm an idiot :)

Steve Py

@ Nick,

It's an assumption either way. Based on that type of behaviour and where that method would likely be called, my guess would be it would be expecting to find the real one at least 50% of the time. The higher the percentage, the less effective that optimization becomes, and at some point it becomes an averaged penalty.

Still, my main point was that the re-factor hurt readability, and unless the gain was significant (i.e. noticable to the end user) then it wasn't worth it.


So obvious when working with ORMs :

Improved performance from 2 queries to one.

Will Smith

I wouldn't call this a "refactoring" as there is a clear change in behavior. This is a rewrite (on a small scale). A refactoring is "restructuring an existing body of code, altering its internal structure without changing its external behavior." as defined by Martin Fowler.

I would assume that said developer has a valid reason for this performance rewrite. neonp's "comment" seems the be the most accurate and concise.

Ayende Rahien


What is the external behavior that was changed?

Will Smith

I knew that question would come up. Perhaps it's a stretch, but, I would say performance is the observable change in behavior here.

To me refactoring follows prescribed methods of modifying the structure of the code and has no effect on the algorithms in place. In the case above it seems the algorithm has been changed to observe improved performance.

I don't know, maybe Martin would ask what I've been smoking.

Patrik H&#228;gne

@Mike: I'm not sure you're serious, but I know for sure that there are a lot of developers out there that actually believe that to be true. The matter of fact is that in simple concatenation cases like this using a StringBuilder would be orders of magnitude slower.

Tom Marien

Comment : Did not slept well this night therefore i thought how i can screw up a working system.

The GetEntryForSlug now can return null, instead of throwing an exception when nothing matched (before uniqueresult, now firstordefault)

Kind regards

Ayende Rahien


UniqueResult will return null if nothing is matched

Tom Marien

I guess the comment counts for me then :P

Comment preview

Comments have been closed on this topic.


  1. Production postmortem: The industry at large - one day from now
  2. The insidious cost of allocations - about one day from now
  3. Buffer allocation strategies: A possible solution - 5 days from now
  4. Buffer allocation strategies: Explaining the solution - 6 days from now
  5. Buffer allocation strategies: Bad usage patterns - 7 days from now

And 2 more posts are pending...

There are posts all the way to Sep 11, 2015


  1. Find the bug (5):
    20 Apr 2011 - Why do I get a Null Reference Exception?
  2. Production postmortem (10):
    01 Sep 2015 - The case of the lying configuration file
  3. What is new in RavenDB 3.5 (7):
    12 Aug 2015 - Monitoring support
  4. Career planning (6):
    24 Jul 2015 - The immortal choices aren't
View all series


Main feed Feed Stats
Comments feed   Comments Feed Stats