Software Craftsmanship

Followup from CodeRetreat

WP_20121208_003

Code Retreat gets underway at Pluralsight in Lehi, Utah

Last Saturday, as part of the Global Day of Coderetreat (GDCR), Utah held it’s third Coderetreat. I was unable to attend the first two so I was looking forward to the day’s activities. Coderetreat was started by Corey Haines as a “day-long intensive practice event, focusing on the fundamentals of software development and design.” In other words, you should come out of Coderetreat being able to write better code. The idea of GDCR is for multiple locations around the world to host the event on the same day. This year, around 160 cities world wide had events. There were 41 locations in US, with three in Utah. Two were hosted by Pluralsight and the other by Domo. I opted to attend the one at the Pluralsight office in Lehi. Thanks to @davidadsit for organizing the local events and @utahkay for facilitating the location I attended. Also, thanks to the host companies and the other sponsors for making the day possible.

So, what was the day like? It was all hands-on. Each person brought their own laptop and got it setup. Kay did an introduction and told us that we’d be working in pairs and have six rounds of coding. Each round would be spent with a different partner. Most attendees were C# developers, but we also had someone doing SmallTalk, Objective C, and even one person trying F# during the day. Each session we were to work on Conway’s Game of Life. The goal was not to solve the problem, but use TDD and pair programming to work through the problem. We only had 45 minutes to work, so solving the problem was not going to happen. As we went along, each session had some issues thrown into to mix things up and add some challenges. For example, we couldn’t use parameters or primitive types. Or, there were Zombies, that is, when a cell died, it stayed dead for three iterations, then came to life.

People have asked me if it was worth taking a Saturday of my time to do this. I will say absolutely. I walked our mentally exhausted, but the learning and professional improvement is still with me. I hope to attend again next year.


Code Review Checklist

Earlier today on one of the forums where I hang out, I got into a discussion of code reviews. I mentioned that I recently put together a brief checklist for my company. One person asked about it, so here it is.

  • Are there things that can degrade performance
  • Do you find any infinite loops
  • Are Else and Switch Default conditions in place
  • Is there duplicate code or conditions
  • Has usability of the finished product been considered
  • Are calculations correct
  • Is the code readable
  • Does the code follow best practices and company guidelines
  • Are comments clear, meaningful, plentiful, and not overdone
  • Are complex algorithms and corner-case input clearly commented
  • Are there refactoring opportunities
  • Did you perform psychic or intuitive review (the code just feels wrong)
  • Are unit tests provided for areas where needed
  • Is the class design secure
    • Are variable scope and method visibility limited
    • Are non-base classes sealed
    • Are properties used to expose fields
    • Does the code use read-only properties
  • Is exception handling implemented correctly, including exception reporting and a proper page displayed to the user
  • Are protections against cross-site (XSS) scripting implemented
  • Are protections against SQL injection implemented
  • For public-facing web sites, have connection strings been encrypted

If you want to learn more about code reviews, look at these references

Best Kept Secrets of Peer Code Review”, Jason Cohen, 2011, published by SmartBear Software

Effective Code Reviews Without the Pain”, Robert Bogue, 2006, Developer.com

Running an Effective Code Review”, Esther Schindler, 2008, CIO.com


Integrating FxCop in TeamCity

Static code analysis is a valuable tool to find many errors in your code. What is static code analysis? It’s a process to analyze the code or assemblies themselves rather than testing the application by running the code. Hence, the analysis is static. There are a couple of free tools that allow you to do static code analysis on .Net code. The first, FxCop analyzes the generated assemblies. It checks assemblies for correctness, library design, internationalization and localization, naming conventions, performance, and security issues. The second tool, StyleCop analyzes that actual source code. I’ll discuss it in a future post.

To get FxCop, you need to download and install the Windows SDK. Once that is done, run %ProgramFiles%\Microsoft SDKs\Windows\v7.1\Bin\FXCop\FxCopSetup.exe to install FxCop. You should do this on both your development machine and your build server. You’ll now have an FxCop entry on your start menu. Use it to launch the FxCop GUI.

I won’t go into how to use FxCop or interpret the results. This is will docmented in the FxCop help file and also here and here. You should create a new FxCop project for each Visual Studio solution that you analyze. You should save the FxCop project file with your solution and check it into version control. We put it in the same folder as the Visual Studio solution file.

We also set a few FxCop project options. To so this, right-click on the FxCop project and select Properties.

On the General page, you should enter the name of your project. This keeps things need and tidy. You may be tempted to check Apply style sheet when saving report. However, when you check this option, it will cause TeamCity to not include the analysis report in its HTML output. You can still get to the report, but it will be presented as raw XML.

The next settings we made are on the Spelling & Analysis page. We checked all the options.

Next you need to select the Targets to add. These are the assemblies generated when you build the solution. There is no need to include Microsoft and third-party assemblies. That will generate too much clutter in your results. Just select the assemblies generated as part of your code. Remember that the location of the assemblies may be different on the build server than on your development machine. For example, our build process  does not generate a Debug version, only Release. If you create MVC applications, you can point to the assemblies in the Bin folder. Because this location is saved with the FxCop project, you need to save a location that’s avalailable on the build server. The location saved is relative to the FxCop project file.

When you have everything working, make sure to save your FxCop project file and then check it into your version control system. Now it’s time to setup Team City to run the analysis.

You probably don’t want to run code analysis with every build, especially if you are doing Continuous Integration (CI) with every checkin. Static code analysis is a good candidate for your nightly build. It should also run only after the build successfully completes and unit tests pass.

Modify the TeamCity project and add a build step. Here’s how we have things setup.

The Installation root is where FxCop was installed on the build server. We are using the FxCop project file because this makes it easier to manage. The developer is responsible for their Visual Studio project and by referencing the FxCop project, we don’t have to modify the TeamCity project when assemblies are added.

Now when you run the build in TeamCity, you’ll get FxCop results as part of the build. The TeamCity home page reports the results. When you drill-down into the Code Analysis, you’ll find a complete list of issues that were found.

And there you have it. The basics of running FxCop as part of your TeamCity CI process.


When Good Code Intententions Go Bad

What is good code? If it gives the correct result, but takes a convulted route to get there, is the code good? I’ve maintained for years that if the code yields the correct result, the code is right, but it must be performant and written following best practices and coding guidelines to be good.

I’ve recently been doing maintance on an old application. This is a C# WinForms application. It uses Click Once for deployment and all data access is via WCF services connecting to SQL Server on an internal server. The nature of the maintance is to yank out all the WCF and replace with direct SQL calls. (It’s not that WCF is bad, but it’s over kill for this app and it was poorly implemented.) Yesterday, I came across two examples of bad programming. So bad, that I had to share.

Here’s the first. I was looking through the data update code and found a method in a particular class. The first line in the method is:

if (true)

Um.. ok. If anyone can make a case that true can be false, I’ll put this line of code back in.

The second is much worse. It was an overloaded class constructor. One of the overloads had 144 parameters. Yes, you read that right. 144 parameters. It was a class that mapped to a table in the database, each parameter is a field in the database. What did this method do? Saved the value of each field to a property on the object. This code was written pre-Entity Framework, but what’s wrong with using a DataTable and pass that around? Here’s some advice for you. Anytime you get more than four or five parameters, it’s time to rethink the entire structure of the method and maybe even the class itself.

I’m back working on the app today, but I’m almost afraid to go back in. I have no idea what else is lurking in the depths of this code.


Reading List for Programming Improvement

Yesterday I had the honor of speaking at Desert Code Camp in Phoenix. In one of my sessions, I was asked about books to improve your skills as a developer. No doubt that I will miss some that should be on this list, but any one of these is a good place to start.

In putting this list together, I found this book, due to be released the end of May. I have it on preorder.

The Clean Coder: A Code of Conduct for Professional Programmers

In case you’re wondering, here’s what I’m reading now

Programming Entity Framework: Building Data Centric Apps with the ADO.NET Entity Framework

1 Comment more...

Utah Software Craftsmanship Group, Feb. 2011

