an appetite for construction

Needless complexity and taking the first bullet

October 5, 2008 · No Comments

Ray Houston blogged recently about needless complexity in the design of code. The question at hand was if a particular function had too many responsibilities, violating the Single Responsibility Principle (SRP). The conclusion reached was that separating each and every responsibility into an individual class leads to a million tiny classes, each with one method, none of whom carries their weight. The c2 wiki calls this ravioli code, the opposite of the classic spaghetti code.

Clearly there are no hard and fast rules here. You could err on the side of making too many classes and presuming that every change is equally likely, or you could err on the side of making the code naive and resist breaking anything apart. So when do you break responsibilities into separate classes? When you think they are likely to change for different reasons. Unfortunately for us, no one can predict the future. Some likely changes are always obvious to us, but some we are not so sure about.

Fortunately, the Agile Patterns, Principles, and Practices book referenced in Ray’s post brings us some more guidance here. When you aren’t truly convinced that a piece of code needs to be flexible, err on the side of simplicity, resist breaking it apart, and “take the first bullet”. Let a change come through requiring more flexibility and then, at that point, go ahead and protect yourself from future changes of that type. It doesn’t solve every problem or protect every design, but it’s a great defense against unnecessary complexity.

→ No CommentsCategories: development

Hoff on Software

August 30, 2008 · 1 Comment

Sometime in the depths of night this week, AutoRevo co-founder Mark Hoffman found the time to establish a blog! Now that the shock has worn off, I’d like to bid him welcome and throw a link his way so that both of my readers (hi mom!) can take a look.

He’s already tearing my posting schedule a new one and he’s not even been doing this a week. Time for me to get off my duff…

→ 1 CommentCategories: development

Don’t be a red shirt

July 1, 2008 · 2 Comments

AutoRevo CTO Mark Hoffman and I had a short Q&A session with the audience immediately after his presentation in Chicago last week. I enjoyed getting to discuss unit testing threaded code and grid frameworks with other developers who have been fighting the same battles we have been at AutoRevo. It’s not often that I get to hear about how other teams approach eBay application development and the kinds of apps they’re writing.

If only everyone was there to actually engage in discussion. Months before the presentation, The Hoff and I had decided to bet that the dreaded Red Shirt would attend. This “Red shirt” epithet traces its roots back to a  yarn Rob Conery spun about Scott Hanselman shutting down a heckler at one of his talks. The eventual victim in this story is instantly identifiable to anyone who’s ever attended any gathering of geeks where one geek has to speak in front of the other geeks. The “Red Shirt” is THAT GUY.

You know THAT GUY: the one who’s there not to learn or to ask questions, but to prove that his propeller spins fastest; he’s the smartest guy in the room, the one who should really be speaking. The one whose every raise of the hand and comment is accompanied by groans or eyerolling from everyone else in attendance. The one who criticizes without offering alternatives because it’s far easier to bulldoze than to build.

It’s hard to imagine a red shirt in any other sort of setting. The AMA was holding a much larger conference at the hotel we stayed in, and I couldn’t help but wonder if they experienced the same sort of issues. Did one doctor heckle another as he was giving a talk on medical procedures? It didn’t seem likely. There’s just something about developers, or maybe engineers in general, that makes us excessively hesitant to accept our peers as authorities on anything. It sails past a healthy skepticism towards conventional thinking, then over that line and rocketing onward towards solipsism.

I’m not saying that it’s wrong to ask questions. There’s a difference between an honest question and one designed to make someone feel like a jackass. If you have an opinion, be prepared to back it up with solid evidence. Telling someone their ideas are stupid is only useful if you have something real to offer that is better.

Ask questions. Drill down. Just don’t be a red shirt. Like the somewhat more well known red shirts, they don’t contribute to the conversation and nobody misses them when they’re gone.

→ 2 CommentsCategories: development

Firefox 3 slow in ASP.NET Development Server

June 26, 2008 · 4 Comments

Ever since I started using Firefox 3 as my default “Browse With…” choice in VS2008, I’d noticed that pages loaded really, really slowly. I pulled out the big guns and fired up YSlow to figure out what the holdup was. We’re talking about 20-25 seconds to render around 200k of data.

YSlow showed me that each individual request to the server took over 1 second each, but when I loaded the same page in staging it took only 3ms. Clearly, the problem was related to Cassini, the VS2005/2008 built-in web server.

Sure enough, I found the answer after I figured out the correct question to ask (for the record, it was “Cassini Firefox Slow”). Since “Cassini” wasn’t the first thing I thought of when I began researching the problem, in the interest of increasing the visibility of the answer I’ll include it here, because it was driving me insane.

