Amusing Bad Programming Tip
Say you have a class with a property that’s a string. Using object initializers you can do this little nugget:
Product p = new Product { ProductName = Console.ReadLine() };
It will work as you’d expect (prompt you for input, then assign it to ProductName). However, that’s pretty easy to miss when you’re quickly scanning code. I’m generally in favor of fewer lines of code, but in this case it would be good design to just break this into two lines.

5 Responses to “Amusing Bad Programming Tip”
April 27th, 2010 at: 3:09 pm
Yikes! Although I’m certain smart developers could convince me that this is no different than inline anonymous delegates, which I’m a big fan of. Interesting that I’m opposed to the example, but I’m all for the delegates. Hmm… why does that feel so dirty?
Ah! Mixing user interaction with class initialization, but isn’t that what Data Binding is essentially doing for us in other technologies like WPF? This is simply Data Binding for Console programs I suppose… Hmm… Okay, I reverse my thinking. I like it if it’s being used as a form of Data Binding for Console programs on the primary console interaction code path and it’s strictly apparent for this reason. But, if I were to find that floating deep in the guts of a program, you can bet there will be a conversation!
April 27th, 2010 at: 3:13 pm
Hahaha. I found by quickly testing some WCF code, thinking “this couldn’t possibly work… oh crap, it does!”
I think mixing class initialization in Data Binding doesn’t feel “dirty” because it is completely abstracted away from the user. There’s no way to abstract a Console.ReadLine in such a way.
April 28th, 2010 at: 5:26 am
I don’t understand the syntax. I’m guessing that there is a class variable called ‘ProductName’ that is initialized by the Console.ReadLine(). Right?
I wouldn’t do that initialization simply because a console application should also be able to get the parameters from the command line as well.
April 28th, 2010 at: 9:07 am
Randy, you are correct. That’s why it’s a BAD programming tip, and why I said not to do it.
May 6th, 2010 at: 8:32 am
Proper formatting would make it a little easier to recognize:
Product p = new Product {
ProductName = Console.ReadLine()
};
I like this feature, but I prefer to initialize each member on a separate line so it’s easier to see what’s happening.