Earlier this week I attended the monthly meeting of the Utah Software Craftsmanship Group. This new group is organized to help you develop your skills, no matter what language or technology you use. As the group is new, meeting format is still a work in progress, but I like what’s being done so far.

So, what did you miss by not being there?

First up we had three lightning talks. These are 15 minute presentations. I found them interesting. Note that we only had two because one presenter couldn’t make it.

First up was a presentation called “The Boy Scout Rule”. The idea for this came from “Uncle Bob” Martin. Think about the old, unwritten Boy Scout rule to leave a camping place the same as you found it. The new rule is to leave the place cleaner than you found it. Applying this to software, clean up messy code. Stuff that smells. Make your code enhancements look like they belong instead of something that 12 people has touched.

In lightning talk two, the presenter talked about what Software Craftsmanship means to them. He had four points:

  1. Continuous Learning – This includes reading, blogging, writing papers, articles, books, magazines, group attendance, conferences, and other activities.
  2. Continuous Improvement – Apply what you learn. Have personal retrospectives. Experiment with things that you learned.
  3. Conscientous Work – Don’t purposely create a ball of mud. Use principles like SOLID, clean code, unit testing, refactoring, and the Boy Scout rule.
  4. Knowledge Transfer – Do things like mentoring, writing, blogging, papers, presenting, training, books. This may sound alot like Continuous Learning, but here you’re doing things for others, where with Continuous Learning, it’s for you.

The next thing on the agenda was a book discussion. We have chosen Apprenticeship Patterns for our first book. You can also read the entire book online for free. Because we’re still feeling out how our meetings work, we discussed the book as a whole rather than a single chapter. However, it was decided that we’ll discuss just Chapter 2 next month.

Some concepts from the book that were discussed include Be the Worst, Breakable Toys, Exposing Your Ignorance, and three levels of progression: Apprentice, Journeyman, and Master.

The last thing we did in the meeting was a Code Kata. A kata is a term from martial arts that basically means practice. So, we took a problem and learning how to work through it using TDD techniques. We did the Prime Numbers Kata and worked through it in C#. Next month we’ll do the same kata in Ruby. You should do a kata a few times a week to improve your skills.

I hope you can join us next month. You can get more information on the Utah Software Craftsmanship Group from our Google Group.


Brownfield Development

Earlier this month, I spoke at the Prairie DevCon in Regina, SK. The last day was a fantastic all day seminar on Brownfield Development by Donald Belcham, coauthor of a book on the topic. A Brownfield project occurs when you have an existing application that you are actively updating and fixing. Sound familiar? It should. Most of us work on Brownfield projects. Greenfield is brand new development on an new product. A legacy project is one that you rarely update, providing only critical bug fixes. In this post, I will summarize the seminar and hopefully give you some valuable information to help with your project and reduce technical debt.

The most important thing to remember when working on a Brownfield project is “Context is King”. In other words, always ask yourself, “Self, why did they do things the way they did?” By asking this question, you’ll understand much about the project and how to best enhance it.

Step 1 in your process is getting an automated build going. This is the single biggest thing you can do to improve your process and improve the application without touching the code. I’ll come back to this in a moment.

Step 2 is to run automated tests. Many QA departments run automated tests, but do you have automated unit testing? You nott have any unit testing or very little or not testing the proper areas of your code. Identify the trouble areas of your code first and devise unit tests for them.

Step 3 is to get your release package inot your automated build. Creating and testing the release package should not be a manual process. There are too many things that can go wrong in a manual process. It’s too easy to miss things or even include things that should not go out to the customer. Also, make sure your install scripts and other release tools, scripts, and artifacts get put into source control.

Does your product include a database? Are you managing it well? Do you have scripts to create and alter the database schema, create stored procedures and functions, security, etc? Are those scripts in your source control? Do you have automated testing setup on those scritps?

How is your development environment setup? Do you have it virtualized so that one version of the application doesn’t interfere with another?

