Construction methods

Friday 13 June 2003This is more than 21 years old. Be careful.

PragDave writes about a small matter, but one that made me think: Construction Methods. He favors static methods over overloaded constructors, because they can be distinguished by name rather than parameter types.

It’s this kind of attention to detail, the willingness to ponder the best approach to even the smallest things, that makes all the difference in the code a developer writes. Dave correctly describes the technique as not particularly new, which also gets him points: too often technologists believe that only flashy revolutionary new techniques can be of value. Not true: mostly what adds value to software is good old-fashioned engineering, and caring about little things that add up throughout a code base.

Unfortunately, for C++ coders, the technique has a serious downside, which is that the static method has to know how you want your object allocated. For example, you can’t create a stack-allocated object this way, and if you have overloaded new, you are in trouble as well unless your static methods can know once and for all which overload to use. But for heap-only languages like Python, Java, and (I guess) Ruby, that isn’t a factor.

Comments

[gravatar]
I strongly agree with the static methods. There are only rare cases where I use overloaded functions, and I find it is usually more trouble than it is worth. I am coding primarily in C++, so I was wondering if you could clarify the issue you had with this in C++
[gravatar]
The issue with C++ is that objects can be constructed either on the heap or on the stack:

CFoo foo1(1,2,3);
CFoo * pFoo2 = new CFoo("abc");

We can make pFoo2 with a static method:

CFoo * pFoo2 = CFoo::withString("abc");

but there's nothing we can do about foo1.

About overloading new: a super-advanced technique in C++ is to use the so-called "placement new" syntax, whereby you can pass arguments into new to help it allocate the memory for the new object. A common example is using multiple heaps to keep objects close together in memory, or to make large-scale object lifetime management easier. This means you call new with extra arguments:

CFoo * pFoo = new(pHeap1)("abc");

To switch this call over to a static method, the static method needs to either know how to call new, or needs to take extra arguments to pass to new, both of which complicate the static method, and make it more intricately bound to the rest of the system.
[gravatar]
OK. There is a reason that most of my "C++" is just "C" with a "C++" compiler. Thanks!

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
Comment text is Markdown.