Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best ways to reuse Java methods

I'm learning Java and OOP, and have been doing the problems at Project Euler for practice (awesome site btw).

I find myself doing many of the same things over and over, like:

  • checking if an integer is prime/generating primes
  • generating the Fibonacci series
  • checking if a number is a palindrome

What is the best way to store and call these methods? Should I write a utility class and then import it? If so, do I import a .class file or the .java source? I'm working from a plain text editor and the Mac terminal.

Thanks!

like image 583
carillonator Avatar asked May 29 '10 23:05

carillonator


2 Answers

You can put your methods into a utility class, then import that class (not the file!).

import my.useful.UtilityClass;

...
boolean isPrime = UtilityClass.isPrime(2);

When things start to get more complicated, and you want to reuse your stuff across multiple projects, you can put it into a jar and add that jar to the projects. Then you can import and use the class the same way as above.

like image 105
Péter Török Avatar answered Sep 28 '22 02:09

Péter Török


The UtilityClass idea is fine, but it also gives you the opportunity to practice TDD. For a new Euler problem, create an empty method in your UtilityClass where you'll solve that problem. Then make a bunch of JUnit tests that use this new method and depend on it being correct. The tests will all fail (or they should, because you haven't written the solution yet!)

Now solve the Euler problem and watch the tests pass! If you want to reuse the code later, the unit tests will keep you correct during refactoring and will provide a place to add regression cases for bugs you may find.

like image 39
jasonmp85 Avatar answered Sep 28 '22 02:09

jasonmp85