static initializer vs constructor

Discussion in 'Java' started by Ed Thompson, Oct 9, 2004.

  1. Ed Thompson

    Ed Thompson Guest

    What can you do in a static initializer that you can't or wouldn't want
    to do in a constructor?

    I am doing some research on static initializer's, and I don't totally
    get the why of it.

    Thanx
    Ed
    Ed Thompson, Oct 9, 2004
    #1
    1. Advertising

  2. Ed Thompson

    Yogo Guest

    > What can you do in a static initializer that you can't or wouldn't want to
    > do in a constructor?
    >
    > I am doing some research on static initializer's, and I don't totally get
    > the why of it.


    If a class contains a static variable, that variable may be accessed without
    creating an instance of the class (thus the constructor is not called).

    You can use the static initializer to initialize the static variable
    (assuming you need more than one statement for that).


    Regards,

    Yogo
    Yogo, Oct 9, 2004
    #2
    1. Advertising

  3. Ed Thompson

    Alex Kizub Guest

    To do something what you need once for all instances.
    Like load Orale driver only once.

    public class DataAccess {
    /** Load Oracle driver one time for application */
    static {
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    } catch (Exception ex) {
    System.out.println("static driver not found: " + ex.getMessage());
    }
    }
    public boolean openCon(String url, String user, String password) {
    java.sql.Connection con = DriverManager.getConnection(url, user, password);

    //...
    return true;
    }

    }



    Ed Thompson wrote:

    > What can you do in a static initializer that you can't or wouldn't want
    > to do in a constructor?
    >
    > I am doing some research on static initializer's, and I don't totally
    > get the why of it.
    >
    > Thanx
    > Ed
    Alex Kizub, Oct 10, 2004
    #3
  4. Ed Thompson

    [private] Guest

    Ed Thompson wrote:
    > What can you do in a static initializer that you can't or wouldn't want
    > to do in a constructor?
    >
    > I am doing some research on static initializer's, and I don't totally
    > get the why of it.
    >
    > Thanx
    > Ed


    A static initializer allows you to do more complex setup tasks for a
    static instance than is possible with a single line init statement.

    For example, I have a class in one of my applications that acts as a
    type code translator from one system to another. I store the lookups in
    several static final maps, and do the initialization like this:

    private static final Map fooBarMap;
    static {
    Map m = new HashMap();
    m.put("a", "b");
    m.put("c", "d");
    fooBarMap = Collections.unmodifiableMap(m);
    }

    You can't put that kind of setup code in a constructor since the
    constructor is called for each new instance of the class, and then you'd
    end up re-initializing the variables every time a new instance is created.
    [private], Oct 10, 2004
    #4
  5. Ed Thompson

    [private] Guest

    Jacob wrote:
    > Ed Thompson wrote:
    >
    >> What can you do in a static initializer that you can't or wouldn't
    >> want to do in a constructor?

    >
    >
    > From a readbility point of view, I always try to avoid
    > static initializers as I don't find it obvoius exactly
    > when the code gets executed. And I have yet too see an
    > example where you *have* to use it.
    >
    > Rather than this:
    >
    > static {
    > statements;
    > }
    >
    > I prefer this:
    >
    > private static boolean isInitialized_; // Implicit false
    >
    > public Constructor()
    > {
    > if (!isInitialized_) {
    > statements;
    > isInitialized_ = true;
    > }
    > }
    >
    > I bit more coding, but with a distinct and clear flow of logic.
    > As a side effect it ensure lazy initialization.
    >
    > If no constructor is involved (the entire code segment act on
    > static data) I'll model it as a singleton class with a private
    > constructor with eqivalent implementation.
    >
    > Did I miss something? I am sure Sun invented this technique for
    > a reason. The examples I've seen in this thread doesn't convince
    > me though as they all can be rewritten like the above.
    >



    The biggest problem with your technique is that it won't work if the
    static variable is declared "final."

    For example, this code using your design with a boolean init flag won't
    compile under Java 1.4.2. It fails with the error "cannot assign a
    value to final variable dateInitialized_"

    public class StaticInitTest {
    private static boolean isInitialized_;
    private static final java.util.Date dateInitialized_;

    public StaticInitTest() {
    if (!isInitialized_) {
    dateInitialized_ = new java.util.Date();
    isInitialized_ = true;
    }
    }

    public static void main(String[] args) {
    StaticInitTest tester = new StaticInitTest();
    System.out.println(tester.dateInitialized_);
    }
    }
    [private], Oct 10, 2004
    #5
  6. Ed Thompson

    Jacob Guest

    Ed Thompson wrote:

    > What can you do in a static initializer that you can't or wouldn't want
    > to do in a constructor?


    From a readbility point of view, I always try to avoid
    static initializers as I don't find it obvoius exactly
    when the code gets executed. And I have yet too see an
    example where you *have* to use it.

    Rather than this:

    static {
    statements;
    }

    I prefer this:

    private static boolean isInitialized_; // Implicit false

    public Constructor()
    {
    if (!isInitialized_) {
    statements;
    isInitialized_ = true;
    }
    }

    I bit more coding, but with a distinct and clear flow of logic.
    As a side effect it ensure lazy initialization.

    If no constructor is involved (the entire code segment act on
    static data) I'll model it as a singleton class with a private
    constructor with eqivalent implementation.

    Did I miss something? I am sure Sun invented this technique for
    a reason. The examples I've seen in this thread doesn't convince
    me though as they all can be rewritten like the above.
    Jacob, Oct 10, 2004
    #6
  7. Ed Thompson

    Ed Thompson Guest

    Yogo wrote:
    >>What can you do in a static initializer that you can't or wouldn't want to
    >>do in a constructor?
    >>
    >>I am doing some research on static initializer's, and I don't totally get
    >>the why of it.

    >
    >
    > If a class contains a static variable, that variable may be accessed without
    > creating an instance of the class (thus the constructor is not called).
    >
    > You can use the static initializer to initialize the static variable
    > (assuming you need more than one statement for that).
    >
    >
    > Regards,
    >
    > Yogo
    >
    >

    Thanx!
    Ed Thompson, Oct 10, 2004
    #7
  8. Ed Thompson

    Ed Thompson Guest

    [private] wrote:

    > Ed Thompson wrote:
    >
    >> What can you do in a static initializer that you can't or wouldn't
    >> want to do in a constructor?
    >>
    >> I am doing some research on static initializer's, and I don't totally
    >> get the why of it.
    >>
    >> Thanx
    >> Ed

    >
    >
    > A static initializer allows you to do more complex setup tasks for a
    > static instance than is possible with a single line init statement.
    >
    > For example, I have a class in one of my applications that acts as a
    > type code translator from one system to another. I store the lookups in
    > several static final maps, and do the initialization like this:
    >
    > private static final Map fooBarMap;
    > static {
    > Map m = new HashMap();
    > m.put("a", "b");
    > m.put("c", "d");
    > fooBarMap = Collections.unmodifiableMap(m);
    > }
    >
    > You can't put that kind of setup code in a constructor since the
    > constructor is called for each new instance of the class, and then you'd
    > end up re-initializing the variables every time a new instance is created.

    Thanx!
    Ed Thompson, Oct 10, 2004
    #8
  9. Ed Thompson

    Jacob Guest

    [private] wrote:

    > The biggest problem with your technique is that it won't work if the
    > static variable is declared "final."


    Good point. So maybe the good practice should be to use
    static initialization *only* on static final variables?

    But it raise another interesting discussion of whether
    "final" should be used for *constants* only or also for
    variables that doesn't change. In my opionion there is
    a conceptual difference on the two. My point is that I
    wouldn't use "final" for the "variable" (dateInitialized_)
    in your example so I still see no use for the static
    initializer.
    Jacob, Oct 11, 2004
    #9
  10. Ed Thompson

    Chris Uppal Guest

    Jacob wrote:

    > From a readbility point of view, I always try to avoid
    > static initializers as I don't find it obvoius exactly
    > when the code gets executed.


    Do you mean that it's not sufficiently /explicit/ when the code gets executed,
    or do you mean that you don't know (or don't expect others to know) what the
    rules are ?

    If it's the former, then I can see your point, but I don't think the gain is
    worth the cost.

    If it's the later then -- since you (or they) will have to read other people's
    code anyway -- it'd be better to learn what the rules are.


    > Did I miss something? I am sure Sun invented this technique for
    > a reason.


    1) The technique (in your posted code, anyway) is not threadsafe.

    2) The technique falls over if you need to have data initialised before any
    instances have been created.

    4) It's potentially fragile, in that you have to remember to include that code
    segment, or a path to it, in every constructor.

    5) It's unnecessarily wordy, in that it (roughly) duplicates what's built into
    the Java design. (Or, to put it another way -- Java's design includes a
    built-in idiom to save you/us the effort of writing all that out every time.)

    6) It's misleading, in that it's not obvious /why/ you are doing it that way
    rather than using Java's standard facilities. If I were reading that code, I'd
    immediately start looking for a reason why it was inappropriate to have to
    "initialisation" code executed /until/ the first instance was created.
    (Remember that class initialisation is lazy anyway.) Then, having discovered
    that there was no technical reason for the use of the idiom, I'd then be very
    suspicious of the rest of the code, since it would suggest (not imply) that the
    writer didn't understand Java, and therefore that the code might well contain
    lurking errors-of-ignorance.

    -- chris
    Chris Uppal, Oct 11, 2004
    #10
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Razvan
    Replies:
    7
    Views:
    17,570
    Lee Fesperman
    Jul 4, 2004
  2. Matthias Kaeppler

    Initializer vs. Constructor assignment

    Matthias Kaeppler, May 7, 2005, in forum: Java
    Replies:
    4
    Views:
    1,012
    Tor Iver Wilhelmsen
    May 8, 2005
  3. Chris K
    Replies:
    1
    Views:
    572
    Victor Bazarov
    Apr 17, 2004
  4. Generic Usenet Account
    Replies:
    10
    Views:
    2,228
  5. joes
    Replies:
    3
    Views:
    314
Loading...

Share This Page