Re: Rules for constructors

From: Chris Smith (cdsmith_at_twu.net)
Date: 03/17/04


Date: Wed, 17 Mar 2004 09:41:29 -0700

Alex Hunsley wrote:
> Anyway, what exactly is the moral of this tale?
>
> I suspect it's either
> a) always check your class is initialised,
> as per
> http://www.javaworld.com/javaworld/jw-12-1998/jw-12-securityrules.html,
> but this is a bit security-paranoid
>
> b) never call non-final methods from your constructor
> (or else they will be overridden causing chaos as I have experienced
> today)
> c) overridden methods should not access member variables that are
> from this class - should only access superclass member variables

I consider it to be somewhere between (b) and (c). Namely,

1. Strongly favor implementations that don't call non-final and non-
private methods from constructors of non-final classes.

2. When such method calls do exist, document this obviously, and don't
access any object state from these methods. (Even limiting state to
that of superclasses is not enough; I can construct a three-level class
hierarchy in which that's not safe either.)

-- 
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation


Relevant Pages

  • Re: Rules for constructors
    ... Alex Hunsley wrote: ... > constructor for A, the initialisation of the member variables in class B ... realising of GUI items from a constructor. ...
    (comp.lang.java.programmer)
  • Rules for constructors
    ... This is because the constructor of B calls super, and by ... the initialisation of the member variables in class B ... (or else they will be overridden causing chaos as I have experienced ... overridden methods should not access member variables that are ...
    (comp.lang.java.programmer)
  • Re: a question about classes
    ... doesn't calling the constructor result in mD and mS being ... The function iFconst has a return value of X, ... assign values to a new X object's member variables. ... This object is returned to the caller. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: No use of initializer list
    ... "will not be used as member variables": ... compileable code (unless you are getting a compile error and the point ... this constructor, what x and y represent, about f, etc), so we can't ...
    (alt.comp.lang.learn.c-cpp)
  • Re: question about objects passed into constructors
    ... > I have a question about passing an object into a constructor. ... whether a pointer is valid but this doesn't tell you whether the object, ... "good/valid" object state and supply some function to check this. ...
    (comp.lang.cpp)