Freitag, 24. Oktober 2014

Xtend - Perfect for Code generation

Before Xtend became a general purpose language, it was designed for building code generators and model-to-model transformations in the Xtext framework. And even though this is no longer Xtend's main focus, the related features are useful in other situations, too!

Template Expressions


Pretty much every modern language has some way to insert variables into a String template. In Xtend this is called a Rich String and has the following syntax:


But Xtend doesn't just have placeholders. You can have loops and branches right inside your templates. In other languages you need to go back to the StringBuilder pattern to do that.


Notice the different coloring in the whitespace above? Some of it is white, while other pieces are grey. This is how Xtend solves the classic "indentation problem". In  most other languages, either your template looks nicely formatted and the generated code is ugly or the other way round. But Xtend is clever enough to notice the difference between indentation in the generated code ("greyspace") and indentation that is just there to make the template look nice ("whitespace").

Template expressions will come in handy later on when we build Active Annotations to teach the Xtend compiler new tricks. Stay tuned for that!

Dynamic Dispatch


Just like Java, Xtend does static dispatch by default. If you have overloaded methods, the argument types known at compile time decide which is chosen. But sometimes you want to defer that decision to runtime. For instance, you might want to build a method that can convert different things to a Date. You pass in on Object and it tries its best to parse it. Possible valid inputs could be Date, Calendar, String, Long, etc.

To implement that in Java, you have to create a big if-else cascade to check the runtime types of the argument and then call the appropriate method.


Also, you have to be careful to put subtypes before supertypes so you don't end up with dead branches.


Xtend makes dynamic dispatch a first class concept. You just write down the different cases. Xtend then looks for the common supertype of the argument types. In this case it's java.lang.Object. Using that argument type, it generates the entry point method similar to what we did by hand in Java. This even works when subclasses add additional overloads. Also notice how we got rid of all the casts that the Java version had.


The toDate method was only a simple example to introduce the concept. Dispatch methods really shine when you build code generators, interpreters and other kinds of object tree visitors. Most of the time you don't know the exact type of the elements in that tree at compile time. With dispatch methods, you don't need to care, the correct method will be selected at runtime.

Mittwoch, 22. Oktober 2014

Xtend - Operator Overloading

Xtend has a nice list of operators you can use out of the box. But you can also overload them for your own types and even for types that others have written. Let's just look at a typical numeric type, Complex numbers:


As you can see, overloading an operator is just done by writing a method whose name matches the operator and its signature. In our example I have overloaded the binary plus and minus operators as well as the unary minus operator. I left out the constructor, toString, equals, hashCode etc. In an upcoming post you will see that Xtend can automatically generate all of these for you.

Now let's see our new number type in action:


The operators work just like you would expect, but the last line is something especially cool: By defining +, you get += for free! But all those constructor calls don't look like we are used to in mathematics. We want to write 1 + 2i. To do this, we add the following static methods to our Complex class


These methods actually extend the double type so it can also be added to and multiplied with Complex numbers. You can add operators to any existing type like this! Now we just need to import them as static extensions in our example and we get a much cleaner syntax.


There's one final tip I want to give you about the compound (+=, -=, *=, /=) operators. In the case of mutable types it makes sense to overload them with a different meaning than +, -, *, /

For example, the Xtend library defines the +-operator for List to mean "create a concatenated view of both Lists, without changing them".


The +=-operator on the other hand means "add all elements of the second list to the first one", which is more efficient if mutating the first list is okay.


Sonntag, 19. Oktober 2014

Xtend - Extension Methods

This is the feature that gave Xtend its name and one of its most powerful tools. At the same time it is one of the least understood features among beginners, so I'll give you a head start.

Extension methods can be called on instances of their first parameter type as if they were defined in that type. That's quite a mouthful, so let's just look at an example:


We defined an isPrime method that takes an int and then we could call 2.isPrime. You can extend any existing type this way. But which methods exactly are available as extension methods? As you have seen in the example above, instance methods of the current class are automatically available as extension methods. But many times you will want to write an extension once and then use it wherever you need it.

The simplest approach is to have static methods and import those using a static extension import. Doing this, these methods are available as extension methods in the whole file.


But often times you don't want static methods. Maybe because the helper method lives in a stateful object. Or maybe because you want to use a service that you get through dependency injection. For these cases you can also mark fields, parameters and even local variables as extensions. Their methods are then available as extension methods wherever the field/parameter/variable itself is visible. Below is an example of an extension field, maybe initialized in the constructor.


This makes typical OO patterns look much cleaner in Xtend. We all know that we should follow principles like "Single Responsibility". But in Java, calling these helpers is annoyingly verbose:


Another common pattern are factory methods and the Master-Yoda language that you use in Java.


In Xtend, using a static extension import, we get much closer to English.


And of course you sometimes need to use APIs that are just inconvenient. The only workaround in Java is creating wrapper classes that hide the bad API. But that of course adds runtime overhead for wrapping/unwrapping. With Xtend you can write some convenient extension methods and avoid this overhead completely.


Notice how there is no more syntactic difference between a normal method and a helper method. This makes for much more readable call chains.


To top it off, Xtend ships a small library with useful extension methods for classes from the JDK. Most importantly these include methods like filter, map and reduce to work with collections in a functional style.

Freitag, 17. Oktober 2014

Xtend - Basic Syntax Sugar

