DRY Ruby Initialization with Hash Argument

You don’t need the constant, but I don’t think you can eliminate symbol-to-string: class Example attr_reader :name, :age def initialize args args.each do |k,v| instance_variable_set(“@#{k}”, v) unless v.nil? end end end #=> nil e1 = Example.new :name => ‘foo’, :age => 33 #=> #<Example:0x3f9a1c @name=”foo”, @age=33> e2 = Example.new :name => ‘bar’ #=> #<Example:0x3eb15c @name=”bar”> … Read more

How to automatically register a class on creation

You can indeed do this using the curiously recursive template idiom. It requires nothing from whoever is extending the class that can’t be enforced by the compiler: template<class T> struct Animal { Animal() { reg; //force specialization } virtual std::string name() = 0; static bool reg; static bool init() { T t; AnimalManager::registerAnimal(t.name()); return true; … 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

What is the pythonic way to detect the last element in a ‘for’ loop?

Most of the times it is easier (and cheaper) to make the first iteration the special case instead of the last one: first = True for data in data_list: if first: first = False else: between_items() item() This will work for any iterable, even for those that have no len(): file = open(‘/path/to/file’) for line … Read more

Python idiom to return first item or None

Python 2.6+ next(iter(your_list), None) If your_list can be None: next(iter(your_list or []), None) Python 2.4 def get_first(iterable, default=None): if iterable: for item in iterable: return item return default Example: x = get_first(get_first_list()) if x: … y = get_first(get_second_list()) if y: … Another option is to inline the above function: for x in get_first_list() or []: … 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);