Welcome to AspAdvice Sign in | Join | Help

Comments in Code Indicate Functions Trying To Escape

I interviewed a couple of college students earlier this week for internship positions with Lake Quincy Media, and one of them reminded me of my own college days when we were graded in part based on how well commented our code was.  In school, comments are typically there as a "check the block" measure to ensure that the professor doesn't take off points for not having them, but in the real world comments can actually serve a good purpose.  One of the things you learn with experience is the difference between comments as a waste of space that clutters up your code files and comments that are actually meaningful.  However, for the purpose of this post, I'm going to look at a specific case, which is comments that indicate an Extract Method refactoring is needed.

Consider the following code fragment:

// format the label based on balance
if(Customer.Balance >= 0)
{
    CustomerBalanceLabel.ForeColor = "Blue";
}
else
{
    CustomerBalanceLabel.ForeColor = "Red";
}


This is somewhat contrived but it's an example of the kind of minimal commenting one often sees as a sort of "I'm supposed to add comments so here's one to meet that obligation" style.  Really anyone reading this code should be able to figure out what the if block is doing in short order, but the comment is useful at least inasmuch as it lets you know this is all about formatting.  One disadvantage of this style of comment is that it doesn't indicate where the formatting code ends.  Presumably there will be another comment later on, beginning a new set of logic, but often that's not the case and it's up to whomever is reading the code to figure out the scope of the comment.

In this case, the comment provides a big clue as to the method name of the method we'll extract.  We might choose to call it FormatCustomerBalanceLabel() and pass it in an instance of Customer if required (if it's not already scoped to the whole class).  After refactoring, the code might look like this:

FormatCustomerBalanceLabel();
...
 
private void FormatCustomerBalanceLabel()
{
    if(Customer.Balance >= 0)
    {
        CustomerBalanceLabel.ForeColor = "Blue";
    }
    else
    {
        CustomerBalanceLabel.ForeColor = "Red";
    }
}

 

