This page contains an archived post to the Design Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Because...
Posted by Bill Venners on 06 Apr 1998, 11:59 PM
Bryan, I have a couple of comments about your constructors. I assume you were looking at the designing initialization chapter at http://www.artima.com/flexiblejava/desinit.html or article at http://www.javaworld.com/javaworld/jw-03-1998/jw-03-techniques.html In this chapter I use the size as an example of an attribute that doesn't have a "natural" default value. In such cases I think it's best to force client programmers to specify a default value. But on the other hand, whether or not size has a natural default value is a subjective call, and I wouldn't really have much of a problem with a no-arg constructor that just sets it to SHORT, as you do here. > public class CoffeeCup { > public CoffeeCup() { > innerCoffee = 0; > setSize(SHORT); > } > public CoffeeCup(int size) { > this(); > setSize(size); > } > public CoffeeCup(int size, int startingAmount) { > this(size); > add(startingAmount); > } > ... //your other functions > } I do see one thing that looks suspicious to me, however. It is something that I was thinking I should mention somewhere in the initialization chapter. You are calling constructors with this() that have fewer parameters. (I.e., from the constructor that takes 2 args, you call the constructor that takes 1 arg. From the 2 arg constructor, you call the no arg constructor.) What I would ordinarily expect to see is the no-arg constructor invoking the 2 arg constructor with default values, and the one arg constructor as well. Like this: public class CoffeeCup { // defs of sizes... private int innerCoffee; private int size; public CoffeeCup() { this(SHORT, 0); } public CoffeeCup(int size) { this(size, 0); } public CoffeeCup(int size, int startingAmount) { size = SHORT; innerCoffee = startingAmount; } // The other methods... } Why do I like this approach better? One reason is that this approach initializes each field once per instantiation, whereas the previous approach has multiple initializations. (But this isn't really likely a significant performance hit.) The big reason I like this better is I think it is a bit easier to read. (But just a bit, I can read and figure out the other one quickly as well.) What do you think? bv
Replies:
|