Thursday, September 02, 2010

The AI of ReSharper

I was just typing this…

image

…when ReSharper 5 suggested its “Loop can be converted into LINQ-expression”:

image

You gotta love this!

Friday, August 27, 2010

Fluent Assertions 1.2.3 released

After a week of testing in some of our projects, it is time to remove the beta marker from release 1.2.3 of our fluent assertion framework, Fluent Assertions. It’s just a small release, as was the previous one, but it still adds some nice additions requested by the community. This is the official list of changes:

  • Added an As<T>() extension method to downcast an object in a fluent way.
  • Added a ShouldNotThrow() and ShouldNotThrow<TException>() extension method for asserting that a (particular) exception did not occur.
  • Fixed a NullReferenceException when comparing the properties of an object to the null-valued properties of another.
  • Fixed an IndexOutOfRangeException when comparing an empty collection with another for equality.
  • Fixed a bug where two equivalent collections that contained duplicate items were not seen as equivalent
  • Minor improvements to the verification messages.
  • Refactored the internal structure of the exception-related assertions, and removed an extra layer of inheritance. Should improve the extensibility.

As usual, you can download Fluent Assertions 1.2.3 from its resident CodePlex site.

Wednesday, August 25, 2010

ALM Practices Part 11: Modeling the business domain using Domain Models

What is it?
A domain model is typically depicted by a UML class diagram in which the classes and associations represent the business concepts and the relationships between them. Although you can use a piece of paper to draw up a domain model, in most cases a UML case tool is better suited for that. Business concepts such as orders, customers or contracts are represented by classes stereotyped as entity. Associations are used to illustrate the roles which that entity fulfills in in the relationship with other entities. An example of a domain model representing a recipe registration application might look like this:
clip_image002[7]
Why would you do it?
  • Because a domain model centralizes the concepts and behavior of the business domain at one place
  • Because while creating it, you'll run into many new important questions on both the static and dynamic aspects of the domain, including constraints, relationships, the business process, roles and responsibilities
  • Because it can be used to verify that the developers and other team members have the same view on the domain as the business people have.
What’s the minimum you need to do?
  • You should clearly communicate that the domain model should not be confused with a data model. It does not imply anything about the database schema and should not contain specific decisions or changes because of that database.
  • Make sure all entities, association roles, attributes, operations and other documentation comply with the Ubiquitous Language.
  • Write in your native language, unless company policy says otherwise.
  • Avoid bidirectional associations. It makes understanding the life cycle of related entities more difficult and introduces technical complexity that ripples throughout the entire system. I also found that bidirectional associations reduces the obviousness of the user interface, because a bidirectional relationships clouds the parent-child obviousness.
  • Always use directional associations. Base those on the conceptional relationship between the entities, not on the way you intend to query the domain for presentation purposes.
  • Always add roles to your associations. They may seem obvious, but by thinking about the role, you may find misinterpretations or an opportunity to get more insights in its purpose.
  • Don't specify a multiplicity of 1, but always specify the others explicitly.
  • Use a composite association when the child's lifecycle is dictated by the parent (like the Recipe-Ingredient association).
  • Don't include any technical terms or .NET-specific types such as string or integer. Use text, number, money or another type from the Ubiquitous Language instead.
  • Make sure that the individual class models are small and do not show more than what the model is intended for.
  • If an entity has a status attribute, carefully consider what impact each status has on the editability and associations of that entity. If these constraint become very complex, consider modeling the State Pattern or choose a design in which every state is represented by a dedicated subclass of the entity.
  • Do not include mutual exclusive associations. If you need these, your entity is probably representing multiple conflicting concepts and should be split up in multiple entities. Again, if these are related to a status attribute, see previous remark.
What’s the usual thing to do?
  • Group related entities that change together, have a dependent lifecycle or form a conceptual whole into a so-called aggregate and choose one entity as the entity that controls access to the others. This is called the aggregate root.
  • My rule of thumb for finding the right aggregate roots is to create a diagram that only contains the aggregate roots. That diagram should include the most important concepts of your domain and clearly illustrate its dependencies.
  • Include detailed constraints on the maximum length of text attributes, ranges of numbers and dates.
  • If such constraints tend to repeat itself for the same kind of data (e.g. an email address, ISBN number, credit card number or currency), consider introducing new classes representing domain-specific primitives with the associated constraints. Stereotype these as a value object and use them instead of primitive types. For instance, the above domain model relies on the following value objects.
image
  • If you find that the same set of entities have completely different meanings and dynamics depending on the department or organizational unit you ask, and you don't see a chance to get them aligned, you may need to introduce different domain models per organizational unit. This practice is often referred to as having more than one bounded context. In other words, different organizational units require different interpretations of the same domain concepts.
  • Consider reading InfoQ's Domain Driven Design Quickly to get a quick-start into the world of Eric Evans' Domain Driven Design.
  • Consider using Sparx’s UML case tool Enterprise Architect since it can generate Microsoft Word documents and a HTML version of the models, making it easy to share the models with the business people.

Tuesday, August 10, 2010

ALM Practices Part 10: Work Item Tracking

What is it?

Using Team Foundation Server’s User Story, Task and Bug work item types as the central unit of work for all the activities done within a project.

Why would you do it?

  • Because it adds traceability between the functional requirements and the way these requirements have been realized on a technical level.
  • Because it introduces a common view of the project between developers and the business people.
  • Because it allows you to keep track of why certain code changes were made.
  • Because it creates an automatic link between the work items representing functional changes, bug fixes and other code changes and the automatic builds.
  • Because it reduces the chance of ending up with loose ends.

What’s the usual thing to do?

  • Track each and every activity that needs to be done in a project as a work item.
  • Use that work item as a central placeholder for all related communication, code changes, discussions, etc.

