Attempting / executing a template in Java

I am a fan of the try / do pattern (or trier / doer), which is best implemented in C # using out parameters, for example:

 DateTime date; if (DateTime.TryParse("2012-06-18", out date)) { //Do something with date } 

I am currently working on a Java 1.5 project for which I am implementing a try / do pattern using the new TryResult class, which is returned from any methods that implement the try / do pattern:

 public class TryResult<ResultType> { private boolean mSuccess = false; private ResultType mResult = null; public TryResult(boolean success, ResultType result) { super(); this.mSuccess = success; this.mResult = result; } public boolean isSuccess() { return mSuccess; } public ResultType getResult() { return mResult; } } 

This works well, but I will port this code to another platform that uses J2ME, and therefore generics are not available.

My current options are to either remove the generics from the TryResult class above, and use the plain old Object and casting, or create a new class for the types that I ended up using (e.g. StringTryResult ).

Is there a better way to implement this template on J2ME / Java 1.3?

+7
source share
2 answers

What you are trying to implement is called Perhaps the monad in functional languages.

There are experiments in java, see here and here .

The problem is that the Java type system, unfortunately, is not advanced enough to support this on a large scale. In addition, standard libraries do not support anything like this, which reduces the use of such a construct only for your own code :(

See Scala and Clojure for languages ​​that support this.

As for Java ME, I would think twice about implementing special types just for the sake of it. This is a good idea in idea theory, however, it would make things more complex, for example. duplicating all types in your application.

+3
source

I do not support this in any way, but a very low-tech way to make " out " variables in Java is to use arrays of single elements:

 String input = ...; Date[] date = { null }; if (DateParser.tryParse(input, date)) { System.out.println(date[0]); } 
0
source

All Articles