comments suggest edit

Ian Griffiths takes an in-depth look at C# 3.0 Extension methods and the potential problems with it. Of particular note is his philosophy, which directly follows from the idea that code should be written for humans, which he summarizes whe he say…

I’m a big fan of code that does what it looks like it does.

Amen brother!

As an example, he highlights the ToUpper method on a System.String instance, which often misleads new developers. He would prefer the more honest and less misleading static method on the String class that would be called like so:

String.ToUpper(input);

I agree wholeheartedly that ToUpper (which sort of follows the Java convention I guess) is misnamed, but (and this really is a minor niggle) I probably would prefer that it still be an instance method, but renamed GetUpperCase. I think that would do a good enough job of being honest and being discoverable.

In any case, if you’re interested in C# 3.0, be sure to read Ian’s take on extension methods.

comments suggest edit

I just heard thunder. I don’t think the weather here in Los Angeles got the memo, but we already had a thunderstorm. To the thunder clounds, go away and come back later when the yearly quota has’t been filled.

comments suggest edit

Found this post in the trackbacks section of my post on Mental Laziness. It’s a classic example of where management pressure often leads to mental laziness.

In this scenario (go read it, it’s short), the ViewState of a system they were working on was extremely large and causing problems for the client. The quick solution was to perhaps use some sort of Http Compression or ViewState compression.

But the author of the post, David, suggests to his coworker that they should dig into why the ViewState is so large as the ideal course of action.

In this situation, with management breathing down your neck, it is prudent to spend some time digging into the root cause of an issue. Often, you’ll end up finding an obvious mistake and dramatically improve the application. But at the same time, you want to be careful not to spend too much time banging your head against a problem when you have a workable (albeit band-aid) solution in your hand.

In their situation, it makes sense to set a time limit to investigate the root cause. Perhaps the root cause is that the pages are just plain big due to requirements, and there is no “mistake” to correct. In that situation, the right solution IS ViewState compression. The extra investigation time bought you that assurance.

Suppose they couldn’t find the solution in that time span. At this point, there is nothing wrong with just putting the compression solution in place without having determined the root cause. However, doing so will incur a Design Debt, and that has to be considered when making the decision.

In the book Refactoring to Patterns, Joshua Kerievsky talks about the concept of Design Debt. Design Debt is the state your code is put in when you write crank out code without regard to its design just to meet a deadline. There are situations when this is necessary. Sometimes you just have to bite the bullet and weigh business needs against design purity and just spew code.

As an illustration of design debt, consider building a house of cards three stories tall. You set up the foundation for three stories, you start to build it, but halfway through, your boss comes in and tells you to build it seven stories tall, and get it done ASAP.

Sure, you can do it without redoing the foundation, but to add even more stories later, you’re going to have to revisit the foundation or the whole thing will come tumbling down. Or at least, it’ll be very slow to build that next floor.

Software is much like this. If you are rushing code to meet a deadline, you will go into design debt and that debt has to be paid off, otherwise future development will often slow dramatically and be much more error prone. The obvious problem is how do you sell this argument to your boss? From the business people’s perspective, you’ve delivered working software with X number of features in a short period of time. Why can’t you deliver the next X number of features in the same period of time?

Ah. Therein lies the rub! The business people don’t understand software, and by meeting their insane deadline, you’ve created the impression that…well…that is a normal project pace.

This is where Kerievsky believes the Design Debt metaphor may be of assistance. By phrasing it into financial terms the business folk can understand, the hope is they’ll trust you and provide time to pay off the debt. It’s a simple formula, If you go into debt. The debt must be paid.

Sure, I can meet this insane deadline. But we will go into debt, and it will have to be paid before we add any more features.

Try to make that an expectation up front if you can. It won’t always work, but if it never works, consider moving to a less dysfunctional work environment.

[Listening to: Suite No. 6 In D Major, Gavotte I - II - Yo-Yo Ma - The Cello Suites - Inspired By Bach CD2 (3:42)]

code comments suggest edit

Found this post in RossCode which mentions a blog post that discusses how to bind enumerations to drop downs, something I’ve done quite often.

RossCode has an issue with using this approach personally because typically, the display text of a drop down should have spaces between words, which is not allowed in an enum value. For example…

public enum UglinessFactor {
    ButtUgly,
    Fugly,
    NotSoBad,
}

In the preceding enumeration, you’d probably want the dropdown to display “Butt Ugly” and not “ButtUgly”.

