November 30, 2007
Using Groovy MarkupBuilders spoiled me for other ways to create HTML pages from code. Others think the same. But in some organizations you have to use Java and can’t use Groovy - at least when you can’t sneak it in.
So I tinkered around in Java to see what’s the best MarkupBuilder I can write with Java. Using DSLs and Fluent Interfaces (times(5).loop), I came up with a nice solution. It’s not Groovy, but it works.
Page page = page(
html(
body(
// A comment
h1("Name games"),
p("Hello ${coolName}, and hello", "id:${id}"),
ul(
new Loop("stefanie", "${name}") {
protected Element each(String item) {
return li(item);
}
}),
loop("[${number}] ", "number", 1, 2, 3),
text("..."),
box("Warning private!"),
p("Are you dynamic?"),
// Some dynamic content
new Action() {
protected String with(Context context) {
return "I'm dynamic, " + context.get("name") + ".";
}
}
)
)
);
There are some tricks to make it better than most such Markup Builders in Java. I tried to use ideas from building DSLs in Java. Those are using static imports and varargs. The body, html and other elements are static imports from a MarkupBuilder class.
public static Element body(String body) {
return new Element("body", body);
}
public static Element body(Element... elements) {
return new Element("body", elements);
}
...
The varargs helps with adding a variable number of childs to an element:
h1(
p("One"),
p("Two"),
p("Three")
);
Another problem is how to put object values into the generated markup. String concatenation leads to noisy code
"Hello " + name + "!"
so I decided to use a expression language where the Java unified expression language comes to mind. There is an open source version available called JUEL. Now I can use
"Hello ${name}!"
Attributes are also treated as expressions and seperated by commas, their names and values seperated with a colon.
p("Hello ${coolName}, and hello", "id:${id}, class:list"),
Loop and Action classes allow for dynamic content.
ul(
new Loop("stefanie", "${name}") {
protected Element each(String item) {
return li(item);
}
}),
I’ve used the template design pattern for this, again with expressions, in a way Spring provides JDBC templates. Another nice idea is with static methods it’s also easy to develop custom, semantic tags, so the developer doesn’t need to know or see the actual HTML markup which is created. For example I used a box “tag” which translates to
public static Element box(String text) {
return div(
p(text)
);
}
Closures in Java 7 will make it much easier to write a MarkupBuilder. The Action and Loop inner classes will go away and the code will be more Groovy like. When they add syntactic sugar to create maps I can drop the “name:value, name:${value}” style for attributes and move to [ "name" : value, "name": value ] instead, which doesn’t need the EL to work. With some small things to add the MarkupBuilder can be used for JSON or XML.
I’m interested and open to all techniques and ideas to improve the markup builder.
Thanks for listening.
November 27, 2007
People most of the time use business logic in their templates, be them JSP, Velocity or Rails. They confuse business logic and UI logic. Those are two different things. I always found it very useful to make UI logic explicit and only have UI logic in my JSPs or templates. So when using IF JSTL tags only test for UI logic not business logic. The examples are for JSP, but nevertheless are valid for other templating engines like Rails or Velocity. Where is the difference between UI and business logic?
<c:if test="${showMenu}">
// show menu
</c:if>
and
<c:if test="${user.loggedIn && user.bookedProducts}">
// show menu
</c:if>
The first example contains only UI logic, the second one contains business logic and should be avoided. With the second version your templating code is depending on your business layer. This makes it hard to refactor or reuse. Somewhere in the controller or an adapter it’s best to translate your business logic to UI logic
boolean showMenu = user.loggedIn() && user.bookedProducts();
Such a sepration makes refactoring and reuse easier and encapsulates the rules how business logic maps to UI logic in one place. You could even write the mapper with rule engines. It also eases the understanding of the template code. Often when using business logic in their templates, people use copy & paste to reuse the logic. So the user.loggedIn code gets distributed over lots of templates. If the logic changes so the menu should only be show for paid users, you need to modify all templates where the logic is used.
<c:if test="${user.loggedIn && user.bookedProducts && user.hasPaid}">
...
</c:if>
(I know about components, sub-templates etc. but people nevertheless use cut & paste for reuse. So make sure they cut&paste the right things)
When externalizing business-to-UI logic into seperate classes, it’s also much easier to test.
public class UserUIState {
private User user;
public UserUIState(User user) {
this.user = user;
}
public boolean showMenu() {
return user.loggedIn() && user.bookedProducts();
}
}
can be easily tested from a Unit test.
User user = with().isLoggedIn().addProduct("Intellij IDEA").create();
UserUIState state = new UserUIState(user);
assertThat( state.showMenu(), is(true));
The test uses fluent interfaces to create a user and a pseudo Hamcrest DSL to specify assertions. The assertions would be nicer written as specs with easyb.
Another aspect of templating is the power of the templating engine. Turing completeness is not a good thing for templating as the power introduces bugs. Less power leads to less bugs. Examples for engines who make this a virtue are String Template and RIFE. The same goes for variables. Never set variables in templates. Never modify state in templates. The best paper on this topic is Terence Parrs
“Enforcing Strict Model-View Separation in Template Engines”.
And of course never use Scriptlets in your JSP or other templating code, the main reason that the developer has to manage two hierarchies in her head. The <html> on one side and the Java { ... } hierarchie on the other.
<% if (loggendIn) { %>
<p>Logged in<p>
<% } %>
With larger pages this leads to bugs. With only one <html> hierarchie, your IDE is able to verify the hierarchie at edit-time which prevents invalid HTML.
You can enfore these rules with code reviews or automatic style and architecture checkers. Probably best to use both to reduce your bug count and enable reusability.
Thanks for listening.
Update: Gavin King got me wrong. Reading simple attributes like "test=${user.loggedIn}" doesn’t contain a lot of “logic” so it’s no must to encapsulate the logic and it leads to unnecessarilly complex code. YAGNI. But "test=${user.loggedIn && user.hasBookProducts && sales.hasPromotion(user)}" does contain logic which should be encapsulated and tested. Perhaps I’m a stronger believer in TDD than Gavin. I wanted to stress that there is a difference between UI and business logic and a lot of people don’t see the difference.
November 24, 2007
With all the innovation in annotations, see Web Beans or Google Guice, just a saturday morning idea: Why not drop the annoying get* convention and replace it with some annotations? The API wouldn’t be as short, but the usage of a getter looks nicer and more fluent. And of course the IDE could hide the @Getter annotation, just as it hides the imports.
@Getter
public Context context() {
return context;
}
public Context getContext() {
return context;
}
November 23, 2007
When reading about reflection on the beautiful code website I thought about solving some problems with reflection and finding new solutions to old problems. One problem is boring code when writing a copy constructor. A copy constructor is a constructor which takes another object and copies it’s attributes. This is often useful when copying objects or moving objects to different system layers. One example would look like this:
public class Employee {
public Employee(Employee other) {
this.name = other.name;
}
}
There are some pitfalls, especially that you only create shallow copies. And there is always clone() and Serializable, which can also be used to create deep copies without such pitfalls. JBoss provides a fast implementation of this technique. But often copy constructors are quite useful if you’re careful and know what you do. I recently had a discussion on how to support domain objects in different parts of a system. One part might call an entity Employee, another part might call it Person. To make them talk together you can either create a composite, an adapter, a wrapper or use a copy constructor (or find a different solution). In such a case a shallow copy is all you want, because the new object should have the same “identity” as the first and not be a copy.
public class Employee {
public Employee(Person person) {
this.lastName = person.getLastName();
this.name= person.getFirstName();
}
}
This should be easier to implement. Copying bean attributes for large objects isn’t much fun, leads to long constructors and unmaintanable code. What about changes in Person? New attributes? So I tinkered with Java reflection and ended with this:
public Employee(Person person) {
BeanCopier copier = new BeanCopier();
copier.copy(person, this, "name:firstName", "age:");
}
I’ve written a BeanCopier which can - well you guessed it - copy beans. The syntax is easy to learn. A BeanCopier has a copy method which takes a source, a copy and the attributes which should be specially handled. By default all attributes which have the same name and type in source and copy are copied. But if they have different names, like name and firstName, you need to specify “name:firstName”. If a property shouldn’t be copied, you can specify “property:” without a target attribute.
The copy method looks like this (the generics are not needed but I was also tinkering with caching where it was quite handy):
public <T, U>void copy(U source, T destination, String... attributes) {
if (destination.getClass().getName().equals(source.getClass().getName())) {
// copy all fields
} else {
// copy all bean properties
try {
BeanInfo sourceInfo = Introspector.getBeanInfo(source.getClass());
PropertyDescriptor[] sourceDescriptors = sourceInfo.getPropertyDescriptors();
for (PropertyDescriptor descriptor : sourceDescriptors) {
String name = descriptor.getName();
if (!"class".equals(name)) {
String attribute = this.find(attributes, name);
if (attribute == null) {
copyAttribute(source, destination, name);
} else if ((attribute.indexOf(':') >= 0) && !attribute.endsWith(":")) {
int colonIndex = attribute.indexOf(':');
String sourceName = attribute.substring(0, colonIndex);
String copyName = attribute.substring(colonIndex + 1);
copyAttribute(source, destination, sourceName, copyName);
}
}
}
} catch (IntrospectionException e) {
e.printStackTrace();
}
}
}
and the copyAttribute method:
private void copyAttribute(Object source,
Object copy,
String sourceName,
String copyName) {
PropertyDescriptor writer;
PropertyDescriptor reader;
try {
writer = new PropertyDescriptor(copyName, copy.getClass());
reader = new PropertyDescriptor(sourceName, source.getClass());
Object value = reader.getReadMethod().invoke(source);
Class sourceType = reader.getPropertyType();
Class destionationType = writer.getPropertyType();
if (sourceType.getName().equals(destionationType.getName())) {
writer.getWriteMethod().invoke(copy, value);
}
}
The code is rough but works. The type test can be improved to work with super types.BeanCopier can be used outside of constructors, often a wise choice. And be careful with “copying” other objects, you might only create a shallow copy.
Of course, I could have taken a look at commons BeanUtils, but isn’t it much more fun to tinker and find a nice solution yourself sometimes?
Thanks for listening.
November 12, 2007
As several people pointed out in my last post that my version of reversing a string with recursion wasn’t tail recursive despite the fact that I wrongly thought it was. Not that it’s important in the context of a job interview for Java developers, whether one uses tail recursion or not. But I thought nevertheless about a Java tail recursive solution. Reading more about tail recursion in several articles and the comments of the last post, I wrote a new version of the String reversal solution. This time with tail recursion. So as a service to the interested reader:
public String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return reverse(str, "");
}
private String reverse(String str, String acc) {
if (str.length() == 0) {
return acc;
} else {
return reverse(str.substring(1), str.charAt(0) + acc);
}
}
Tail recursion means, the last call in the recursive function is a call to the function and there is nothing left to do when the recursive call returns. Why tail recursion? With tail recursion it’s easy for the compiler to remove the recursion and drop the growing stack. So with an optimized tail recursive function you will not run out of stack space what you otherwise would quite easily.
Update: For comparison the non-tail recursive solution.
public String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
Update 2: The call stack for the recursive solution for “ABC” would be:
-> reverse(”ABC”)
-> reverse(”BC”) + ‘A’
-> (reverse(”C”) + ‘B’) + ‘A’
-> (”C” + ‘B’) + ‘A’
-> “CB” + ‘A’
-> “CBA”
and for the tail recursive version:
-> reverse(”ABC”, “”)
-> reverse(”BC”, “A”)
-> reverse(”C”, “BA”)
-> reverse(”", “CBA”)
-> “CBA”
Comparing those two the first one increases the stack to a point until it starts to pop the stack. The tail recursive version does not use the stack to keep a “memory” what it has still to do, but calculates the result imediatly. Comparing the source though, in my view the tail recursive version takes all beauty out of the recursive implementation. It nearly looks iterative.
Someone has read my post about interviewing where I wrote about String reversal, but got it totally wrong. Ironic. He didn’t show much attention to detail, took quotes out of context, put things into my mouth that I’ve never said and concluded “Want a job? Reverse a string. The sad state of job interviews today.” This post even got to DZone. So my post could also be titled: The sad state of DZone today.
Most of my interviews are 1h to 1.5h and sometimes 15 minutes of the interview is about reversing a String. This is mainly to get into the thinking of the candidate, see how he deals with fringe cases (null values as arguments) and if he chooses a JDK reverse method or not. Jonethen didn’t pay much attention to detail, so for a starter he got my name wrong, it’s Stephan not Stephen. A minor detail but a sign for what was to come later in his post and the comments.
Jonathan is angered by my mentioning of the recursive version of reversing a string. Although I wrote why I think it’s interesting to discuss a recursive solution, he ignores my arguments and writes
“.. only that he would be much more impressed if someone did write it out.”
I didn’t say that.
“He would probably give higher preference to someone who did use that technique,…”
No I won’t and I didn’t say that either. I said “The best implementation in Java is to use the reverse method of the StringBuffer class in the JDK.” I specifically pointed out that the reverse version is impractical in Java for the immutable String class alone, not to mention the surrogate pairs problem. So to make myself clear again, the best solution is to use the reverse method of the StringBuilder class. Any candidate who uses this method has already impressed me, because from my experience very very few developer know this. Most would write some kind of array swap method. But it’s not the cause I ask this question. It’s to see if someone can write code (which doesn’t need to be compiler ready, he’s no IDE in the end) and get into a discussion about programming, unit testing, fringe cases, how to handle errors, quality assurance and other topics. And if someone has read this blog? Or another blog? And knows the answer? Well good, the answer is just the beginning. And considering that very few developers read blogs and articles to learn something new, I’m happy to interview a candidate who reads blogs in general.
Without getting personal, I look for more attention to detail in the candidates I have than Jonathan did when he did shred my post. And I look with far more attention to detail into candidates than Jonathan did use when reading my post. Ironic.
One poster in the comments of Jonathans post suggested using StringBuilder instead of StringBuffer, because StringBuilder is not synchronized and faster therefore. I think modern VMs can use escape analysis to detect synchronized blocks or methods which can be optimized away, as in the local usage of StringBuffers. There should be no difference between StringBuffers and StringBuilders in modern Java VMs. But it doesn’t hurt to use StringBuilder.
Ending his article: “If a interviewer wants to talk about my past projects with me, then it should not take him long to realize that I am a competent.” Or read a blog, as Jonthan suggested in Blogging gets people hired.
Hopefully he doesn’t read your blog.
Peace
-stephan
PS: I wish I don’t sound the least bit like Hani ;-)
November 11, 2007
Lately I wrote about interview questions, specifically about asking how to write a String reverser method. When searching for a job as a PR-consultant my girl friend was sent a PDF to answer questions - which I guess the company uses to gather fresh ideas - and she had to send the answers back written in the PDF. This got me thinking.
If you have lots of candidates for a programming job, screening them online might safe you some time. You could ask the candidates to write some code, for example “to reverse a String”. How do you determine if the answer is correct? Write a unit test. How do we execute code the candidate entered into a form? Just use a compiler. Janino is a Java compiler which can compile Java source code that it reads from a String:
import org.codehaus.janino.SimpleCompiler;
import java.io.StringReader;
public class Evaluator {
public static void main(String[] args) {
String source =
"import java.util.*;\\n" +
"public class MyReverser implements Reverser {\\n" +
" public String reverse(String str) {\\n" +
" return new StringBuilder(str).reverse().toString();\\n" +
" }\\n" +
"}";
try {
SimpleCompiler compiler =
new SimpleCompiler("Test", new StringReader(source));
Reverser reverser =
(Reverser) compiler.getClassLoader().loadClass("MyReverser").newInstance();
System.out.println(reverser.reverse("Stephan"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
You present an input form, protected with a token you’ve sent the candidate. Making the job easier, you can provide a syntax highlighting editor like codepress. When he enters the code, Janino compiles it, runs a JUnit or TestNG test and tells the candidate if his code is correct or not. Obviously people will cut and paste code into the box when you ask for the answer to a simple problem like string reversal (Google is just one click away). But asking the candidate a more tricky question, which he cannot google might work. Like ask them to write an elevator simulation (state machine with several elevators) and test the result with a unit test.
Even better you could also make them write code to satisfy a Fitnesse story. With fitness it’s easy to add further constraints to the test and you can ask the candidate to extend the test with constraints he considers necessary. Make him write his tests too ;-)
The nice thing with Java, compared to Ruby and PHP, is that Java has a fine grained security concept. With a Java security manager you can make this application safe by preventing access to file and system resoures and still execute the code the candidate entered into the form. The same goes for other languages on top of the VM. So for asking Ruby questions you can use JRuby.
Hope this gives you some ideas about asking interview questions online.
Thanks for listening.
November 9, 2007
Interviewing developers for a programming job is hard and tedious. There are some excellent Guides, like the Joel Guerilla Guide to interviewing, but in the end you need to decide yourself to hire or not to hire. To get a quick idea about their programming abilities I have considered asking the String reverse question. Others have used this question with some success. There are lots of answers to this question which gives you room to explore the candidates skills. Thinking about this myself, I found some answers on how to reverse a String in Java. The answer the candidate gives is a good way to see how he thinks. You could combine this question with one about interfaces and ask for a reverser interface:
public interface Reverser {
public String reverse(String str);
}
The best implementation in Java is to use the reverse method of the StringBuffer class in the JDK. It’s fast, efficient and knows how to handle unicode surrogate pairs, something most other solutions ignore.
public class JdkReverser implements Reverser {
public String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return new StringBuffer(str).reverse().toString();
}
}
Not only is the chosen implementation interesting as an answer, but also does the candidate reuse the JDK or not or does he tell you at least “there has to be something in the JDK”. Which is quite as good, because googling in reality will help him find the JDK solution. You don’t want developers to implement everything themselves.
Handling problems
Ask him where the bug is in this code, even if there is none. Or how his code can go wrong. His answers can lead into a discussion about how to handle a null value
- return null
- return “”
- throw NullPointerException
- throw IllegalArgumentException
and the merits of every solution. The second discussion point is how to optimize the solution, like returning the string itself for “” and every one length string (which is a reversal of itself already).
Recursion
Then ask the candidate to write a recursive solution of the reversal problem (which is the most beautiful but least usable one).
public String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
Some developers can’t handle recursion in their head. Most candidates will need some time and some help, but actually get to a solution. Those that can’t handle several stages of recursion in their head probably can’t handle complex problems or several layers in their head either.
You can ask them about the efficiency of the recursive solution, ask about Tail Recursion, ask about the ineffeciency of the “+” operation for Strings, how to handle that, about why Strings are immutable (most of the time at least) and ask the candidate how many String objects are created for reversing “Stephan” with his recursive solution. When discussing this one of my developers said “Easy”, he was doing Lisp at the university the whole time, which I didn’t know until then, excellent news!
Ask where the stop condition is in the above code to end the recursion.
More solutions
Some more solutions, one with swapping a StringBuffer in place:
public String reverse(String str) {
if ((null == str) || (str.length() <= 1 )) {
return str;
}
StringBuffer result = new StringBuffer(str);
for (int i = 0; i < (str.length() / 2); i++) {
int swapIndex = str.length() - 1 - i;
char swap = result.charAt(swapIndex);
result.setCharAt(swapIndex, result.charAt(i));
result.setCharAt(i, swap);
}
return result.toString();
}
One with swapping an array:
public String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
char[] chars = str.toCharArray();
int right = chars.length - 1;
for (int left = 0; left < right; left++) {
char swap = chars[left];
chars[left] = chars[right];
chars[right--] = swap;
}
return new String(chars);
}
and one with appending to a StringBuffer:
public String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
StringBuffer reverse = new StringBuffer(str.length());
for (int i = str.length() - 1; i >= 0; i--) {
reverse.append(str.charAt(i));
}
return reverse.toString();
}
}
Perhaps the candidate even knows about the tricky XOR swapping solution.
From there it’s an open field. You could ask the candidate to write a JUnit test for his reverse method. Not only can he show how to write a unit test, but what he considers as test cases (”", null, “A”, “Even”, “Odd”, ….).
I hope this helps you in your decision with hire or no hire. And I hope it helps me in the future to decide this question for myself. As Joel said: when in doubt, always no hire.
Thanks for listening.
Gmail seems to have increased the size of my mailbox with their recent update. Nice, thanks.

November 5, 2007
Lots and lots of people lament the explicit type system in Java, either they are dynamic ducks or inference intellectuals. Taken from the Boo manifesto:
“Nothing more tiresome than writing the same type name over and over just to make the compiler happy. I’m not talking against static typing in general (boo is statically typed), I’m talking against being coerced by a tyrannical compiler to say things it should already know.”
Beside the fact that my IDE does the typing with auto completion - of course the compiler knows - DUH. But the developer does not know. The developer who wrote the code does know, for about a month. When not working with the code for some time or another developer taking over - then is where the problem rises it’s head. Explicit Static Types are not for the compiler, but for the developer.
def person = Factory.getPerson()
Is person of class Person? Or perhaps Student or Employee? I’m wading through legacy code and the first thing that gets out is correct naming. What once was a person soon gets a Human. How should I know? Explicit typing is writing documentation. Not helping the compiler.
Some people claim explicit types increase lines of code. I can’t see how:
def person = new Person()
versus
Person person = new Person()
There are other things in Java that increase lines of code. Not explicit types. If I had some whishes free, I’d opt for properties and getting rid of unnecessary getter and setters, I’d like to have constructors with named parameters like in Groovy, I want syntactic sugar like [] and [:] for list and map creation, I want all attributes public unless declared private, all methods public unless declared otherwise, I want to drop the “;”, remove unneeded (cast)s where I declared the type explicitly and I wish for closures. But drop explicit types? NO!
My style of programming uses lots of interfaces. A class usually has several small ones and I try to narrow down a class to the interface I use. Narrowing down an object reduces coupling and increases reusability.
public class Person implements Nameable {
private String name;
public String getName() {
return this.name;
};
}
...
Nameable nameable = new Person();
printName( nameable );
Can I do this with type inference? What about
List persons = new ArrayList();
I guess type inference doesn’t help you here, coding against an interface and coding against more abstract entities as proposed by Robert C. Martin is out of the window. With type inference and without explicit types your code will depend on the concrete implementations, not the abstract definitions (or not depend on anything, which depends on your view ;-) Explicit typing is about reducing scope, knowledge and coupling.
Conclusion: Explicit types help the developer and create better, more understandable, more readable and more reusable code.
Sidenote to ducks: People claim that while they need 95% test coverage for dynamic code to find typo bugs, with explicit types the compiler gets the bugs for them:
“We discovered that anything shy of 95% code coverage with Rails means that type-os turn into runtime failures. We do not have any code coverage metrics for the lift code, but we have seen only 1 defect that’s been checked in in the 2 weeks since we started using lift.”
Thanks for listening.
Update: Jari wrote something about types inference, scala and IDE annotations on his blog.
November 4, 2007
Alex wrote in his latest Java 7 Roundup about my idea of a @license and Paul’s @copyright addendum. I wrote about the idea here.
@License(name = "Apache",version = "2.0")
@Copyright(owner = "Stephan Schmidt")
public class Example {
public void doWhatever() { ... }
}
In the comments of that post Paul Hammant mentioned a @copyright annotation, which could help verify the copyright status of code. The best and easiest way to use @license and @copyright would be to add it at the package level. Few people know that Java got a package level construct called package-info.java where developers can add package level annotations:
“Typically package-info.java contains only a package declaration, preceded immediately by the annotations on the package.”
Hopefully such an annotation would be implemented as a Java standard and used by all major DI containers like Spring, Guice and Apache Composer, because as I wrote in the comments:
“A container could know about licenses and issue a warning when injecting incompatible stuff. This would make some managers in companies happy.”
As I want to pursue the idea further, it would be best to move this with a short JSR into Java 7.
November 3, 2007
Apple should release a roadmap for their Java support and their plans for Java 6 I think. Think different. Some do.
Reading the post Searching Jars Redux on the “Code To Joy” blog, where Michael shows a closure Example in Java iterating through Jar content, saying ” old-style Enumeration, don’t blame me or closures!” about some ugly code using an Enumeration. It would be nice to just use for to iterate over an enumeration. This can be done easily. You can use Enumerations with the Java 5 for syntax when using a little Adapter around an Enumeration.
public static void main(String[] args) {
Vector<String> vector = new Vector<String>();
vector.add("Stephan");
for (String name : iterate(vector.elements())) {
System.out.println("Name: " + name);
}
}
public static <T> Iterable<T> iterate(Enumeration<T> enumeration) {
return new IterableEnumeration<T>(enumeration);
}
The IterableEnumeration is quite easy to write:
public class IterableEnumeration<T> implements Iterable<T>, Iterator<T> {
private Enumeration<T> enumeration;
public IterableEnumeration(Enumeration<T> enumeration) {
this.enumeration = enumeration;
}
public Iterator<T> iterator() {
return this;
}
public boolean hasNext() {
return enumeration.hasMoreElements();
}
public T next() {
return enumeration.nextElement();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
Together with static imports and a static iterate method, the Java code looks much nicer.
Go for more beautiful Java.
Thanks for listening.