Monday, June 27, 2011

My Coding Rules

Rules I follow when coding. They keep me on track for solid code.

- Don't clutter the namespace. Use as few variables as possible,
  while still maintaining clear code. Aim for low amounts of
  plain-coloured text in your editor!
  Turn this,

  def two_n_four():
      result = 2 + 4
      return result

  into this,

  def two_n_four():
      return 2 + 4

- Use as many built-ins as possible. They will be faster than anything
  you can write.

- Early / multiple returns. This reduces indentation and increases readability.
  Turn this,

  def the_func(best_arg):
      if not isinstance(int, best_arg):
           result = 'Hey stop that'
      else:
         x = foo(best_arg)
     y = bar(x)
     result = baz(y)
      return result

  into this,

  def the_func(best_arg):
      if not isinstance(int, best_arg):
           return 'Hey stop that'
      return baz(bar(foo(best_arg)))

- Low line numbers. Multiple returns can aid this. Multiple returns DO NOT
  necessarily make code harder to follow!
  Remember, the easiest way to do something is the easiest way to do something.

- Functional programming style = beauty.
  Turn this,

  def factorial(num):
      '''I'm pretty fast and typically procedural!'''
      result = 1
      while num > 1:
              result *= num
        num -= 1
      return result

  into this,

  def factorial(num):
      '''Look how many lines I didn't take!'''
      return reduce(lambda acc, n: acc * n, range(1, num+1), 1)

PYTHON RULES
- Write docstrings.

- Bind specific imports to local names!
  e.g.,
    from functools import reduce as _reduce

- Use iterators. Then use some more. A lot of functions accept iterators
  as arguments and they can really reduce the amount of work that needs
  to be done before an answer is arrived upon.

- Use decorators to rid your functions of 'administrative work'.
  Like this:

def non_empty(func):
    '''Does not allow an empty list to be passed to a function.'''
    def inner(arg):
        if len(arg) < 1:
            raise ValueError('Empty list given.')
        return func(arg)
    return inner

@non_empty
def mean(items):
    '''Calculates the mean of a list of numbers.'''
    return sum(items) / len(items)

This keeps the function clean and to the point. Anyone looking at the
decorator should also be able to tell what it does by its name.

---

My personal goal in programming is a harmonious mix of beauty and
efficiency. I believe programming to truly be an art (I often do it
to calm down) and I employ the rules above to make sure my code is
as clear and elegant as I can possibly make it.

No comments:

Post a Comment