How do you do that?

  • Register all functional and non-functional requirements as User Story work items and all bugs as Bug work items.
  • Also include non-coding related activities such as deployment activities, writing documentation, assisting the marketing department and such. This improves the transparency of the work that is done in a project.
  • Break these down into one or more linked Task work items and use these for each and every source control check-in.
  • If you are faced with a research task which is difficult to estimate, consider using a Spike with a time-boxed amount of work.
  • Never check-in anything without associating it with a task.
  • Never check-in anything without providing a clear description describing the set of changes (as Check-In Comments).
  • Use Check-In Policies to require developers to provide the comment and the associated work item(s).
  • Rigorously file all loose ends and ‘things to do at some time’ as a Task, preferably linked to the associated Bug or User Story.
  • Consider adding a custom Storyotype field to the User Story work item type to differentiate between functional and non-functional requirements and to assist in scoping the User Stories.

Tuesday, August 03, 2010

ALM Practices Part 9: Ubiquitous Language

What is it?

The Ubiquitous Language is a unified language consisting of verbs and nouns from the business domain of an enterprise system and should be used by all team members, stakeholders and other involved persons.

Why would you do it?

  • Because it creates a bridge of understanding between the developers and the business people.
  • Because it forces different stakeholders (possibly working in different departments) to use the same name for the same concept.
  • Because it improves the readability of the domain model for both developers and business people.
  • Because it improves traceability from functional design, through the user interface all the way into the details of the code base.

What’s the usual thing to do?

  • Maintain a list of verbs and nouns from the domain and promote its usage during verbal communication, in documentation, in user interfaces, and in the entire codebase.

How do you do that?

  • Let the business people propose a proper verb or noun for the concept.
  • Be aware of the fact that different stakeholders may use the same name for different concepts, or different names for the same concepts. Make sure they choose a single unique name for each individual concept.
  • If a name conflicts with a common engineering concept and serious confusion is expected, consider proposing an alternative name.
  • Unless it is company policy to communicate in English, write your domain model in the native language of the business stakeholders.
  • If your policy is to write code in English and the Ubiquitous Language is in your native language, create a glossary that maps the verbs and nouns from the native domain model into the English translations. Be very pro-active in enforcing these specific translations, because from experience I know developers have a tendency for coming up with alternative translations.
  • Be aware of names that are often used intertwined, but represent the same concept. Force one word for that.
  • Be aware of concepts with multiple intentions. They may be different things and require different entities in your domain model.
  • Also be aware for a concept that appears to have mutual exclusive business rules in different circumstances. In most cases, introducing different concepts (and thus different entities) can prevent significant maintenance burden and confusion.
  • If, throughout the project, you come up with a better name for a concept, make sure you adapt your entire code base, functional documentation and the application itself. If you don’t, you end up with many different names for the same concept, causing significant confusion in the project.

Sunday, July 04, 2010

ALM Practices Part 8: Automatic Builds & Continuous Integration

What is it?
An automatic build is a fully automated compilation of a specific version of your source code repository and which runs at regular intervals. More often than not, such a build includes additional steps such as running a static code analysis and code coverage, executing all automatic unit and integration tests, and possibly even a full-blown deployment of the product and the database to a test server. Continuous Integration, or CI, is just a fancy name for saying that a build runs whenever a developer checks-in his changes into the source code repository. This essentially forces all developers to continuously integrate their changes into a working product. However, since these kind of builds are run very frequently, extra steps are usually limited to unit tests and code coverage.

Why would you do it?

  • Because two developers each working in the same area of the code base cannot fully guarantee that their changes will not cause any functional issues.
  • Because the deployment of a new release to a development, test or acceptance server usually involves many manual steps, each highly susceptible to errors.
  • Because deploying your product or system in an automated way requires that it has been built for that. Introducing an automatic daily deployment forces you to deal with possible issues early in the project which would not have appeared until the final release date otherwise.
  • Because it then becomes trivial to redeploy an earlier version of your product or system, for instance when a new release includes some critical bugs and you want to roll back, or to analyze functional changes between versions.
What’s the bare minimum you need to do?
  • Use a continuous integration build that compiles your solutions and runs your unit tests.
What’s the usual thing to do?
  • Deploy the most recent version of your product or system to your central development server.
  • Automatically deploy the database schema changes and test data to your central database.
  • Include a build step that assigns a unique version number to all executables and DLLs so that you can easily see which version is deployed.
How do you do that?
Setup a Continuous Integration build in Team Foundation Server 2008 or 2010 using the following steps:
  • Create a dedicated Build Definition in Team Build 2008 or Team Build 2010 for every solution related to your product or system and configure it so that is triggered by every check-in.
  • Don’t forget to configure your definition to build the release version of your solution.
  • Optionally, configure the build to enable Code Analysis using the project-specific settings. Read this post on how to configure this using the Default Template in Team Build 2010.
  • Use the <TestContainer> element to configure which test assemblies to inspect for unit tests, or use a wildcard, for instance *\**\*.specs.dll to run all test in assemblies post-fixed with .specs.dll.
  • If your tests need a specific .testrunconfig, open up the underlying build.proj file and add a <RunConfigFile> element as explained by this post.
  • Notice that in Team Build 2010, you can skip the previous two steps and use the Build Definition dialog box instead. See this post for more info.
  • Make sure you keep the CI build fast, for instance by only running the unit tests that are independent of any slow resources such as I/O, databases, etc.
  • You can speed up the build by enabling the incremental build and disabling the step that copies the results to a dedicated network drop folder (configured through the <SkipDropBuild> property.
Setup a Daily Build in Team Build 2008 that deploys the latest version to a dedicated test server using the following steps.
  • Use separate solution configurations to have project settings specific to the deployment environment. So in addition to the default Release and Debug configuration, you could introduce Test, Acceptance and Production configurations.
  • Introduce alternative .config files associated with specific solution configurations, such as for instance web.production.config or enterpriselibrary.production.config and configure Team Build 2008 to deploy the correct version using this block in your web application project:
<Target Name="AfterBuild" Condition="('$(Configuration)' != 'Debug') and ('$(Configuration)' != 'Release')">
<!-- If a configuration-specific web.config exists, replace the default web.config with it –> <Copy Condition="Exists('$(DeploymentFolder)\web.$(Configuration).config')" SourceFiles="$(DeploymentFolder)\web.$(Configuration).config" DestinationFiles="$(DeploymentFolder)\web.config" />
<Delete Files="$(DeploymentFolder)\web.$(Configuration).config" />
<!-- If a configuration-specific enterpriselibrary.config exists, replace the default enterpriselibrary.config with it –> <Copy Condition="Exists('$(DeploymentFolder)\enterpriselibrary.$(Configuration).config')" SourceFiles="$(DeploymentFolder)\enterpriselibrary.$(Configuration).config" DestinationFiles="$(DeploymentFolder)\enterpriselibrary.config" />
<Delete Files="$(DeploymentFolder)\enterpriselibrary.$(Configuration).config" />
</Target>
  • If you’re using Visual Studio 2010, you can reduce the amount of overlap between those alternative .config files using Config Transformation Files.
  • To deploy a web site using Team Build 2008 without the Web Deployment project, customize the .csproj of your Web Application project to automatically deploy the entire website to a dedicated server using the following example config. Notice that you need to set the $(DeploymentFolder) property to a valid UNC path.
<Target Name="AfterBuild" Condition="('$(Configuration)' != 'Debug') and ('$(Configuration)' != 'Release')">
<Message Text="Deploying Web Site to '$(DeploymentFolder)'." Importance="high" />
<!-- Create the _PublishedWebsites\app\bin folder –> <MakeDir Directories="$(DeploymentFolder)\bin" />
<!-- Copy build outputs to $(DeploymentFolder)\bin folder. –> <Copy SourceFiles="@(IntermediateAssembly)" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" />
<Copy SourceFiles="@(AddModules)" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" />
<Copy SourceFiles="$(IntermediateOutputPath)$(_SGenDllName)" DestinationFolder="$(DeploymentFolder)\%(Content.SubFolder)%(Content.RecursiveDir)" SkipUnchangedFiles="true" Condition="'$(_SGenDllCreated)'=='true'" />
<Copy SourceFiles="$(IntermediateOutputPath)$(TargetName).pdb" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" Condition="'$(_DebugSymbolsProduced)'=='true'" />
<Copy SourceFiles="@(DocFileItem)" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" Condition="'$(_DocumentationFileProduced)'=='true'" />
<Copy SourceFiles="@(IntermediateSatelliteAssembliesWithTargetPath)" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" />
<Copy SourceFiles="@(ReferenceComWrappersToCopyLocal); @(ResolvedIsolatedComModules); @(_DeploymentLooseManifestFile); @(NativeReferenceFile)" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" />
<!-- copy any referenced assemblies to $(DeploymentFolder)\bin folder –> <Copy SourceFiles="@(ReferenceCopyLocalPaths)" DestinationFolder="$(DeploymentFolder)\bin" SkipUnchangedFiles="true" />
<!-- Copy content files recursively to $(DeploymentFolder)\bin folder –> <Copy SourceFiles="@(Content)" DestinationFolder="$(DeploymentFolder)\%(Content.RelativeDir)" />
</Target>
  • To deploy a web site using the Web Deployment project type in Visual Studio 2010 project type, read this post.
  • To deploy a web site using Team Build 2010 and MSDeploy, read this post.
  • If you want to automatically add an incremented version number to all assemblies using Team Build 2008, read this post. If you want to do this using Team Build 2010 with an Upgrade Template, read this. And if you want to use the Default Template, read this.
If you also want to deploy the database automatically, include the following additional steps.
  • Install Visual Studio Team System 2008 Database Edition and GDR R2. You don’t need any additional licenses for that.
  • Import the schema and configuration of your database using a Database Project.
  • Configure your database project so that a specific database is linked to a specific solution configuration. For instance, a local build should deploy your database to your local development PC, while the Daily Build should deploy it to a central database server.
  • Add a dedicated AfterDropBuild target to the build.proj of your Build Definition to build and deploy the database project to the configured database:
<Target Name="AfterDropBuild">
<MSBuild Projects="$(SolutionRoot)\Main\Source\ConstructIT\Database\Database.dbproj" Properties=" OutDir=$(OutDir)" Targets="Deploy"/>
</Target>
  • For more information on database deployment using Visual Studio 2008, read the Gert Drapers’ blog.
  • This also works with the Team Build 2010’s Upgrade Template, but if you want to do this with the Default Template, follow the steps in this post.
Other tips and suggestions
  • Make an arrangement with your team that the first on entering the office in the morning will be responsible for checking the build status, and if one of them failed, fixing the problem(s).
  • Write down any important details around the build (such as common problems, details on every build, etc) on your project or department site, and make sure there is more than one team member who knows how to customize or adapt the build.
  • Use the Build Notification tool part of the TFS Power Tools to keep an eye on the build through its corresponding icon on the Windows Task Bar.
  • You can tweak a Team Build 2008 Build Definition (or a 2010 Upgrade Template) using the many properties mentioned on this site.
  • Most of the guidance is intended for Team Build 2008, but will work just as well on a Team Build 2010 Upgrade Template. However, if you want to find out how to get the most out of the workflow-based Default Template, check out this series of posts written by MVP Ewald Hofman.

Wednesday, June 30, 2010

ALM Practices Part 7: Refactoring

What is it?

A mindset and practice that requires you to continuously reevaluate a region of code each time you make a change. In essence, you need to look at the code related to your changes and reconsider whether the original solution is still the best solution accounting for the information you currently have (and did not have at that time). Refactoring is a core practice of the Test Driven Development.

Why would you do it?

  • Because, unfortunately, experience has proven that is virtually impossible to design a foundation or architecture that we never have to chance anymore. So in reality and in most situations, software is created incrementally by adding new bits and pieces on top of each other without reconsidering its foundations.
  • Because any technical solution, both on an architectural level or at code level, is based on the knowledge you have at that point. Practice has proven that this knowledge improves over time and often becomes more focused, but is difficult to predict beforehand.
  • Because of advancing insight it is possible that certain domain concepts (such as those part of the Ubiquitous Language) have been refined or renamed, and you want to make sure your code reflects those changes that all time.
  • Because if you apply refactoring rigorously, you can start a project with Little Design Up Front instead of the infamous Big Design Up Front (can you predict the future?). Refactoring keeps your code base in good shape, so it’ll be easier to adapt your system or product to new requirements or technical changes.

What’s the bare minimum you need to do?

  • Replacing obscure or complex code with more simpler code that complies with common design principles and design guidelines.

What’s the usual thing to do?

  • Rewrite redundant and/or similar code so that you never have to apply the same change to multiple blocks of code, or, in other words, be DRY (Don’t Repeat Yourself).
  • Remove unnecessary or unused code (including commented-out code).
  • Considering the Single Responsibility Principle, move code that is at the wrong place in the code base.
  • Remove unnecessary dependencies between unrelated classes.
  • Rewrite code to comply with your coding guidelines and coding layout rules.

How do you do that?

  • Apply Test Driven Development because it promotes choosing the simplest working solution possible and includes refactoring as one of its basic steps.
  • Uphold to The Boy Scout Rule. Always, and with that I mean always, make sure that each and every source control check-in leaves your code base in a better shape than it was before.
  • Keep the A4 cheat sheet of the Coding Guidelines for C# 3.0 and C# 4.0 close to continuously remember yourself of its most important guidelines.
  • During a review, not only check that a block of code is functionally correct and uses the right layout, but also try using a high-level view to see whether that block of code is still at the right spot, or needs refactoring.
  • Check that the name of a type or member is still covering its purpose.
  • Print out the ReSharper Keymap and learn yourself the keyboard shortcuts for its many refactoring features.
  • Make sure you use ReSharper’s Visual Studio Keyboard Scheme so that other developers will not run into issues when you are pair programming with them.
  • Also include your automated unit tests when refactoring your code. Unit tests are first class citizens in your code base, and must of top-notch quality at all time.
  • Use the complexity of your unit tests as a measure of quality. If they are difficult to understand or anything other than small, changes are that the tested class (or subject-under-test) is either too complex or has too many responsibilities.
  • Consider using Clone Detective for Visual Studio to analyze your code base for duplication. It’s a free add-on for Visual Studio that will detect similarities in code constructs and can give you a quick analysis of your duplication.
  • Consider using the Wall of Pain principle to keep track of your major architectural or technical issues and have a controlled and transparent way for fixing those.
  • Seriously consider reading Robert C. Martin’s (a.k.a. Uncle Bob) Clean Code and Steve McConnell’s’ Code Complete. Both books provide very valuable guidance and background information on how to create high quality software.

Monday, June 28, 2010

Coding Guidelines for C# 3.0 and C# 4.0 now available

As promised earlier, you can now download the concept version of my new Coding Guidelines for C# 3.0 and C# 4.0 from a dedicated CodePlex site at www.csharpcodinguidelines.com. The list of changes is quite big, and includes new guidelines covering object-oriented design, design principles, C# 4.0 and the smells and heuristics from Robert C. Martin’s book Clean Code. I’ve also removed many guidelines that have become obsolete or deal with situations that rarely occur. And the entire document has become much easier to read because I’ve changed to a less formal writing style.

A common question I receive regularly is how to introduce coding guidelines or coding standards into a team or organization, so I’ve adapted my April post on Coding Guidelines and included it into the document. Another question I get asked commonly is what to do if something is not covered by the document. For this, I’ve included my most favorite design principles that should help you determine when something is valid or not.

Similarly to the quick reference guide for the C# 3.0 version of the document, I’ve included a two-page A4-sized cheat sheet with the most important guidelines and some handy tables on naming, ordering and layout.

And finally, Jonne Kats and I started creating a set of FxCop and StyleCop rules that verify your code against some of the guidelines in this document. It’s a side project, so it may take a while before a first release will be made available. In the mean time, check out the source code repository regularly.

And last but not least, this document has not been cut in stone. So if you have remarks, comments, additions or complaints, just let me know. I’ve already received valuable feedback from the community and will continue to update the document whenever something useful comes to my attention.

Sunday, May 30, 2010

Things to do to fill up my free time

Now that my CQRS/Event Sourcing talk for DotNED is done, the pressure on the free hours between work and family has been reduced significantly. That doesn’t mean I’m going to sit back and relax. Oh no, I’m full of ideas. so let’s see some of my plans.

  • I’m still going to continue developing The CQRS Kitchen to find and solve all special cases you may run into when building an enterprise system using CQRS and Event Sourcing. I also want to align a bit more with the Ncqrs Framework, but I have to figure out a way to do branching and merging
    from/to the their project.
  • I’ve just started with the update of my C# 3.0 Coding Guidelines to include C# 4.0 specific guidelines, as well as some ideas from Robert C. Martin’s Clean Code book. I’ve moved all current versions to the new CodePlex site here.
  • I’ve also started creating my first FxCop / Static Code Analysis rules that should validate a large portion of the C# Coding Guidelines. The work-in-progress can be followed here.
  • Obviously, I’ll continue improving Fluent Assertions with improvements and suggestions. Currently it is stable, and I’m not aware of any major issues.
  • I still have to translate my article about User Stories and Storyotypes from Dutch to English.
  • Because of the enormous amount of effort needed for the CQRS talk, my series of posts on Application Lifecycle Management have stalled. I will continue soon though.
  • I’d like to write an article on how to write focused, maintainable unit tests dealing with TDD and BDD-style testing, state-based versus interaction-based testing, patterns such as Test Data Builder, and obviously, Fluent Assertions.
  • And of course I’ll continue submitting proposals for DotNED, SDN, SDC and other events.

Friday, May 28, 2010

CQRS and Event Sourcing

Yesterday evening I did a talk on building a .NET-based system using Command Query Responsibility Segregation and Event Sourcing. We had a lot of awesome discussions on its applicability, and as usual, I ran out of time again. I could have easily spend a full day on this subject, but unfortunately, I only had about 1 hour and 45 minutes to my disposal.

All code is available as a CodePlex project and I’ll be continuing development on the demo application so that it includes all major and all corner cases. I’m going to try to make it a great reference for anybody whose intention is to start building CQRS-based systems.

Thursday, May 06, 2010

May 27th: CQRS and Event Sourcing, an alternate architecture for Domain Driven Design

Most of us will be familiar with the standard 3- or 4-layer architecture you often see in larger enterprise systems. Some are already practicing Domain Driven Design and work together with the business to clarify the domain concepts. Perhaps you’ve noticed that is difficult to get the intention of the 'verbs' from that domain into this standard architecture. If performance is an important requirement as well, then you might have discovered that an Object-Relational Mapper and a relational database are not always the best solution.

One of the main reasons for this is the fact that the interests of a consistent domain that takes into account the many business rules, and those of data reporting and presentation are conflicting. That’s why Betrand Meyer introduced the Command Query Separation principle.

An architecture based on this principle combined with the Event Sourcing concept provides the ideal architecture for building high-performance systems designed using DDD. Well-known bloggers like Udi Dahan and Greg Young have already spent quite a lot of of posts on this, and this year’s Developer Days had some coverage as well.

But how do you build such a system with the. NET framework? Is it really as complex as some claim, or is just different work? If you want an answer to this, sign up for this evening and come see how I've built a concrete Silverlight demo app.

Subjects that I’ll cover:

  • Tasked-based UIs
  • Command Handling
  • Event Handling
  • Eventual Consistency
  • Repository & Aggregates
  • Versioning events and commands

You can find the latest details on this evening and the registration info here.

Tuesday, April 20, 2010

ALM Practices Part 6: Code Analysis & Guidelines

What is it?

Coding guidelines, or coding standards if you will, are documents consisting of rules and recommendations on the use of C# in enterprise systems. They deal with code layout, naming guidelines, the proper use of the .NET Framework, tips on writing useful comments and XML documentation, and often also include guidance on proper object-oriented design. Visual Studio’s Static Code Analysis (a.k.a. FxCop) can automatically verify a majority of those rules and recommendations by analyzing the compiled assemblies. You can configure to do that at compile time or as part of a continuous or daily build. The Aviva Solutions C# 3.0 Coding Guidelines adds additional rules and recommendations and provides a list of Code Analysis rules that are applicable for Line-of-Business applications and frameworks.

Why would you do it?

Because not every developer
  • is aware of the potential pitfalls of certain constructions in C#.
  • is introduced into certain conventions when using the .NET Framework (e.g. IDisposable)
  • is aware of the impact of using (or neglecting to use) particular solutions on aspects like security, performance, multi-language support, etc.).
  • knows that not every developer is as capable in understanding an elegant, but abstract, solution as the original developer.

