Saturday, September 10, 2011

Java => Scala: Scalava

So many are lamenting about how crappy Java is and that we need a replacement (like me). But do we? Shouldn't we just start by using the tools which java gives in the most awesome way possible?

Ingredients needed:
Java 6
guava.jar (google-collections)
lombok.jar (add to classpath and IDE)

Features:

Packages (included in java)
Originally, they seem to be designed to contain "modules", while public was only intended for those (perhaps few) ankle points where they were communicating with the "outer" world. That idea has a lot (and i mean a lot) of problems (like interfaces and their demand for public methods), so it does not make sense to really track that route consistently. But it still does make sense to use packages to ease your development:
Advantages:
- No visibility modifier needed (good for methods)
- multiple toplevel-classes in a single file (good for implementing many small classes)
- Allows you to make certain "dangerous" stuff available in a broader sense than private but still restricted to a fixed amount of classes you can control - unlike protected and public.

Unnamed Fields, classes and Methods
Scala uses conventions to make methods invisible and provide singletons.
By using a trick, you an do this in java as well: Just create elements which consist of nothing more than an underscore. Sounds strange? It is, in fact just a convention with nice effects:

package functions: class _ {}
Create a PACKAGE-PRIVATE _ in each of your packages to store static functions which do not belong to objects. That way, you have a place where all your fresh functions can end up, until they provide usefull enough to get their own "utilsXYZ".
In the end, no instantiable class should have static methods beside factories, and this is the way to enforce this and help to re-use code!
Same goes for constants
Note that the class must be package-private: otherwise, you end up with WAY to many _ in your code-completion!

Singletons:
Singletons can be stored in a public _ field, which reduces their code bloat and makes the name nicely readable: Singleton._ instead of Singleton.get() or Singleton.INSTANCE crap.

Singleton-Factories
Useful trick for interfaces:
public interface List{
   ListFactory _ = new ListFactory();
   class ListFactory{
      LIst of(){ ... }
   }}

Usage:
List._.of()

No comments:

Post a Comment