Tuesday, 16 December 2014

Stop Making Everything Public

Part one of my Three Steps to Code Quality via TDD series.

We always default to public class when creating a new class. Why? The concept of visibility in OO languages appears very early on in programming books, yet more often than not most of the classes we create default to public visibility.

@simonbrown stated that each time you make something public you need to make a donation to charity. In other words we should think more about why the class we are making should be visible to everyone. I really like this idea that the use of the public keyword should be a well thought out decision.

Server side development has a part to play in the lack of concern given to visibility issues. Library or framework developers on the other hand must carefully consider what is part of the public API. Any changes made after are considered breaking and require careful consideration. Yet in the land of server side development this is see as a non issue. This is wrong. If we treat our tests as consumers of our public API, constantly updating them or modifying them should be a warning symbol.

Use internal or private classes for details and public classes for your API. The beauty of this is that TDD drives your public API, which should be fairly stable. Internally however you want the ability to refactor without a suite of tests breaking, otherwise what is the point of writing automated tests?

Implementation details are introduced as part of the refactor step. Ideally they should never be introduced without a passing test in place, as previously the simplest possible thing should have been done.

What should be public then?

  • Application services (use cases) that adapters talk to.
  • Adapters - controllers, console application, presentation layer.
  • Domain concepts - money or customer for example
  • Strategies - things you need to inject, repositories, third parties

Doesn't this lead to god classes?

No. As part of the TDD cycle, when refactoring you can extract implementation details. There is no reason why the public types should suffer.

Doesn't this lead to large tests on the public types?

No. You'll use less test doubles (stubs, mocks, fakes) and in turn reduce setup. For any logic that appears to be painful or common you can introduce domain concepts which can and should be public. The tests can be wrote at this level then. Just find the right test seam.

What is the benefit?

The ability to switch implementation details without breaking public functionality. A whole world of refactoring options are available, inline method, extract method, extract class, inline class, replace with library and so forth. As long as the tests pass, you can be confident.

Sunday, 14 December 2014

Three Steps to Code Quality via TDD

Common complaints and problems that I've both encountered and hear other developers raise when it comes to the practice of Test Driven Development are:
  • Impossible to refactor without all the tests breaking
  • Minor changes require hours of changes to test code
  • Test setup is huge, slow to write and difficult to understand
  • The use of test doubles (mocks, stubs and fakes is confusing)

Over the next three posts I will demonstrate three easy steps that can resolve the problems above. In turn this will allow developers to gain one of the benefits that TDD promises - the ability to refactor your code mercifully in order to improve code quality.


  1. Stop making everything public

Saturday, 13 December 2014

Factory Obsession

I have noticed a pattern over the years with developers of which I will refer to as factory obsession. Everything is a factory or builder object. To some, the use of new is banned.

Consider a object that is responsible for some business logic and finally saves the result to a persistent store.

Message here is a value object, however the new can cause an odd fear within developers. Therefore a factory is required. Or is it? How can we test the repository is updated with the new message without reference equality?

An example test in C#, using the Mock framework with this newly introduced factory would look like:

This fear of new is wrong.

  • Instantiating value types is a good thing.
  • Instantiating entities is a good thing.
  • Instantiating services can depend - if the service is expensive we don't want to create lots of instances on a whim.

Here the factory offers nothing but a more strongly coupled solution.

If we ignore the factory the test becomes easier to write. To do this equality should be correctly implemented upon the message value type. I have questioned this in the past but for correct Domain Driven Design (DDD) semantics this is a good thing to follow.

We can take this further though. If we ditch the factory idea all together and replace the repository with a fake implementation we can have an even cleaner test fixture. You would still need equality but the design retains its flexibility.

Factories have their place, like all design patterns, however they should be introduced as part of the refactor step in most cases. Hiding the new keyword is not a goal. The fact that mocking frameworks default to reference equality shouldn't force you to make a more complicated or coupled solution to a problem.

Tuesday, 18 November 2014


Some tasks in software development are mundane such as formatting and code conventions. Where possible tooling should take away some of this pain, however sometimes you need a developer to take on a task that requires a great deal of time and/or effort to complete. Tooling will only get you so far.

An example of this would be declaring that all projects build and compile with zero warnings. I've tried this in the past after a team retrospective. We had hundreds of errors per project, covering about fifteen projects at the time. Spending several weeks of development time resolving these would not have be fun nor financially viable. However we really wanted to implement this change


  • I wrote a single test which would execute as part of the build process that asserted the count of the errors per project.
  • Every now and then whenever I had some slack time (10 mins before a meeting, 30 mins at the end of the day etc...) I would open up a project and fix some errors. Then run the test and try and lower the number of errors it was asserting against until I hit the lower limit.
  • Rinse repeat this process and after a while a project would assert that there are no errors.
  • From here on it was impossible for a developer to commit in a change that would raise a warning.
  • The limit would ensure that during this period no new errors were added, increasing the work load.

After a month or so all the projects reported zero warnings. Going forward the test was modified so that new projects added to source control would be checked and have the same tests run against them, meaning no new projects can have a warning count greater than zero.

It turns out this has been documented before - its called Ratcheting. While I didn't know it at the time its nice to have a name to use when describing this technique.

Thursday, 6 November 2014

Dependency Injection (DI) Containers


One place for configuration
Rather than scattered through out the system. Most DI containers have some sort of "module" system where you group associated components together.
Different types of lifestyle can be achieved. Per request, per thread, singleton and others. Usually other frameworks have the ability to plug into these containers, meaning such features integrate nicely.
Feature rich
Included along with the basic DI components is usually a large amount of additional features which may or may not be needed.


Usually in the form of frameworks or libraries. DI is a simple concept, but such containers can make getting to grips with it tremendously difficult.
Configuration can be difficult. Rather than just applying DI you need to learn the tooling. XML configuration has widely fell out of favour, but even code based configurations can be costly to setup.
Runtime errors
Any errors that might have occurred at compile time (in a static language) now become runtime errors. Circular references are easily introduced if you are not careful. Made a mistake during configuration? The system will be out of action. If you're lucky the stacktrace can point you in the right direction, but usually these are vague and/or confusing.
With the container in charge you lose control of what should be an easy part of your development process. The more convention based configuration you apply, the more chance things can go wrong. Simple changes such as multiple implementations of an interface can prove difficult to configure without breaking previous conventions. Much of the time adding a new class to the system feels risky - you won't know until runtime if you've got it working.


Keep your dependency wiring at your application root - most likely main. This is my preferred, default approach to begin with.
KISS - Modules
If this configuration starts to get out of hand - use modules. Need to modify how the kitchen is built? Just open up KitchenModule.cs. With direct access to the references of these dependencies you can control scoping. For example you can re-use the same kitchen instance between house instances.
As always you can refactor towards an DI container if you feel the need to use one.