Scott Hanselman

The Weekly Source Code 10 - Patterns Considered Harmful

October 31, 2007 Comment on this post [15] Posted in ASP.NET | Microsoft | Source Code
Sponsored By

In my new ongoing quest to read source code to be a better developer, I now present the tenth in an infinite number of a weekly series called "The Weekly Source Code." Here's some source I'm reading this week that I enjoyed.

Our theme this week is "Patterns Considered Harmful" with examples of source doing things we're "not supposed to do."

  • ÜberUtils - Strings from Brad Vincent. Don't like System.String? Well, spot-weld a bunch of useful stuff onto it with C# 3.0 Extension Methods. Brad starts to talk about how his utils might be Considered Harmful:

    "Now I know some people might argue that this is extension method abuse, but look at how much more power my strings have...and anything that helps me code quicker and smarter is not abuse in my book - it's smart coding!"

    Here's just two of his many useful additions you can hardly consider harmful:
            public static string XOR(string input, string strKey)
            {
                if (IsEmpty(input)) return input;
                string strEncoded = string.Empty;
                int nKeyIndex = 0;
                for (int i = 0; i < input.Length; i++)
                {
                    strEncoded += Convert.ToChar(input[i] ^ strKey[nKeyIndex]);
                    nKeyIndex++;
                    if (nKeyIndex == strKey.Length) nKeyIndex = 0;
                }
                return strEncoded;
            }
    
            public static string ToTitleCase(string Input)
            {
                return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(Input);
            }
  • This item isn't source, but rather a study topic. I saw that Jeff Atwood had a recent post on "Considered Harmful" docs and mentions the seminal GOTO considered harmful paper. Take a free moment and go read the interesting January 2003 thread of discussion between a number of programmers and Linus Torvalds, creator of Linux about Linus's use of GOTO in the Linux Kernel. Why? Here's a teaser from Linus:

    "No, you've been brainwashed by CS people who thought that Niklaus Wirth (Editor: Author of GOTOs Considered Harmful) actually knew what he was talking about. He didn't. He doesn't have a frigging clue."

    > I thought Edsger Dijkstra coined the "gotos are evil" bit in his
    > structured programming push?

    Yeah, he did, but he's dead, and we shouldn't talk ill of the dead. So these days I can only rant about Niklaus Wirth, who took the "structured programming" thing and enforced it in his languages (Pascal and Modula-2), and thus forced his evil on untold generations of poor CS students who had to learn langauges that weren't actually useful for real work.
    - Linus

  • Putting everything all on one line. I'll do a separate post on this, but Lee Holmes (author of the Windows PowerShell Cookbook) and I were doing some PowerShell recently, parsing CSV files and did this. Lee doesn't recommend it, but I think it's pretty:
  • Import-CSv File.csv | Select File,Hits | Group { $_.File -replace '/hanselminutes_(\d+).*','$1' } | Select Name,{ ($_.Group | Measure-Object -Sum Hits).Sum }

Feel free to send me links to cool source that you find hasn't been given a good read.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
October 31, 2007 10:37
Hey Scott - thanks for the link back. ÜberUtils is my attempt at creating the ULTIMATE REUSABLE UTILS CLASS LIBRARY. Utils.Strings is the 3rd and latest in the series. I am hoping to post many more useful snippets of code for the public domain. Suggestions for future modules are welcome too.
October 31, 2007 12:06
I'm confused. You talk about
"Patterns Considered Harmful" with examples of source doing things we're "not supposed to do."


(Imho)
Gotos = Evil. Haven't needed one in over 5 years now (even then only in vb6) and my code is more readable for it.
Regions= nice sometimes abused at other times.
Extension methods = not used yet.. but I love the Uber utils
October 31, 2007 12:24
My point is that it's fun/interesting to look at these supposed anti-patterns and re-decide for ourselves if they really are evil.
October 31, 2007 17:21
The gotos in kernel discussion was fascinating - thanks Scott. My take-away: goto is a tool. Choose the right tool for the right job. Don't blame the tool when it is abused. Blame the tool that abused the tool.
October 31, 2007 19:47
I am sorry this was a horrible post.

at the start you go with the theme sentence:

>Our theme this week is "Patterns Considered Harmful" with examples of source doing things we're "not >supposed to do."

but then the bullet points that followed that I thought were going support patterns are harmful just arent related to that at all. I think you honestly owe us an article on harmful patterns.
October 31, 2007 19:49
While I have an enormous amount of respect for Linus, I have to respectfully disagree that Pascal was not a useful "work" language. My initial CS programming courses in college were taught in Pascal (on a VAX). It is certainly a terse language, but it does have the advantage of being a good language to teach with and it laid down a pretty solid foundation for my career. Pascal gave me the discipline and good habits I needed to learn languages like C (and later C++ and Java). I know that programming can be taught with any language - but I felt Pascal was a good framework for instilling fundamentals. When I first started doing Windows programming it was with Delphi (not chosen because of Pascal - but because it was the best tool available at the time) - and I have some pretty fond memories of that tool.

