Showing posts with label trap. Show all posts
Showing posts with label trap. Show all posts

Wednesday, November 19, 2014

Metaprogramming Trap with Interfaces in Java 8

Consider the following little example:
package prv.rli.codetest;

import java.lang.reflect.Method;

public class BreakingInterfaces  {
    interface Base {
        BaseFoo foo();
        interface BaseFoo {           
        }
    }
   
    interface Derived extends Base {
        DerivedFoo foo();
        interface DerivedFoo extends BaseFoo {
           
        }
    }
   
    public static void main(String[] args) {       
        dumpDeclaredMethods(Derived.class);
    }

    private static void dumpDeclaredMethods(Class<?> class1) {
        System.out.println("---" + class1.getSimpleName() + "---");
        Method[] methods = class1.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("----------");
    }
}
What would you expect to be the output? We have a derived Interface which overrides the only method of its base interface in a covariant way. So one method only.

If you compile the above examplt with jdk1.7.0.55 the output is indeed:
 ---Derived---
public abstract BreakingInterfaces$Derived$DerivedFoo BreakingInterfaces$Derived.foo()
----------
But when using jdk1.8.0.25 the output is:
---Derived---
public abstract prv.rli.codetest.BreakingInterfaces$Derived$DerivedFoo prv.rli.codetest.BreakingInterfaces$Derived.foo()
public default prv.rli.codetest.BreakingInterfaces$Base$BaseFoo prv.rli.codetest.BreakingInterfaces$Derived.foo()
----------
 For reasons unknown to me, the base class method resurfaces here which may lead to unwanted behaviour when using reflection.

Monday, December 17, 2012

The Traps of String.split in Java

I just stumbled across a few peculiarities in the split Method of java.lang.String.

We'll start with a simple example:
    String value = "A:B";
    String[] parts = value.split(":");
    System.out.println("Parts has " + parts.length + " elements: " + Arrays.asList(parts));       
No surprises here. We get the output:
    Parts has 2 elements: [A, B]

Now let's try the empty string:
    String value = "";
    String[] parts = value.split(":");
    ...
Since there is no ":" in the empty string, the whole input string is returned:
    Parts has 1 elements: []
 


This may easily let you jump to the conclusion that the returned array of strings will always at least contain one element, since it returns the input if no delimiter is found. But that is not the case:
    String value = ":";
    String[] parts = value.split(":");
    ...
This will give:

    Parts has 0 elements: []

So even though our input string is now longer, the output array has fewer elements. How comes? Well if we split ":" along ":", we get ["", ""], but split() will not by default include trailing empty strings and thus the array returned is []. This seems counterintuitive to me.

The solution is to use the 2 parameter version of split and pass a negative number as the second parameter:
    String value = ":";
    String[] parts = value.split(":", -1);
    ...
which will give:
    Parts has 2 elements: [, ]

With that in mind, we can easily answer the question what the following code will give us:
    String value = "|";
    String[] parts = value.split("|");
    ...

 Since this looks just like the ":"-example above, it must give us an empty array, right?
Wrong. It gives us:
    Parts has 2 elements: [, |]
Whoa, what has happened? The parameter passed to split is actually treated as a regular expression and "|" is the or-operator of regular expressions, so we try to split the input string at every occurence of "nothing or nothing" which boils down to splitting the input string before any character, which gives us an array containing an empty string and the pipe character.
If you do:
    String value = "abc";
    String[] parts = value.split("|");
you'll get:
    Parts has 4 elements: [, a, b, c]
If you really want to split at pipe characters you have to use split("\\|"), since this will escape the regular expression meaning of the pipe character.

To summarize it, there are two caveats:
  • Use the two parameter version of split(), if you want to avoid getting an empty array.
  • Escape characters with special meaning in regular expressions (e.g. . * + [ ] ^ $)

 










 



 

Sunday, September 4, 2011

The pitfalls of compound assignment operators

Compound assignment operators

You may well know, that in Java (assuming x and y are int variables), instead of writing
    x = x + y;
you can use
    x += y;

The shortcut form is called compound assignment operator and it exists for a lot of operators. They seem harmless enough at first sight.

Now look at this:
    int x = 5, y = 3;
    x *= y + 1;
    System.out.println(x);
You may think that the second line is equivalent to x = x * y + 1, but it is not. It is equivalent to x = x * (y + 1). Therefore x becomes 5 * (3 + 1), i.e. 20.

Short circuit evaluation

Short circuit evaluation describes the fact, that in Java (and many other languages) a boolean expression is only evaluated as long as its final result is not yet known.
    boolean result = true && foo(); // foo gets called
vs.
    boolean result = false && foo(); // foo gets not called
You can (and should) use that to your advantage: Cheap operations to the left, expensive ones to the right (in case of &&, it is the other way round for ||). It also common to use short circuit evaluation for precondition checking:
    boolean result = x != null && x.getMyBool();
If x is really null, we must not call the getMyBool method as it would throw a NullPointerException.

The misleading &= operator

Back to compound assignment operators, there is a &= operator. At first sight, it looks like you could abbreviate
    keep = keep && foo();
by
    keep &= foo();
But, alas, you loose short circuit evaluation, because that really means
    keep = keep & foo();
And the & operator has no short circuit evaluation.

This can be detrimental to the performance of your code, e.g. in cases like this:
   keep &= expensiveOperation1(); 
   keep &= expensiveOperation2(); 
   keep &= expensiveOperation3(); 
   keep &= expensiveOperation4(); 
Or outright fatal, if an operation must not be called
   Object x = null;
   boolean keep = x != null;
   keep &= x.toString().isEmpty();
And there is no &&= compound assignment operator. 

Conclusion

It makes me wonder whether the comfort of saving a few keystrokes and having slightly more compact code to read outweighs these pitfalls and the increased complexity of the language.




Wednesday, July 20, 2011

Removing entries from a Java Collection

Let's look at some simple code:
public static void main(String[] args) {
  Map<String, String> m = new HashMap<String, String>();
  m.put("A", "B"); m.put("C", "D"); m.put("E", "F");
  for (Map.Entry<String, String> e : m.entrySet()) {
    if (e.getValue().equals("D")) {
      m.remove(e.getKey());
    }
  }
} 
After setting up a map which contains three entries (A->B, C->D, E->F), it iterates over its entries and removes an entry, if it matches a certain condition.
Compile, Run, works perfectly (on my machine, with my JDK, etc.)

Now we just change the condition to:
if (e.getValue().equals("B")) {

Compile, Run, oops - we get a ConcurrentModificationException like this:
Exception in thread "main" java.util.ConcurrentModificationException
  at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
  at java.util.HashMap$EntryIterator.next(HashMap.java:834)
  at java.util.HashMap$EntryIterator.next(HashMap.java:832)
  at prv.rli.codetest.CodeTest.main(CodeTest.java:11)

Why?
  • The for (x : y) statement is syntactic sugar for the old school collection iteration with an Iterator:
    Iterator<Map.Entry<String, String>> it = m.entrySet().iterator();
    while (it.hasNext()) {
    Map.Entry<String, String> e = it.next();
    }
  • An Iterator may throw a ConcurrentModificationException (a RuntimeException), if you change the collection it iterates over.



But why only with "B"?
  • Pure luck. The HashMap happens to be ordered like this: {E=F, A=B, C=D}, therefore the entry with value D is the last one and since the iterator will return false for hasNext(), we leave the loop, next() is no longer called and nothing happens.
So what is the correct way of removing an element from a map? There are several ways, which we will look at: Using the remove method of the iterator
Iterator<Map.Entry<String, String>> it = m.entrySet().iterator();
  while (it.hasNext()) {
    Map.Entry<String, String> e = it.next();
    if (e.getValue().equals("B")) {
      it.remove();
    }
  }
The Iterator interface provides a remove method, which will remove the element the last call to next() returned. Unfortunately the remove method may not be supported by some iterators. In this case the call to remove() would throw an UnsupportedOperationException. If we cannot use it.remove() we can also remember the keys of elements to remove and remove them after the iteration has completed:
  Set<String> toRemove = new HashSet<String>();
  for (Map.Entry<String, String> e : m.entrySet()) {
    if (e.getValue().equals("B")) {
      toRemove.add(e.getKey());
    }
  }
  m.keySet().removeAll(toRemove);
Note that we can use the for (x : y) notation here. Finally, if you remove most elements of a collection you can also create a new collection and only copy those elements you want to keep:
  Map<String, String> m2 = new HashMap<String, String>();
  for (Map.Entry<String, String> e : m.entrySet()) {
    if (!e.getValue().equals("B")) {
      m2.entrySet().add(e);
    }
  }
  m = m2;

This may have advantages in terms of memory consumption, because the new collection will not waste space for deleted entries.