You have a set of large set (say 250) of classes. You know that all those classes have a common public property on them – let’s say Id, which is an integer. Currently none of these types have any common base class, nor do they have any common interfaces. The classes are code-generated and you cannot modify them; however they are partial so you can add interfaces to them. You already have good code coverage of the rest of your system and are expected to write unit tests around any code you write.
You need to write a method called Print that will be provided with a load of objects – say, 10,000 of them – and print their Id to the Console. This routine will be run as a batch task so performance is not an issue.
Do you: –
a) Create an interface called IIdentifiable, with a single int getter called Id. Painstakingly go through all 250 of your entities, create partial versions of them and manually put the interface on them. Writing unit tests as you go in the standard TDD approach, you code your Print method. You ensure that you only take in IEnumerable<IIdentifiable>, so you can simply iterate over the collection.
Sure, creating the interface and creating those 250 partial files might take a few hours and increase the number of files in the solution, but making the routine type-safe is the right thing to do.
b) Don’t bother with an interface – the Print method will take in IEnumerable<dynamic>. You simply pass in whatever objects you want to print out. You write a set of unit tests around the callers to that method to give you confidence that you won’t ever call the method with types that don’t have Id. As you don’t have to modify the partial classes, the method only takes about twenty minutes to code including your unit tests.
Why bother with all that faffing around with an interface for a single property when we own the code and know when we call it? Doing it this way gets the job done much quicker so I can get on with coding other features in the system.
Which solution would you go for? Is using dynamic here “cheating”? Is it risky? Does it indicate a bad design of your class hierarchy? Or does it indicate a willingness to pick the right tool for the job? Would it save the client that’s paying you any money? Do you care?