Results 1 to 3 of 3
Thread: Best practices question
- 05-27-2010, 03:12 PM #1
Member
- Join Date
- Apr 2010
- Posts
- 14
- Rep Power
- 0
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)
Ex 2:Java Code://calling class ClassA obj = new ClassA(); //utility class public ClassA() { method1(); method2(); method3(); }
Java Code://calling class ClassA obj = new ClassA(); obj.method1(); obj.method2(); obj.method3();
- 05-27-2010, 03:17 PM #2
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
- 05-27-2010, 06:27 PM #3
Senior Member
- Join Date
- Mar 2010
- Posts
- 266
- Rep Power
- 4
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
or otherwise, if all three methods always execute together and in that order,Java Code:ClassA obj = new ClassA(); obj.method1(); obj.method2(); obj.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).Java Code:ClassA obj = new ClassA(); obj.doTheWork(); class ClassA { public void doTheWork() { method1(); method2(); method3(); } }


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks