Monday 24 September 2018

Using a composite key in a map

Once again I stumbled upon old code, that could use some refactoring.

It took me and my colleague a few seconds to process what the software designer had in mind when he did this.

As it was up to me to add another field to the construction, making it even more terrible than it was, it was time for a refactoring.

Refactored solution

We quite quickly came up with using a Composite Key, which of course is the default way to deal with this sort of thing.

Added benefit

There was some trickery going on to properly deal with NULL keys (which are sometimes not allowed in a Map implementation1).

This disadvantage now disappears with this nice composite key.

Test setup

I tested it with a list of cars, and I do not wish to withhold the test setup:

Fuzzy matching

Of course it is quite easy to just match on some of the criteria. In this case, we could use a Map containing Lists, where the composite key used has empty fields, and would cause a list of cars to be returned and a full composite key (all search criteria) would just yield a list containing one specific car.

If we wish to use fuzzy matching, we are in a bit of a bind.

I'm pretty sure there are always other (perhaps even better) ways of doing this. If you know of some, let me know.

I'm always interested.

References

[1] Oracle JavaDoc - Map Implementation
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
Different Types Of Cars List
https://auto.ndtv.com/news/types-of-cars-1450327

No comments:

Post a Comment