What’s the usual thing to do?

Ensure that all code, including unit tests, complies with your coding guidelines and the Code Analysis rules selected for your project.

How do you do that?

  • Ask all developers to carefully read the C# 3.0 Coding Guidelines at least once. This will give them a sense of the kind of guidelines the document contains.
  • Make sure there are always a few hard copies of the Quick Reference close.
  • Include the most critical coding guidelines on the checklist and verify the remainder as part of your Peer Review.
  • Decide which CA rules are applicable for your project and write these down somewhere, such as your TFS team site. The C# Coding Guidance site on CodePlex offers Visual Studio 2010 rule sets for both Line-of-Business applications and more generic code like frameworks and class libraries.
  • Add a custom Code Analysis Dictionary containing your domain- or company-specific terms, names and concepts. If you don’t, Static Analysis will report warnings for (parts of) phrases that are not part of its internal dictionary.
  • Configure Visual Studio to verify the selected CA rules as part of the Release build. Then they won’t interfere with normal developing and debugging activities, but still can be run by switching to the Release configuration.
  • Add the verification of the CA rules part of your Continuous or Daily Build.
  • Add a rule to your team that the first one who comes in the office in the morning will check the build for CA warning and will make sure somebody (not necessarily himself) solves it as soon as possible.
  • Add an item to your project checklist to make sure all new code is verified against CA violations, or use the corresponding Check-in Policy if you want to prevent any code from violating CA rules at all.
  • ReSharper has an intelligent code inspection engine that, with some configuration, already supports many aspects of the Coding Guidelines. It will automatically highlight any code that does not match the rules for naming members (e.g. Pascal or Camel casing), detect dead code, and many other things. One click of the mouse button (or the corresponding keyboard shortcut) is usually enough to fix it.
  • ReSharper also has a File Structure window that shows an overview of the members of your class or interface and allows you to easily rearrange them using a simple drag-and-drop action.
  • Using GhostDoc you can generate XML comments for any member using a keyboard shortcut. The beauty of it, is that it closely follows the MSDN-style of documentation. However, you have to be careful not to misuse this tool, and use it as a starter only.
  • Consider reading the book Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin. It provides excellent guidance on writing elegant and simple code that is easy to maintain and to extend. His ideas have evolved into a new quality standard maintained by many well-known community members.

Friday, April 16, 2010

Interaction Design according to Alan Cooper

I've recently finished the book The Inmates Are Running The Asylum by Alan Cooper, a well known proponent for interaction design. To be honest, I never really saw the purpose of interaction design in our projects. But after reading this book, I now know I didn't really understand what it was about and why it is so important.

One of my colleagues, Stefan Bookholt, has mentioned the need for some good interaction design many times, but his persistence was often met by laughter. This post is not really a review of the book, but rather my public apologies to him for not listening earlier.

First of all, this book is really worth its money and very easy to read. It's so full of real life cases and anecdotes, it really helps you to gain a solid understanding of why interaction design is so important.

Some highlights you should remember the next time you have a discussion about the functional design of your application.

  1. Less is more. It's better to have just a few well-designed features that get the job done, than hundreds of options that confuse the end-user.
  2. Your product should be goal-oriented. That sounds obvious, but it is quite difficult to understand the actual goals an end-user is trying to accomplish. Tasks are not goals, just the steps to reach it. Without knowing the goal, it is very difficult to build a system that helps the user to reach that point.
  3. Users don't like to feel stupid because your product is too complex for them to use (but they'll never admit that).
  4. Users are only beginners for a short time. The biggest share of the market consists of intermediate users (who might or might end up as experts)
  5. User forums don't work either because users are bad in making decisions about functionality. They don't know what is and what is not possible and usually miss the big picture or the vision your system is supposed to reach.
  6. Developers should not do interaction design. Why? Because they have their own way of looking at things and are known for confusing the needs of end-user with their own.
  7. Interaction design should not happen concurrently with programming because it can have a radical impact on the design of your application.
  8. Industrial Design is not interaction design because it deals with the look-and-feel of a product, not its usability.
  9. User Interface design is not interaction design. Like Industrial Design, UI design focuses on the look-and-feel and positions of buttons. Interaction design looks at the way an application should fulfill a goal.
  10. UI style guides are not necessarily a good thing, because they restrict creativity. It is okay to have a common standard for coloring, icons and font styles. But an interaction designer should be able have the freedom to create an application that solves the goals of its end user, even if that means that the guide is violated.

