Common Ruby Idioms

The magic if clause that lets the same file serve as a library or a script: if __FILE__ == $0 # this library may be run as a standalone script end Packing and unpacking arrays: # put the first two words in a and b and the rest in arr a,b,*arr = *%w{a dog was … Read more

LBYL vs EAFP in Java?

If you are accessing files, EAFP is more reliable than LBYL, because the operations involved in LBYL are not atomic, and the file system might change between the time you look and the time you leap. Actually, the standard name is TOCTOU – Time of Check, Time of Use; bugs caused by inaccurate checking are … Read more

Is there a downside to adding an anonymous empty delegate on event declaration?

Instead of inducing performance overhead, why not use an extension method to alleviate both problems: public static void Raise(this EventHandler handler, object sender, EventArgs e) { if(handler != null) { handler(sender, e); } } Once defined, you never have to do another null event check again: // Works, even for null events. MyButtonClick.Raise(this, EventArgs.Empty);

Named Parameter idiom in Java

The best Java idiom I’ve seem for simulating keyword arguments in constructors is the Builder pattern, described in Effective Java 2nd Edition. The basic idea is to have a Builder class that has setters (but usually not getters) for the different constructor parameters. There’s also a build() method. The Builder class is often a (static) … Read more

`if key in dict` vs. `try/except` – which is more readable idiom?

Exceptions are not conditionals. The conditional version is clearer. That’s natural: this is straightforward flow control, which is what conditionals are designed for, not exceptions. The exception version is primarily used as an optimization when doing these lookups in a loop: for some algorithms it allows eliminating tests from inner loops. It doesn’t have that … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)