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.
I don't endorse this an any way, but a really low-tech way to do "out" variables in Java is to use single element arrays:
String input = ...;
Date[] date = { null };
if (DateParser.tryParse(input, date)) {
System.out.println(date[0]);
}
Related
Say I have a List of object which were defined using lambda expressions (closures). Is there a way to inspect them so they can be compared?
The code I am most interested in is
List<Strategy> strategies = getStrategies();
Strategy a = (Strategy) this::a;
if (strategies.contains(a)) { // ...
The full code is
import java.util.Arrays;
import java.util.List;
public class ClosureEqualsMain {
interface Strategy {
void invoke(/*args*/);
default boolean equals(Object o) { // doesn't compile
return Closures.equals(this, o);
}
}
public void a() { }
public void b() { }
public void c() { }
public List<Strategy> getStrategies() {
return Arrays.asList(this::a, this::b, this::c);
}
private void testStrategies() {
List<Strategy> strategies = getStrategies();
System.out.println(strategies);
Strategy a = (Strategy) this::a;
// prints false
System.out.println("strategies.contains(this::a) is " + strategies.contains(a));
}
public static void main(String... ignored) {
new ClosureEqualsMain().testStrategies();
}
enum Closures {;
public static <Closure> boolean equals(Closure c1, Closure c2) {
// This doesn't compare the contents
// like others immutables e.g. String
return c1.equals(c2);
}
public static <Closure> int hashCode(Closure c) {
return // a hashCode which can detect duplicates for a Set<Strategy>
}
public static <Closure> String asString(Closure c) {
return // something better than Object.toString();
}
}
public String toString() {
return "my-ClosureEqualsMain";
}
}
It would appear the only solution is to define each lambda as a field and only use those fields. If you want to print out the method called, you are better off using Method. Is there a better way with lambda expressions?
Also, is it possible to print a lambda and get something human readable? If you print this::a instead of
ClosureEqualsMain$$Lambda$1/821270929#3f99bd52
get something like
ClosureEqualsMain.a()
or even use this.toString and the method.
my-ClosureEqualsMain.a();
This question could be interpreted relative to the specification or the implementation. Obviously, implementations could change, but you might be willing to rewrite your code when that happens, so I'll answer at both.
It also depends on what you want to do. Are you looking to optimize, or are you looking for ironclad guarantees that two instances are (or are not) the same function? (If the latter, you're going to find yourself at odds with computational physics, in that even problems as simple as asking whether two functions compute the same thing are undecidable.)
From a specification perspective, the language spec promises only that the result of evaluating (not invoking) a lambda expression is an instance of a class implementing the target functional interface. It makes no promises about the identity, or degree of aliasing, of the result. This is by design, to give implementations maximal flexibility to offer better performance (this is how lambdas can be faster than inner classes; we're not tied to the "must create unique instance" constraint that inner classes are.)
So basically, the spec doesn't give you much, except obviously that two lambdas that are reference-equal (==) are going to compute the same function.
From an implementation perspective, you can conclude a little more. There is (currently, may change) a 1:1 relationship between the synthetic classes that implement lambdas, and the capture sites in the program. So two separate bits of code that capture "x -> x + 1" may well be mapped to different classes. But if you evaluate the same lambda at the same capture site, and that lambda is non-capturing, you get the same instance, which can be compared with reference equality.
If your lambdas are serializable, they'll give up their state more easily, in exchange for sacrificing some performance and security (no free lunch.)
One area where it might be practical to tweak the definition of equality is with method references because this would enable them to be used as listeners and be properly unregistered. This is under consideration.
I think what you're trying to get to is: if two lambdas are converted to the same functional interface, are represented by the same behavior function, and have identical captured args, they're the same
Unfortunately, this is both hard to do (for non-serializable lambdas, you can't get at all the components of that) and not enough (because two separately compiled files could convert the same lambda to the same functional interface type, and you wouldn't be able to tell.)
The EG discussed whether to expose enough information to be able to make these judgments, as well as discussing whether lambdas should implement more selective equals/hashCode or more descriptive toString. The conclusion was that we were not willing to pay anything in performance cost to make this information available to the caller (bad tradeoff, punishing 99.99% of users for something that benefits .01%).
A definitive conclusion on toString was not reached but left open to be revisited in the future. However, there were some good arguments made on both sides on this issue; this is not a slam-dunk.
To compare labmdas I usually let the interface extend Serializable and then compare the serialized bytes. Not very nice but works for the most cases.
I don't see a possibility, to get those informations from the closure itself.
The closures doesn't provide state.
But you can use Java-Reflection, if you want to inspect and compare the methods.
Of course that is not a very beautiful solution, because of the performance and the exceptions, which are to catch. But this way you get those meta-informations.
Say I have a List of object which were defined using lambda expressions (closures). Is there a way to inspect them so they can be compared?
The code I am most interested in is
List<Strategy> strategies = getStrategies();
Strategy a = (Strategy) this::a;
if (strategies.contains(a)) { // ...
The full code is
import java.util.Arrays;
import java.util.List;
public class ClosureEqualsMain {
interface Strategy {
void invoke(/*args*/);
default boolean equals(Object o) { // doesn't compile
return Closures.equals(this, o);
}
}
public void a() { }
public void b() { }
public void c() { }
public List<Strategy> getStrategies() {
return Arrays.asList(this::a, this::b, this::c);
}
private void testStrategies() {
List<Strategy> strategies = getStrategies();
System.out.println(strategies);
Strategy a = (Strategy) this::a;
// prints false
System.out.println("strategies.contains(this::a) is " + strategies.contains(a));
}
public static void main(String... ignored) {
new ClosureEqualsMain().testStrategies();
}
enum Closures {;
public static <Closure> boolean equals(Closure c1, Closure c2) {
// This doesn't compare the contents
// like others immutables e.g. String
return c1.equals(c2);
}
public static <Closure> int hashCode(Closure c) {
return // a hashCode which can detect duplicates for a Set<Strategy>
}
public static <Closure> String asString(Closure c) {
return // something better than Object.toString();
}
}
public String toString() {
return "my-ClosureEqualsMain";
}
}
It would appear the only solution is to define each lambda as a field and only use those fields. If you want to print out the method called, you are better off using Method. Is there a better way with lambda expressions?
Also, is it possible to print a lambda and get something human readable? If you print this::a instead of
ClosureEqualsMain$$Lambda$1/821270929#3f99bd52
get something like
ClosureEqualsMain.a()
or even use this.toString and the method.
my-ClosureEqualsMain.a();
This question could be interpreted relative to the specification or the implementation. Obviously, implementations could change, but you might be willing to rewrite your code when that happens, so I'll answer at both.
It also depends on what you want to do. Are you looking to optimize, or are you looking for ironclad guarantees that two instances are (or are not) the same function? (If the latter, you're going to find yourself at odds with computational physics, in that even problems as simple as asking whether two functions compute the same thing are undecidable.)
From a specification perspective, the language spec promises only that the result of evaluating (not invoking) a lambda expression is an instance of a class implementing the target functional interface. It makes no promises about the identity, or degree of aliasing, of the result. This is by design, to give implementations maximal flexibility to offer better performance (this is how lambdas can be faster than inner classes; we're not tied to the "must create unique instance" constraint that inner classes are.)
So basically, the spec doesn't give you much, except obviously that two lambdas that are reference-equal (==) are going to compute the same function.
From an implementation perspective, you can conclude a little more. There is (currently, may change) a 1:1 relationship between the synthetic classes that implement lambdas, and the capture sites in the program. So two separate bits of code that capture "x -> x + 1" may well be mapped to different classes. But if you evaluate the same lambda at the same capture site, and that lambda is non-capturing, you get the same instance, which can be compared with reference equality.
If your lambdas are serializable, they'll give up their state more easily, in exchange for sacrificing some performance and security (no free lunch.)
One area where it might be practical to tweak the definition of equality is with method references because this would enable them to be used as listeners and be properly unregistered. This is under consideration.
I think what you're trying to get to is: if two lambdas are converted to the same functional interface, are represented by the same behavior function, and have identical captured args, they're the same
Unfortunately, this is both hard to do (for non-serializable lambdas, you can't get at all the components of that) and not enough (because two separately compiled files could convert the same lambda to the same functional interface type, and you wouldn't be able to tell.)
The EG discussed whether to expose enough information to be able to make these judgments, as well as discussing whether lambdas should implement more selective equals/hashCode or more descriptive toString. The conclusion was that we were not willing to pay anything in performance cost to make this information available to the caller (bad tradeoff, punishing 99.99% of users for something that benefits .01%).
A definitive conclusion on toString was not reached but left open to be revisited in the future. However, there were some good arguments made on both sides on this issue; this is not a slam-dunk.
To compare labmdas I usually let the interface extend Serializable and then compare the serialized bytes. Not very nice but works for the most cases.
I don't see a possibility, to get those informations from the closure itself.
The closures doesn't provide state.
But you can use Java-Reflection, if you want to inspect and compare the methods.
Of course that is not a very beautiful solution, because of the performance and the exceptions, which are to catch. But this way you get those meta-informations.
how can you emulate functional programming in java, specifically, doing things like map a function to a collection of items?
map(func, new String[]{"a","b","c"});
what's the least verbose & awkward way to do it?
All attempts of functional programming will have some part of verbose and/or awkward to it in Java, until Java 8.
The most direct way is to provide a Function interface (such as this one form Guava) and provide all kinds of methods that take and call it (such as Collections#transfrom() which does what I think your map() method should do).
The bad thing about is that you need to implement Function and often do so with an anonymous inner class, which has a terribly verbose syntax:
Collection<OutputType> result = Collections.transform(input, new Function<InputType,OutputType>() {
public OutputType apply(InputType input) {
return frobnicate(input);
}
});
Lambda expressions (introduced in Java 8) make this considerably easier (and possibly faster). The equivalent code using lambdas looks like this:
Collection<OutputType> result = Collections.transform(input, SomeClass::frobnicate);
or the more verbose, but more flexible:
Collection<OutputType> result = Collections.transform(input, in -> frobnicate(in));
I have used lambdaj and functionaljava for this sort of things. And there are probably others...
Just wrap the function you want to apply on the list with a class or an interface.
public interface Func {
Object f(Object input);
}
public void map (Func func, Object[] arr) {
for(int i=0;i<arr.legnth;i++) {
arr[i] = func.f(arr[i]);
}
}
map(
new Func() { public Object f(Object input) { return input; } };,
new String[]{"a","b"});
As you note, Java isn't designed for functional programming and while you can emulate it, you have to really want to do this even if is it more verbose and more awkward than using standard programming in Java.
Take #Joachim's example.
Collection<OutputType> result = Collections.transform(input, new Function<InputType,OutputType>() {
public OutputType apply(InputType input) {
return frobnicate(input);
}
});
This uses 12 symbols, not counting close brackets. The same thing in plain Java would look like.
List<OutputType> list = new ArrayList();
for(InputType in: input)
list.add(frobnicate(in));
This uses 7 symbols.
You can do functional programming in Java, but you should expect it to be more verbose and awkward than using the natural programming style of Java.
You could download OpenJDK 8 which is scheduled for prodcution release next year and use the new Lambda Expressions for functional programming. See http://macgyverdev.blogspot.se/2012/10/functional-programming-in-java.html for examples of how these closures will be used in the Collection APIs and how they compare with pre-Java 8 solutions like Guava and LambdaJ.
I am in a situation where I want to use mutable versions of things like Integer. Do I have to use these classes (below) or does Java have something built in?
http://www.java2s.com/Code/Java/Data-Type/Amutableintwrapper.htm
You could always wrap the value in an array like int[] mutable = {1}; if including the code for a mutable wrapper class is too cumbersome.
No, Java doesn't have these built in. And that is for a reason. Using mutable types is dangerous, as they can easily be misused. Additionally, it is really easy to implement it. For example, commons-lang has a MutableInt.
Since JDK 1.5 java now has java.util.concurrent.atomic.AtomicInteger
This is a thread safe mutable integer, example of use:
final AtomicInteger value = new AtomicInteger(0);
then later on:
value.incrementAndGet();
Here's a small class I made for a mutable integer:
public class MutableInteger {
private int value;
public MutableInteger(int value) {
this.value = value;
}
public void set(int value) {
this.value = value;
}
public int intValue() {
return value;
}
}
You could easily extend this to any other primitive. Of course, like everyone else is saying, you should use it carefully.
You can use an nnnn[] as a mutable object for any primitive type as #Alexandre suggests, java also has AtomicInteger and AtomicLong.
IMHO int is usually a better choice than Integer and that is mutable.
Can you more details of why you need a mutliple object, perhaps there is another way to achieve the same thing.
AtomicInteger has already been mentioned. Mutable Doubles can be emulated with AtomicReference<Double>. The already mentioned warnings apply and it is bad style, but sometimes you have code like this
double sum=0
for (Data data:someListGenerator())
sum+=data.getValue()
and want to refactor it in functional Java 8 style. If the code follows this pattern but adds considerable complexity to it, the most sensible conversion could be
AtomicReference<Double> sumref=new AtomicReference<>(0d);
someStreamGenerator().forEach(data->
sumref.set(sumref.get().doubleValue()+data.getValue()));
double sum=sumref.get().doubleValue();
Of course, this is at least questionable style. But I found myself more than once in a situation with a twisted loop over a ResultSet computing and partly cumulating three different information from it. This makes it really hard to convert the code into proper functional style. Converting the cumulating parts according to the above pattern seemed to me a reasonable tradeoff between clean code and oversimplified refactoring.
You can import the org.omg.CORBA package(or just the class you need) and in it you can use the Holder classes.
For example, it has the "IntHolder" where the field where it stores the integer is public, giving access to modify it.
public static void triple(IntHolder x){
x.value = 3 * x.value;
}
IntHolder mutableInt = new IntHolder(10);
triple(mutableInt);
System.out.println(mutableInt.value);
It also has "LongHolder" and "DoubleHolder" and tons of others that you can use. Use with caution.
Here is the api for it: https://docs.oracle.com/javase/7/docs/api/org/omg/CORBA/package-summary.html
I have a list of XML tags and a method for each of them inside my class, getting that tag as an argument and doing its work. So all the methods get the same input and I want to loop through the list of tags, calling appropriate method each time.
In Python I've made it with a hash of strings (names of tags) to lambdas (self.methodName()) and I want to translate it to Java.
Now in Java, I can't (?) make such a hash and even can't use strings (tag names) in a switch statement (with each branch calling a certain method). The possibility of using 10 or so subsequent ifs seems horribly ugly and I'm looking for a better way to code that.
Map string to a class instance by instantiating classes and saving them (probably in a hash). All the classes must implement the same interface of course.
You'll find that if you code this way a better structure starts to emerge from your code--for instance you might find that where before you might have used 2, 3 or 10 similar methods to do slightly different things, now the fact that you can pass data into your constructor allows you to do it all with one or two different classes instead.
This interface and the classes that implement it (for me at least) nearly always evolve into a full-featured set of classes that I needed all along but might not have recognized otherwise.
Somehow I never seem to regret writing code the "Hard" way, but nearly always regret when I choose the easier path.
What do people think of this?
public static enum Tags {
TAG1, TAG2, TAG3
}
public class Stuff {
...
switch (Tags.valueOf(str)) {
case TAG1: handleTag1(); break;
case TAG2: handleTag2(); break;
case TAG3: handleTag3(); break;
}
}
The upside is that this is concise and efficient (at least in this case). The downside is that it is not so good with mixed case tags and tags with Java non-identifier characters in them; e.g. "-". (You either have to abuse accepted Java style conventions for the enum member identifiers, or you have to add an explicit String-to-enum conversion method to the enum declaration.)
Using a switch statement for dispatching is evil in some peoples' book. But in this case, you need to compare what you are gaining with what you are loosing. And I'd be surprised if polymorphic dispatching would give a significant advantage over a switch statement in terms of extensibility and maintainability.
I'd go with what Bill K suggested in regards to implementing the same interface. But if you have the issue of wanting to call methods with different names you could try using reflection and do something like this:
Method method = Foo.class.getDeclaredMethod("methodName", parametersTypes); // Get the method you want to call
Foo foo = new Foo();
method.invoke(foo, args); // invoke the method retrieved on the object 'foo' with the given arguments
you can invoke the method using reflection:
Class.getMethod
therefore you don't need a switch or a set of ifs.
Here is an example of the proposal of Bill K (if I understood it right)
public class Example {
static interface TagHandler {
void handle(String tag);
}
static final Map<String, Example.TagHandler> tagHandlers = new HashMap<String, Example.TagHandler>() {
{
put("tag_1", new Example.TagHandler() {
public void handle(String tag) {
System.out.println("Handling tag_1: " + tag);
}
});
put("tag_2", new Example.TagHandler() {
public void handle(String tag) {
System.out.println("Handling tag_2: " + tag);
}
});
}
};
public static void main(String[] args) {
String[] tags = { "tag_1", "tag_2", "tag_1" };
for (String tag : tags) {
tagHandlers.get(tag).handle(tag);
}
}
}
An indirect answer: XML typically represents data, not instructions. So it is probably more useful to map parser handling onto fields. This is what JAXB does. I suggest using JAXB or similar.
Unless you have a huge amount to do, I would strongly advise against reflection in a statically typed language. A string of } else if (tag.equals("blah")) { (or with interning, } else if (tag == "blah") { isn't going to kill you. You can even map strings onto their enum namesakes, but that is a little reflectiony. Switch-on-string should be with us in JDK7.