How to handle a static final field initializer that throws checked exception

If you don’t like static blocks (some people don’t) then an alternative is to use a static method. IIRC, Josh Bloch recommended this (apparently not in Effective Java on quick inspection). public static final ObjectName OBJECT_NAME = createObjectName(“foo:type=bar”); private static ObjectName createObjectName(final String name) { try { return new ObjectName(name); } catch (final SomeException exc) … Read more

Is an empty initializer list valid C code?

No, an empty initializer list is not allowed. This can also be shown by GCC when compiling with -std=c99 -pedantic: a.c:4: warning: ISO C forbids empty initializer braces The reason is the way the grammar is defined in §6.7.9 of the 2011 ISO C Standard: initializer: assignment-expression { initializer-list } { initializer-list , } initializer-list: … Read more

In Ruby, what’s the relationship between ‘new’ and ‘initialize’? How to return nil while initializing?

In Ruby, what’s the relationship between ‘new‘ and ‘initialize‘? new typically calls initialize. The default implementation of new is something like: class Class def new(*args, &block) obj = allocate obj.initialize(*args, &block) # actually, this is obj.send(:initialize, …) because initialize is private obj end end But you can, of course, override it to do anything you … Read more

Multiple constructors: the Pythonic way? [duplicate]

You can’t have multiple methods with same name in Python. Function overloading – unlike in Java – isn’t supported. Use default parameters or **kwargs and *args arguments. You can make static methods or class methods with the @staticmethod or @classmethod decorator to return an instance of your class, or to add other constructors. I advise … Read more

Static constructor equivalent in Objective-C?

The +initialize method is called automatically the first time a class is used, before any class methods are used or instances are created. You should never call +initialize yourself. I also wanted to pass along a tidbit I learned that can bite you down the road: +initialize is inherited by subclasses, and is also called … Read more

Calling a Java method with no name

This: static { System.out.print(“x “); } is a static initialization block, and is called when the class is loaded. You can have as many of them in your class as you want, and they will be executed in order of their appearance (from top to bottom). This: { System.out.print(“y “); } is an initialization block, … Read more