[Grace-core] Inheritance and object initialisation

Andrew P. Black black at cs.pdx.edu
Wed Jul 25 12:32:52 PDT 2012


I just realized that, if one wants the Smalltalk-like (and Java-like) behavior of every object running an "initialize" method _after_ it is created, then we can get that behaviour in a similar way to the way that Smalltalk gets it — by inheritance.  Thusly:

	def initializingClass = object {
			method initializedNew {
				self.new.initialize
			}
			method new is abstract  	// I assume that "is abstract" means that it can be overridden without an overrides annotation.
			method initialize is abstract
	}

	def aCanvas = object {
			inherits initializingClass.new
			method new { 
				object {
					inherits ...
					... define your instance object here ...
				}
			}
			
			method initialize {
				// this method executes after the instance of aCanvas has been created.
				// you can do all of the side effects you want here.  self refers to the new object
			}
	}


As in Smalltalk, this pattern works well when there are no parameters to the factory method.   However, if the programmer is following Kent Beck's Constructor Method Pattern (which I always tell my students to do)

	Constructor Method Pattern: Provide methods that create well-formed instances. Pass all required parameters to them.

then the factory method will almost always have parameters, and if the programmer is using the intention-revealing selector pattern, then the factory method won't be called "new", but will have a name that communicates the role of the arguments.

In this case, implicit initialization is a bit less elegant:


	def aCanvas = object {
			inherits initializingClass.new
			method new { 
				object {
					inherits ...
					... define your instance object here ...
				}

			method windowOfWith(w)height(h) {
					def result = self.initializedNew
					result.height := h
					result.width := w
					result
				}
			
			method initialize {
				// this method executes after the instance of aCanvas has been created, but before the assignment of h and w to its fields
				// you can do all of the side effects you want here. self refers to the new object
	}


Personally, I don't see that this is better than just requesting initialize directly from inside the  windowOfWith(w)height(h) method, 

			method windowOfWith(w)height(h) {
					def result = self.new
					result.initialize
					result.height := h
					result.width := w
					result
				}

but if a programmer really objects to requesting initialization explicitly, then this pattern is available.

	Andrew





More information about the Grace-core mailing list