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:
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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With