I assume you are using Source Code Control (SCC), but are you using it properly? Do you know all the capabilities of your SCC tool? Do you know how to do everything the SCC tool does? What about branching and merging? Is it simple? Can you do it? Does it case great pain? Is it difficult to merge code from one engineer with that of another? How often do you check in? By checking in frequently, you will reduce merge problems.

What is your automated build, or even better, are you practicing Continuous Integration (CI)? [Note: I am coauthor of the book "Continuous Integration in .NET"]. You’ll get immediate feedback on your project, which will reduce risk and help you make a better product for our customers.

If you take on a new Brownfield project, the first thing you should do is look at the build script, release management processes, etc. You’ll learn alot about how the application is built and prepared for the customer. Next you should run the tests in the code. This will show where code issues may exist. If you get lots of problems with these items, odds are you’re in trouble already on the project.

When fixing bugs, identify the pain points and devise unit tests. Look for fear in the eyes of current team members when you suggest modifying code in a particular module. This fear tells you that they don’t want to touch that code because it is very brittle and will break with the smallest of code changes. These are areas that can benefit most from unit testing.

Do you have unit tests and are your running code coverage to know that the unit tests are really testing the code efficiently?

Are you doing proper defect analysis? Things like bug counts don’t tell you much. You need to look at areas where bugs come from. Does one module get more bug reports than another? Are bug reports coming from QA or from customers. These are the things that tell you the most.

Is the application well architected? (Odds are it isn’t according to today’s standards.) When you hear about three tiers, that refers more to a physical layout. Layers is more logical. Look at Domain Driven Design to help out here as it greatly simplifes complexity.

The UI layer should use a standard UI design pattern such as Model-View-Controller (MVC), Model-View-Presenter (MVP), or Model-View-ViewModel (MVVM) in the case of Silverlight and WPF.

The business layer should be divided up into different layers itself with Services (connecting to external resources, but not data), Translators (data processors), Domain Model (business rules), and Repositories (data access/store) making up the main concerns and aspects cutting across them. For example, a logging utility, that’s needed by all the concerns. In a .NET environment look at something like Castle Windsor to make it easier to handle aspects.

What kind of data repositores are you using? Are you using a relational store, and if so, do you use some type of an Object Relational Mapper (ORM) such as the .NET Entity Framework or NHibernate? Are you calling web services? Is the data RESTful? Is the data in plain text, XML, or .ini files?

WOW! That’s alot of stuff to consider and deal with. So, how do you cut through all the chaos in your Brownfield application? You have five options:

  • Horizontal layers – not very appealing from a technical standpoint.
  • Module by module – not a small undertaking
  • Bottom up – In this case, you start to update the data access layer and move up to the UI
  • Top down – start at the UI and move down to the data access layer
  • Slicing – probably the most appealing. Take one very small piece of functionality, for example, save a patient record, and rework all the code needed to do that, from UI to data access.

What about your code? Is it good? Is it DRY? Are you practicing YAGNI? How about SOLID? Do you practice Separation of Concerns? These are all techniques to make your code easier to read and maintain.

Do you use Design Patterns? Do you stay away from the Singleton pattern, that is probably the most elitist pattern in the world?

Finally, are you improving confidence that your code, and the application are good? Here are some things you can do:

  • Reduce regression errors
  • Make it know that what you’re doing is difficult
  • Do integration tests
  • Refactor your code
  • Add unit tests
  • Know that it’s 100% fallacy that you will ever get 100% of your code under test. And you shouldn’t care. You only need to test the things you need confidence in.
  • Set your direction and know where you are going form here.
  • Do code katas to improve your coding skills

If you want to know more about Brownfield development, there are two books that have very valuable information. The first, Brownfield Development in .NET, is by the guy that presented the seminar, Donald Becham. Don’t let .NET in the title scare you away if you aren’t doing .NET development. All the concepts apply, it’s the tools that are different. The second book is Working Effectively with Legacy Code by Michael Feathers.

You can survive Brownfield development. With the concepts and tools these two books present, survival may not only be easier, but you may thrive in a Brownfield application.


Copyright © 1996-2010 Developer.Blog();. All rights reserved.
iDream theme by Templates Next | Powered by WordPress