0

to avoid the overridable method call in constructor dilemma this approache delegate the variables initialization and calls to overridable methods to a member method that return reference to the instance its self and exception to be thrown if trying to use instance without invoking the initialization method/s so that the creation of objects will look like this

    SuperClass sup = new SuperClass().initialize("big");
    SubClass sub = new SubClass().initialize("sato", "try initialzer");
    SubClass sub2 = new SubClass().initialize("happy");
    SubClass sub3 = new SubClass().initialize();

my super class should implement methods of initializable interface it has two methods

1) initialize method in which i write code to do the following in order

a) call setter methods and other initialization code
b) make call to overridable method putting them at end of the method
this method can be overloaded to provide versions of it with necessary arguments as illustrated in complex example

2) isInitialzed method to check if the initialization done or not when a call to a method in my class that reference a variable that is initialized in initialize method and initialization not done i throw my NonInitializedInstanceException

the subclass should override the initialize method/s "all the super class versions of the initialize method" and do the following in order

1)initialize its variables
2)can call super method that don't throw NonInitializedInstanceException
3)call super.initialize() method
4)call setter methods "note that the super call the setters so to avoid our setter been useless we should call it after super initialize method call"
5)can call super method that throw NonInitializedInstanceException

handling overloaded versions of initialize done by calling the one with more parameters from the less parameter one

the following are my code

the interface

 /**
 * @author ahmed mazher
 * @param <T> making class initializable 
 * 
 */
public interface Initializable<T> {

    /**
     * do the initialization job and return reference to the implementing
     * class current instance 
     * @return
     */
    T initialize();

    /**
     * test the variables that you initialize in the initialize method
     * if it was initialized or not "or what ever test you see appropriate"
     * @return
     */
    boolean isInitialized();
}

the NonInitializedInstanceException class

/**
 * @author Ahmed mazher 
 * runtime exception to be thrown by method that reference variables that
 * are initialized by the initialize method of the initializable interface
 * you can test if initialization was done or not by isInialized method 
 * of the same interface if false throw the exception 
 */
public class NonInitializedInstanceException extends RuntimeException {

    private static final long serialVersionUID = 1L;


    @Override
    public String getMessage() {
        return super.getMessage() 
                + " you must call instance.initialize() method "
                + "before calling this method";
    }

}

example of using them

/**
 * @author ahmed mazher
 * testing the initializer pattern
 */
class LearnJava {

    public static void main(String args[]) {
        SuperClass sup = new SuperClass().initialize();
        SubClass sub = new SubClass().initialize();
    }

}

class SuperClass implements Initializable<SuperClass> {

    private String initializeDependentName;
    private final String nonInitializeDependentVal = "well done";
    @Override
    public SuperClass initialize() {
        //initializing super Class fields
        setInitializeDependentName("super class");
        //overidable method call in initializer "replacement of 
        //call in constructor"
        overridablePrintName();
        return this;
    }

    public final String getInitializeDependentName() throws NonInitializedInstanceException {
        if (!isInitialized()) {
            throw new NonInitializedInstanceException();
        }
        return initializeDependentName;
    }

    public final void setInitializeDependentName(String initializeDependentName) {
        this.initializeDependentName = initializeDependentName;
    }

    public final void youCanCallMeBeforeInitialization(){
        System.out.println(nonInitializeDependentVal);
    }

    public void overridablePrintName() {
        System.out.println("I'm the super method and my name is " + getInitializeDependentName());
    }

    @Override
    public boolean isInitialized() {
        return initializeDependentName != null;
    }
//to avoid some one messing with isInitialized() make your
    //private one and use it instead but don't forget to call it inside
    //the body of isInitialized() to maintian integrity of inheritance hierarchy
//    private boolean privateIsInitialized(){
//        return initializeDependentName != null;
//    }
//    @Override
//    public boolean isInitialized() {
//        return privateIsInitialized();
//    }

}

class SubClass extends SuperClass {

