Code Generation with LINQPad 4

Today I encountered a task at work that offered the prospect of some pretty dull development work–code that needed to be written that was almost the same in multiple cases (but not quite).  It seemed like work that could benefit from the use of T4 templates, but quickly became frustrated by the process of setting up and debugging a template.  The interleaving of angle bracket markup with code was never fun in XML, and T4 templates began to resemble that very quickly.

So after abandoning the T4 template approach, I fired up LINQPad to see if I could accomplish my goal in that.  As it turned out, writing a small C# program in LINQPad for code generation was a lot easier.  I just needed to remember two key things about string substitution in verbatim string literals.  Here they are:

  1. Curly brackets need to be escaped.  So “{” should be “{{” and “}” should be “}}”.  Not doing this will result in a FormatException.
  2. Double quotes need to be escaped.  So ” should be “”.

Beyond that, it was a matter of writing a code template inside a verbatim string literal (@”<code template goes here>”) with format items where needed ({0},{1},…).

I’ve made a code sample available as GitHub gist here.  So far, I’ve used this technique to generate nearly 20 files in a fraction of the time it would have taken to write them manually.  Very little manual tweaking of the files was needed after generation, which left more time to test the generated code in real scenarios.

Infinity, Epsilon and NaN

I inadvertently learned some new things about the .NET double struct while refactoring some code over the past couple of days.  A large set of test data we received recently revealed that we weren’t correctly handling the following edge cases of body mass index (BMI) calculation.

  • Edge case 1: a height of zero inches
  • Edge case 2: a weight of zero pounds and a height of zero inches
  • Edge case 3: a weight of zero pounds and a non-zero height

Incorrectly handling the first case resulted in an overflow exception in our code, but only because it tried to pass the result of a BMI calculation that returned the constant PositiveInfinity into another method.  To handle this condition more gracefully (since a height of zero inches and/or a weight of zero pounds are considered valid inputs), a check for PositiveInfinity is needed.  The .NET framework provides the static method IsPositiveInfinity for such comparisons.

Incorrect handling of the second case caused an error as well.  But this time the BMI calculation returned the constant NaN.  Like PositiveInfinity, NaN has a static method to check for it (IsNaN).

Enough time has gone by (and enough code changes have taken place) since I first started this post back in September that I don’t recall precisely what the original code did in the third case.  Under normal circumstances the BMI calculation would return zero, but our implementation returns the NaN constant if the BMI (or inputs to it) falls outside what are considered valid ranges.

Advice for Aspiring Software Engineers

Last night, I gave a talk at Towson University to a section of software engineering students (a friend of mine is their professor).  The goal of the talk was to share advice and experiences that would help them in their careers.  What follows is the notes I spoke from, with revised and extended remarks (indicated by [extra]).


  1. Intro/bio
  2. Internship(s)
  3. Interviews(s)
  4. Work
  5. Beyond Work
    1. Keep in touch
    2. Keep learning
    3. Keep your skills sharp


Imagine being paid to test drive a car for 12 weeks.  That’s what an internship is—the only opportunity you may have in your working life to take a job and a company for a 12-week test drive.  You’ll get to see if you like the day-to-day of your particular role.  You’ll get to see if you like your boss, your co-workers, the culture of the organization.  When you are choosing your first real job, they can be a very useful filtering mechanism to determine which companies you should consider seriously and which ones you should skip.  If an internship works out really well, that company could give you your first full-time job.

If at all possible, don’t graduate without one.  A successful internship puts you ahead of recent college graduates without one because you have proof that you can do real work.

Internships are also a great opportunity to begin to build networks beyond your classmates.  Even if you’re a natural introvert, make an effort to be social.  You never know when a friendship might result in a reference, an interview, or a job—for you, or a friend you make.

