Results 1 to 3 of 3
  1. #1
    mchammer11 is offline Member
    Join Date
    Apr 2010
    Posts
    14
    Rep Power
    0

    Default Best practices question

    Hi, I just completed a change with new functionality, with a utility class doing most of the gruntwork... and I was wondering which was the better practice... Creating an object of the class, and in the constructor calling the various utility methods, or creating an object, and using that object to call the various methods...Examples shown below (Currently I am using the first way shown)

    Java Code:
    //calling class
    ClassA obj = new ClassA();
    
    //utility class
    public ClassA() {
         method1();
         method2();
         method3();
    }
    Ex 2:

    Java Code:
    //calling class
    ClassA obj = new ClassA();
    obj.method1();
    obj.method2();
    obj.method3();

  2. #2
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    It depends. If you will always have to execute all three methods in the same order and use the created reference again, that's fine.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  3. #3
    iluxa is offline Senior Member
    Join Date
    Mar 2010
    Posts
    266
    Rep Power
    5

    Default

    In general, it's not a very good practice to stick complex logic into a constructor... whoever uses your class expects the constructor to create the object and thats it. So I'd prefer

    Java Code:
    ClassA obj = new ClassA();
    obj.method1();
    obj.method2();
    obj.method3();
    or otherwise, if all three methods always execute together and in that order,

    Java Code:
    ClassA obj = new ClassA();
    obj.doTheWork();
    
    class ClassA {
      public void doTheWork() {
        method1();
        method2();
        method3();
      }
    }
    You're saying class is utility. Is it stateless? If so, consider making the methods static, so you won't have to create instances of that class at all (like java.lang.Math, for example).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •