make() and initialize()

Home
Introduction
Tips and Techniques
Projects
Libraries
Links

Nolan Darilek asks on comp.lang.dylan:

"I've finally encountered a situation in which I'd like to override the default/generated constructors.

I've seen code which overrides make, and code which overrides initialize on the new class.

What is the difference between make() and initialize()?"

Scott McKay replies:

"'make' allocates a new instance. You can completely override 'make', for example, if you are maintaining a cache of objects and want to return an existing object. 'make(<vector>)' in Fun-O Dylan does this to return a canonical empty vector, e.g.

'initialize' initializes its slots. You can't completely override 'initialize' methods. They should always have a call to 'next-method()' in there somewhere, most often at the very beginning."

Bruce Hoult also replies:

"Are you familiar with C++? It's the same as the difference between "operator new" and the constructor.

make() ("operator new" in C++) finds some memory space to put the new object in.

initialize() (the constructor in C++) puts some sensible initial values into that memory space.

You write your own initialize() if you want to do things that can't be done with init-value, init-expression, init-function. Which basically means (I think) things that need to set up more than one slot in some pattern.

You write your own make() if you want to:

- substitute a different sort of object than the user asked for e.g. make(<vector>) actually returns a <simple-object-vector>. This is the "factory method pattern" in C++ or Java.

- return an existing object instead of a new one. e.g. from a cache or free-list or maybe something like the "Fly-weight Pattern".

The place the Dylan/C++ analogy breaks down is that in C++ the constructor is always run after operator new, but in Dylan if you write yoru own make() then you don't have to call initialize() (which is handy if you're returning an existing object)"


Copyright © 2000, Chris ^M Double. All Rights Reserved.
^M All products and brand names are the registered trademarks or trademarks ^M of their respective owners.

^M