I was an intern at The Washington Post the summer before I graduated from Maryland.  Halfway through the summer, they asked if I could return in the fall as a part-time employee and I accepted.  At the end of the year, the Post made an full-time offer for a help desk position.  I got better offers and took one of those instead, but I have no doubt it would have been much harder without that internship and part-time experience.

[extra] I said during the talk that all other factors being equal, the candidate with an internship wins over the candidate without one.  To be more complete, I should have said that a candidate with a lower GPA and an internship can and does beat a candidate with a higher GPA and no internship.  My undergraduate GPA was just shy of 3.0.  But because I had a successful internship, 4 months of part-time work experience at the same company, and a great reference from my boss, I had multiple offers before graduation.


When it comes to interviews, expect to be asked about anything and everything on your resume.  So if you can’t back it up in an interview, don’t put it on your resume.  I interview people for jobs on a regular basis, and always ask questions to find out if they really know all the things their resume claims.  If you have an internship under your belt, you’ll have real work experience to put on that resume.

Also expect to write code on the spot for a problem you’ll have had no advance notice of.  If you’re not asked to write it on a whiteboard, the interviewer may just put a laptop in front of you with an editor and wait for you to write it.  In interview situations like these, it’s very important that you verbalize what you’re thinking as you develop your solution to the problem.  If you stare at the whiteboard or the laptop for a long time without saying anything, the interviewer might think you’re stumped—even if that isn’t the case.  If you aren’t sure about some aspect of the question, it’s better to ask for clarification and be sure than to assume and be wrong.  I ask a simple LINQ problem in every interview—and nine times out of ten, the candidate gives the wrong answer because they assumed they knew what I was asking for instead of making sure.

[extra] The following is a version of the LINQ question I ask in interviews:
Given the following:
var listOfNumbers = new List<int>{3,6,9,12,15,18,21,24,27,30,33,36};

write the LINQ statement that returns every number in the list divisible by 12 and by 6.


Software engineering involves a lot of collaboration.  In my role, in order to develop a single feature or piece of functionality, there could be a handful of other people involved:

  • business analyst
  • other developers
  • project manager
  • program manager
  • tester

In addition to being able to write software well, it’s just as important—if not more so—to be able to communicate clearly and effectively and listen actively.  As a software engineer, that means:

  • Regularly updating your teammates and bosses on your progress
  • Asking for help if you’re stuck
  • Informing business analysts about missing, incomplete or unclear requirements
  • Informing project managers if you’re going to miss a deadline
  • Writing estimates of how long a task will take

I do all of things in my job, in addition to helping other developers on the team, designing and implementing software, and testing.

We’d all love to work on brand-new software, but most of us won’t get the chance.  It is highly likely that the first work you do will be maintenance of and/or enhancements to an existing system.  So developing an ability to find bugs in software (whether you originally wrote it or not) will be important to your success as a software engineer.

Beyond Work

Keep in touch, keep learning, keep your skills sharp (and add new ones).  That’s a basic summary of the steps you need to take to go further in your career as a software engineer.

It is impossible to overestimate the importance of networking to your career (and I don’t just mean having a huge number of Facebook friends, Twitter followers, or LinkedIn connections).  By networking I mean staying in regular touch with people you’ve worked with in the past or know from school that you’ve enjoyed working with (and would like to work with again).  If you’re in the same geographical area, catch up with them in person once a year if you can manage it.  If you don’t live in the same area, go beyond a word or two on Facebook.  Don’t be the guy or girl who only checks in when they need something.

Having a strong one will not only bring you a wealth of useful advice and support when you need it, it will help you find work too.  A couple of examples from my own experience:
a. I worked with a guy named Dave at USWeb.  We worked together for a couple years before I left and the company folded.  We kept in touch off and on over the years, but hadn’t had regular contact in awhile.  Over 12 years after we actually worked together, he gets in touch because he’s looking for a job and trying to decide between two companies—the one where I currently work, and one I worked for previously.  I tell him my current company is better (not just trying to be a good company man, my former employer was terribly dysfunctional) and write up a referral for him.  He gets hired and over a year later he’s still having a great time.
b. Two other guys I worked with at USWeb—Murali and Allen.  One was director of technology, the other a senior developer.  I kept in fairly regular touch with Allen.  So after almost four years at Ciena, I’m looking for a change.  Murali, our former boss, is program manager at a local consulting firm and wants to surround himself with good people from previous gigs.  He contacts Allen first, but Allen likes where he is and isn’t looking to make a change.  But Allen gives Murali my contact information.  I interview, I get hired, I work there a couple of years before moving on to a management role at a different company.

Don’t pass up opportunities to expand your networks beyond classmates and people you’ve worked with in the past.  This area has plenty of software user groups.  They’ll have stand-alone website or be on meet  Join one.  Get to know people that regularly attend.  One of my current co-workers is someone I first met at a .NET user group in Rockville (RockNUG).  A year-and-a-half later, when he got tired of commuting from Maryland to Virginia to work, we talked after a user group meeting about openings at my company.  He’s been there six months now and is doing great work for us.

Figure out how you learn best.  Some of us learn best through reading.  Some through lecture.  Some through examples.  Figure out which one of these you are and spend regular time outside of work learning however works best for you.

Conferences and user groups provide great opportunities to network and learn.  Smart companies use them to raise their profile and to recruit new talent.  The companies I consider the best ones in my career are the ones that sent at least some of their employees to a conference or training every year.  Even when I haven’t worked for companies that pay for employees to get training, I believe it’s important enough that I’ve paid my own way on more than one occasion for a particular conference.  I went to SXSW Interactive last year and met up with former co-workers I hadn’t seen in 10 years.  I met people from all over the world, as well as a few people who were literally across the parking lot from me.  Seriously!  I met a couple of programmers and a designer who work at a small firm in a building less than 100 yards away, but we had to fly over 1500 miles to meet.

Blogs, podcasts and screen-casts provide great learning opportunities as well.  However you commute between home, school and work, it’s time you could spend listening to one of the many podcasts available on technologies or software development.

Starting a blog is a great way to practice and improve your written communication.  I first started back in 2003, and my only purpose was to have a way to remember the process I went through to solve particular problems that I could access from wherever I wanted.  On occasion, I would get a comment or two from others on the web that helped me solve a problem I’d posted about or improved on a solution I’d come up with.  Sometimes a post has been useful to other developers than myself.  I’ve even gotten requests for help in the comments.  Once you have a blog, it also makes a handy place to publish a linkable copy of your resume.  That’s a piece of advice your professor gave me many years ago, and now   I have plenty of visibility to companies (and recruiters) without really having to bother with job boards.

Giving a talk is a great way to practice and improve your verbal communication.  User groups are always looking for people to come and speak, and if there’s a technology that you know well (or want to know well), having to give a talk about it in front of an audience is one way to give yourself an incentive to research it and learn it well enough to be able to answer questions about it.  I try to give a few talks every year to one of the user groups I attend in Rockville.

[extra] Starting a podcast is another option you might consider.  I listen regularly to a few podcasts by veteran software developers (Hanselminutes, .NET Rocks, etc) and learn a lot that way.  But I think we would also benefit from hearing software engineers who are relatively new to the work world, or even from interns.  In addition to creating opportunities to hone both your writing and speaking skills, you’ll get to learn about audio and production.

With the amount of time you’ll spend working (and otherwise living your life), one of the habits that I’ve personally found the most difficult to maintain is writing code regularly that isn’t specifically for my job.  One of the benefits of school, especially in a computer science program, is courses where you have to learn multiple programming languages and produce working solutions in a relatively short period of time.  The diversity of languages is a great way to force yourself to think differently about how to solve a particular problem.  To the extent you make it a habit to learn a different programming language every year or two, the better your skills in your main programming language will become.

Music, martial arts, sports and medicine are endeavors that have practice built into them.  Software engineering doesn’t.  We usually treat our work as our practice.  You will improve more quickly as a developer if you practice designing and building software separately from the work you do everyday.

Practice!  There are plenty of sites out there with different code katas (small problems that you write code to solve).  Larger, longer-term side projects are also a great idea—especially if they’re tied to a hobby or something else that interests you outside of your job.  In addition to these, the web is full of open source projects that could use contributors (github, codeplex, sourceforge, etc).  Try to contribute however you can—even if it’s documentation—and you’ll benefit from the experience.

[extra] When it comes to practice in improving your software engineering skills, it works best if you consistently increase the level of difficulty.  John Sonmez explains why here.  He also links to an incredible example by Jennifer Dewalt.  Programming contests (including things like TopCoder) may be worth your consideration.

String concatentation

Yesterday, Bill Wagner (author of a number of excellent books on C#) wrote a post on string concatenation, string.Format, and StringBuilder.  I found it a useful update to what I previously understood.  I’d written a brief post on string.Format 7 (!) years ago, and at that time I thought string.Concat (a.k.a. “blah blah blah” + “blah blah blah”) shouldn’t ever be used because of the immutability of strings meant a new string was created for each concatenation operation.  Wagner touches on what operations create objects that will need to be garbage collected, as well as providing an example of when string.Concat is actually ok.

(h/t The Morning Brew)



Europe in Winter: Barcelona, Spain (Day 2)

The bus mentioned in yesterday’s post was the Barcelona Bus Turistic.  It turned out to be a lot of fun and would have been an even better value if we’d had the time to book it for 2 days instead of one.  We purchased two tickets for the north-south route via Viator.  Our hotel was conveniently located just a short walk from one of the stops.  The route takes you past every attraction of note in Barcelona, and with the option to get on and off the buses at various points when desired, it’s possible to see a lot of Barcelona this way.  In addition to the bus tickets, we received large coupon books of discounts to a large number of the attractions the bus takes you past.  Another underrated benefit of the bus–good wireless internet access.

One such discount is for the Montjuic cable car, which takes passengers to and from Montjuic Castle.  The views of the city from a cable car are pretty amazing, and the castle at the top is a nice place to walk around a bit, or just sit and relax.  There are many other stops worth getting off to see that I’d like to visit on a return trip, including Camp Nou, the Gothic quarter, and some of the museums.

Tomorrow, we bid a too-soon farewell to Barcelona and fly to Nice, France.

Europe in Winter: Barcelona, Spain

Barcelona is the first stop on our trip to Europe (hotels courtesy of my lovely wife, flights courtesy of me). In our first 36 hours here, we’ve managed to recover from the change in time zones between DC and Barcelona, visit La Sagrada Familia, and visit Park Guell. Both were highly-recommended by the concierge at our hotel (Ritz-Carlton Barcelona, also known as Hotel Arts Barcelona).

Buying tickets ahead of time for La Sagrada Familia is highly-recommended also. We bought a tour with an English-speaking guide on for under 40 euros and probably saved ourselves 2-3 hours of waiting in line to get in. The guided portion of the tour was around an hour–the guide shared a wealth of historical information about the architect (Gaudi), the building, some of the sculptors, Catholicism, and the Bible itself. As someone who appreciates history and churches, the tour was excellent.

Park Guell was quite a bit of walking, but also fun. The monument zone of the park charges admission, which gives you access to some of Gaudi’s interesting outdoor works (along with some shops and restrooms). Once you leave the monument zone however, you can’t return without paying the same fee again. The best views of Barcelona are actually outside the monument zone anyway (if you don’t mind climbing a lot of stairs).

We got to and from both attractions and our hotel by metered cab. Ride costs ranged between 8-12 euros. Only one of the four cab drivers we’ve had so far spoke enough English for us to have a conversation.

Tomorrow, we’ll probably try the 1-day hop-on, hop-off bus and see as many attractions as we can.

Candied Sweet Potatoes 2013

Since the first time I posted a candied sweet potato recipe, I’ve made it a few more times.  What follows is the 2013 version I made this past Thanksgiving (and will probably make for Christmas since family and in-laws have been asking):

4-5 lbs of sweet potatoes
1 20oz can of pineapple (preferably crushed)
1 1/2 cups of dark brown sugar
1 1/4 cup of unsalted utter
cinnamon, nutmeg, & ground ginger to taste

If you only have regular pineapple instead of crushed pineapple, slice it up into small pieces. Otherwise, skip to the rest of the instructions below.
Fill an 8qt pot 2/3rds of the way with water. Bring to a boil. Boil the sweet potatoes for around 15 minutes. Drain and set aside to cool for peeling and slicing later.

In a saucepan, melt the butter (over low heat), add the brown sugar and stir. Add cinnamon, nutmeg, and ginger until the sauce tastes how you want it.

After you’ve peeled and sliced the sweet potatoes, lay down a layer of them, drizzle/smear on some of the sauce, and sprinkle on some of the pineapple. Repeat until you’ve filled whatever casserole dish or foil pan you’re using.

Bake this at 425 degrees for around 55-60 minutes.

Re-Introducing NuGet (and introducing Chocolatey)

Last month, I presented on the topics of NuGet and Chocolatey at RockNUG as the lead-in to David Makogon‘s Polyglot Persistence talk. Since the time I first gave a presentation on NuGet at a previous employer a couple years ago, the package manager has matured quite a bit. Because there was far more than 30 minutes worth of material to discuss, the rest of this post will cover material I didn’t get to, commentary from the audience, and the answer to a question about tags.

In discussing the term package manager, I indicated that it meant more than one thing:

  • automation of dependency management for operating systems (think Unix or Linux distributions)
  • automation of dependency management for programming languages (think Perl’s CPAN, Ruby Gems, Node.js npm)

NuGet is the second type.  I find Chocolatey quite interesting because it’s a package manager of the first type that leverages the capabilities of NuGet to accomplish its work.

NuGet enables us as developers to define and re-define what a third-party dependency is.  The team at Fortigent (one of RockNUG’s sponsors) has made packages out of some of the functionality they’ve developed internally.

There are a couple of different ways to create packages:

The second way is recommended for integration with build systems.  Typing “nuget spec” in the location of the csproj file you want to make a package out of will generate a “nuspec” file (in addition to automatically referencing other files as dependencies).  Edit this file in order to add tags, licensing, links and other information you want to make available in your package.  Typing “nuget pack” followed by the csproj file will generate a file with the .nupkg extension.  The extension merely hides the fact that it’s a ZIP file with some additional information.

In addition to creating packages, NuGet gives us the ability to set up our own package feeds.  The feed can be a simple as a network share with packages in it.  One step up from that is to create an empty ASP.NET Web application and add NuGet.Server to it.  This will add everything to the application needed to host your own packages (or others from third parties).  You can even publish your packages to this type of application if you wish.  The pinnacle of NuGet package distribution is to host your own fork of the NuGet Gallery (available on GitHub).  One software vendor, JetBrains, forked the NuGet Gallery to publish documentation on all the plug-ins available for the latest version of ReSharper as well as make it possible to download ReSharper itself.  Chocolatey uses the NuGet Gallery code in a similar way.  Unlike the ReSharper gallery (which doesn’t let you download plugins), the Chocolatey gallery does allow it (though the actual installs require command-line interaction, which is helpfully displayed next to each package).

One of the NuGet-related projects I found particularly interesting is  Its objective is to recommend NuGet packages in the same way we receive movie, music and product recommendations from Netflix, Spotify or Amazon.  Simply upload the packages.config file for your project and get recommendations back.  I learned about this (and other .NET development-related topics) on The Morning Brew.

Q & A

While there weren’t any questions at the end, there was one asked during the presentation about the “tags” element of the nuspec file inside each package.  When you look at a package in the NuGet Gallery (like EntityFramework for example), you see a list of linkable tags.  Clicking on one actually triggers a search for each package that shares a particular tag.  So if  you’re a package author who wants their package to be discovered more easily, putting the right keywords in the “tags” element will help.

Reducing Duplication with Interfaces, Generics and Abstracts

The parts of our application (a long-term service and support system for the state of Maryland) that follow the DRY principle best tend to start with a combination of generic interfaces inherited by an abstract class that implements common functionality.  The end result–specific implementations that consist solely of a constructor.  I was able to accomplish this as well in one of my more recent domain implementations.  I’ve created a sample (using fantasy football as a domain) to demonstrate the ideas in a way that may be applied to future designs.

Let’s take the idea of a team roster.  A roster consists of players with a wide variety of roles that can be grouped this way:

  • QBs
  • offensive linemen
  • skill position players
  • defensive linemen
  • linebackers
  • defensive backs
  • special teams

Since I want specific implementations that are (very) small, I’ll need to find common attributes between these different groups.  Each roster grouping above is just a list of players.  Things that are common to all players (regardless of position) include attributes like:

  • first name
  • last name
  • team name
  • position

The first three attributes are just strings of text, so I treat them as such in my implementation.  Position could be treated that way too, but instead I’ll implement an enumeration with all the positions and leave the implementation of it to position-specific classes I’ll create later.  Going back to the roster grouping idea as a list of players, we can use a generic interface implemented by an abstract class so that implementations of the groups above will differ only by constructor.  Now, when I implement a Quarterbacks group,  the only differences between it and the implementation of an OffensiveLinemen group are the class names and types.  The RosterGroup class contains all the important functionality, including the IEquatable implementation that enables comparison of groups.  I followed a ReSharper suggestion to make IRosterGroup explicitly covariant.


How can I become a world-class coder in under three years?

I came across this question on Quora today and decided I would answer it.  There were enough up-votes by people following the question that I’m re-posting my answer below:

I’m not sure what the term “world-class coder” means to you.  But I would actively discourage the notion that there is some point you can reach in the practice of software development (whether it’s 3 years or 20 years) where you can look at yourself and say “Achievement unlocked!  I am a world-class coder at last.”  What may give you more satisfaction over time than the question of “where do I rank” in some mythical best coders on Earth list is “Am I a better developer now than I was last week?  Last month? Last year?”

The things that previous commenters have suggested are great ideas for continuous improvement and refinement of your skills in programming.  Do as many of those things as you can.  Beyond those, I’d suggest the following:

  • Be willing to learn from anyone.  I’ve made my living writing software since 1996 and I regularly learn new things about my craft from people a decade or more younger than me.

  • Keep track of what you learn–and share it.  Whether it’s through blogging, Stack Overflow contributions, or something else–write about it.  You may not encounter the exact problems you’ve solved in the future, but they will often be close enough that what you’ve captured will help you solve them much faster than you would have otherwise.  The ability to explain what you know to others is a very valuable and rare one.  The process of preparing to give a presentation to others on a topic has often been a good forcing function for me to learn that topic to the level where I can explain it well.

  • Learn about subjects beyond programming.  The importance of the ability to understand new domains well enough and deeply enough to design and implement useful software for them cannot be overstated.  I’ve delivered software solutions for news organizations, healthcare companies, marketing companies and defense/intelligence contractors in my career so far.  Making myself familiar with the sort of terminology they use and the way such companies operate (above and beyond a specific project) definitely results in a better end product.  One or more such topics can end up being great fodder for pet projects (which are great vehicles for learning things you aren’t already learning in a job).

Proudly powered by WordPress
Theme: Esquire by Matthew Buchanan.