Steve Smith's Blog
Applying Interface Segregation to Configuration Files
In .NET, it’s very easy to set up custom configuration section handlers to handle your application or component’s configuration needs. As my previous post shows, it’s also very easy to configure these with attributes that enforce required fields and other validation. However, over time it’s very easy to create fairly large configuration sections that violate the Interface Segregation Principle, which states that classes shouldn’t be forced to depend on things they don’t need.
Consider this relatively simple configuration section:
<configSections>
<section name="ConfigurationSettings"
type="InterfaceSegregation.Configuration1.ConfigurationSettings, InterfaceSegregation"/>
</configSections>
<ConfigurationSettings
ApplicationName="Interface Segregation"
AuthorName="Steve Smith"
CacheDuration="60"
DatabaseServerName="localhost"
DatabaseName="Northwind"
DatabaseUserName="ssmith"
DatabasePassword="secret"
WebServiceBaseUri="http://localhost/"
/>
I’ve intentionally made it a bit more verbose than needed (obviously the database settings could be combined into a connection string, etc), but the intent is to show that my relatively generic Settings section has completely lost its cohesion. Let’s look at an interface that we’ve created to support these settings (because we don’t want to have an Insidious Dependency On Our Configuration File in our code):
public interface IConfigurationSettings : IApplicationIdentitySettings
{
// application identity settings
string ApplicationName { get; }
string AuthorName { get; }
// performance tuning settings
int CacheDuration { get; }
// data access settings
string DatabaseServerName { get; }
string DatabaseName { get; }
string DatabaseUserName { get; }
string DatabasePassword { get; }
// web service api settings
string WebServiceBaseUri { get; }
}
public class AboutPage
{
private readonly IConfigurationSettings _configurationSettings;
public AboutPage(IConfigurationSettings configurationSettings)
{
_configurationSettings = configurationSettings;
}
public AboutPage() : this(ConfigurationSettings.Settings)
{}
public void Render(TextWriter writer)
{
writer.Write("{0} By {1}",
_configurationSettings.ApplicationName,
_configurationSettings.AuthorName);
}
}
This class takes advantage of Dependency Injection to eliminate a direct dependency on the ConfigurationSettings class/file, through the use of the IConfigurationSettings interface. However, it’s still depending on a much larger interface than it needs, and thus is violating ISP. Fortunately, there’s a very easy fix for this that will let us ensure this class only depends on what it needs, without breaking anything else in our application. The refactoring involves creating a new interface for AboutPage to depend upon, that is more cohesive and only includes things AboutPage (and perhaps other classes that require the same things) requires. First, we need to identify these settings and come up with a name for the new interface:
public interface IApplicationIdentitySettings
{
string ApplicationName { get; }
string AuthorName { get; }
}
Next, we need to modify the IConfigurationSettings interface so that it no longer has these settings, but inherits them from the newly created IApplicationIdentitySettings interface:
public interface IConfigurationSettings : IApplicationIdentitySettings
{
// performance tuning settings
int CacheDuration { get; }
// data access settings
string DatabaseServerName { get; }
string DatabaseName { get; }
string DatabaseUserName { get; }
string DatabasePassword { get; }
// web service api settings
string WebServiceBaseUri { get; }
}
Finally, the AboutPage class can be modified to use the new, more focused interface. In its default constructor, though, it can still use the ConfigurationSettings.Settings class, as this implements IConfigurationSettings, which now automatically implements IApplicationIdentitySettings:
public class AboutPage
{
private readonly IApplicationIdentitySettings _applicationIdentitySettings;
public AboutPage(IApplicationIdentitySettings applicationIdentitySettings)
{
_applicationIdentitySettings = applicationIdentitySettings;
}
public AboutPage()
: this(ConfigurationSettings.Settings)
{ }
public void Render(TextWriter writer)
{
writer.Write("{0} By {1}",
_applicationIdentitySettings.ApplicationName,
_applicationIdentitySettings.AuthorName);
}
}
Summary
The Interface Segregation Principle states that classes should not be forced to depend on things they do not use. By refactoring “fat” interfaces into smaller, more focused and cohesive interfaces defined by the clients that use them, we can reduce the coupling in our code. This results in code that is easier to change, maintain, and test, not to mention being much more fun to work with. Be breaking up the fat interface but using interface inheritance to ensure the original interface remains unchanged, this refactoring can be done to existing codebases without requiring extensive changes that spider through every class that touches the original interface.
Startup Business Checklist 2010
Below is my current checklist for startup businesses in 2010. This is meant to be relatively industry-agnostic and focuses primarily on online components of the business (meaning, it may not apply to businesses which avoid the Internet for whatever reason). I’ve included numerous links to more information and references. Checklists are a great way to ensure you don’t forget important things – check out the Checklist Manifesto for how one doctor is attempting to apply this logic to medicine.
If you’re not reading this on my blog, you’re likely missing out on the latest updates to this post – click here to view the source article: Startup Business Checklist 2010
( ) Domain(s)
You’re going to need a domain name. Maybe more than one. At a minimum, unless you’re trying to be clever with an oddball root domain like del.icio.us or bit.ly, you’re going to want a .com address. If you find several variants, choose one that is your canonical (the one you want everyone to use) URL, and ensure the other domains either 301 redirect to the main URL, or have some content that sends links to your main URL. I use GoDaddy for all of my domains, but there are plenty of other domain registrars available. You shouldn’t need to pay more than $10 per year for a domain (not counting any other services).
- GoDaddy (direct link) | Go Daddy $7.49 .com Domain Sale (sale/affiliate link)
- DirectNIC
- Register.com
I’ve personally used each of the above services, and they’re ranked in order of my preference.
Note that you may get some extra SEO benefit from having an established domain (one that has been registered for some time) as well as a domain that does not expire for a long time (expiration more than a year or two in the future). A useful tool for checking the status of a registered domain is WHOIS, which most domain registrars support (somewhere) or which you can do from Whois.com (which apparently also does domain registration but I can’t vouch for them).
I’ve found that Google Apps (the free edition) is quite sufficient as a starting point for most start-up companies. You get a ton of space, a great user interface that doesn’t require you to install anything locally and that you can use from anywhere, and virtually no spam. For free (with non-intrusive ads). And of course you can upgrade to give them money if and when you need to do so.
It’s worth grabbing the domain and then email early on, as many of the steps below will require these. Also, with the advent of OAuth and OpenID for authentication, you can very likely use your Google Email, Facebook, or Twitter account as your login for many of the other services listed here, saving you from having one more set of credentials to remember.
( ) Web Hosting
I’ve used each of the following for web hosting and have had good experiences with each one:
- ORCSWeb – Bar none the highest quality managed hosting company for Microsoft .NET applications. If you want someone else to deal with keeping your web servers updated, online, and running 24/7 so you can deal with what your company actually does, call them.
- DiscountASP.Net – Very affordable and I know lots of people who swear by them. Also dedicated to Microsoft solutions, as far as I know.
- Dreamhost – I’ve used them for Wordpress blogs (and Michelle’s blog is hosted there now) and they’re inexpensive and their tools make getting started very easy. I’m not familiar with them beyond Wordpress, but of course they offer other hosting options as well.
- WP Engine – Recommended by Jason Cohen, WP Engine takes Wordpress to the next level.
What you need for web hosting really depends on what kind of business you’re in. If you’re building an online application, you probably will need a database, the ability to run code, etc. If you’re launching a non-Internet business, then you might only need a basic marketing website, which you’re best of creating via a content management server (CMS) package.
( ) Content Management Server
Again, don’t underestimate Wordpress. It’s free and there are plugins for nearly everything. However, one of the most common questions you’ll find in the Wordpress communities is “How do I make it not look like a blog?” If you want a site you can manage without having to use developer tools and FTP, you definitely want to investigate content management servers or CMSes. In v3 of Wordpress, which offers post types, there are themes available that let you do a lot without having to drop down to the raw PHP or HTML.
In the Microsoft space, there are quite a few CMSes to choose from, including many commercial offerings. My current favorite is Umbraco, which is a nice open-source CMS that can handle medium- to large-scale sites. It’s built on .NET and very extensible. One of my Umbraco-certified friends, Craig Palenshus, uses Umbraco to manage the NimblePros’ web site. You can also use Graffiti or DotNetNuke or any number of other commercial CMS offerings.
Even if you’re building an online business built on custom software, it’s worth considering a CMS for your company site. Remember, you may not want to use your developer resources for every change to your home page’s welcome text.
( ) Analytics
Another free Google tool, Google Analytics is really a no-brainer. It’s not perfect. It’s even a little shady at times (like, if a user has ever come to your site by way of any search on Google, they are forever after categorized as a visitor from Google, not an organic visitor. It’s still an amazing tool for the (free – not even ads – you just are giving them loads of data for free) price tag. Once you have an account, you just need to use the unique identifier or script blog in your blog and on your web site.
( ) Blog
Your company needs a website, but it probably also should have a blog. People want to know what you’re doing, and your marketing brochure site (or social network, or whatever) doesn’t let them get to know you. If you just want something for under $10/mo with no technical skill required that you can do just about anything with, then Wordpress is the way to go (see Dreamhost above). If you’re a developer or have developers on your team and you have some valid reason why it’s important that you be able to change the code used to run your blog, then if PHP isn’t your thing you might look at these open source .NET alternatives:
- BlogEngine.Net – Brendan’s blog is now running this
- Graffiti – My blog currently uses Graffiti
- dasBlog – ScottHa’s blog uses dasBlog (of course, since he’s one of the main developers of dasBlog)
You’ll also want to use Feedburner (now Google) for your feeds. Saves you bandwidth and offers some nice features.
( ) Logo
You’re going to need a logo. You might need one for your company and one for your product. But you’ll need at least one. If you know a good designer (like Craig), you can have them create one for you. Otherwise, there are services out there that can produce a lot of logos for your consideration via a winner-take-all contest where you offer the prize.
- LogoTournament.com - $250 prize minimum. I think they’re the dominant player in this category of sites.
- 99Designs.com – Same idea, about the same price, minimum
I’ve also used LogoBee.com successfully in the past.
( ) Customer Feedback
Once you get some customers, even the non-paying beta users and early adopters, you’re going to want to know what they think. Talk to as many of them as you can – there’s no substitute for that – but to get scale you’re going to want a tool to manage feedback. The two sites that make this very easy are:
- UserVoice.com – My personal preference.
- GetSatisfaction.com – Seems to be roughly the same as UserVoice, but much longer to say and spell… Either one is probably a good choice over (a) nothing or (b) trying to build your own.
( ) Project Management
You’ll need some way to identify things that need doing, prioritizing these things, and seeing them progress from ideas to completed tasks. There are about 6 billion project management software packages out there. I’ve used a small fraction of these and have developed some opinions. I personally prefer lean and mean and simple to big and complex and does everything you might never need. If you’re already using UserVoice or GetSatisfaction, you might be able to use these for your project management, as well. More likely, though, you’re going to want another tool.
- 37Signals.com – BaseCamp has a huge following and has pretty low initial requirements/costs. For a startup, it’s probably worth considering.
- AgileZen.com – For simple software feature/bug tracking, a kanban board works great (literally, on a wall or whiteboard). If you need something virtual, though, AgileZen is a nice tool for that job.
- Axosoft OnTime – If you need more than just a kanban tracking board, OnTime probably has the features you need. It’s a very full-featured software bug/feature/project management tool. I have a love/hate relationship with it.
- Pivotal Tracker – A free kanban/sprint planning tool.
( ) Source Control (software development)
Assuming your business requires some custom software development, you’re going to need a place to safely store your code. Depending on how selection above for web hosting, you might be able to host your source control on your hosted server(s). If not, you can install something in your office or use one of many online options. The de facto standard free solution remains Subversion, but distributed source control platforms are becoming more popular every day, with the two leaders being Git and Mercurial. If you go the Subversion route, I recommend TortoiseSvn and VisualSvn Server.
I haven’t used hosted source control before, but these are the three I hear are the best:
- Unfuddle.com – Hosted Subversion (and Git)
- Github.com – Hosted Git
- Bitbucket.org – Hosted Mercurial
Don’t forget you can also use public open source code repositories for free (assuming you have few secrets):
- Codeplex.com – Microsoft open source projects with source control, issue tracking, and more. Support for TFS, SVN, and Mercurial clients for source control.
- SourceForge.net– The largest open source repository in the world
- Google Project Hosting (Google Code) – More free stuff from Google – supports SVN and Mercurial.
( ) Continuous Integration (software development)
If your business requires custom software development, you should have a build server that performs builds (and tests) every time your team checks in changes to the application. If you don’t, you’re doing it wrong. My two favorites are:
- TeamCity – Free for small projects, worth it for larger ones, and almost entirely web-based setup and configuration.http://www.google.com/reader
- CruiseControl.Net – The grand-daddy of CI servers, CC.NET is full-featured but requires a fair bit of manual XML file tweaking to set up. Be sure to get CCTray to go with it – that app rocks.
I’ve also used Visual Studio’s build server, which with the 2010 edition is quite easy to set up and use as well. I haven’t used Hudson, but I’m told it’s also good (Jason Cohen says he and most CruiseControl users he knows have switched to Hudson, which has “same basic tech, much better implementation. Also has better support for things like ruby instead of mainly being for Java.”).
( ) Social Networking
You’re going to want to get social networking accounts that are as close to your domain and/or product name as possible. The following listed ones are the minimum I recommend. Even if you have nothing to say right now, it doesn’t cost you anything to set up these accounts and just sit on them for when you do decide you want to use them.
( ) Twitter Account (usually in addition to your own, if you have one)
( ) YouTube Account
( ) LinkedIn Group and/or Company Page (coming soon)
( ) StumbleUpon Account
( ) Other Sites via Knowem.com (checks hundreds of sites at once!)
If you do start needing to manage multiple social networking accounts, I’ve found HootSuite.com to be invaluable. It lets you manage them all centrally, delegate permissions to others as needed without sharing the actual account credentials, and it works from anywhere (web app). A nice option for a non-web solution is TweetDeck (which I used until I switched to HootSuite).
Another option if you have partners/cofounders is cotweet, which offers a free account you can use to manage the company twitter account together. It includes the ability to assign things to your colleagues for follow up, or to send/receive notifications about who is “on duty.” Good stuff if you’re seriously looking to have an active presence on twitter.
( ) E-Commerce (if applicable)
( ) Checking Account
Lots of choices. Personally I prefer a bank with a physical presence near me so that I can meet a real person if problems arise, rather than going through their automated or offshored phone system.
( ) Payment Processor
Lots of choices again. I’ve used and have generally heard good things about Authorize.Net. I’ve heard good and bad things about PayPal. And of course you may be able to bypass dealing with this level of detail entirely if you are selling a virtual product, in which case you might use a service like FastSpring, which NimblePros uses to sell its Nitriq code analyzer and Atomiq code de-duplicator products. Note some of the services listed under Storefront application can also be leveraged to process your payments.
( ) Storefront application
Many choices. You can roll your own. There are open source solutions available like nopcommerce for ASP.NET. You can also integrate with services like Google Checkout, Yahoo Stores, or Amazon Payments. Personally I’ve gone the roll your own approach in the past, but in most cases I would recommend building on an existing product or service, especially as a quick way to get to market.
( ) Google Alerts
( ) Find and monitor 3-6 competitors
Google Alerts is another perpetually beta service offered by the giant company. If you haven’t used it before, basically you give it search terms you’re interested in (like, say, your competitors’ product and company names, along with your own), and then it will email you whenever Google finds new content that matches these terms. You can set it to batch up the results and email you once per day or per week, or to email you immediately. Be sure to monitor your twitter alias and blog name if these differ from your product/company name. I recommend getting the emails as they happen, as this lets you quickly join the conversation when it involves your product in the blogotwitterosphere.
( ) Update Personal LinkedIn
( ) Answer (and Ask) Questions on LinkedIn related to your industry
( ) Find other communities where you can become known as an authority
( ) Find and Connect with Bloggers, Twitter Users in your industry’s community
How you do this will depend on your industry and your existing relationship with its community. Use your favorite search engine to search for articles and news of interest to your industry, and note the top blogs that come back from such searches. Begin by following these people using your RSS reader (Google Reader is nice if you don’t have a preference; Microsoft Outlook also supports RSS subscriptions). Most prominent bloggers are likely to also be active on Twitter at this point, so follow them there as well. You’ll most likely have separate accounts for personal use and for your brand/company/product, so choose whether it makes sense to follow these individuals with either or both such accounts.
Check this off when you’ve found 5 influentials in your industry whom you are now following. Make a point to engage with them via their blog and/or twitter.
( ) Grade and Track Web site
Once you have your web site up, it’s a good idea to monitor it using a tool like WebsiteGrader.com. This is separate from looking at your site’s traffic via Analytics (above). WebsiteGrader will give you a bunch of metrics related to how your site performs from technical, search engine optimization, and social media perspectives. I suggest logging the main metrics for your website (and twitter) and comparing yours with your main competitors on a periodic (monthly or quarterly) basis. You’ll find Grader apps for Twitter, Facebook, LinkedIn, Books, Press Releases and more at Grader.com.
( ) Scout labs or similar tracking
You’ll want to track some of the things you discover over time so you can see how you’re doing compared to your competition. ScoutLabs appears to do this very well, though I haven’t used their product myself (it’s not necessarily cheap). However, it does look very impressive. Assuming you don’t have tons of VC money to spend, an alternative is to use Excel or a Google Spreadsheet to track your Twitter followers, Feedburner subscribers, WebsiteGrader score, and competitors’ scores over time. And you can make the pretty charts yourself, too.
( ) Subscribe to your own personal LinkedIn RSS feed
Assuming you’re using an RSS reader regularly already, this can be an easy way to keep up with your professional contacts, and expand your network. The RSS feed should be here:
http://www.linkedin.com/rssAdmin?display=
assuming you have a LinkedIn account already and are signed in.
Acknowledgements
Thanks to Jason Cohen (a smart bear) for adding a few great ideas to the list.
System.Core in VS2010 Projects
I just ran into an odd issue with a VS2010 project. In my case it was an MVC 2 application I was upgrading from VS2008. One of the built-in controllers (ProfileController) was failing to compile because it could not resolve the Linq extension method symbols Single() and Matches(). These are located in the System.Core assembly. I checked my project references in Solution Explorer, and System.Core was not listed. So I tried Add Reference, and System.Core was listed as included and gave me the option of to Remove it.

After some searching, I found this blog post, aptly named Do NOT remove the reference to System.Core from your VS2010 Project. It pointed out that this file is “special” and that if you remove it (or it gets lost somehow) you need to re-add it manually to your project using this syntax:
<ItemGroup>
<Reference Include="System.Core" />
</ItemGroup>
There is also a connect issue describing this bug (which is currently marked as Postponed), Cannot remove System.Core.dll reference from a VS2010 project.
In my case this appears to have been an upgrade issue, as the project worked fine in VS2008 before I ran the upgrade wizard to VS2010, and then in the course of trying to get it to compile for the first time, I ran into this issue. Adding the assembly to the project file by hand (via Notepad) solved the problem in my case.
Using CCTray with JetBrains TeamCity
TeamCity is a great build server tool from JetBrains (makers of the awesome Visual Studio add-in, ReSharper). The user-interface and features of the TeamCity web front-end are wonderful and are leaps and bounds easier to use for new users than my previous favorite, CruiseControl.Net, which required much XMLness to configure. However, one of my favorite tools from CruiseControl, CCTray, still has no equal among competitors like TeamCity and even the Visual Studio tray watcher for Team Build.
Why CCTray Is Awesome
CCTray has one job and it does it extremely well. That job is to let anybody interested in any software projects (that support CCTray) know whenever something happens with the build status of one of these projects. It’s a lightweight, easy to configure tray application that more-or-less instantly provides feedback on build status via one or more of the following notification options:
- Balloon window
- Custom sound
- Synthesized Speech
Additionally, it shows at-a-glance status of all watched projects instantly (no need to wait for it to talk back to the server), and double-clicking on a given project will load its project page with details about the most recent build in the browser. Custom sounds in the dev team area are a great way to ensure that all devs immediately know whenever a build fails. I recommend having the team agree on standard sounds, and having at least one machine in the team room with speakers on and CCTray installed with these sounds. When the red alert klaxon or similar “bad” sound starts playing, everyone should immediately be focused on getting the build fixed.
CCTray supports unique sounds for successful builds, broken builds, fixed builds (first success after fails), and still failing (subsequent fails after first fail) builds.

Here are some sample sounds you can get started with for CCTray build events.
Why JetBrains’ Tray App Is Less Awesome
The built-in TeamCity build monitor is lacking in sounds and is also very slow to respond. When you click on its icon, it needs to talk back to the server to get the latest status updates. While this perhaps ensures the most up-to-date information, I’m looking for real-time responsiveness from my tray application – I know I can go hit a web page if I want the latest and greatest detail. For a while there you couldn’t use more than one build server with the TC build monitor, too, but I believe this is now possible in the latest version. Speediness and sounds are my main reasons for preferring CCTray at the moment, though.
Using CCTray with JetBrains TeamCity
A couple of weeks ago, Yegor Yarko posted a plug-in for TeamCity that makes it possible to use TeamCity with CCTray. He includes the instructions with the post – basically you just need to drop his add-in file into the .BuildServer/plugins folder and then restart TeamCity.
You also need to make sure TeamCity is set up to have guest access enabled, which is done from the Administration – Server Configuration page.
Finally, open up CCTray and point it at your TeamCity server’s URL with the following path:
/guestAuth/app/cctray-standalone/cctray/projects.xml

Voila! You should now be able to view your projects via CCTray! Install it on all of your team’s machines (and any project managers or customers who might care to watch the project’s progress) and keep the build GREEN.
There are a number of code analysis tools available for .NET developers, including some stats that are built into the pricier SKUs of Visual Studio. Recently, I’ve been playing with a relatively new product (released earlier this year by Microsoft agile consulting shop NimblePros.com) called Nitriq. Nitriq is a bit like LINQPad for your code. If you’re not familiar with it, go download LINQPad now – it’s a great tool worth paying for. I’ll wait until you’re back…
Back? Great! I think we were discussing using Nitriq for code analysis, which by the way you can run for free on a single assembly. Before going any further, it’s worth mentioning something that many of us often forget or perhaps never learned, and that is that code is data. Some languages, like Lisp, make it very easy to manipulate code as if it were data (and vice versa), but even in static, managed languages like C# it is worth remembering that our code itself is data that we can query, analyze, and from which we can learn.
So before we go any further, what kinds of questions might we ask of our code? One of the best use cases for such code analysis is to find code smells, anti-patterns, and other things that would generally indicate a lack of quality. Static Cling is one-such anti-pattern I’ve described previously that it would be great if we could detect it.
Static Methods That Instantiate Objects
var results =
from m in Methods
let ConstructorCalls = m.Calls.Where(
callMethod => callMethod.IsConstructor).Count()
where m.IsStatic && !m.IsConstructor && ConstructorCalls > 0
select new { m.MethodId, m.Name, m.FullName, ConstructorCalls };
There’s nothing inherently wrong with static methods from a testability and code quality standpoint provided they are leaf nodes in your object graph. It’s when they start newing up objects that things tend to become tightly coupled and you start down the path toward the Big Ball of Mud architecture. So, being able to find static methods that instantiate objects would be a worthwhile query to run. It’s likely there are a few static methods that deserve to be made into instance methods on classes, and whatever objects they’re instantiating could probably be passed into the method or the new class’s constructor using dependency injection. (I’m a big fan of keeping things loosely coupled by explicitly declaring dependencies – if you’re interested I have a few posts on dependencies).
I know from experience that finding these kinds of static methods and cleaning them up is a very worthwhile exercise and will result in a better system. The time to clean it up is usually either when you have some extra time in an iteration, or when you’re already touching the code in question – I don’t generally advocate spending large amounts of time purely on cleanup. Customers like to see fixed bugs and new features, and delivering customer value needs to be the top priority. But being able to maintain the ability to deliver that value requires keeping our codebase tidy – so clean up these dust bunnies when you encounter them.
General Stats
The code I’m running Nitriq on at the moment has the following stats (see image at right). I’m analyzing 3 related assemblies in an ASP.NET web forms application. You can see that these 3 “core” assemblies being analyzed have a total of 81 namespaces, 1067 types, 8876 methods, etc. The total physical line count is about 64k. These assemblies call other assemblies that aren’t included in the analysis, including third party DLLs and of course the .NET framework itself. All told, that includes another 40 assemblies and another 2608 methods that aren’t directly included in the analysis, but are used by my assemblies.
Running the query above to seek out static methods that instantiate objects, I get 228 such methods. This works out to about 2.5% of the total codebase, which is pretty small, but in looking at the actual methods returned I immediately recognize several that I’ve struggled to test or refactor in the past, so I know I can make it better.
Trouble Methods
A number of computer science papers have linked cyclomatic complexity and line count of methods and files to the number of bugs occurring in these methods or files. More recently, some papers have attempted to link design flaws with defect incidence, with some success[1]. There Naturally if the likelihood of bugs per lines of code is constant, one would expect there to be more of them in longer files than in shorter ones, but in fact the bug rate per line of code increases with the length of the file[1]. Unfortunately, accurate prediction of software defects is a difficult problem, as this 11-year-old IEEE Critique of Software Defect Prediction Models indicates[2]. But until we have better tools, it remains useful for us to attempt to keep our code neat, clean, and as simple as possible (but no simpler).
One of the design flaws noted in D’Ambros’ paper is Dispersed Coupling, which relates to the number of other types used by a particular class (or method). We can pull out this information, along with other useful data points like LOC, cyclomatic complexity, and parameter count using the following LINQ query against our code:
Methods to Refactor
var results =
from method in Methods
where (method.Cyclomatic > 25 ||
method.PhysicalLineCount > 200 ||
method.TypesUsed.Count > 30 ||
method.ParameterCount > 7)
&& method.Type.IsInCoreAssembly
select new { method.MethodId, method.Name,
method.Cyclomatic, method.PhysicalLineCount,
OutTypes = method.TypesUsed.Count,
method.ParameterCount };
The intuition underlying the Henderson-Sellers method of calculating Lack of Cohesion of Methods (LCOM) is that in a cohesive class C, many methods access the same fields of C. Formally, let
- M = set of methods in class
- F = set of fields in class
- r(f) = number of methods that access field f
- ar = mean of r(f) over f in F
We then define LCOM of the class under consideration to be
LCOM = (ar - |M|) / (1 - |M|)
var results =
from type in Types
let methodCount = type.Methods.Count
let instanceFields = type.Fields.Where(f => !f.IsStatic)
let fieldAccesses = instanceFields.Select(f => f.GotByMethods.Union(f.SetByMethods).Distinct()
.Where(m => m.Type == type).Count())
let accessAverage = fieldAccesses.Count() == 0 ? 0 : fieldAccesses.Average().Round(2)
let lcomHS = ((accessAverage - methodCount) / (1 - methodCount)).Round(2)
where lcomHS > .9 && instanceFields.Count() > 0 && type.IsInCoreAssembly
orderby lcomHS descending
select new { type.TypeId, type.Name, lcomHS, methodCount, fieldCount = instanceFields.Count(), accessAverage, type.FullName };
&& !type.FullName.Contains("Web")
Piece of Chalk $1.00
Knowing What To Mark With It $49,999.00
References
[1] On the Impact of Design Flaws on Software Defects, D’Ambros, Bacchelli, Lanza
[2] A Critique of Software Defect Prediction Modules, Fenton
Getting Started with Code Contracts in VS2010
The idea of Design By Contract has been around for quite a while, and Microsoft Research has had a project focused on this topic for several years now, called Spec#. With Visual Studio 2010, there is now support for Code Contracts which are a DevLabs project based on the Spec# project. You can read more about and download Code Contracts for VS2010 here.
Once you’ve downloaded and installed Code Contracts, you’ll have a new tab in your VS2010 projects:
With the Code Contracts installed, you can start to use them in your code in place of things like guard clauses to ensure that a parameter is not null. The benefit of this approach is that you get a richer experience at design/development time and you can also ensure, via compilation errors, that certain things simply cannot occur in your application.
Code Contracts uses the notion of PreCondition and PostCondition (among other things) to define what a method expects, and what it claims will be the state of things once it has completed. As a simple example, consider this method that formats a Customer object and returns a string:
public class TextRenderer
{
public string RenderCustomer(Customer customer)
{
Contract.Requires(customer != null, "customer must not be null");
return String.Format("{0} - {1}", customer.FirstName, customer.LastName);
}
}
Note the first line of the method is using Code Contracts (found in System.Diagnostics.Contracts) to state the requirement that the Customer parameter not be null. With my current settings, this requirement doesn’t cause a compilation error, so I’m able to still build and run my tests that demonstrate that I expect a NullReferenceException from such behavior:
[TestClass]
public class TextRendererShould
{
[TestMethod]
public void RenderCustomerWithName()
{
var customer = new Customer() { FirstName = "Steve", LastName = "Smith" };
var renderer = new TextRenderer();
var result = renderer.RenderCustomer(customer);
Assert.AreEqual("Steve - Smith", result);
}
[TestMethod]
[ExpectedException(typeof(NullReferenceException))]
public void BlowUpWithNull()
{
var renderer = new TextRenderer();
var result = renderer.RenderCustomer(null);
Assert.AreEqual("Steve - Smith", result);
}
}
However, in Visual Studio since I’ve set the project to show squigglies for contract violations, I do see this:
These same warnings are also present in the compiler output, and of course we can choose to treat warnings as errors if we want the build to fail when these rules are violated:
Code Contracts are pretty easy to get started with, and there is support for VS2008 as well as VS2010 so even if you don’t have the latest Visual Studio you may want to check them out. The documentation is pretty good, too. Read the User Doc PDF to see more examples of how to get started with Code Contracts to improve the quality of your code today.
Screencast and Podcast Recording Gear
I’m working on some screencasts and have had some gear recommended to me that I’m ordering now. I’ll post back later with an update on how I like these, but if anybody else is interested in what I’ve been told is the best stuff to get, here you go.
Microphone
The microphone of choice is the Rode Podcaster, pictured at right. It has a built-in pop filter, so no need to pick up one of those. This is a USB microphone and doesn’t require any additional boxes or cables. From the product description:
Seamless integration was the idea, and it was obtained by creating a studio dynamic microphone with unparalleled A/D converters, so that the microphone can be plugged into any computer with no in/out boxes, no expensive pre-amps, just a USB cable.
This is currently $229 on Amazon.
Mount
The microphone doesn’t come with anything but, well, the microphone (so I’m told). So, you need something to stick it to, and that’s where the Rode PSM 1 Shockmount for Podcaster comes in. This particular model is:
…optimized for use with the Rode Podcaster. Shockmounts prolong the life of your mic and can remove unwanted low frequency rumble.
We definitely don’t want unwanted rumbles, so we’ll throw this into our cart, too ($39).
Stand
People who know things about this stuff tell me that putting a mic on stand directly on your desk (where you’re probably going to be doing some typing) is a BAD PLAN. Thus, some kind of boom mic stand is a good way to go. A friend of mine says he actually went the route of going to a music store, picking up a standard floor mount for a mic, and then mounting it upside down from the ceiling. That sounds amazingly cool, but I’m looking for something a bit more flexible to my office layout, so something I can attach to my desk far away from where I type seems like a good way to go. Thus, the Rode PSA 1 Swivel Mount Studio Microphone Boom Arm looks like a good choice.
Assembly
I don’t have any of these yet, but when I do I’ll try and update this post with some pictures and/or comments on how it all comes together.
Sadukie tagged me with her books post a couple of weeks ago and I’ve been meaning to respond with a post of my own. I have a post I update periodically that includes some of my most recommended developer books (where I’ve been meaning to add Agile Principles, Patterns, and Practices in C# by Robert and Micah Martin) – if you’re looking for ways to improve yourself as a software developer I would start there.
Currently Reading
Right now I’m reading Disclosure, by Michael Crichton. I’m a fan of his stuff, and in the last year I also read Next, State of Fear, and A Case of Need. I’ve also been reading a lot of James Rollins novels (which Michelle got me started on), which are good light entertaining reads. I’ve read Deep Fathom and Sandstorm and Amazonia, and I think my next one is Map of Bones, which I’ve not yet started. Deep Fathom is a good one to start with if you’re so inclined. The Percy Jackson books, which I read shortly after my then-7-year-old daughter read, were also fun and entertaining.
Digital Reader
My wife got me a Nook for Christmas this past year, and I took it on several trips and loaded it with a few books from the library and PDFs of things I wanted to read later. It worked pretty well at first, but I have to say I’m not very happy with it at the moment. It keeps getting into a state where I can’t turn it on or interact with it. I won’t bore you with the details of all the various rituals I’ve gone through in terms of charging, connecting to AC vs. PC for power, resetting, etc. but suffice to say it’s been rather frustrating (even moreso than trying to get it out of its original packaging, for which there are videos to show you how to do it). In short, I think I would rather try a Kindle, or maybe even an iPad, in lieu of this device. The one thing that it has that’s cool, which I’m not sure the other devices support, is grabbing digital books from the local library. But of course when you can’t get the thing to turn on, the allure of such things fades.
Recommendations
One book I really enjoyed reading last year is Zen and the Art of Motorcycle Maintenance. I’ve been meaning to blog about the book and its relationship to Software Craftsmanship (which, by the way, there’s a group that meets in Hudson Ohio monthly to improve themselves in this regard), and hopefully I’ll get that done soon. However, whether you’re a software developer or not, this is certainly an interesting book to read. There are some great lessons about quality that I think are worthwhile for any reader.
Also, though they’re not books, I highly recommend the web comics XKCD and Calamities of Nature for geeks.
Tag!
So what are you folks reading these days?
Working with Application Pool Identities
There a new feature of IIS called Application Pool Identities that was apparently introduced with SP2 of Windows Server 2008. There’s a nice overview of Application Pool Identities here, which is the basis for this post, which is just my notes on the feature.
If you’re setting up new web sites and application pools in IIS on Windows Server 2008, it’s likely they’ll default to ApplicationPoolIdentity, like this:
This is all well and good, and for the most part you don’t need to care about how this works behind the scenes or why it’s different than the other bazillion different esoteric accounts you’ve had to know about over the last 10 years when setting up IIS for ASP.NET (IUSR_MACHINENAME, NETWORKSERVICE, IUSR, etc.). The most recent installment in IIS user best practices, before ApplicationPoolIdentity, was NETWORKSERVICE:
NETWORKSERVICE is a built-in Windows identity. It doesn't require a password and has only user privileges; that is, it is relatively low-privileged. However, a problem arose over time as more and more Windows system services started to run as NETWORKSERVICE. This is because services running as NETWORKSERVICE can tamper with other services that run under the same identity. Because IIS worker processes run third-party code by default (Classic ASP, ASP.NET, PHP code), it was time to isolate IIS worker processes from other Windows system services and run IIS worker processes under unique identities.
Got that? The NETWORKSERVICE account was low-privileged, so it was a best practice to use it. But unfortunately, since so many apps followed this practice, it became likely that NETWORKSERVICE would have too much access to a variety of applications/processes, so something new had to be used.
Enter Application Pool Identities. On IIS7.5 on Windows Server 2008 R2, your application pools will run with their own individual identity, each of which is actually a virtual account created with the same name as your application pool. You may see these accounts in the ACLs for the files in your web site, and you’ll need to know how to reference them yourself if you want to configure security settings for your site correctly (e.g. to allow users to upload files to your web application). They are not actually users or accounts, so they will not show up as a user in the Windows User Management Console.
For example, if you look at the Security settings for a particular filesystem object in your web application, you might see something like this:
Note, though, that if you go looking for these users on the server, you won’t find them. If you choose to change permissions by clicking Edit, then Add, then change the location to your server (if it defaults to a domain), then Advanced, and finally Find Now (yes, that’s a lot of buttons), you WON’T SEE THESE ACCOUNTS:
So where are they and how do you add them?
You have to know the secret, which is to prefix Application Pool Identities with
IIS AppPool\
Thus to grant rights to the DefaultAppPool you need to use
IIS AppPool\DefaultAppPool.
If your application pool is named mywebsite.com, then your identity would be
IIS AppPool\mywebsite.com
When they appear in your ACL list, the IIS AppPool won’t be listed. This is to ensure greater confusion on your part, because you don’t have enough things to try and remember as a web developer and/or server administrator. If you type in the correct value and then click Check Names, it will remove the IIS AppPool\ prefix and underline the account name for you, like so:
Hope this helps! For more info I suggest reading this article on Application Pool Identities.
Also, don’t forget you can follow me via twitter, email, or RSS.
Software Engineering 101 in Cleveland
Next week I’ll be one of several speakers at a free one-day event being held at the Microsoft office in Independence, Ohio. The event is designed for Microsoft developers who are seeking to improve their skills in software engineering, including object-oriented design, design patterns, and automated testing. The event is being hosted by Microsoft and organized by the Hudson Software Craftsmanship group and NimblePros consulting services.
Initially there were 50 slots available – I think there are about 15-20 left as of today. The event is scheduled for 16 July 2010 from 830am to 4pm, so if you can get approval to come for some free hands-on training, sign up fast before it’s sold out.
You can register for the event and view the agenda here. If you’re planning on attending the Cleveland Give Camp, there will be a number of folks going to both, and the SWE101 event should wrap up in plenty of time to make it to the GiveCamp.

Download the PDF