Java Member Initialization Templates

I have a MyClass class:

public class MyClass {
  private MyComplexType member1;
}

I need to do a fairly intensive initialization on member1. It is enough that it easily guarantees its own method called from the constructor MyClass.

My question is which of the following formats is best for this method?

private MyComplexType initMyComplexType() { 
  MyComplexType result = new MyComplexType();  
  // extensive initialization on result...
  return result;
}

called like this:

public MyClass() {
  member1 = initMember1();
}

OR

private void initMember1() {
  member1 = new MyComplexType();
  // extensive initialization on member1...
}

called like this:

public MyClass() {
  initMember1();
}

What is the best style for a private party? Why?

+3
source share
7 answers

I would choose the first option, because it more clearly expresses the purpose of the init method and clearly shows the data stream.

, init . , , . , , , .

init , doExtensiveComplexCalculation, -.

+6

, 1 MyComplexType .

Jörn Horstmann:

public class StaticOverrideParent {

 protected static void doSomething() {
  System.out.println("Parent doing something");
 }
}

public class StaticNoOverride extends StaticOverrideParent {

 public static void main(String[] args) {
  doSomething();
 }
}

public class StaticOverride extends StaticOverrideParent {

 protected static void doSomething() {
  System.out.println("Doing something");
 }

 public static void main(String[] args) {
  doSomething();
 }
}

StaticNoOverride " -". StaticOverride " -".

+4

1. , , , , init() , . .

, template/ factory . ( , ) . , .

: , initComplexMember() buildContextMember().

+3

, .

+3

( , , ), - strong . Java:

. : .

, , , :

{

    // whatever code is needed for initialization goes here
}

Java . .

. . :

class Whatever {
    private varType myVar = initializeInstanceVariable();

    protected final varType initializeInstanceVariable() {

        //initialization code goes here
    }
}

, . , . Java.

( , , ).

+2
+1

. , . , , , .

+1

Source: https://habr.com/ru/post/1753316/


All Articles