Xtend comes with a lot of syntactic sugar that makes your code more readable. In this post we will look at the basics and see how you can make your code much shorter even without learning Xtend's advanced features.

Let us take this simple snippet of Java code as an example and make it more readable step by step.


For starters, here is the 1-to-1 translation to Xtend, without using any syntax sugar.


I was serious when I said Xtend is similar to Java. Now let's remove all the small distractions: Visibility modifiers, semicolons, empty parentheses and the return keyword are all optional in Xtend. Also, since getters and setters are so widespread in Java-land, Xtend allows you to use them with the same syntax as fields.


Okay, that's a little better, but the real deal comes next. Xtend has very powerful type inference. You almost never have to write down a type if you don't want to. Xtend will even look at the control flow to infer types of earlier declarations. In our example, it can determine that the type of the Map must be <String, Person> by looking at the call to byName.put.



Another little trick up Xtend's sleeve is the use of the variable it. If you give a variable that name it becomes an implicit receiver, just like the this keyword in Java. Instead of calling it.name, you can just call name.


Xtend also has lambdas and probably the most beautiful syntax for them. Even with the arrival of Java 8, Xtend is still easier on the eyes. Xtend allows both interfaces and abstract classes with one abstract method to be written as a lambda. Our example is much easier to express in this functional way. Exactly how Xtend manages to add new functional APIs to existing types like List will be the topic of another entry in this series.



To top it of, Xtend has literals and operators for List, Map, Set, BigInteger and BigDecimal. It will also automatically convert between Arrays and Lists. This makes these basic types much more fun to use. It even adds a few operators on top of what you know from Java, including the null-safe feature call (?.) and the elvis operator (?:) for supplying a default value. See the documentation for a full list.


This last snippet also shows how you can use a positional syntax in lambdas, when you don't want to give the parameters names. It could have alternatively been written like this:


This wraps up the basic syntax sugar of Xtend. In the upcoming posts we will look at advanced language features that allow you to write even more expressive code.

Dienstag, 14. Oktober 2014

Xtend - The Series


Xtend is a statically typed programming language that compiles to readable Java code. It stays true to Java's type system and libraries, giving it the best interoperability of all the popular JVM languages. On top of that it adds a lot of syntactic sugar and powerful abstraction features that really cut down on the boilerplate you have to write. Together with its flat learning curve, top-notch IDE and build-system integration, it is easy to pick up and will give you immediate benefits.

The release of Xtend 2.7 has brought about a new milestone of language features, performance and IDE integration. So much has been done over the last few releases that I thought an up-to-date blog series was in order. I still see a lot of outdated information and misconceptions floating around the world wide webs. So even if you already gave Xtend a try one or two years ago, there is a lot to be learned.

In the first post of this series I will show you how to get started and how to reach the community. In the following posts, I will present individual features of Xtend in-depth. So stay tuned =)

Easy setup


To use Xtend inside Eclipse, just follow the links on the download page. You can look at some examples by using New->Example->Xtend Introductory Examples.

Xtend classes live right next to your plain old Java classes. Xtend needs a small runtime library. If your project doesn't have it yet, you will get a quickfix the first time you try to edit an Xtend file.

If you are like me and prefer to set up your projects using your favorite build system, we also got you covered. For Maven, there is the Xtend Archetype. Eclipse's Maven integration will take care of the rest. For Gradle, you can use the Xtend Gradle Plugin. Using that, just call gradle eclipse on the command line and you have a fully configured Eclipse project.

Flat learning curve


Xtend's basic syntax is almost identical to Java, so programmers coming from there will feel right at home. They are actually so similar that we will provide a Java->Xtend converter in the next release.

One important difference is that in Xtend, everything is an expression and has a return type. So you can for instance assign the result of an if-expression to a field. No need for (static) initializers or similar ugly constructs.

Also, Xtend enforces the distinction between defining a method and overrides, reducing potential errors. Apart from that you will notice that Xtend has better visibility defaults: Classes and methods are public, fields are private.

Xtend's switch expression can switch over anything, making it a good alternative to if-else cascades. And if you do type checks in switch- or if-expressions, then Xtend will automatically cast the variable for you inside the corresponding block. So even before learning anything about the advanced language features, you are already getting some benefit over Java.



Community


Xtend has a very friendly and helpful community. You will find enterprise developers, Eclipse plugin authors and Android App writers all taking part in discussions. The Xtend team takes inquiries very seriously, looking through the forum and answering questions on a daily basis. Just drop by if you have any questions or want to share some cool library or success story. We are looking forward to having you on board!

Montag, 13. Oktober 2014

See you at EclipseCon Europe

EclipseCon Europe is just around the corner, so it is time for some shameless self-promotion ;) Among the many awesome talks on Xtend and Xtext will also be one given by me and my colleague Sebastian Zarnekow.

Tue 16:45 to 17:20: New & Noteworthy in Xtend

In this overview we will show you many great features that were added in the 2.6 and 2.7 releases. Among them are inner classes, swifty lambda sugar and improved operator overloading. The small standard library also got some often requested additions as well as cool new Active Annotations. Of course it’s not only the language itself but also the Eclipse based IDE, that got a lot of attention. It comes with better performance, more powerful code analysis, organize imports on packages, improved template proposals and a revised outline view.

You will also get a glimpse at what we have planned for the future, like the long anticipated IntelliJ support and faster builds. And of course you can get in touch with us at the itemis booth. I'm looking forward to see you there!