Implicit casts for modifying legacy code

When dealing with legacy code it can be difficult to see where to make a change. Seeing and tracking the usage of a method /constructor parameter can require a skilled eye.

It is sometimes easier (if possible) to change the value of parameters by changing their types instead to one which provides an implicit cast to the old type. Here’s an example:

becomes:

The EntityReference class will now implicitly be converted to a string when asked for one and similarly be initialised from strings. It’s a seamless switch from using the simple value type to a type with logic.

Now you know any code that’s used from the BusinessLogic method will use a reference that follows the business rule (that it must always be upper-case). The intention also becomes more explicit and readable by encapsulating the logic in a specific class.

This example was possible because there were no side effects as a result of calculating the new reference. Also care should be taken with null references – as a rule I try not to allow null objects to be passed around and throw ArgumentNullException when given any. If you don’t, then you may need to make sure the returned Value Object is null in these instances to guarantee consistency with the previous behaviour.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s