I'm a fan of the try/do (or trier/doer) pattern, which is best implemented in C# using out
parameters, e.g.:
DateTime date;
if (DateTime.TryParse("2012-06-18", out date))
{
//Do something with date
}
I'm currently working on a Java 1.5 project, for which I'm implementing the try/do pattern using a new class called TryResult which is returned from any methods which 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 is working well, but I will be porting this code to a different platform which uses J2ME, and therefore generics aren't available.
My current options are to either remove the generics from the TryResult
class above and using plain old Object
and casting, or make a new class for the types I will end up using (e.g. StringTryResult
).
Is there a better way to implement this pattern on J2ME/Java 1.3?
What you are trying to implement is called a Maybe monad in functional languages.
There are experiments to do this in java, see here and here.
The problem is, Java's type system is unfortunately not advanced enough to support this on a large scale.. Also, the standard libraries do not support anything like that, which reduces the use of such a construct to your own code only :(
See Scala and Clojure for languages that support this.
As far as Java ME goes, I'd think twice about implementing special types just for the sake of this. It is a nice in idea theory, however, it would make things just more difficult, eg. duplicating all types in your whole app.
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