Wednesday, 23 November 2016

DDD - Events

The act of something happening is one of the most crucial aspects of implementing Domain Driven Design (DDD). I missed the importance of domain events when first exploring DDD.

Why

Most requirements come in the form when something happens, do this. Something in this case would be an action, and this would be the result taken afterwards. Most domain events can be discovered when requirements use this sort of language.

Another important consideration is that most requirements are evolutionary. They are often added as the feature is developed. What may start off as a single piece of behaviour, may evolve into something much more complex. Events allow this evolution in a decoupled manner.

Example

When a blog post is published, update the authors statistics. In code this may have a signature similar to:

The publish method is responsible for the publishing of the post. This entity holds responsibility for the pre-conditions and post conditions of such action. Also the method takes a domain service that will update the authors statistics as this is not the responsibility of the Post entity itself.

A new requirement may be to automatically send out a tweet with the post title and description. Without events this could be added in a similar manner.

Again the service will do the right thing once invoked, in this case send a tweet out. As you can see we could repeat this sort of enhancement over and over. While this does indeed complete the functionality that the business requires, the solution is far from elegant. A much better solution is to rely upon domain events.

Solution

The difference here is the publish method does nothing other than its internal logic. However it does publish (raise) an event to indicate a post has been published. Subscribers (listeners) to this event can then perform their corresponding actions.

Using the previous example two subscribers would be configured to send tweets and update author statistics. Each of these subscribers (handlers) would run in process by default, so their internal implementation should be as simple as possible. In other words record the request, and process this in the background. The code to raise the event is relatively simple, and can simply forward to any registered subscribers based upon a type. Any failure should not cause the publish to fail. Alternatively external subscribers could also handle this event, though this implementation would require the use of resilient and durable storage such as message queues or databases.

Ultimately domain events allow for extremely loosely coupled code, that is open for extension. Each handler can be developed and tested in isolation. The use of composition means that new features should become easy additions, with low risk.

One aspect that may stand out is that the use of this pattern uses a static class to publish events. While in most cases this would be poor for testing, this is not the case here. For tests prior to each step executing you can simply clear any registered handlers and configure what is required. If no handlers are configured, then nothing occurs. Also test handlers that simply report that fact a message has been raised are more than adequate.

Downsides

While this refactored example is loosely coupled, and open for extension, the intent of what happens after a publish is somewhat lost. Before it was clearer to see what the Publish method would do. This is a trade off, though the pros outweigh the cons here. Most IDE's have a way of showing you the use of all types, so we could easily see any handlers that consume the PostPublishedEvent.

Even with IDE/editor support, the loosely coupled nature of Domain Events can be tricky to debug at runtime. For example I once accidentally configured a game engine to handle events triggered from player movement. This meant that each frame of the game executed the collision detection algorithm twice, instead of once. Without a clear audit of what handlers are being executed upon what events, the use of domain events can be tricky to debug.

Lessons

  • Domain Events are a key area of DDD.
  • Use events to write loosely coupled code.
  • Ensure you have a method of auditing with handlers respond to which events.

Tuesday, 8 November 2016

POODR Highlights Part 2

Two other stand out topics from POODR were the use of tests and inheritance. The first set of higlights covered dependencies and arguments.

Tests

A conclusion that I agree with is that in general most programmers write too many tests.. A great quote in the book sees tests (as) the canary in the coal mine; when the design is bad, testing is hard. Sadly too many poor tests are often written. Examples such as property or construction tests, framework tests or tests that are coupled to the implementation are all common problems. Instead we should aim to get better and more value out of our tests by writing fewer of them, but of higher quality. In short test everything once and only in the proper place. A first step is to simply focus on the ROI that tests give, and focus on the high risk areas.

The test categories are broken down into two core types of tests.

  • Incoming Public Messages (public API)
  • Outgoing Public Messages (To public API of another object)

State based tests should be used for incoming public messages. While verification based tests should be used for outgoing public messages as the state is tested on the receiver, elsewhere. The distinction between commands and queries is also highlighted. In summary incoming messages should be tested for the state they return. Outgoing commands should be tested to ensure they get sent. Outgoing query messages should not be tested, merely stubbed.

These testing rules are nothing new, but the summary and importance of following these guidelines is nicely summarized within the chapter covering testing principles.

Inheritance

Inheritance is widely abused and misunderstood. Either inheritance is the solution for all problems, or you're advised to never use inheritance. POODR takes a more pragmatic approach. Inheritance is a tool that can sometimes provide an excellent solution, however you are better off duplicating code and defer such decisions until you know more.

The wrong abstraction is harder to work with than duplicated code as duplication can easily be removed. A bad abstraction that is used in many places is much harder however. The application of the Rule of Three can help here.

Lessons

  • Tests are hard - write less but focus on the quality.
  • Minimize the number of tests you write by using boundaries via incoming/outgoing messages.
  • Inheritance is not all bad.
  • Defer or hold back using inheritance until you understand the problem.

Thursday, 27 October 2016

POODR Highlights Part 1

Practical Object-Oriented Design in Ruby or POODR is clearly a book about Ruby development, however the odd aspect is much of the concepts apply to other languages. In fact I've taken these ideas and used them both before and after reading the book in other dynamic languages and even static languages such as C#. In summary the book is well worth a read, even if you don't do Ruby development full-time.

