Code of the week
This piece of code make me so happy:
private static IDictionary<string, Func<Stream, ICommand>> commandFactories = new Dictionary<string, Func<Stream, ICommand>> { //storage {"add", s => new AddCommand(s)}, {"append", s => new AppendCommand(s)}, {"cas", s => new CasCommand(s)}, {"delete", s => new DeleteCommand(s)}, {"prepend", s => new PrependCommand(s)}, {"replace", s => new ReplaceCommand(s)}, {"set", s => new SetCommand(s)}, // retrieval {"get", s => new GetCommand(s)}, {"gets", s => new GetsCommand(s)}, //modifications {"incr", s => new IncrCommand(s)}, {"decr", s => new DecrCommand(s)}, //misc {"flush_all", s => new FlushAllCommand(s)}, {"quit", s => new QuitCommand(s)}, {"version", s => new VersionCommand(s)}, };
This is something that I do quite often, and it is good to have a way to do it easily.
Elegant Code
I just finished writing this, and I find it very pleasing to look at:
public class EntitiesToRepositories { public static void Register( IWindsorContainer windsorContainer, ISessionFactory sessionFactory, Type repository, params Assembly[] assemblies ) { if(typeof(IRepository<>).IsAssignableFrom(repository)) throw new ArgumentException("Repository must be a type inheriting from IRepository<T>, " +
"and must be an open generic type. Sample: typeof(NHRepository<>)."); foreach (IClassMetadata meta in sessionFactory.GetAllClassMetadata().Values) { Type mappedClass = meta.GetMappedClass(EntityMode.Poco); if (mappedClass == null) continue; foreach (Type interfaceType in mappedClass.GetInterfaces()) { if(IsDefinedInAssemblies(interfaceType, assemblies)==false) continue; windsorContainer.Register( Component.For(typeof(IRepository<>).MakeGenericType(interfaceType)) .ImplementedBy(repository.MakeGenericType(interfaceType)) .CustomDependencies(Property.ForKey("ConcreteType").Eq(mappedClass)) ); } } } private static bool IsDefinedInAssemblies(Type type, Assembly[] assemblies) { return Array.IndexOf(assemblies, type.Assembly) != -1; } }
Tricky Code
Without running the code, what is the result of this masterpiece?
class Program { static void Main(string[] args) { DoSomething("a","b"); } public static void DoSomething<T>(IList<T> set) { Console.WriteLine(set.Count); } public static void DoSomething<T>(params T[] items) { List<T> set = new List<T>(); foreach (T t in items) { if (t == null) continue; set.Add(t); } DoSomething(set); } }
It surprised the hell out of me until I figured out what was going on, then I was very amused. This code works exactly as it should be, to produce a very different result than the expected one.
Code that makes me laugh
Going into a new code base
I had a chance at DevTeach to just take an hour and start looking at a large code base. I made the claim several times in the past that no matter the quality of the developers and the quality of the code base, there is no way someone can just sit down on a code base and start working on that.
I tried to grok the code without help, and I failed. I could probably do that, but it would take several days. That was especially true since it was in Windows Forms, and that is not a field that I have done much at. Not knowing anything about the actual domain was a big issue as well.
After about 30 minutes of sitting down and going over the code with the developer, I got a whole new level of understanding about the application. How it works, how the structure is built. I look at a test and can work how this is used, etc.
I still have very little knowledge about that application works, but after 30 minutes, I am confident in my ability to both grok the code and work with it. In fact, after getting the introduction to the code base, I can say that this is probably one of the better code bases that I have seen.
One of the more interesting parts was that when I looked at each class, it was when I took a step back and looked at the interactions it gotten really interesting.
It was a pleasure to read the code.
Pushing the limits
Okay, I just finished writing this piece of code, I am not quite sure how to treat this. It is either elegantly concise or horribly opaque.
I suspect both.
Somehow, you can probably wee that I have a C++ background, and even though the CLR doesn't give me the entire thing, you can still push it fairly far.
Of course, it still makes my head feel like this sometimes:
Can you figure it out? Functional caching
Okay, here is a challenge, without running the code, what do you think should be the result of this program, and why?
public class Program { private static void Main(string[] args) { Fetch<int> method = Get; method = AddCaching(method); method(); method(); method(); } public static int Get() { Console.WriteLine("Called"); return 1; } public delegate T Fetch<T>(); public static Fetch<T> AddCaching<T>(Fetch<T> fetch) { T cachedObject = default(T); bool isCached = false; return delegate { if (isCached == false) { cachedObject = fetch(); isCached = true; } return cachedObject; }; } }
Did you know: Find out if an exception was thrown from a finally block!
This is a big biggie for me, because it enables a much nicer syntax for a lot of stuff. But first, let us show this:
using(new ExceptionDetector()) { if(new Random().Next(1,10)%2 == 0) throw new Exception(); }
How can you tell, from the ExceptionDetector, if an exception was thrown or not? Well, conventional wisdom, and what I thought about until 15 minutes ago, says that you can't. I want to thank Daniel Fortunov, for teaching me this trick:
public class ExceptionDetector : IDisposable { public void Dispose() { if (Marshal.GetExceptionCode()==0) Console.WriteLine("Completed Successfully!"); else Console.WriteLine("Exception!"); } }Amazing!
Understanding Bad Code
Frans' contribution to the conversation about maintainable code deserve its own post, but I would like to mention this part in particular:
you will not [understand the code]. Not now, not ever. And not only you, but everyone out there who writes code, thus that includes me as well, will not be able to read code and understand it immediately.
You know what? That is not limited to bad code. I had hard time grokking good code bases, simply because of their size and complexity (NHibernate and Windsor comes to mind). Other code bases are as large, but they have easier approachability, probably because they are dealing with less complex domain an tend to have a wide coverage rather than deep (MonoRail comes to mind).
A while ago I was involved with an effort to migrate an ancient system to SQL Server 2005. The system compromised of over 100,000 lines of code, spread over some thousands of files scattered randomly in a case sensitive file system (you can guess why this is significant). The code base was about 85% SQL and 15% bash shell scripts. The database in question was a core system and contained slightly over 4,000 tables. One of the core tables was called tmp1_PlcyDma and was used to do business critical processing. That code base took data driven code generation to a level I have never seen before. I gave up trying to track down 7(!) levels of code->generating code->execute code->generating code->rinse->repeat
To say that the code base was bad is quite an understatement. To mention that the only place where I could run the code was by using a telnet console into a test environment that was not identical to production is only the start. I could mention no debugging, runtime of ~5 hours, test time of ~3 hours, etc. The code grew organically over a ten years period and you could track the developer progress from merely annoying to criminally insane (he invented his own group by construct, using triple nested cursors and syntax so obscure that even the DBA that worked with the system for the last 5 years had no idea what was going on).
Perhaps the thing that I remember most from this project that we had a bug that kept two people hunting after it for three weeks. The issue was a missing ';'. Oh, and the criteria for success in this project was successful migration, with bug-per-bug compatibility, and no one really knew what it did, including the authors(!).
But, you know what, after a month or so of looking at the code, it got to the point where I could look at something like pc_cl_mn.sql and know that it would contains the monthly policy calculation, and that this piece of code was doing joins manually via cursors again, that plcy_tr_tmp.sql was the "indexes priming" script, etc, etc.
The code was still a horror, but once you understood that the authors of this code had a... "special" way of looking at databases, you got to the point where you could get the point of the code in an hour instead of a day, and then move that to a saner approach.
So, what does this horrifying story has to do with Frans' point above?
The premise that you can read and understand code immediately is highly dependant on what you are familiar with. I know of no one that can just sit in front of an unfamiliar code base and start producing value within the first ten minutes. But on a good code base, you should be able to be able to start producing value very quickly.
rails:ConditionalRender - still trying to get WebForms to work right
Well, as it turns out, there are some things that you can do to make WebForms more palatable. Smart use of ITemplate and some additional magic can take you a fairly long way. I am still severely limited (splitting behavior between markup & code behind is extremely annoying) in what I can do, but it is good to know that it is possible:
<rails:ConditionalRenderer runat="server" Condition="<%# ((Policy)Container.DataItem).Expired %>" DataItem="<%# Container.DataItem %>" > <WhenTrue> Policy has expired! </WhenTrue> <WhenFalse> Policy is valid until <%# Eval("ExpiryDate") %> </WhenFalse> </rails:ConditionalRenderer>
[ParseChildren(true)] public class ConditionalRenderer : Control, INamingContainer { public bool Condition { get { .. } set { .. } } [Templatecontainer(ConditionalRenderer)] public ITemplate WhenTrue { get { .. } set { .. } } [Templatecontainer(ConditionalRenderer)] public ITemplate WhenFalse { get { .. } set { .. } } public object DataItem { get { .. } set { .. } } public override void EnsureChildControls() { if (Condition) WhenTrue.InstansiateIn(this); else WhenFalse.InstansiateIn(this); } }
Unmaintainable Code
I have several ways of categorizing code. Production quality, test, demo, and utilities. When I am talking about utilities, I am talking about little programs that I use to do all sorts of small tasks. There I rarely worry about maintainability, and today there was a gem here:
public delegate Control BuildSpecialCase(TextBox textbox);
private BuildSpecialCase GetSpecialCaseControl(string name)
{
if (name.IndexOf("ConnectionString", StringComparison.InvariantCultureIgnoreCase) != -1)
{
return delegate(TextBox t)
{
Button change = new Button();
change.Click += delegate { t.Text = PromptForConnectionString(t.Text); };
change.Dock = DockStyle.Right;
change.Text = "...";
change.Width = 30;
return change;
};
}
if (name.IndexOf("File", StringComparison.InvariantCultureIgnoreCase) != -1)
{
return delegate(TextBox t)
{
Button change = new Button();
change.Click += delegate
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
dialog.FileName = t.Text;
if (dialog.ShowDialog(this) == DialogResult.OK)
{
t.Text = dialog.FileName;
}
};
change.Dock = DockStyle.Right;
change.Text = "...";
change.Width = 30;
return change;
};
}
if (name.IndexOf("Folder", StringComparison.InvariantCultureIgnoreCase) != -1 ||
name.IndexOf("Dir", StringComparison.InvariantCultureIgnoreCase) != -1)
{
return delegate(TextBox t)
{
Button change = new Button();
change.Click += delegate
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.SelectedPath = t.Text;
if (dialog.ShowDialog(this) == DialogResult.OK)
{
t.Text = dialog.SelectedPath;
}
};
change.Dock = DockStyle.Right;
change.Text = "...";
change.Width = 30;
return change;
};
}
return null;
}
Can you figure out what is going on?
As long as we are talking about unmaintainable code, here an example from code meant for production that I just wrote:
But for that I have tests :-)
For Experts Only
There are some things that programmers really shouldn't do. I was once called to help figuring out why a batch process would run for a few hours at 100%. The previous guy has claimed that this was a natural occurance of the task at hand (loading XML file to DB), and that he had already optimized it as far as possible.
int count = 0;
XmlDocument xdoc = new XmlDocument();
xdoc.Load(filePath);
foreach(XmlNode node in xdoc.SelectNodes("data/row"))
{
count++;
new Thread(delegate(object state){
XmlNode n = (XmlNode)state;
using(SqlConnection con = new SqlConnection("... "))
using(SqlCommand cmd = con.CreateCommand ())
{
cmd.CommandText = "INSERT INTO .... ";
cmd.ExecuteNonQuery();
}
Interlocked.Decrement(out count);
}).Start(node);
}
while(count!=0);
After de-optimizing the code, I managed to get 10,000% performance improvement, and you could actually use the server for more than a single task.
Beautiful code
I think that I already mentioned that I like the Jafar's blog, he just posted an entry with some beautiful code in it. You can check it here, took me a few seconds to figure it out, but Wow, this is a nice way of working with the code.
The only thing that I don't like is that there isn't enough of generic type inferencing.
Update: more good stuff from the same guy here.
And I took the path less traveled by...
Evaluate the following approaches:
List<Address> addresses = new List<Address>();
addresses.Add(customer.HomeAddress);
addresses.Add(customer.BusinessAddress);
addresses.Add(customer.ShippingAddress);
addresses.RemoveAll(delegate(Address a) { return a == null; });
And:
List<Address> addresses = new List<Address>();
if (customer.HomeAddress != null)
addresses.Add(customer.HomeAddress);
if (customer.BusinessAddress != null)
addresses.Add(customer.BusinessAddress);
if (customer.ShippingAddress != null)
addresses.Add(customer.ShippingAddress);
Which do you think that I used? Which would you rather use?
Stories from the Code Reviews: Threading
I am doing code reviews, and I am running into some unique ideas about how code should work. Take into account this new locking pattern:
public void ShouldOnlyAllowSingleInstance()
{
object syncLock = new object();
lock(syncLock)
{
// code that modify a thread-shared resource
}
}
Everyone know that you can use threads to increase the reponsiveness and throughput of your application, but this approach reach a whole another level, although it didn't manage to meet quite the scalability requirements
public void CopyData(IDbCommand cmd)
{
cmd.CommandText = "SELECT * FROM TableWith_700_Rows;"
IDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
CustomerCopier customer = CustomerCopier.FromReader(reader);
new Thread(customer.DoCopy).Start();
}
}
// In CustomerCopier
public void DoCopy()
{
using(SqlConnection connection = CreateConnectionToSourceDb())
{
using(ITransaction tx = connection.BeginTransaction(SeperationLevel.Serializable))
{
// execute insert
}
}
}
Oh, and here is a general comment, while green is a soothing color, I do not need to see so much of it on the screen.
Update: In case is wasn't clear, the above samples are really bad code.
Generic Specialization
It is not often that I am arriving to work and the first application that I open is Visual Studio, and I can't get it to open fast enough. Today was such a day, mostly because I got an Eureka moment. It is not often that I get those, so I really want to try it out.
Check out the following code:
public
class Aggregator<T> : Aggregator<T, List<T>>
{}
public
class Aggregator<T,
TCollection>
where
TCollection : ICollection<T>, new()
{
private
ICollection<T> collection = new TCollection();
}
Can you tell why I am excited? Because this means that I have static generic specialization (I already have dynamic generic specialization, thanks to Windsor) back!
Notice that for all intents and purposes, I can either use Aggerator<T>, or use the more generic version of Aggerator<T, TCollection>, which allows me to pass my own ICollection<T> implementation.
This is actually compiler supported Inversion Of Control!
Now, of course that I can do this using ctor parameter, but this puts the burden on the client code, and couples the base implementation to the defaults. This approach keeps the base implementation frees from any default whatsoever.
I intend to make use of this soon, so I'll post about the results.
Stored Procedures and SQL Injections
Related to the previous post, I present you a simple SP that is highly vulnerable to SQL injections, and is directly related to my statement about evil sadistics bastards.
ALTER
PROCEDURE GetDataForDate@date DATETIME
AS
DECLARE @sql nvarchar(max)
SET @sql = 'select * from data_' + convert(nvarchar(30),getdate(),112)
EXEC sp_executesql @sql
I think you can deduct what the rest of the system looked like, and what fun it was optimizing the reports that run over data gathered for years.
My favoriate piece of code for this week...
I found that I need to group a collection by a certain attribute of its member quite often. Usually because I'm trying to do some crazy things with deeply nested and timed to put some data on the screen.
Anyway, here is the code:
public static IDictionary<T, ICollection<K>> GroupBy<K, T>(ICollection<K> collection, Converter<K, T> converter)
{
Dictionary<T, ICollection<K>> dic = new Dictionary<T, ICollection<K>>();
foreach (K k in collection)
{
T key = converter(k);
if (dic.ContainsKey(key) == false)
{
dic[key] = new List<K>();
}
dic[key].Add(k);
}
return dic;
}
It is not earth shattering or anything like it, but it is going to make a lot of tasks a lot easier now.
(BTW, this is now a part of Rhino Commons).
Freakish Type System Issues
Take a guess, what is going to be the result of the following code?
Enum one = DayOfWeek.Sunday;
Enum two = DayOfWeek.Sunday;
Assert.IsTrue(one == two);
Update: Tomas Restrepo, hit the nail on the head in the comments.
System.Enum is a reference type. The first line actually translates to:
There is boxing done here, and then the == is doing reference equality. I actually learned about this from Tomas, a while ago, when discussing about wierd-ass questions.
This is a freakish issue because Enum inherits from ValueType, so you would expect it to keep value types semantics. Check the comments for Tomas' for explanation
I Have Refactored !!!

