Reading other people’s code is great, be it good or bad, functioning or broken there is always something to discover – and generally it is something that makes you think: “d’oh, why didn’t I see that before?”
I liked my latest discovery so much that I thought I’d share it myself for those, like me, that just hadn’t thought of it or indeed seen it elsewhere.
Record Types are the subject. We are all aware of the complications that record types bring to Apex; often you will want to perform a different action in your code depending on the type of record that you have. Or you’ll want to get a value from one field for one record type but from another for the rest. That’s cool and it makes sense but how do you write the code to do that? Hard coding the record type id is a common practice and it just about works, so long as you have declared the record types in your production org as the ids stay the same when you create sandboxes. However things don’t normally happen this way. Often a developer will create a new record type in her sandbox and make use of it there but when you move between environments this code breaks as the record type doesn’t exist and if you create it the id will be different; try running CI in an environment like this! Another problem I see with this method is that, even if the ids are consistent between environments the code is fairly meaningless: what exactly is id 00D123…..? So much for self documenting code, eh?