Objectively is there a correct or incorrect way to perform anyone task in a given technology? "Best Practices" is a term that gets thrown around a lot as of late, but everywhere I've ever worked has a slightly different take on what "Best Practices" means. I started thinking in more general terms, as a Python developer there are relatively few ways to do most tasks in Python unlike Perl or Javascript. If you want to pop a list
item = my_list.pop(0)
is pretty much your only option. The same goes for keying a dictionary
item = my_dict['key']
Though with a dict you do have another option if you are not sure that your key exists
item = my_dict.get('key','default')
gives you a nice leap-before-you-look option. What most people would call idiomatic Python, but there is also the option
try:
item = my_dict['key']
except KeyError:
item = 'default'
Also a leap-before-you-look solution but more verbose. Can you objectively say that one is more correct than the other. What I think is missing here is context. Here is another example, which of the following is the best way to store information
class MyObject(object):
name = ''
age = 0
dictionary = dict(name='',age=0)
To me it depends on the context, if all you are doing is moving information around then the dict is fine, but as soon as there is some domain logic I would consider a custom type. The custom type will allow me to encapsulate the domain logic behind an interface. Instead of leaving the domain logic out in the open as you perform the necessary state transformation by keying the dictionary. The correct choice also depends on programming style, I tend to work in OOP while someone who is a functional programmer would chose a different approach.
When a flame-war breaks out often the disagreement is because of desperate contexts colliding, a kernel programmer arguing with a web developer about code efficiency verses horizontal scaling. The notion of correct and incorrect is subject to context, and if you lose sight of context then you're just blowing a lot of hot air.
No comments:
Post a Comment