A few of the highlights for me will be spread out across the following posts.

Dependencies

The author takes a firm stance on dependencies. Anything that cannot be controlled by the class itself should be protected from change. In other words a message sent to self/this is preferred than directly interacting with a dependency.

I've followed this pattern in the past, but the seeing the justifications for the benefit of this has made me realise the importance of such a practice. In the first example the publish method directly knows about the twitter feed it must interact with. In the second example the class sends a message to itself, while the class internally will still know how to interact with the dependency this is hidden. The private method has this responsibility.

With a single use you could argue there is not much difference, but the PostPublished method is a nice seam for both testing and changes. We could easily add assertions or make changes within the PostPublished method without fear of changing anything else. Finally if the PostPublished method is used in multiple places this abstraction pays for itself straight away.

Arguments

Arguments are another key area that can change. Just like dependencies, the book focuses on the idea that making small changes up front can lead to flexible code that can handle change in the future. While you could argue that the order of arguments changing in the future may never happen, using named arguments has a great side effect on readability.

In static languages your IDE will most likely have a automated method of adding these in, so the C# example below can easily add named arguments with the press of a keyboard shortcut.

Named arguments provide increased readability with very little effort. Tests often benefit from the use of named arguments as you can remove the need for temporary variables, and instead in-line them to the location of use. While the third example is more wordy, they can safely be re-ordered without fear of compilation or runtime errors.

Lessons

  • Wrap dependencies even if they are only used once. A message to self/this is preferred. Easier to change and provides seams for future work.
  • Use named arguments for improved readability and the ability to reduce temporary variables. Named variables can be dropped if there is only one argument or the variable is well named.

Tuesday, 11 October 2016

The New Guy

Everyone is new at some point. No matter your experience level. You're either new to the team or new to the business. Being the new person is both a blessing and a curse.

You're New

When you're new you come with no baggage. You're full of questions and curiosity.

  • Why do we do it this way?
  • Isn't there a better way of doing this?
  • Have you considered this instead?

These are all great questions for new starters to ask, and for teams to hear.

You Have a New Team Member

When you have a new team member you gain someone with a fresh perspective. They're full of questions and curiosity. Rather than history, they'll be open to new and fresh challenges. A new member can ask you to question current practices. It is very easy to overlook problem areas only until someone with a fresh outlook arrives.

How to be New

There are two roles a new team member must play.

  • Learning
  • Challenging

The learning phase should involve questions, shadowing and pairing. The goal is to learn about the system, the architecture and the business.

The second phase should be to challenge and question the status quo. Provide better solutions, or ask for justifications and explanations. This is both win-win for the team and the new member. They'll learn and the team will gain a fresh insight into their successes and failures.

The key part of being a new team member is balance within these areas. Too much learning and no challenging will benefit no one. Likewise kicking up a fuss over every detail is not going to end well.

New Starter Balance

A past mistake I've made is swaying towards learning the system, versus challenges areas that were clearly wrong or needed improving. This is a tough area, as you don't want to rock the boat, but at the same time some rocking is required. The key is to balance this.

Advice to my past self would to tackle areas that you can have an impact in. For example a neglected process or area. By picking your battles in this manner you can slowly build your brand within the team, further allowing you to take on the more controversial challenges. For example if you've been around for a while, and proven yourself you'll have an easier time suggesting and implementing change.

Lessons

  • Remember the Monkey and Banana Analogy.
  • Balance between learning and challenging when a new starter.
  • Start slowly when a new starter, stack up small wins over time instead of a big bang approach.
  • Embrace new starters, use them to test your processes and documentation.

Monday, 3 October 2016

Constant Object Anti Pattern

Most constants are used to remove magic numbers or variables that lack context. A classic example would be code littered with the number 7. What does this refer to exactly? If this was replaced with DaysInWeek or similar, much clarity is provided. You can determine that code performing offsets would be adding days, rather than a mysterious number seven.

Sadly a common pattern which uses constants is the use of a single constant file or object.

The beauty of constants is clarity, and the obvious fact such variables are fixed. When a constant container is used, constants are simply lumped together. These can grow in size and often become a dumping ground for all values within the application.

A disadvantage of this pattern is the actual value is hidden. While a friendly variable name is great, there will come a time where you will want to know the actual value. This forces you to navigate, if only to peek at the value within the constant object. A solution is to simple perform a refactor to move the variable closer to use. If this is within a single method, let the constant live within the method. If a class, let the constant live at a field level. Finally if the constant is used across multiple classes, find a shared home and rely on a well thought out namespace.

A similar issue regarding constants is the use of configuration files or similar to set the values. While the const keyword is dropped in this case, the object performs the same role. A public key, followed by a value that is used. The anti pattern in this case is treating all values as requiring configuration. Unless you need to change such values at runtime or based on deployment models, inline constants are much preferred. Literal values, mainly strings can often be left inline with limited downsides also. For example, a fixed, relative file path is much better left inline. If you are worried about lack of context, then the use of named arguments can help.

Lessons

  • Keep constants local to methods, or classes.
  • Avoid constant objects or files as these will become bloated and lack context.
  • Only introduce configuration for aspects that need or will change. Defer second guessing.
  • Use named arguments to add context for inline variables.