Monday, August 3, 2009

Patterns

"Decoupling objects so that changes to one can affect any number of others without requiring the changed object to know the details of others" - Observer pattern

"Group objects and treat them the group like an individual object. Create a class hierarchy in which some subclasses define primitive objects and other classes define composite objects that assemble the primitives into more complex objects" - Composite pattern

"An object that represents an algorithm is a strategy. When you want to replace the algorithm(s) used for a task, either statically or at runtime, you can encapsulate the algorithm within an object" - Strategy pattern

Wednesday, April 8, 2009

do { } while(0);

This is often seen in kernel code. Here's a nice explanation from the linux kernel newbies FAQ:

http://kernelnewbies.org/FAQ/DoWhile0

Saturday, April 4, 2009

Python's "for-else" and "while-else" loops

Almost every imperative procedural language has a for and while kind of loop. But Python is the only language that has an "else" attached to for or while. And the else does not have what you would think is the intuitive meaning (it doesn't get executed only if the for or while is never executed i.e. the condition is false to begin with). Rather, if the for or while ends normally without a break statement (i.e. it ends because its condition becomes false), the else is executed.

To me with my beginners knowledge of Python, it seems a bit unclean, and out of place for a precise and tightly controlled feature set language like Python. Let's see if I am proven wrong when I know more.

Edit on 4/8:
As expected, I was proven wrong. Turns out there is a very useful common idiom that is addressed by this. We typically code a "did_it_happen_flag" in a for or a while loop (pseudocode)


while(...) {

  if(...) {

    did_it_happen = TRUE;

    break;

  }

}



if(!did_it_happen) {

  printf("It didn't :-(");

  // Do something useful

}








This can be coded in Python like this:


while (...):

  if(...) : break

  ...

else:

  print "It didn't :-("



This way that extra check is not required - if the break were never hit, the else associated with the while takes care of taking the action we need.