Auto-register class methods using decorator

Here’s a little love for class decorators. I think the syntax is slightly simpler than that required for metaclasses. def class_register(cls): cls._propdict = {} for methodname in dir(cls): method = getattr(cls, methodname) if hasattr(method, ‘_prop’): cls._propdict.update( {cls.__name__ + ‘.’ + methodname: method._prop}) return cls def register(*args): def wrapper(func): func._prop = args return func return wrapper … Read more

anti-if campaign

The problem is not the ‘if’ statement, it is the programmers who write bad code. EDIT: Also, as others have pointed out, you should be using polymorphism (if available) when you are using if statements to check the type of an object, but if statements in and of themselves are very useful and fundamental constructs.

When do we need decorator pattern?

The Streams in Java – subclasses of InputStream and OutputStream are perfect examples of the decorator pattern. As an example, writing a file to disk: File toWriteTo = new File(“C:\\temp\\tempFile.txt”); OutputStream outputStream = new FileOutputStream(toWriteTo); outputStream.write(“Sample text”.getBytes()); Then should you require some extra functionality regarding the writing to disk: File toWriteTo = new File(“C:\\temp\\tempFile.txt”); OutputStream … Read more

Using a class’ __new__ method as a Factory: __init__ gets called twice

When you construct an object Python calls its __new__ method to create the object then calls __init__ on the object that is returned. When you create the object from inside __new__ by calling Triangle() that will result in further calls to __new__ and __init__. What you should do is: class Shape(object): def __new__(cls, desc): if … Read more

Singleton with parameters

Singleton is ugly but… public class Singleton { private static Singleton _instance = null; private static Object _mutex = new Object(); private Singleton(object arg1, object arg2) { // whatever } public static Singleton GetInstance(object arg1, object arg2) { if (_instance == null) { lock (_mutex) // now I can claim some form of thread safety… … Read more

Android Button setOnClickListener Design

If you’re targeting 1.6 or later, you can use the android:onClick xml attribute to remove some of the repetitive code. See this blog post by Romain Guy. <Button android:height=”wrap_content” android:width=”wrap_content” android:onClick=”myClickHandler” /> And in the Java class, use these below lines of code: class MyActivity extends Activity { public void myClickHandler(View target) { // Do … Read more