Monday, April 12, 2010

Fluent Assertions 1.2 has been released

It has been only 6 weeks since I first released Fluent Assertions to the public, followed by version 1.1 a week later. In the weeks thereafter, I received some nice ideas from the community which caused me to start working on the next version.

But it was not easy. I found that designing a small framework like this really requires you to carefully design the syntax you want to offer. For instance, I underestimated the limits of the current version of C# and had to make some tough decisions along the way. But I'm done now, so get version 1.2 from CodePlex. However, please read this post before you start introducing it in your project. Those tough decisions will cause some minor inconvenience.

New collection assertions

The collection assertion methods now include a BeNull() and NotBeNull() to ensure that a collection is initialized or not. I’ve also made sure that the Contains() method of a generic collection takes an object of the right type instead of System.Object (this breaks existing usages though). And if that is not enough, you can also pass in a lambda expression to specify that the collection should contain a specific instance. Something like this:

dtoCollection.Should().Contain(dto => dto.Id != null);

Similarly, you can also use a lambda when asserting the count of a collection:

collection.Should().HaveCount(c => c >= 3);

If the subject-under-test does not comply with the expression, it will include the actual expression of the lambda in the error message. As a matter of fact, this applies to all assertion methods that take a lambda expression.

Comparing objects by their properties

I’ve added the possibility to assert the equality of entire objects by comparing their properties by name. This even works if the types of the properties differ but a built-in conversion exists (through the Convert class). As an example, consider a Customer entity from some arbitrary domain model and its DTO counterpart CustomerDto. You can assert that the DTO has the same values as the entity using this syntax:

dto.ShouldHave().AllProperties().EqualTo(customer);

As long as all properties of dto are also available on customer, and their value is equal or convertible, the assertion succeeds. You can, however, exclude a specific property using a lambda, such as for instance the ID property:

dto.ShouldHave().AllPropertiesBut(d => d.Id).EqualTo(customer);

The other way around is also possible. So if you only want to include two specific properties, use this syntax.

dto.ShouldHave().Properties(d => d.Name, d => d.Address).EqualTo(customer);

Comparing dates and times

In addition to simple assertions between two DateTime objects, I’ve added a whole bunch of methods for asserting that two dates or times differ a specific amount of time (specified using a TimeSpan). With these you can do things like:

dt1.Should().BeWithin(TimeSpan.FromHours(50)).Before(dt2);
dt2.Should().BeLessThan(TimeSpan.FromDays(1).After(dt2);

It supports BeMoreThan(), BeAtLeast(), BeExactly(), BeWithin() and BeLessThan() before or after a specific date and/or time.

Other improvements

In addition to fixing several minor bugs reported by the community, I have spend a considerable amount of time in making sure the assertion failure messages clearly explain why it failed. For instance, a date/time assertion might return the following (lengthy) exception message:

”Expected date and/or time <2010-04-08 09:59:59> to be within 2d and 2h before <2010-04-10 12:00:00> because 50 hours is enough, but it differs 2d, 2h and 1s.”.

The part after the because is the part that you need to add using one of the many overloads. It really helps to keep the developer from the need to start the debugger.

One particular bug I fixed was when asserting that a collection of strings contained a particular string, it was interpreted as an IEnumerable of Char. Obviously it never succeeded, regardless of the fact that the original string was part of the collection.

I also looked at extensibility a bit more by making classes public and ensuring you can override an assertion class at the right spots. I still have to do some work here, but whenever somebody has a problem, I’ll fix it soon enough.

So what did you break?

As a result of some important feedback from the community, my desire to remove a lot of noise from the syntax, and limitations of the language I ran into, I decided to introduce some changes that will break existing code. Fortunately, it is just a cosmetic change, so some smart search/replace should get you back on track easily.

First of all, I’ve renamed almost all Equal() methods to Be(). So instead of myString.Should().Equal(“hello”) you now have to write myString.Should().Be(“hello”). The only exception to this is the one for comparing two collections for equality, since it’s purpose to see if they have the same items.

Also, I’ve renamed the Satisfy() method for asserting an arbitrary object against a lambda expression to Match(). Apparently, the word satisfy was a bit to technical. On the flipside, you now get multiple overloads which allows you to do the following.

o.Should().Match(obj => obj == null)
o.Should().Match<CustomerDto>(d => d.Name.Length > 0);
o.Should().Match((CustomerDto d) => d.Name.Length > 0);

The whole exception throwing assertion syntax was way too noisy, so I removed some unnecessary parts and changed the overall syntax. For instance

someObject.ShouldThrow(x => x.SomeMethod()).Exception<SomeException>();

has been changed into

someObject.Invoking(x => x.SomeMethod()).ShouldThrow<SomeException>();

Which doesn’t really remove noise, but feels more natural to me when invoking a lambda expression. When using an Action<T>, the syntax has changed as well. Consider a class with a method Foo() that should throw an instance of SomeException:

Action act = () => someObject.Foo();

In 1.1 asserting that Foo() really threw that specific exception with specific values for its Message and a custom property SomeParam had to be done like this:

act.ShouldThrow().Exception<SomeException>().
   And.WithMessage(“Something went wrong”).
   And.ValueOf.SomeParam.Should().Equal(23);

In 1.2 I’ve changed it into:

act.ShouldThrow<SomeException>().
   WithMessage(“Something went wrong”).
   And.SomeParams.Should().Equal(23);

You can download version 1.2 from here.

Tuesday, March 30, 2010

Is Entity Framework 4.0 ready for the real work?

This morning, on the Developer Days 2010, I did a talk on the current state of affairs of the 4.0 version of the Entity Framework, including a rough comparison with NHibernate 2.1. Apparently this is something that’s on the mind of many people. The room was supposed to accommodate a maximum of 80 attendees, but at least 30 people were standing in the back or sitting on the ground and 10-20 more were refused access. I think that counts as a success… Anyway, you can find the slides here and download the demo code from here.

During the day many attendees asked me about the final conclusion. So, is Entity Framework 4.0 ready for the real work?

Yes…because the designers are excellent for rapid application development and suitable enough for simple domain models that provide a one-to-one mapping to the database. Moreover, you don’t need to struggle with big bundles of documentation to quickly get started.

But…the Code First functionality in CTP3 is still too limited for serious Domain Driven Design. It simply misses too much concepts very common in mature OR/Ms like NHibernate and its fluent add-on Fluent NHibernate. Worse, there is no Go-Live yet, so you can’t use it in production systems yet.

Nevertheless, the choice between NHibernate and EF4 is not trivial and depends entirely on the context of your project. NHibernate is still my first choice, but looking at the progress Microsoft has made the last year or so, I’m confident EF will gain some ground soon…

My two days of fame at the Developer Days 2010

Some of you who have been visiting the Dutch Developer Days 2010 in The Hague today may have noticed the flyers and banners for promoting the new online version of the .NET Magazine. Those who already know me may have noticed that it’s me on those banners. 

 
Since the photographer spent a considerable amount of time setting up his photo studio at Aviva Solution, and the fact that he shot almost 100 pictures, I wanted to give him Marco Hofste, the photographer, some credits. You can find his portfolio over here.

Wednesday, March 24, 2010

The curious case of the unsolved extension methods

As part of my effort to improve the type-safety of Fluent Assertions, I’ve been investigating the possibility to use C# extension methods all the way. Unfortunately I think I’ve ran into the limitations of C# 3.0 (and C# 4.0 since it doesn’t add anything useful for this). Essentially, I’d like to do the following things.  

var someList = new List<string> {"hello world"};

someList.Should().HaveCount(1);

someList.Should().Contain(s => s.Length > 0);

The first one is easy because it does not require any type-specific extensions and can be implemented by the following piece of code:

static class Extensions

{

    public static EnumerableConstraints Should(this IEnumerable subject)

    {

        return new EnumerableConstraints();

    }

}

public class EnumerableConstraints

{

    public ShouldConstraint(IEnumerable subject) { }

 

    public void HaveCount(int expectedCount)  { }

}

The second one is more tricky. In order for the Contain() method to take a lambda expression on a List<string>, it needs to know the actual type of items in the IEnumerable collection. We can fix that by changing the type of the subject parameter to IEnumerable<T> and pass the <T> type parameter to the class that exposes the actual assertion methods:

static class Extensions

{

    public static EnumerableConstraints<T> Should<T>(this IEnumerable<T> subject)

    {

        return new EnumerableConstraints<T>(subject);

    }
}

 

public class EnumerableConstraints<T>

{

    public void HaveCount(int expectedCount) { }

    public void Contain(Func<T, bool> predicate) { }

}

That solves our initial two requirements, so let’s add another one. I’d like to be able to use a lambda expression on any possible type. Something like this:

var dto = new FindOrdersDto { CustomerName = “blah”, MaxItems = 10 };
dto.Should().Match(d => d.MaxItems < 100);

The first idea that pops up in my mind is to add an overload of Should<T> to the Extensions class, like this:

static class Extensions

{

    public static EnumerableConstraints<T> Should<T>(this IEnumerable<T> subject) { }

 

    public static BasicConstraints Should<T>(this T subject) { }

}

Unfortunately, this overload takes precedence over the overload taking an IEnumerable<T> and breaks the first working example. That’s a real bummer. If only I could use a where constraint stating that the <T> does not  comply with a specific constraint. For instance

public static BasicConstraints Should<T>(this T subject) where not T : IEnumerable

I’ve also tried to change the HaveCount(), Contain() and Match() methods into extension methods on a single generic class ShouldConstraints<T> like this:

static class Extensions

{

    public static ShouldConstraints<T> Should<T>(this T subject)

    {

        return new ShouldConstraints<T>(subject);

    }

 

    public static ShouldConstraints<T> HaveCount<T, TItem>(

        this ShouldConstraints<T> constraints, int expectedCount) where T : IEnumerable<TItem> { }

 

    public static ShouldConstraints<T> Contain<T, TItem>(

        this ShouldConstraints<T> constraints, Func<TItem, bool> predicate) { }

 

    public static ShouldConstraints<T> Match<T, TItem>(

        this ShouldConstraints<T> constraints, Func<TItem, bool> predicate) { }

}

 

class ShouldConstraints<T>

{

    public ShouldConstraints(T subject)

    {

        Subject = subject;

    }

 

    protected T Subject { get; set; }

}

This compiles fine, but causes the compiler to complain about missing type parameters because it is unable to infer these from the usage. This forces us to use this rather ugly syntax:

var someList = new List<string> {"hello world"};

someList.Should().HaveCount<List<string>, string>(1);

someList.Should().Contain<List<string>, string>(s => s.Length > 0);

Other solutions that crossed my mind included testing the ability to define two extension methods with the same name and the same parameters but having different constraints such as:

public static EnumerableConstraints Should<T>(this T subject) where T : IEnumerable
public static ComparableConstraints Should<T>(this T subject) where T : IComparable

But this is, as I expected, not supported by C#.

The conclusion? Well, as far as I can tell, my problem is currently unsolvable…

Tuesday, March 23, 2010

ALM Practices Part 5: Checklists

What is it?
An (online) list of verification tasks to sign off as part of the delivery process of a newly delivered unit of work. Usually these include things that are often forgotten, or aspects that require explicit verification. See an example of such a list here.
Why would you do it?
Because quite often, things considered common sense, are overlooked anyhow. Browser compatibility is one example of this. Also, most teams have written down some form of project-specific rules and guidelines. However, writing something down and complying with them are two different things. So it may be wise to include the most important functional, technical or administrative guidelines on the checklist.
What’s the bare minimum you need to do?
  • Create a minimal checklist on the project site and adapt and extend it all along the project. Use it with important deliveries.
What’s the usual thing to do?
  • Use the checklist as a formal sign off document after finishing a use case, screen or user story.
How do you do that?
  • Store the checklist as a wiki on the SharePoint site associated with your TFS Team Project. This lowers the threshold for the team to change or update the checklist with new insights, and causes it to become a team effort for gaining high quality.
  • Make sure each entry on the list is short, concise and that it means the same for every member of the team.
  • If an entry on the list requires the verification of multiple aspects of the product, split the entry in multiple single-purpose entries. If you don’t, you risk the chance that people only roughly look at it and quickly sign off the corresponding entry.
  • Include the most important design guidelines and coding standard rules as individual entries.
  • Ensure that your team members complete one checklist per screen, use case or user story (depending on your planning unit) and file it either physically or on the project site.

Friday, March 19, 2010

TFS, ALM, what’s in a name?

In response to my posts on Peer Reviews, Unit Testing & TDD, and Common Code Layout, someone noticed that all these posts were part of my Team Foundation Server Development Practices series, but not every post actually mentioned TFS. Obviously, he was right. The reason for using the TFS prefix is that our company is heavily using TFS as a platform for supporting Application Lifecycle Management. Most of the practices I talk about include a lot of practical advice on how to get the most out of the TFS product suite. Nevertheless, I’ve renamed the series to ALM Practices to better emphasis the real purpose of it. So what’s planned?

  • Code Analysis & Coding Standards
  • Refactoring
  • Automatic Builds & Continuous Integration
  • Checklists
  • Work Item Tracking & Tracibility
  • Architectural & Technological Audits
  • Pair Programming

Monday, March 15, 2010

ALM Practices Part 4: Common Code Layout

What is it?

A collection of rules stating what a block of code should look like. These may include rules on where line breaks are required, how to place parentheses, how much whitespace to put before and after those parentheses, how many spaces to use when indenting and where to insert empty lines.

Why would you do it?

  • To allow developers to work on virtually any part of the code base without being confronted with another different layout. And even though this may seem like a feeble issue, I’ve seen firsthand how difficult it can be to navigate through a block of code which uses an entirely different layout.
  • To improve the reviewability of your code base. For the same reason another developer benefits from it, the reviewer needs to be able to easily scan code for often-made mistakes or other issues.

What’s the bare minimum you need to do?

  • Use a standard layout for the entire code base and remind everyone to adhere to it.

What’s the usual thing to do?

  • Use a product such as ReSharper and configure it in such a way that it will format your code automatically according to the standard layout.

How do you do that?

  • Together with your team, agree on a common layout and write it done somewhere such as your team site, preferably accompanied by a piece of example code that illustrates all aspects of the standard.
  • If another team within the company has already created something like that, consider adapting their standard. This eases the burden when team members move from one project to the other.
  • Consider buying a ReSharper licence and use its Code Style sharing feature so that all team members will automatically receive the most up to date version of the standard settings. It also allows you to reformat entire files, projects or even the entire solution with one click of the mouse.
  • Create a one-page cheat sheet with a block of example code that clearly demonstrates the proper layout and distribute it amongst the team members. Use it while performing a Peer Review.
  • Install StyleCop and use it for automatically checking the layout and the XML documentation according to a configurable set of rules.
  • Add compliance to this standard code layout to the project quality Checklist (I will blog about that later on) so that developers and reviewers don’t forget to check for it.