Skip to main content

Mapping Objects via TDD

Why we map?

Many times at Codeweavers we often have tasks which involve mapping between various objects. It is no secret that I dislike such tasks. The reason we map between objects though is actually a good thing as pointed out by several developers. Mapping means our components are less coupled. For example, we can write one feature and then simply map different web services to use this feature. If we chose not to map to a common object we would need to re-implement this functionality for each service. Therefore not only do we decouple our code, but our codebase is much DRYer.

What ways do we do it?

  • One approach is a test per property. One developer will write a failing test for a property (accessor), while the other developer writes the code to make this test pass. During this process the keyboard flicks back between each developer very rapidly, in fact most of the time when writing a property per test is spent sliding the keyboard to the other developer.
  • Another approach we have tried on occasion is to have one developer write one test for the whole class, while the second developer will write the mapping code to make this test pass. We may or may not split each assert into separate tests. TDD purists will find this odd, as it does indeed go against our normal work flow. On the other hand, the reason we do this is the tests and code are virtually identical; therefore it is quicker. The downside with this "big bang approach" is the developer writing the code to make the tests pass may miss something. If this happens, finding out what is wrong is much harder as the code was written in one big go.
  • The final approach we have attempted is to not test mapping code, after all what could go wrong? It turns out a lot. Mapping often defaults values to specific values, or is subtly different to the source object. Much time can be wasted when all your tests are passing, yet the application is falling over because some data is being set incorrectly.

What is wrong with this approach?

My main gripes with mapping, albeit an integral part of our development process is how boring it is. Not to mention how slow mapping tests can be to write. After an hour to have successfully mapped an object you feel exhausted, not because of how challenging the process was, but how tedious the task was. I also cannot seem to shake the fact that after this process is complete you feel as if you are exactly the same distance away from your goal as you were before. For someone on the outside looking in, no "real" work has been done.

Enter AutoMapper

AutoMapper is a project I wish I had created myself. AutoMapper as the name suggests will map objects to other objects on your behalf. For example, imagine a view model that needs mapping from a bog standard DTO. Providing the objects names follow the same conventions, auto mapper will automatically map these values for you. Currently we have only used this on an internal project, though based on the official website AutoMapper's usage is widespread with great success.

Not all mapping is straight property to property however. Sometimes the source or destination will be of a different type. AutoMapper can handle this. It is worth mentioning special flavours of mapping such as enums are supported straight out of the box too. Additionally not all mapping is one to one. Other times default values may be required, but AutoMapper's fluent interface allows this to be achieved with limited fuss. AutoMapper can also handle more bespoke, advanced mapping scenarios. For example we mapped a raw string into a complete object with default values. This required a custom value resolver to be wrote, which in turn defeats the purpose of using a tool like AutoMapper but as this scenario was a one off this was not a problem. All together we're becoming big fans of this tool, it is just a shame it has taken so long for us to discover it.

Benefits

There are huge benefits to using AutoMapper. After getting to grips with the tool we have been able to map a complete webservice within less than thirty minutes. The trick to creating a hierarchy (objects containing other objects) is to take a bottom up approach. By taking this approach each step is gradual and steady. You are not forced to implement a large chunk of functionality in one go. In combination the way to test this was to use the built in AutoMapper validation. This one assert will ensure that any mapping that has been written is indeed valid. This will cover all your standard scenarios. From here, we wrote one test per object to ensure that any defaulting we had set up was indeed performed. For the scenario discussed above the webservice response had around ten types, this meant ten, quick unit tests ensured the whole mapping functionality worked correctly. The built in testable assertion makes much of this process a joy to do. While the two main methods you use with AutoMapper are static, we simply wrapped these in instance methods that we use in our production code.

Like most open source projects, the documentation for AutoMapper is pretty weak, though the error output you receive when developing is outstanding. Each failed test will indicate in plain English what is wrong, and better yet how to solve it. A few of us are pretty excited about AutoMapper and I look forward to mapping again in the future, something I feel odd stating. Yes, this tool is that good.

Comments

Popular posts from this blog

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 …

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 breakingMinor changes require hours of changes to test codeTest setup is huge, slow to write and difficult to understandThe 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.StepsStop Making Everything PublicLimit the Amount of Dependencies you Use A Unit is Not Always a Method or ClassCode quality is a tricky subject and highly subjective, however if you follow the three guidelines above you should have the ability to radically change implementation details and therefore improve code quality when needed.

DRY vs DAMP in Tests

In the previous post I mentioned that duplication in tests is not always bad. Sometimes duplication becomes a problem. Tests can become large or virtually identically excluding a few lines. Changes to these tests can take a while and increase the maintenance overhead. At this point, DRY violations need to be resolved.SolutionsTest HelpersA common solution is to extract common functionality into setup methods or other helper utilities. While this will remove and reduce duplication this can make tests a bit harder to read as the test is now split amongst unrelated components. There is a limit to how useful such extractions can help as each test may need to do something slightly differently.DAMP - Descriptive and Meaningful PhrasesDescriptive and Meaningful Phrases is the alter ego of DRY. DAMP tests often use the builder pattern to construct the System Under Test. This allows calls to be chained in a fluent API style, similar to the Page Object Pattern. Internally the implementation wil…