Don’t write more code than is necessary to get the job done. This is another in my series of posts on Code Gardening - the practice of making small improvements as you see them while you are working.
It can be very easy to write too much code. There are a lot of reasons why this might happen; the important thing is to recognise code like this when you see it and to fix the problem on the spot.
Here’s a (recreated) example of some code designed to populate a domain object from a snippet of Xml:
This code is straightforward enough - for each of the four desired properties (
BirthYear), the appropriate element is sought and, if found,
used to populate the domain result.
Unfortunately, the developer has written too much code - the creators of the
namespace anticipated the need for this scenario and elegantly solved it right in the framework.
The static casts automatically do the right thing, returning the value of the attribute (if available) or null if not. Better yet, because the casts turn each assignment into a single line, we can collapse everything into a single initialization statement.
Unfortunately, developers work too hard all the time without knowing it. This Xml based example is just that - an example - of the broader issue.