This is what an interface looks like after about two week of work and seventeen refactoring. At one point, it looked like this:
interface IHaveMultipleOccurrences<T> : IHaveNameAndId, IHaveValidityRange<T> where T : IHaveValidityRange<T>
But the fear of the compiler puking on me kept the design a little simpler.
Why you can't code in Hebrew...
In response for my DDD in Hebrew, I was asked why it is not recommended to code in Hebrew. I decided to question my initial response, and give it a shot. I quickly gave it a try and created the following domain model. I don't expect you to be able to read it (although if you can, you'll find it hilarious).
Here is my DDD in Hebrew, the classes are Employee (right, top), Report (Left, Top), HoursReport (Middle, Bottom), WontBeHereReport (Left, Bottom) and Repository<T> (Right, Bottom):

I run into a couple of issues just with designing this diagram:
- Trying to specify a generic parameter in Hebrew cause issues because of alignments. Basically, the whole class name is presented in the wrong way (this is a common issue with mixing Hebrew & math together).
- Intellisense is mostly useless, check out this, you may not be able to see it, but the Hebrew is half-way reversed.
- For some reason Visual Studio is working a lot harder when I write code in Hebrew.
Let us move to more serious issues, take a look at this simple program:

Main issues:
- Hebrew is written right to left, the code here is structured left to right.
- Hebrew doesn't have upper/lower casing, so words need to be seperated by "_".
- I often need to switch keyboard setttings ( even something as simple as "<" has different orientetions in Hebrew and English).
- I need to use primitives (such as DateTime) in English.
- I need to mix English and Hebrew in the same line (see the "new" lines).
- All control flow is in English.
- You can't grep this source. At least not easily. Hebrew and the command line do not mix.
That is even beside the nice point of the enconding hell that you get yourself into. It is very easy to save this as ASCII (if you open it in an editor that doesn't support unicode, or simple use a tool to go over it) and lose all the hebrew characters.
Sorry Eliezer, but you will have to write Hebrew# and language pack, and write a translation layer for the framework if you really want me to use it.
C# Riddle #5
Following Alex's post about traps in interviews, I thought about posting bits of code that I won't use in interviews. Mostly because I don't think that it is fair to the interviewee. I can think about crazy usages to langauge features, and not in a good way.
Consider the following peice of code (which is valid C# 2.0):
{
yield return delegate(Customer c)
{
return c.Name != "";
};
yield return delegate(Customer c)
{
return EmailService.IsValid(c.Email);
};
}
How would you use this method, and what is wrong with it?
Great Interview Question
Here is something to add to the indicators list:
What does the following do?
If they can't figure this out, you got a problem.
More interesting question may be:
Contrast the results of the following two operations:
- selected = selected++;
- selected = ++selected;
[Via The Daily WTF - Sidebar]
Things that will make me come after you with a BIG stick: Part 1
For some reason, I get to see a lot of WTF?! in the field, and I think that this is about time that I do something about it. I'm going to start a series of posts about the stragest stuff that I see.
Today, we have the New Data Model to observe. As you hopefully know, there are three (and only three) ways to create associations in the database, one to many, many to one and (using an association table) many to many. Trying to invent new ones will cause pain.
Take for example this table diagram:

It may not seem bad to you until you dig a bit deeper and realize that both Items.Id and Items_Security.ItemId are primary keys, and both are Identity Columns!
Some is not getting the rule about "Do not use hard coded constants in your code"
I run into this bit of code today:
public enum OriginalFromMainFrame
{
Ten = 10,
Twelve = 12,
TwentyFive = 25
}
Some certainly heard about good software practices, but there is something left to be desired in the implementation...