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

OO Javascript constructor pattern: neo-classical vs prototypal

This looks like the non-singleton version of the module pattern, whereby private variables can be simulated by taking advantage of JavaScript’s “closures”. I like it (kinda…). But I don’t really see the advantage in private variables done in this way, especially when it means that any new methods added (after initialisation) do not have access … Read more

Why is __init__() always called after __new__() in Python?

Use __new__ when you need to control the creation of a new instance. Use __init__ when you need to control initialization of a new instance. __new__ is the first step of instance creation. It’s called first, and is responsible for returning a new instance of your class. In contrast, __init__ doesn’t return anything; it’s only … Read more

How do I alias a class name in C#, without having to add a line of code to every file that uses the class?

You can’t. The next best thing you can do is have using declarations in the files that use the class. For example, you could rewrite the dependent code using an import alias (as a quasi-typedef substitute): using ColorScheme = The.Fully.Qualified.Namespace.Outlook2007ColorScheme; Unfortunately this needs to go into every scope/file that uses the name. I therefore don’t … Read more

How would you code an efficient Circular Buffer in Java or C#?

I would use an array of T, a head and tail pointer, and add and get methods. Like: (Bug hunting is left to the user) // Hijack these for simplicity import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; public class CircularBuffer<T> { private T[] buffer; private int tail; private int head; @SuppressWarnings(“unchecked”) public CircularBuffer(int n) { buffer = (T[]) … Read more

How will I know when to create an interface?

it solves this concrete problem: you have a, b, c, d of 4 different types. all over your code you have something like: a.Process(); b.Process(); c.Process(); d.Process(); why not have them implement IProcessable, and then do List<IProcessable> list; foreach(IProcessable p in list) p.Process(); this will scale much better when you add, say, 50 types of … Read more