The original version required 9 lines of code in the original method and a comment to explain what was happening.  The refactored version requires only one line of code and no comment is necessary since the name of the function makes it obvious what the code is doing.  Something I notice most new graduates (and students) tend to do is create very large functions, and this refactoring is one way to get away from that.  Ideally, you should be able to view any function in your application on your screen in its entirety without scrolling.  If you have to scroll (or, God forbid, print it out on several pages) to read the entire thing, odds are good that it's difficult of understand and you're going to spend more time than necessary trying to comprehend it (and you'll be more likely to introduce bugs).  And don't even get me started on the testability of small, discrete functions versus huge monolithic functions.

Sponsor
Posted by ssmith | 5 Comments

TECHbash is Coming to PA

In just 10 days (May 10th, 2008), TECHbash 2008 will kick off in northeastern Pennsylvania.  The show has been around since 2005 and will include several hundred developers, IT professionals, and industry experts from PA and surrounding states.  Joe Stagner from Microsoft will be giving the keynote and my company, Lake Quincy Media, is one of the sponsors of the show.

Speakers will include MVPs Miguel Castro, Sam Gentile, and many more.  Jason Gaylord (who runs the .NET Valley User Group) is one of the primary organizers of the event and has done a very good job.

Sponsor
Posted by ssmith | 1 Comments

Regional Director Sidebar Gadget

Keep up on Microsoft Regional Directors' blogs with this Vista sidebar gadget.

Sponsor
Posted by ssmith | 0 Comments

DevConnections Spring Slides and Demos

Last week I gave three presentations at the DevConnections spring show in Orlando.  I received a lot of great feedback from attendees which I definitely appreciate, especially since I was feeling a little bit bad about having run out of time in my first two talks (and overcompensating a bit on my last one, which ended a few minutes early).  I definitely try to err on the side of too much content, with the idea being that if I can't fit it all in, at least the slides and demos are there for attendees to reference, and I'm happy to answer emails with questions about any of the material.

What's New in ASP.NET 3.5

Slides and Demos

My first talk was on What's New in ASP.NET 3.5, and it was well-attended for a Tuesday 8am talk.  I did make it through everything that's actually new in ASP.NET 3.5 and VS 2008 that I had prepared - the only things I had left that I couldn't get to were actually things that are still pre-release, like Silverlight 2 and ASP.NET MVC which I very briefly showed.  There was a lot of interest in LINQ as well, and there were some good questions about LINQ-to-SQL and how to fit LINQ into existing N-Tier architectures.  The recurring theme of "Are DataSets dead?" was interesting as well, and I'm sure some of the other speakers had similar discussions (I hope some of the attendees interested in the topic went to some of the LINQ-specific talks).  The main content for this talk was the ListView and DataPager, along with some simple LINQDataSource stuff and LINQ demos using LINQPad.  I also showed off some VS2008 new features like nested master pages and JavaScript debugging and Intellisense.

 

Pragmatic ASP.NET Tips, Tricks, and Tools

Slides and Demos

The second talk was a tips and tricks talk, which drew from my own experience as well as a variety of blog posts and other similar talks which I tried to credit in the slide deck.  One attendee came up to me at the attendee party Tuesday night, while I was standing with three other speakers, and gave me a nice ego boost (while simultaneously embarrassing me).  He exclaimed that he was extremely grateful for my tips and tricks talk because it had made the conference worthwhile for him, and that "it was good to see a speaker who brought some real technical content to their presentation" or something close to that.  This, with three other very good speakers standing there...  I thanked him and introduced him to the other speakers and suggested he check out their excellent talks on Wednesday.

At any rate, I apologize again for running out of time with this one.  I know I crammed way too much material in for a 75 minute talk, and next time perhaps I'll consider giving a 2-part talk.  Many attendees came to this one and then also went to my third talk, and since I had a few minutes left after finishing that one I actually completed the tips and tricks presentation then, for about 20-30 people who had asked for it.

 

Improve User Experience with Asynchronous Processing

Slides and Demos

My third and final talk for Tuesday was on asynchronous processing in ASP.NET.  I basically covered three scenarios and did so with a minimum of tangents and user discussion, allowing me to get through the material a bit quicker than expected (plus I really didn't want to go over 3 times in one day).  The first scenario was async fetching of files by the browser (increasing the number of files the browser can fetch simultaneously).  The second one discussed async on the server, within ASP.NET requests, and showed a couple of different techniques for achieving this with web services and web requests.  This is an important technique for both scalability and performance.  The third scenario demonstrated how to defer loading of long-running user controls to the client by rendering the page quickly with empty DIVs which populate themselves using AJAX callbacks.  This was the meant to be the high point of the presentation and shows an extremely cool way to achieve great usability.  I didn't get a standing ovation or anything, so I'm not sure that I effectively demonstrated how cool it is (I've shown it at user groups with much greater response).  Perhaps by 5pm on the 2nd day of the conference everyone was worn out.  I still need to write up these techniques for ASPAlliance.com but I still haven't had a chance.  For now, download the slides and demos and check it out.

Sponsor

Twitter as Smoking Cessation Aid

I was talking to a couple of friends and occasional smokers today, and both were commenting about how nice it is that Seattle is almost entirely non-smoking now, so they didn't light up while in town for the MVP Summit.  I've never smoked, but listening to them, clearly they were not addicts in the hard-core packs-a-day kind, but they would smoke socially or just to be doing something.  So it occurred to me, especially given that the three of us had just spent half of lunch each individually checking various Twitter feeds (and email) on our phones, that perhaps Twitter and similar apps on mobile devices are having a positive health impact.  Why light up a cigarrette when you can keep your hands busy with your phone checking Twitter, texting friends, or scrolling through emails on your Blackberry Windows Mobile Device?

Any smokers care to affirm or deny that this effect exists?  Now if only the constant use of mobile phones didn't come with its own social costs, especially with significant others...

Sponsor
Posted by ssmith | 4 Comments
Filed under:

Triskaidecaphobia

Office 13 is going to actually be called Office 14, since there are some people who assign some negative significance to the number 13 (see Triskaidekaphobia).  Since this is clearly a significant concern in the world of computing, it seems natural to me that other areas of Microsoft's platform should work harder to avoid this unlucky number.

On a slightly related note, I was glad to see that the Westin Seattle actually is honest about the numbering of its floors, and does *not* label the 13th floor 14 in an effort to appease people's superstitions.  Scott Cate and I stayed on the 13th floor this week, and even had the super-duper unluck of having 13 on our door twice (in a palindrome!) in room 1331.  However, we were somehow able to escape the imminent doom this would normally portend.

Back to the subject at hand, though, let's find some other areas in which we can eliminate fear of the .NET framework.  To start with, arrays and enumerable collections should automatically skip the 13th index and label it 14 instead.  Thus something like this:

string[] myStrings = new string[20];

foreach(int i=0;i<myStrings.Length;i++)
{
   Console.Write(i + " ");
}

would output

0 1 2 3 4 5 6 7 8 9 10 11 12 14 15 16 17 18 19

To get this to work, you would need to update the CLR or the IEnumerable functions in the base collection classes, but it would be worth it to avoid the evil 13.  To implement this yourself, you would need to add in special logic:

if(i<=12||i>=14)
Console.Write(i + " ");

This would still pass the FxCop rule "thou shalt not have the number 13 anywhere in your code" that will need to be added, but really users shouldn't need to write this themselves.  However, static analysis and style warnings really aren't sufficient to address the importance of something like this.  We really need to entire system to grind to a halt at the very mention of the unmentionable 0xD.  Thus, we'll need a new exception, the Triskaidexception.  Its use might look like this:

if(value > 12 && value < 14)
{
  throw new Triskaidexception("Evil number detected!);
}

 

But seriously, since the actual product isn't going to carry the lucky number 13, I think it's pretty silly to eschew this incremental number in order to avoid superstition.  All that does is breed ignorance and superstition further, and in the 21st century, from a company full of a lot of very well-educated and intelligent people, I would hope to see less fear of the potential marketing detriment of others' superstitions.

Sponsor

Microsoft Cloud Services

One of the quietly announced (at MIX - WMV here) new things coming from Microsoft "soon" is SQL Server Data Services (SSDS).  The SSDS team has a blog on MSDN.  Ryan Dunn discussed it with me recently and also has been blogging about it.  Last week he announced the release of PhluffyFotos, a sample site built on top of SSDS.  You can sign up for the beta of SSDS here.  Roger Jennings has some comments here.

So, what is SSDS (read the FAQ)?  Essentially, it's a way for you to access data from "the cloud" providing a highly scalable and globally available data access story.  One scenario that benefits greatly from this approach is the application that suffers from extreme spikes in activity punctuated by lengthy lulls.  For instance, a ticket sales company that has millions of requests within the hour that some tickets go on sale, and then just thousands of requests the rest of the month.

Amazon and Google are both pushing cloud services and clearly this is an area that Microsoft is moving into as well.  SSDS is the first of what I expect will be other such services, and it will be interesting to see how the various offerings compare.  If nothing else, the competition between the various companies should drive pricing down, both for these services directly as well as for traditional application hosting solutions.  Eventually, I expect a developer could upload an application and configure its data source requirements and host the entire thing "in the cloud" paying some metered rate for the various resources (disk, cpu, bandwidth, and extra services) consumed by the application.

Sponsor
Posted by ssmith | 1 Comments
Filed under:

ASP.NET AJAX Download Performance Improvement Request

I'm a big fan of ASP.NET AJAX in general, but one concern I have and something that has forced me to use other technologies is the size of the library.  It's about 85kb when compressed and unfortunately that is quite large if you're trying to include it on most every page on a site (or, much much worse, every advertisement in a large Microsoft developer advertising network).  One can certainly argue that this will be cached, and that is true, but for many sites that get most of their traffic from search engines (ASPAlliance gets over 70% of its traffic from this), you have to assume that many users will not have the .js file cached, and that is a significant increase in the total page size.

I would like to suggest (and have done so previously, but less publicly) that it would be a good thing if the ASP.NET AJAX javascript library were hosted by Microsoft as an option.  This would involve some slight changes to the coding (specifically I would add a property to the <ScriptManager> control to enable using the Microsoft provided library), and would require that Microsoft make a commitment to having the .js file available via their infrastructure.  In practice this would not be very different from the distribution model that they are currently using for Silverlight deployment, but would be much smaller (per file - 85kb vs 4mb).

The chief advantage of this approach would be a huge reduction in the number of downloads of the AJAX javascript file required for clients, and an increase in performance across the board as a consequence.  The likelihood that any given browser would have a cached version of the AJAX javascript would be much higher if a large number of AJAX-enabled sites referenced the Microsoft hosted AJAX library.  The cost (in bandwidth) to use AJAX would go down.  The performance for all AJAX-enabled web applications would go up.  Clients that do not wish to cede control of the distribution of the download could continue hosting the files themselves without any change.  The change in behavior of ScriptManager could easily be rolled out in an SP or as part of vNext, and would make AJAX more attractive when compared to alternate (lighter weight) JavaScript frameworks such as jQuery.

Sponsor
Posted by ssmith | 9 Comments
Filed under: ,

Extract Control for ASP.NET in Visual Studio

I've been posting about some feature requests for ASP.NET/Visual Studio, so here's one more in that thread.

One nice feature of Blend is the ability to select a chunk of XAML and choose to "Extract User Control".  The result works very nicely, creating the separate control and inserting the reference to that control into the original XAML document.  It would be very cool if ASP.NET had this same notion, wherein one could select a chunk of ASPX markup and choose "Extract User Control" and have it create the .ascx file for you and insert the reference to that control into the original page.

Another nice addition to take this another step further would be the ability to convert an ASCX file into a compiled control.  I wrote an article and did some talks a few years ago about the evolution of controls from ASPX to ASCX to .CS (.VB).  This is pretty much all a manual process and progression (it was then, and it is still today), but it would be nice if this were a bit easier via a VS tool or even a third party refactoring tool.  Perhaps this already exists, in which case I'll look for comments from the Resharper/RefactorPro guys shortly... (like last time) :)

Sponsor
Posted by ssmith | 2 Comments

2008 Goal Progress Update

If you just read my blog for technical stuff, you can skip this one.

So at the start of the year I set a few personal goals.  Since the best way to achieve goals, I've found, is to break them down into smaller and smaller pieces (as in "The journey of a thousand miles begins with the first step"), I thought I would assess my progress on the five goals I set for myself.

Goal 1 - 200 Blog Posts in 2008.  That breaks down nicely into 50 per quarter, and in the first quarter I published 52 posts, just barely on track.  February was pretty light with only 9.  I'm sure if it had had 30 days in it I could have written a lot more posts.  Of course, if it had had only 28 days, I might not have had nearly as many...  We'll call this one 25% complete.

Goal 2 - Lose 17 pounds.  So far I've lost 10 pounds.  That's pretty good, and definitely on track, although I'm still hovering around where I was for most of 2007 (I basically lost what I gained over the holidays and maybe a tiny bit more).  So, it's definitely good but I know the next jump will be harder.  And then keeping that all off as of 1 January 2009 will be hard.  But I'm on track.  This goal is about 58% complete.

Goal 3 - Write a Silverlight book.  Progress has been slow.  I have two chapters due this month and the whole thing should be turned in for the first draft by mid-June.  So I need to make a lot of progress this quarter.  If I do another update around the start of July, this goal should (had better be) close to complete.  Right now it's probably only around 5%.

OdinGoal 4 - Get a puppy.  Done!  We got an English Mastiff puppy named Odin in January.  He was about 8 weeks old when he came home and around 20-25 pounds.  Now he's about 4 months old and 60 pounds.  It's amazing how fast these guys grow.  This was the easiest of my goals to achieve, and is now 100% done.

Goal 5 - Achieve next belt in karate.  I've been practicing regularly, which probably has helped with Goal #2.  I don't expect to test for my next belt until Fall, but I think I'm on track, so we'll say this one is 25% done at this point.

If nothing else, putting these out for public consumption helps motivate me to work toward them, since now if I don't achieve them, the whole world knows about it.  My apologies to those of you who simply don't care.  Why did you keep reading this far?

Sponsor
Posted by ssmith | 2 Comments
Filed under:

OpenXML Standardized and Sour Grapes

Earlier this week, the OpenXML document format was standardized by the ISO/IEC, with a huge 86% of voting countries favoring the format (news here, among other places).  While this is interesting and a win for anyone using Microsoft Office document formats (who isn't?), it's also a bit disappointing that those who opposed the format's standardization have opted not to accept the decision of the global community.  Instead, they've shifted into sour grapes mode and are attacking the process and everyone involved (at least the ones who didn't agree with their perspective).  Jan van den Beld has a great writeup of the accusations being thrown about by the folks who couldn't enforce their will upon the world through proper channels - you should check it out if you're at all interested in this topic.

Sponsor
Posted by ssmith | 5 Comments

CruiseControl.NET Caching Old Project Locations SOLVED

As I mentioned in my previous post, we're just wrapping up a continuous integration solution for a client (and if you're not using this for your team, you should be.  If you don't have time to do it, contact us to do it for you.  You'll thank me later.) and one of the last requirements changes was an update to where on the build server's hard drive the project files should reside once they're checked out from source control.  After making this change in the cc.net.config file for the various ccnet projects, and also making the change in the source control provider's working folder association for the build account username, I figured things would just work.  I forgot about one thing, and it caused me frustration for the better part of a day.  That thing was the CCNET state files.

After making my changes from d:\buildserver\source\ to the new location in the ccnet.config file (and doing a find and replace to be sure I hadn't missed it anywhere), I started looking for places the source control client may have been caching the old working folder associations.  I went down this road for a while, and did find a bunch of places where the client was storing settings, but nothing with this location.  And my builds were all failing because this folder no longer existed, so the attempts to perform a get from source control were failing.  I searched the registry - nothing.  I searched the entire file system (all disks!) - nothing.  Unfortunately this was not my server and it had the default configuration on it of not searching all files (Scott Forsyth at Orcsweb has the registry hack to correct this, detailed here).  In an act of desperation, I had the client restart the server for me.  Still no good.

At this point I grabbed the CCNET source and started going through it to try and find where it was getting that path from.  Being open source is great for this, but of course it's not like I can search the source for the folder name I'm looking for, and CCNET deals with a bunch of different folders (both in source control and on disk) so it's a bit tough to follow if you're unfamiliar with the code exactly which variables refer to which paths in the build process.  As I was getting close to finding the problem in the source, I noticed something in my CCNET /server folder - a bunch of [PROJECTNAME].state files.  This was one of those combination "ah-ha!" and "oh, man, was it really that easy" moments.

Yes, it turns out that if you open up these state files, they include, among other things, the location on disk for the project.  If you're going to search the file system for a particular string in a file, be sure you're searching all file extensions since various vendors will make up all kinds of extensions and put text into them.  If you update ccnet.config to use a new workingDirectory it won't care because it's going to look at what is in the state file instead.  You can configure the state file location in your ccnet.exe.config or ccservice.config - by default you'll find them co-located with these EXEs.  Just remember to look for them.

The state files include the following elements - if you see any of these being cached by Cruise Control, go delete the state files and it should stop caching them.

  • ProjectName
  • ProjectUrl
  • BuildCondition
  • Label
  • WorkingDirectory
  • ArtifactDirectory
  • Status
  • StartTime
  • EndTime
  • LastIntegrationStatus
  • LastSuccessfulIntegrationLabel
Sponsor
Posted by ssmith | 2 Comments

Not Working for Microsoft

I thought I should post a follow-up since I'm sure many people ready my post on Tuesday about going to work for Microsoft on some code-named project and (a) didn't remember it was April Fool's Day and (b) didn't then read the comments where I pointed out that it was a joke.  I'm still happily self-employed and working on Lake Quincy Media, ASPAlliance.com, and a new consulting business that so far is trying to focus on agile development and in particular setup of continuous integration for shops that don't already have it (just wrapping up one of these).

I like being my own boss (or at least, having my wife as my boss - she's the CEO of Lake Quincy and runs the show there), but if I ever did go to work for somebody, it would probably be Microsoft.  So... maybe some day, but not yet.

Sponsor
Posted by ssmith | 2 Comments
Filed under:

Refactor Request

Not sure if it's already there, but the folks at DevExpress or JetBrains (or Microsoft, but I don't want to wait for another VS) should have a refactoring for CodeRush/Refactor! or Resharper that will convert verbose properties into C# 3.5 short properties, like so:

Make this:

protected bool isSponsored = false;
public bool IsSponsored
{
    get { return isSponsored; }
    set { isSponsored = value; }
}

Into this:

public bool IsSponsored { get; set; }

 

Ideally, it should work in two forms:

1) Right click on the property (field name let's say) and offer it as an option in that context.

2) Apply to all properties in a class.

And it should only do it if it is safe, of course.  If I had set isSponsored to true in the original code, the refactoring wouldn't have been possible, since it would have changed the behavior.

Of course, if some enterprising developer has already done this, please comment with a link.  Maybe Keyvan's done it - he just published a book on VS extensibility...

Sponsor
Posted by ssmith | 8 Comments
Filed under: ,

Silverlight Rehab

Check out Dan Fernandez, Adam Kinney, and others in this very funny 5 minutes video about Silverlight Rehab on On10.net.

Sponsor
Posted by ssmith | 0 Comments
Filed under:
More Posts Next page »