If memory serves (and it does so less and less these days <GRIN>) MS hired a lot of the Delphi folks away from Borland to get VB up to speed and really going (versions 3+).

I totally agree with "goto" as a tool. Rarely is anything ever purely evil.
October 31, 2007 20:57
mikeJ - I'm sorry you missed the joke. The whole point of "considered harmful" is that nothing is considered harmful in a "forbidden way." Everything is a tool. I was trying to make a point. Kent got it. :P
October 31, 2007 22:04
I found the goto discussion fairly interesting, but not because of the topic itself. Rather, it is interesting as a socio-anthropoligical study of the sad state of many discussions between us programmers - I think it's a pretty archetypical example of the mixture of strawman arguments, logical fallacies and bullying strategies that seem to taint our conversations in general. First off, I think that Linus Torvalds, despite his indisputable merits as a programmer (or perhaps indeed because of them) comes across as a rather rude and childish, claiming that people whose opinions differ from his as being 'brainwashed' or 'braindamaged'. How do you lead a meaningful discussion if those are the premises? And when someone insists on laying the premises like that? I, for one, am not impressed.

Let me also provide a concrete example of a strawman argument and logical fallacy (to back up my claims at least a little bit, which I feel is not the norm): "If you think people can't write spaghetti code in a "goto-less" language, I can send you some *lovely* examples to disabuse you of that notion." Now, nobody (neither Dijkstra nor Wirth nor Rob Wilken, as far as I can tell) made this claim. Saying that goto implies spaghetti is not at all the same thing as saying that spaghetti implies goto. You make your life too easy as a debater when you invert people's arguments like that.

Lest I be misunderstood, let me add that I think the discussions lead on this blog and the Hanselforum are very different. In general, they fare way better than the average - it is one of the reasons I keep reading them with interest.

Regarding the topic itself, viz. the moral standing of goto, I think it is fairly easy to sum up. Goto is a tool, and so can be used for good or bad. However, not all tools are created equal. Some are more prone to unsuitable use than others; hence, the problem with goto is not that it necessarily leads to evil, but that it might be preferable to avoid it (and lose the benefits it might offer to some people in certain circumstances) due to the number of people who seem to be using it to make pasta of the non-savory kind.
October 31, 2007 22:30
Factual error: Dijkstra wrote "Goto Considered Harmful", not Wirth, who edited the CACM at the time. Quoting wiki:

Edsger Dijkstra's letter "Go To Statement Considered Harmful",[1] published in the March 1968 Communications of the ACM (CACM), in which he criticized the excessive use of the GOTO statement in programming languages of the day and advocated structured programming instead.[2] The original title of the letter, as submitted to CACM, was "A Case Against the Goto Statement," but CACM editor Niklaus Wirth changed the title to the now immortalized "Go To Statement Considered Harmful."
November 01, 2007 9:30
Isn't a try catch block just a controlled GOTO anyway? We're still using the concept...
November 01, 2007 12:02
You nailed it, Dave!
November 01, 2007 12:35
Check out the open source FileHelpers library. It's pretty cool and certainly on topic with your recent CVS work.
November 01, 2007 23:10
Dave, you're absolutely correct about throw/catch being a global GOTO (i.e. a GOTO in the worst form). This is why it's very important to not use .NET exception handling where conditional logic would suffice. As always, use the right tool for the right job. There are "exceptions" to every rule :).
November 03, 2007 0:46
This reminds me of two anecdotes about Wirth:

- our University of Cape Town CS departmental head was ex ETH/IBM Zurich, and as a result Niklaus Wirth visited periodically. I remember him starting one talk by putting up a slide title "The Road To Progress". Blocking the road was a huge rock title "UNIX". I don't remember much more than that as after having a good laugh I mostly stopped listening. BTW his alternative O/S - written in Oberon - relied on co-operative multitasking. We all know how great that worked.

- old CS joke - why do Europeans pronounce Niklaus Wirth "nik-louse vert" and Americams pronounce it "nickles worth"? Because Europeans call by name but Americans call by value.

November 15, 2007 23:52
Anyone here actually done programming before VB 3? I mean as a full time job with regular pay and benefits? Well, those who have can testify to HAVING to use goto to modify old spaghetti code already full of them in languages that allowed them. Oh, "refactor" or "reengineer" the stuff instead of using GOTO? I'm not talking about your little apps that have a couple pages with a dozen controls and access maybe 5 - 7 tables, I'm talking about 20,000 line behemoths (hairballs like Windows 2000) that access hundreds of tables and have hundreds of screens. Refactor that. Yes, I much prefer C# and ASP.NET but sometimes I'm sucked back into the underworld of legacy horror and goto's are a fact of life!

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.