Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Common functions

Status
Not open for further replies.

fatcodeguy

Programmer
Feb 25, 2002
281
CA
Hi. I have a set of functions that will be used by various classes, but I don't know how to implement them. Currently, I've created a seperate class for them and made the functions all static:

public class CommonFunctions{
public static int function1(){...}
public static void function2(String str){...}
.......
}

Now how do I call these functions from another class without having to go CommonFunctions.function1(). Can I import these functions? Thanks.
 
I honestly cannot think of a better method that the one you are using.

If you extend
Code:
CommonClass
(ie
Code:
 MyClass extends CommonClass
) you get all the functions available to you, but then MyClass cannot extend anything else. This may work for some of your classes but I'm sure you have extended other classes already, rulling that option out.

Making them an interface means you could implement them even if you class was already extended, but you would have to type out the actual code for every class them implements that interface since an interface only provides you with the method's header. This is good OO programming since it allows you to change the implementation of each function so it is specific to the class. However if each function is generic and will not change (as yours seem to be) then it is not very good code reuse.

Making them static (globally visible, depending on package rules) all within 1 class (as you have done) works well.

If someone has a better solution I too would love to heard it, since I have run up against this problem before and have solved it using static methods. ----------------------------------------
There are no onions, only magic
----------------------------------------
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top