    private String job;

    @Override
    public SubClass initialize() {
        //initializing subClass fields
        setJob("testing initialize method");
        //call super method that throws nonInitialiezinstanceException 
        //before call super.initialize() method will rise the exception
        //unless you overided the isInitialized method "welling to take the risk"
        //------------------------------------------------------------------
        //System.out.println(getName().toUpperCase());
        //------------------------------------------------------------------
        //call super method that not throws nonInitialiezinstanceException 
        //before call super.initialize() method
        youCanCallMeBeforeInitialization();
        setInitializeDependentName("subClass");
        //calling super.initialize() method initialize super methods
        super.initialize();//initialize the super class
        //call super method that throws nonInitialiezinstanceException 
        //after call super.initialize() method will not rise the exception
        //unless you overided the isInitialized method in stupid way ^_^
        System.out.println(getInitializeDependentName().toUpperCase());
        //calling the setter method now to change my property as calling
        //it before the super initialization is useless as the super 
        //initialization will erase it
        setInitializeDependentName("subClass");
        System.out.println(getInitializeDependentName().toUpperCase());
        return this;
    }

    public final void setJob(String job) {
        this.job = job;
    }

    @Override
    public void overridablePrintName() {
        System.out.println("i'm overriden method and i do " + job);
    }

    @Override
    public boolean isInitialized() {
        //return false;//stupid version 
        //return true;//take the risk
        return job != null && super.isInitialized();//a good one 
    }

}

a more complicated example using initializer with arguments

class LearnJava {

    public static void main(String args[]) {
        SuperClass sup = new SuperClass().initialize("big");
        SubClass sub = new SubClass().initialize("sato", "try initializer");
        SubClass sub2 = new SubClass().initialize("happy");
        SubClass sub3 = new SubClass().initialize();
    }

}

class SuperClass implements Initializable<SuperClass> {

    private String initializeDependentName;
    private final String nonInitializeDependentVal = "well done";

    @Override
    public SuperClass initialize() {
        return initialize("i'm super with no name");
    }

    public SuperClass initialize(String name) {
        //initializing super Class fields
        setInitializeDependentName(name);
        //overidable method call in initializer "replacement of 
        //call in constructor"
        overridablePrintName();
        return this;
    }

    public final String getInitializeDependentName() throws NonInitializedInstanceException {
        if (!isInitialized()) {
            throw new NonInitializedInstanceException();
        }
        return initializeDependentName;
    }

    public final void setInitializeDependentName(String initializeDependentName) {
        this.initializeDependentName = initializeDependentName;
    }

    public final void youCanCallMeBeforeInitialization() {
        System.out.println(nonInitializeDependentVal);
    }

    public void overridablePrintName() {
        System.out.println("i'm the super method my name is " + getInitializeDependentName());
    }

    @Override
    public boolean isInitialized() {
        return initializeDependentName != null;
    }

    //to avoid some one messing with isInitialized() make your
    //private one and use it instead but don't forget to call it inside
    //the body of isInitialized() to maintian integrity of inheritance hierarchy
//    private boolean privateIsInitialized(){
//        return initializeDependentName != null;
//    }
//    @Override
//    public boolean isInitialized() {
//        return privateIsInitialized();
//    }
}

class SubClass extends SuperClass {

    private String job;

    @Override
    public SubClass initialize() {
        return initialize("i'm subclass no one give me name");
    }

    @Override
    public SubClass initialize(String name) {
        return initialize(name, "no one give me job");
    }

    public SubClass initialize(String name, String job) {
        //initializing subClass fields
        setJob(job);
        //call super method that throws nonInitialiezinstanceException 
        //before call super.initialize() method will rise the exception
        //unless you overided the isInitialized method "welling to take the risk"
        //------------------------------------------------------------------
        //System.out.println(getName().toUpperCase());
        //------------------------------------------------------------------
        //call super method that not throws nonInitialiezinstanceException 
        //before call super.initialize() method
        youCanCallMeBeforeInitialization();
        //calling super.initialize() method initialize super methods
        super.initialize(name);//initialize the super class
        //call super method that throws nonInitialiezinstanceException 
        //after call super.initialize() method will not rise the exception
        //unless you overided the isInitialized method in stuped way ^_^
        System.out.println(getInitializeDependentName().toUpperCase());
        //calling the setter method now to change my property as calling
        //it before the super initialization is useless as the super 
        //initialization will erase it
        setInitializeDependentName("setter called in subclass");
        System.out.println(getInitializeDependentName().toUpperCase());
        return this;
    }

    public final void setJob(String job) {
        this.job = job;
    }

    @Override
    public void overridablePrintName() {
        System.out.println("i'm overiden method my name is "
                + getInitializeDependentName()
                + " and i do " + job);
    }

    @Override
    public boolean isInitialized() {
        //return false;//stuped version 
        //return true;//take the risk
        return job != null && super.isInitialized();//a good one 
    }

}

suggestion of using static method factory pattern and as i expected static pain never ends here is my trial to adapt my pattern into static one but i failed i don't know how to make subClass invoke superClass create method to affect its instance

class LearnJava {

    public static void main(String args[]) {
        SuperClass.create("nono");
        SubClass.create("sato","test factory");

    }

}

class SuperClass{

    private String name;
    protected SuperClass() {
    }

    public static SuperClass create(String name) {
        SuperClass sup = new SuperClass();
        //initializing super Class fields
        sup.setName(name);
        //overidable method call useless as i always call the super instance version 
        sup.overridablePrintName();
        return sup;
    }

    public final String getName(){
        return name;
    }

    public final void setName(String name) {
        this.name = name;
    }

    public void overridablePrintName() {
        System.out.println("i'm the super method my name is " + getName());
    }
}

class SubClass extends SuperClass {

    private String job;

    protected SubClass() {
        super();
    }

    public static SubClass create(String name, String job) {
        SubClass sub = new SubClass();
        //initializing subClass fields
        sub.setJob(job);
        //call the super class initializer to affect this sub class instatnce 
        //seems no way to do it
        sub.create(name);
        SubClass.create(name);
        SuperClass.create(name);
        return sub;
    }

    public final void setJob(String job) {
        this.job = job;
    }

    @Override
    public void overridablePrintName() {
        System.out.println("i'm overiden method my name is "
                + getName()
                + " and i do " + job);
    }
}

i hope it be a good idea waiting for your comments and suggestions

Ahmed Mazher
  • 323
  • 3
  • 7

1 Answers1

1

It's a good idea to look for some initialization methods which will provide you some good structure and high quality code but I think you may refer to the Factory Method Pattern so you can improve what you have done already

The factory method pattern is a way to encapsulate object creation. Without a factory method, you would simply call the class's constructor directly: Foo x = new Foo(). With this pattern, you would instead call the factory method: Foo x = Foo.create(). The constructors are marked private, so they cannot be called except from inside the class, and the factory method is marked as static so that it can be called without first having an object.

Anas EL KORCHI
  • 2,008
  • 18
  • 25
  • the problem with static factory pattern is that it is static "static endless pain ^_^ " – Ahmed Mazher Jul 14 '16 at 16:12
  • I think a static factory pattern is less pain because you gonna instantiate and initialize your object with only one instruction Foo.create(), otherwise you can use the same pattern with some slight customization you can make the constructor public so you can use it to instantiate your class and in your constructor you may call the initialization method implicitly – Anas EL KORCHI Jul 14 '16 at 16:16
  • 2
    Please note: the static factory pattern is **NOT** the same as the [Factory Method Pattern](https://sourcemaking.com/design_patterns/factory_method) from the Gang of Four. Static Factory is more commonly used, but violates the [Open/Closed Principle](https://en.wikipedia.org/wiki/Open/closed_principle). – jaco0646 Jul 15 '16 at 14:23