Well if you follow standard .NET naming conventions and Pascal Case your enum values, the following method SplitUpperCaseToString may be of service. It depends on another method SplitUpperCase which will split a camel or pascal cased word into an array of component words.

As a refresher, a Pascal Cased string is one in which the first letter of each word is capitalized. For example, ThisIsPascalCased. By contrast, a Camel Cased string is one in which the first letter of the string is lowercase, but the first letter of each successive word is upper cased. For example, thisIsCamelCased.

public static string SplitUpperCaseToString(this string source) {
  return string.Join(" ", SplitUpperCase(source));
}
 
public static string[] SplitUpperCase(this string source) {
  if (source == null) {
    return new string[] {}; //Return empty array.
  }
  if (source.Length == 0) {
    return new string[] {""};
  }
 
  StringCollection words = new StringCollection();
  int wordStartIndex = 0;
 
  char[] letters = source.ToCharArray();  char previousChar = char.MinValue;
  // Skip the first letter. we don't care what case it is.
  for (int i = 1; i < letters.Length; i++) {
    if (char.IsUpper(letters[i]) && !char.IsWhiteSpace(previousChar)) {
      //Grab everything before the current character.
      words.Add(new String(letters, wordStartIndex, i - wordStartIndex));
      wordStartIndex = i;
    }    previousChar = letters[i]; 
  }

  //We need to have the last word.
  words.Add(new String(letters, wordStartIndex,     letters.Length - wordStartIndex)); 
 
  string[] wordArray = new string[words.Count];
  words.CopyTo(wordArray, 0);
  return wordArray;
}

Try it out and let me know if it was useful for you.

UPDATE (8/3/2010):Fixed a bug so that this doesn’t affect strings that already have spaces in them.

comments suggest edit

Perhaps it’s a rather innocuous practice, but after seeing one too many I am compelled to rant a bit, if only to be a total jerk. What do I speak of? I was going through the blogs in my blog reader the other day and I started noticing the predilection for geek blogs to have “cute” titles and/or subtitles with code snippets. I know we’re geeks, but must we be THAT geeky? It’s become so trendy that I must start the backlash now.

Since I know he can take some good natured ribbing, let’s start with my friend, Jon Galloway.

Title: JonGalloway.ToString()\ Is the ToString() really necessary? Seriously. Isn’t the title of your blog already a string? Hopefully the compiler optimizes this redundancy away.

Title: {public virtual blog}\ Next we have Ryan Farley’s virtual blog. Does a virtual blog imply that you’re not the one writing it, or that you feel your thoughts aren’t concrete? Perhaps the text we see really isn’t there, but are mere wisps of our imagination?

I’m sorry, but the title of your blog just doesn’t compile. Where is the implementation, the member name, and the getter? Perhaps you meant:

public abstract Blog MyBlog {get;}

Even so, you left yourself open for someone else to override your blog.

Title: protected virtual void jaysonBlog {A conduit to the voices in my head.}\ Another virtual blog, but at least this one is protected. Unfortunately, it doesn’t compiled (yes, I tried). And here I thought you were spreading better practices for C# coding.

Title: `(joe (@ (version "2.0")) ,(mk-blog))\ Subtitle: (define (mk-blog) (lambda () (begin (call/cc brain) (mk-blog)))) Joe Duffy couldn’t simply use a language we can all recognize. Nooooooo, he had to take it to the next level and go all the way to LISP. Does your mom read your blog? And does she worry that you spend too much time with the computer after seeing that title?

Title: Bob Yexley Net\ Subtitle: -- SELECT * FROM [bobs].[brain] WHERE category IN (SELECT title FROM [blog_Categories])\ And lest we leave out you DBAs, here is some SQL code from the subtitle of Bob’s blog. Good going Bob!

So as it is now apparent by now, my lashing out is merely a response to my own feeling of geek inadequacy when faced with true geekdom. In order to join the geek big leagues, I hereby re-title my blog…

.method public hidebysig static string YouHaveBeen() cil managed

{

    .maxstack 1

    .locals init (

    string title)

    L_0000: ldstr “Haacked”

    L_0005: stloc.0

    L_0006: br.s L_0008

    L_0008: ldloc.0

    L_0009: ret

}

I hope I am worthy.

comments suggest edit

Ok, I am looking for some blogging fresh meat, so I thought I’d try my hand at starting a meme. The criteria is purposely vague and very simple. I want you to list ten blogs you’ve really enjoyed reading recently. Especially the underrated, undiscovered, recent finds. They don’t have to be your favorite blogs of all time, just ones that have caught your notice recently.

Here are the official rules…

  • The Blog must have an rss (or ATOM) feed.

Ok, that’s it. Here’s my list in no particular order…

  • Coding Horror\ Jeff Atwood does a great job of telling it like it is. He provides pragmatic insight into software development.
  • Apophenia\ Found danah boyd’s blog via Dare. She provides interesting insight into social networking softaware.
  • BurningBird\ Shelley’s always been a good read, but the pictures of balloons has pushed her way up my list.
  • .NET Undocumented\ I read Wesner Moise because he digs deep into .NET so I don’t have to.
  • ComputerZen\ For you .NET geeks out there, this isn’t really a find as his blog is quite widely read, and for good reason. He’s in this list as a sort of blogtime achievement award for continually putting out good content.
  • JonGalloway.ToString()\ Take my blog, remove most of the crap, and you have Jon Galloway’s blog. Yes, this makes my list despite the code title.
  • Sharp as a Marble\ Robb’s humor is sharp and biting. He can insult twenty generations of your family and have you laughing about it.
  • Dare Obasanjo aka Carnage4Life\ Look up the term Job Security in wikipedia and I wouldn’t be surprised if you found a picture of Dare. Only someone who knows he can get a job anywhere can say what he says about his employer and keep working. Fortunately someone over there recognizes he’s part of the solution, not the problem.
  • Neopoleon.com\ Need I say more? Only Rory can talk about suicidal thoughts and have you laughing about it. Don’t you feel like a schmuck now?
  • IanG on Tap\ Nobody is always right, except maybe for Ian. For a real in-depth insight into C# or IO Completion ports, Ian is the go to guy. This guy knows too much, I fear someone will take him out it.

comments suggest edit

Leave it to Ian to cut through the crap and give a very clear and detailed account of what exactly the new var keyword in C# does.

When reading through blogs, mailing lists, and newsgroups, you can encounter a lot of noise from people who are just looking for something to rant about without actually taking the time to understand what they’re talking about. This can be about the most annoying thing in the world.

So if you caught yourself asking:

What’s wrong with “Object”?

I encourage you to read Ian’s post.

comments suggest edit

Certainly there’s been a bit of a bad reaction regarding the name changes of Indigo to WCF and Avalon to WPF.

What were once creative names have been exchanged for rather droll ones. Much like expecting to go to amusement park but ending up in a business park. However, creative names can have their downsides.

I recently started reading a book to get more in-depth knowledge of a version control system I am using on a project. In these times of heightened tensions and when the President tells us to be ever vigilant, the stares I get while reading my copy of Practical Subversion can be a bit unnerving. I can just hear the thoughts going on in an observer’s head.

Well at least he’s not reading Radical Subversion.

comments suggest edit

In 1582, the Julian calendar was really starting to show its age. A bunch of brains got together and came up with the Gregorian calendar, which was received by the general population with a big middle finger in the air. Many saw it as an attempt by greedy landlords to cheat tenants out of a week of rent.

That’s when Pope Gregory XIII got involved and flexed his Papal muscle. He decreed that the day after October 4, 1582 would be October 15, 1582, thus inventing time travel. I personally have tried this move to gain early access to my retirement money without penalties, but to no avail.

The Gregorian calendar ended up shoved the Julain calendar aside and has been in place ever since. In truth, the Gregorian calendar is merely a modification of the Julian calendar in which years divisible by 100, but not divisible by 400 do not have leap years.

But enough history, after 423 years, Josh Baltzell has recognized that the Gregorian calendar is in need of an overhaul. He proposes refactoring the months so that each month is only 28 days. This would require adding an extra month. Personally, I am in favor of any proposal that will add another picture to my Code Listings of the Month centerfold calendar.

Check out his proposal and let him know what you think.

comments suggest edit

Picked up our airline tickets to Spain today. We’ll be visiting in November, landing in Madrid, travelling through Andalucia and ending up in Barcelona. The main thing I want to visit in Madrid is the area where I used to live called Torrejon de Ardoz.

On the way there, we have a five hour stop over in Philadelphia. Apart from eating some cheesesteaks, anybody know what there is to do in Philly?

comments suggest edit

UPDATE: Looks like I was sleeping during my class on 70s funk. It was Albert Hammond who wrote It Never Rains In Southern California, not Kool and the Gang. Thanks Jeff.

Raining in Los
angeles It’s really a funny site to see how Angelenos freak out when it rains here.

Contrary to the axioms of Kool and the GangAlbert Hammond, it does rain here in Southern California. Of course it is so infrequent that people talk of the last time it rained as if describing the fish that got away.

Why, the last rain made the Noah episode look like spit in the desert.

In any case, the sound of rain on the rooftop and thunder in the distance makes it very hard to get out of bed for me. But out of bed I am as I have plenty of work to do.

comments suggest edit

You’ve no doubt heard me rant against premature optimization in the past, but Eric Gunnerson points out another “Premature” action to be avoided, “Premature Generalization”.

His discussion centers around a very specific question of whether to use private properties to access private fields, or just allow access to the field. Note this discussion pertains to fields that are not publicly accessible via property nor direct access.

The place you’ll often see premature generalization is when inexperienced developers start applying Design Patterns everywhere. If you need to instantiate a factory, implement an adapter class and use a bridge to the toilet just to take a dump, then you probably live with a developer with a premature generalization problem.

Like optimization, generalization is good when it is applied judiciously in the right places. With optimization, one should measure measure measure before applying optimizations. With generalization, I typically suggest that a developer must feel the pain first before generalizing. That simply means that the lack of generalization is starting to cause more work than it saves. In my experience, this often boils down to the rule of threes. If you have to implement something a third time, refactor it.

For example, suppose you have an import tool for some system and as far as you know, you’ll only have to support one import client. By all means write an importer specific to that client. Now your boss tells you to implement an importer for another client. Write that one specific to that client. Once again your boss tells you to implement an importer for yet another client. At this point a pattern has been established. Your boss is a liar and you’ll probably need to implement importers for many clients. Now is the time to refactor the code and generalize the concept of importers. Maybe create a plug-in model or an Import Provider.

[Listening to: Cass & Slide / Perception - Sasha - Sasha: Global Underground: Ibiza [2 of 2] (9:27)]

comments suggest edit

It wouldn’t be fair to point out the mistakes of other developers being lazy without pointing out that I have been very guilty of this myself. The point of the post is not to trash another person’s coding habits, but to present an ideal to work towards. Sometimes, intellectual “laziness” is absolutely necessary as in the example presented in the comments of that post.

When I started off as an ASP developer (remember VBScript?) I needed to store name value pairs within a cookie. So I started off storing a string like so in the cookie.

Response.Cookies("ChocolateChip") = "name1=value1,name2=value2,..."

But I ran into an issue that some of the values contained commas, so I chose a delimiter I was sure would never be in the content…

Response.Cookies("ChocolateChip") = "name1=value1*&*name2=value2*&*..."

And proceeded to write a butt load of string parsing code to insert and extract values from the string, making sure not to insert duplicate names, etc…

Of course later, I got around to reading more about Cookies in ASP.NET and I discovered that you can create cookies with keys. So the ugly code above became…

Response.Cookies("ChocolateChip")("name1") = "value1" Response.Cookies("ChocolateChip")("name2") = "value2" '...

Had I spent a few extra minutes up front reading about cookies rather than programming by intellisense, I would have saved myself a lot of time. In the end I ripped out my code and used the built in mechanism.

<blatantLie>To my defense, I was only five at the time and I had been hit by a bat earlier that day so I was seeing double.</blatantLie>

comments suggest edit

Lazy A while ago, Jeff Atwood wrote about the merits of laziness for successful software developers. Lest this become the mantra of sub-performing developers everywhere, I wanted to follow up with a clarification.

It’s fine to be lazy as he describes in the article, just don’t be intellectually lazy. What do I mean by this? First and foremost, when you are writing code, make sure you really understand what the code is doing. The classic illustration of mental laziness is encountering an off-by-one error.

When encountering the error, the lazy developer would simply append a “

  • 1” to the end of the stament, re-run the code, and if it seemed to work, move on. Or they might change a “< x” to “<= x” For simple cases, this may be the correct solution, but the problem arises when the developer doesn’t take the time to evaluate why the error was made in the first place. Sometimes, the simple fix only works for a narrow range of inputs and masks a larger error.

This solution is merely one example of a whole class of anti-solutions I call “Try It and See” solutions. The developer simply moves code around a bit and crosses his fingers to see if it works.

Off-by-one errors are only the tip of the iceberg. This class of anti-solutions often come up when when a developer is using a framework such as ASP.NET in which he is unfamiliar.

On a recent project, I noticed one of the developers had put nearly all of the page logic within the PreRender override. I asked the developer why he put it there, since the proper place would have been in OnLoad. He replied that OnLoad was too early to run that code because the controls didn’t have their settings from the inline control declaration within the aspx file.

Hmm, I’m pretty sure they would be there by then I told him, and he said in his experience, they are not. So I emailed him the order of events within the ASP.NET page lifecycle and pointed out that the method AddParsedSubObject happens after the constructor and way before OnLoad is called.

I believe that he did encounter a weird problem a long time ago with control declarations not filtering through, but rather than dig into the problem and really understand what was going on, he simply moved the code to PreRender, saw that it worked now, and cleared his hands of the problem.

I can understand that on a rush project, there’s a temptation to simply try things till they work and then move on, but you will save more time in the long run if you take a break and dig into the problem to get a real clear understanding of what is happening.

Likewise, spend time getting up to speed on the framework you are using. For example, ASP.NET has a usable form validation framework. Learn it. Use it. There’s no point in wasting time writing your own framework for validation unless you know the ASP.NET validation framework inside and out and really need to work around its limitations. And if you are going to write your own, consider buying a package first such as Peter Blum’s validation package.

So once again, be lazy, but not mentally lazy. Write unit tests up front where they make sense. Learn the framework you are using. Understand the code you are writing or debugging. And in the long run, you’ll be making your life (and your coworkers lives) easier. Perhaps that’s the true laziness.

comments suggest edit

dsc00687 I am back from our first Board of Director’s meeting in San Francisco. The sheer amount of legal formality required in conducting business as a corporation is really quite interesting. They aren’t kidding when they say it will increase the amount of paperwork you deal with.

Just as an example, my business partner Micah needed to open a business bank account a few days after incorporating. He approaches the teller and she informs him that she needs to see the minutes to a company meeting.

Not one to be carrying the minutes to all his meetings in his wallet, Micah was in a bit of a bind. However, one of the bank employees had the proper form to fill out for the minutes to a meeting. However, by law, there has to be a minimum of ten days and maximum of thirty days notice to the shareholders of a company before a shareholder meeting may commence.

So you can see the conundrum here as in this situation, Micah had only given himself about five minutes notice, well under the required ten days. Fortunately, there is a waiver form a shareholder can fill out to state that he or she did not receive the ten days notice, but that it is just fine with the shareholder. So as the sole shareholder, Micah had a quick meeting, filled out the minutes, filled out the waiver, and got the damn bank account open.

comments suggest edit

Mathematicians and Computer Scientists know that the Donald that has had real impact in our world is Donald Knuth, not Mr. Trump. He is a giant in the industry and very well respected.

He’s also tireless and persistent. Consider this, he has been working on his seminal work, The Art of Computer Programming for 43 years and he figures he has 20 more years of work left. Volume 2 of the work, Seminumerical Algorithms, formed much of the backbone for my college thesis on pseudorandom number generation.

So it is with great amusement that I read his letter to the w3c flaming them for depracating certain html elements and attributes. Good find Dare!

comments suggest edit

dsc00694 Akumi and I decided to turn the business trip into a short weekend getaway. After the meeting, we all went out to Espetus, a brazilian churrasco place. Each table had a simple dial. Turn it to green and the waiters with the sticks keep coming to your table offering slices of sweet glorious meat. Turn it to red to put a temporary end to the gluttony. Needless to say, it took an extreme amount of willpower to turn that dial to red once we set it to green.

The next morning, Akumi and I ate at a fantastic Dim Sum place, the name escapes me right now but we have the card somewhere.

Once again gorging ourselves, we were pleased to have a bill with a grand total of just some pocket change over twenty bucks. What a deal!

We then met up with an old friend of Akumi’s and the friend’s wife. The friend is a product designer and works for the very well regarded IDEO. His wife works at a marketing agency and is responsible for the Banana Republic account. They are what are known as “creative types”.

After a great time with them, we checked out some stores, I played with the PSP at the Sony Metreon, then we headed over to Oakland to catch a plane back. Now I’m up way too late for my own good hacking away at this blog. Good night.

comments suggest edit

Just got back from the PDC Underground at the Westin Bonaventure which had its fair share of great and not so great grok talks. I went with Micah and Jon and met a few people I’ve only been acquainted with via subscribing to their blogs.

One is Jeff Key who is a heck of a funny guy. Also met Stuart Celarier who had a long day overseeing the BOFs and didn’t arrive at the Westin till past midnight.

Also making a quick appearance was Don Box sporting a shirt with “WTF?”. I thought he was pimping The Daily WTF but he informed me that it stood for Windows Transaction Framework. WTF?

Of course I ran into the ever friendly and communal Adam Kinney.