I attended a python dojo at dev8D last week and a conversation ensued regarding type checking within a function. As python is loosely typed and dynamic, any object could be passed into pretty much any function. A question was asked about whether a function should check for the type it was going to use prior to actually using it. It was not deemed to be “Pythonic” to check the types but rather to ensure adequate exception handling is in place in case of,well…. an exception!
I thought about this for a while and wondered if this notion could be applied to my own programming. Consider the following method:
Obviously, all we’re doing here is writing out to the console the title, first and surname of an imaginary person object. Our method only contains the essence of what we want the method to do and it would be great if that was all it had to contain but we have to think and code a little more defensively than that! So what could possibly go wrong in our little example that means we’ve got to consider adding more code to our method? Our main concern should be that the person object doesn’t actually equate to anything, so maybe we should check it exists before we try to use it:
By carrying out a null check on the person object before using it, we’re almost seeking permission before we use it. We’re certainly placing ceremonial code before the essence. This seems a bit smelly if you ask me. We’re checking for a null value every time the method runs, adding processing overhead to the method even when everything’s “peachy”.
By using a try/catch statement, we can let the essence run with sooner, but seek forgiveness and run the “ceremonial code” only runs when something goes wrong.
Although the examples in this post have centred around dealing with null references, any scenario could have been used.
I didn’t really have a strong view regarding this matter but having thought it through, I’m going seek forgiveness from now on and hopefully will be able to produce some even more “concise essence”, with an apology always on stand-by…!