Enter “about:config” in the address bar to go to your Firefox configuration page and then filter by “ipv6″. Set “network.dns.disableIPv6″ to “true”.  Enjoy development again.

→ 4 CommentsCategories: development

Live from Chicago

June 17, 2008 · No Comments

I’m currently attending the eBay Developers’ conference in Chicago, to assist AutoRevo’s CTO Mark Hoffman with his presentation on building scalable applications to talk to the eBay API. I’ll post a link to the published presentation materials as soon as I find them.

Basically we were talking about how we solved scalability in a practical and effective way using a small framework of our own devising. The source code was tiny enough that it could be written over a long weekend, yet it allows us to easily and quickly add commodity servers to solve large problems more rapidly.

A big thanks to all the developers who attended the talk! I enjoyed getting to meet and discuss the topic with other people with the same problems and concerns; I just wish we had more time to talk about it all.

→ No CommentsCategories: development

Investigating PEX and Agile

May 23, 2008 · 2 Comments

PEX, short for Program Exploration, has arrived from Microsoft Research. Along with the download is a tutorial PDF explaining how it is used. I’ve been interested in this project since it was announced, but warily. Microsoft’s understanding of the purpose of unit tests has been iffy for years ( for example, see the MSTest Unit Test Generation Wizard included in VS2005/2008 ). Did they get this right or is this more of the same “tools over knowledge” that we’ve come to expect?

I’ll spend some time going over the documentation materials and trying it for myself, but I wonder if people who are more experienced with TDD would see some things I don’t. I’d really like to hear some longtime .NET agilists‘ take on this product.

→ 2 CommentsCategories: development

Alt.NET Geek Codes

April 22, 2008 · 2 Comments

Scott Hanselman has put together an Alt.NET geek code. You know, as if we weren’t all bad enough already. ;)

The geek code is a time-honored internet tradition whereby those of us with unhealthy obsessions can identify one another without need for all these onerous “words”.

Apparently, I’m a:
IOC(Fac):MOC(RM):MOC(MQ):TDD(NU):TDD(Xu):TDD(MS):SCC(Svn):SCC(TFS):SCC(Gmail):ORM(NH):ORM(SS):ORM(L2S):XPP(-):DDD(T+):DDD(B+):DDD(+):JSL(MS):CIS(TFS):GoF(S):GoF(Sn)
I’m also a tremendous nerd for posting this.

Go get your own.

P.S. : What, no Autofac under “IoC container”?

Edit: Fix’d.

→ 2 CommentsCategories: development

Some Functional Programming in C# 3.0

February 27, 2008 · No Comments

This is a follow-up to Some Functional Programming in C# 2.0. I’ve updated the code to use some new functionality available in C# 3.0. There’s nothing earth-shattering here, just some conveniences that are new to C# 3.0. Everything you see here could be done in C# 2.0; the syntax is just shorter.

First, the code:


public class Functions
    {
        public static void Retry( int maximumRetries, Action workToRetry )
        {
            Retry( maximumRetries, convertActionToFunc( workToRetry ) );
        }

        public static T Retry( int maximumRetries, Func workToRetry )
        {
            int retryCounter = 0;
            while ( true )
            {
                try
                {
                    return workToRetry();
                }
                catch ( Exception )
                {
                    retryCounter++;
                    if ( retryCounter > maximumRetries )
                    {
                        throw;
                    }
                }
            }
        }

        private static Func convertActionToFunc( Action action )
        {
            return delegate { action(); return null; };
        }
    }

 Here’s what’s changed since the last version:

  • There are now two flavors of Retry. One takes a generic Action delegate, and the other takes a Func<T> delegate. Previously the code only offered the Func<T> so you’d have to make every function you passed to Retry return a value even if you weren’t intending to use it. The new version offers an Action overload of Retry() that calls a private function to do this for you.
  • I’ve removed my custom delegate, RetryFunction<T> in favor of using the new generic delegates provided by the .NET 3.5 framework. I’ll take any chance I get to have my version require less code.
  • I’m offering some unit tests to demonstrate how Retry is called in either flavor. The tests are fairly cheesy; they show syntax but they fake throwing some exceptions to prove that a function is retried if it fails. It also shows some other new language features in C# 3.0: parameterless lambdas and lambda statements.

Here are the unit tests. They’re written with MSTest which is standard with Visual Studio 2008:


[TestClass]
    public class RetryFixture
    {
        [TestMethod]
        public void TestActionRetry()
        {
            int counter = 1;
            Functions.Retry( 5, () =>
            {
                counter++;
                if ( counter < 5 )
                {
                    throw new ApplicationException();
                }
            } );
            Assert.AreEqual( 5, counter );
        }

        [TestMethod]
        public void TestFuncRetry()
        {
            int counter = 1;
            int finalCount = Functions.Retry( 5, () =>
                {
                    counter++;
                    if ( counter < 5 )
                    {
                        throw new ApplicationException();
                    }
                    return counter;
                } );
            Assert.AreEqual( 5, finalCount );
        }
    }

As I promised in my previous post, C# 3.0 hasn’t radically altered the code, just made it a bit cleaner and easier to use. Any feedback you may have is welcome :)

Thanks to jamie for reminding me about this particular loose end.

Update: WordPress is being flaky and randomly eating parts of my post and the generic <T> syntax in my source code. If this doesn’t build, let me know so I can fix the posted version of the code.

→ No CommentsCategories: development

Explicit casting vs the “as” keyword

November 14, 2007 · 2 Comments

I’ve been subscribed to the Los Techies RSS feed for a few months. I find that I agree with a lot of the bloggers posting there and enjoy learning from their insights into design and methodologies. For instance, today Jimmy Bogard wrote about the perils of downcasting and how breaking the open-closed principle by making assumptions about your parameters’ lineage can limit the ability of your code to adapt to change.

One small detail in the post stood out at me because it reminded me of a past design decision.

“To make things worse, it explicitly casts instead of using the C# “as” operator (TryCast for VB.NET folks).  At least then it won’t fail when trying to downcast, it would just be null.  “

On a previous project I recall when we excavated the “as” operator from the C# documentation. Normally, when you perform an explicit cast in your code, casting to a type that the object to be casted cannot be cast to throws an InvalidCastException.

Walrus bucketLover; 
Cat tabbyCat = (Cat) bucketLover; // throws InvalidCastException since a Walrus is not necessarily a Cat

The “as” keyword instead returns null in the case that you have cast an Walrus to something as ridiculous as a Cat. When you use the “as” keyword you can cast indiscriminately and completely throw caution to the wind.

Walrus bucketLover;
Cat tabbyCat = bucketLover as Cat; // sets tabbyCat to null. No exception is thrown..

This seems like a good thing, right? Throwing exceptions is bad. Conversely, not throwing exceptions is good. We made the decision to always use “as” instead of an explicit cast. All seemed well… except that trouble was brewing. If tabbyCat could now be null, then we needed to check for null immediately after the cast. After all, if tabbyCat was null then we couldn’t continue execution of the code in that method. A basic assumption that the method depended on, that an argument needed to be of a particular type, was not met and thus we could go no further on.

Clearly, we needed a way to tell a higher level of code unambiguously that an assertion had failed and we needed to handle it in some way. That sounded like an exception to me. Otherwise, code further downstream had a chance of getting a null tabbyCat object, and it might not be immediately obvious that the reason tabbyCat was null was that a cast had failed.  

Walrus bucketLover;
Cat tabbyCat = bucketLover as Cat;
if ( bucketLover == null ) throw new InvalidCastException();

Hmmm. If only the code could do this more succinctly. Wait, one quick refactoring later and:

Walrus bucketLover; 
Cat tabbyCat = (Cat) bucketLover;

That code snippet may seem familiar. It’s what we started with. The lesson I learned here was that guarding execution with explicit casting wasn’t always the wrong decision. Letting the cast throw an exception when assumptions weren’t met allows the code to be more succinct. It allows the code to be more concise because you don’t have to spend a lot of time checking for nulls everywhere, and you don’t have to worry about tracking down the source of a NullReferenceException.

I realize that using exceptions versus using return values for everything is a religious debate, and I’m not trying to say any approach is morally and unambiguously right or wrong. What it does allow you to do is have your code be more focused on its particular work and less on the nuts and bolts of the underlying language.

I think we can  all still agree that downcasting is evil.

→ 2 CommentsCategories: development

Delicious TDD Resources

October 24, 2007 · No Comments

I’ve been studying test-driven development off and on for awhile and am trying to commit to practicing it as much as I can. I am finding myself not knowing the best way to proceed much of the time and so have been accumulating links for articles that either helped me or seemed useful for future reading. If that sounds like something that you would find useful, I’m putting the links on del.icio.us here. I will probably have more to say on this particular topic in the future, so start holding your breath now and I promise I will try to post soon before you asphyxiate.

→ No CommentsCategories: development