Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat are the best practices for determining the tasks of Constructor, Initialization and Reset methods
    text
    copied!<p>This is a general OOP question although I am designing in Java. I'm not trying to solve a particular problem, just to think through some design principles.<br> From my experience I have reached the habit segregating object setup into three phases.</p> <p>The goal is to minimize: extra work, obfuscated code and crippled extensibility.</p> <p><br><b>Construction</b><br></p> <ol> <li>The minimal actions necessary to create a valid Object, passes an existence test</li> <li>Instantiate and initialize only "one time", never to be over-ridden, non variable objects that will not change/vary for the life of the Object</li> <li>Initialize final members</li> <li>Essentially a runtime stub </li> </ol> <p><strong>Initialization</strong></p> <ol> <li>Make the Object useful</li> <li>Instantiate and initialize publicly accessible members</li> <li>Instantiate and initialize private members that are variable values</li> <li>Object should now pass external tests with out generating exceptions (assuming code is correct)</li> </ol> <p><strong>Reset</strong></p> <ol> <li>Does not instantiate anything</li> <li>Assigns default values to all variable public/private members </li> <li>returns the Object to an exact state</li> </ol> <p>A Toy example:</p> <pre><code>public class TestObject { private int priv_a; private final int priv_b; private static int priv_c; private static final int priv_d = 4; private Integer priv_aI; private final Integer priv_bI; private static Integer priv_cI; private static final Integer priv_dI = 4; public int pub_a; public final int pub_b; public static int pub_c; public static final int pub_d = 4; public Integer pub_aI; public final Integer pub_bI; public static Integer pub_cI; public static final Integer pub_dI = 4; TestObject(){ priv_b = 2; priv_bI = new Integer(2); pub_b = 2; pub_bI = new Integer(2); } public void init() { priv_a = 1; priv_c = 3; priv_aI = new Integer(1); priv_cI = new Integer(3); pub_a = 1; pub_c = 3; pub_aI = new Integer(1); pub_cI = new Integer(3); } public void reset() { priv_a = 1; priv_c = 3; priv_aI = 1; priv_cI = 3; pub_a = 1; pub_c = 3; pub_aI = 1; pub_cI = 3; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload