Discussions

EJB programming & troubleshooting: Static Classes vs Object Instantiation

  1. Static Classes vs Object Instantiation (3 messages)

    Hello.

    I have a simple "data accessor" class that has no attributes, but rather a simple method that takes a primary key as the input, and returns a Person object from a database. Now, I am wondering whether I should use a static method, or instantiate an instance of the class before calling the finder method.

    i.e.

    So, if the finder class is called PersonFinder, I can do either of the following:

    Option a)
    Person myPerson = PersonFinder.FindByID("12345");

    OR
    Option b)

    Person myPerson = new PersonFinder().FindByID("12345");


    1) Is Option B wasteful from a performance perspective - i.e. are we instantiating objects for no good reason?

    2) Will the static class option a introduce a bottleneck if multiple users are accessing it at the same time - i.e. How does the JVM deal with simultaenous multiple requests to a static method?

    3) Any other issues I should consider?

    4) Which option have you used in the past and why?

    Thanks for your help

    Paddy




  2. 1) Is Option B wasteful from a performance perspective - i.e. are we instantiating objects for no good reason?
    Yes your thinking is correct if the methods does not hold any state then they can be made static, which in turn helps the class loader.

    2) Will the static class option a introduce a bottleneck if multiple users are accessing it at the same time - i.e. How does the JVM deal with simultaneous multiple requests to a static method?
    Use synchronized keyword to make the method thread save.

    3) Any other issues I should consider?
    Making a generic interface which supports latter stage maintenance. If in future this method need to use some state in that case it may be needed to make it non static. which make impact on all the modules that use this method as static.

    4) Which option have you used in the past and why?
    In case i will prefer using static method except for the case that i foresee a need that this method in future will hold some state.

  3. The only case I can think of where you would want to use option b is if you wanted to be able to choose different Person Finders at runtime, i.e.:

    PersonFinder pf = FinderFactory.get("Person");

    Person p = pf.findById(12345);

    Otherwise a is best.

    Tom
  4. I tend to agree with both answers given here, but I have seen many instances of commercial code that use the object instantiation approach - so I'm guessing that this is no coincidence, but rather a well known (but not often explained) pattern.

    Can anyone shed any additional light?

    Tha

    Paddy