Simplify your OSATE and AADL analysis code with Java 8 lambda
If you already wrote analysis code inside OSATE, you probably know that when writing an analysis plug-in, filtering components (according to their type, property, etc) can be painful. It can introduce a lot of useless code that browse the model to find the component of interest. The code used to browse the model is long and add a lot of noise, making the review difficult.
Over the last months, I started to use the xtend language for writing my analysis plugin. It was a way to simplify my code and learn a new language. When I started to read about Java 8, I was excited to use the lambda expression mechanism. And realized that it can be leveraged to simplify the design of my AADL plugins.
Bottom line: it remove a lot of noisy code to only focus on what is really important. It makes the code more understandable and easy to read.
I will illustrate that with an example. In this example, I get all data components that have the Data_Size
property set to 0. The difference between a standard, recursive implementation and the lambda-expression is simple: about 20 lines of code vs 3 lines of code.
The imperative version looks like this (see below): you have to browse the component hierarchy and check the component category and Data_Size
value. Really, what you care in this code is the condition that filter the component. All the rest is noise, not useful but can still introduce a lot of bugs.
public static List<ComponentInstance> findComponentRecursive (ComponentInstance si)
{
List<ComponentInstance> res = new ArrayList<ComponentInstance> ();
for (ComponentInstance ci : si.getComponentInstances())
{
if ( (ci.getCategory() == ComponentCategory.DATA) && (GetProperties.getDataSizeInBytes(ci) == 0.0 ))
{
res.add(ci);
}
res.addAll(findComponentRecursive(ci));
}
return res;
}
public static List<ComponentInstance> findComponent (SystemInstance si)
{
return findComponentRecursive (si);
}
Let’s now have a look at the same implementation but with the lambda expression. What you really have is a method that filters the components using a predicate. Simple. Easy to read. Efficient.
public static List<ComponentInstance> findComponent (SystemInstance si)
{
return (List<ComponentInstance>) si.getAllComponentInstances().stream()
.filter( comp -> (comp.getCategory() == ComponentCategory.DATA) && (GetProperties.getDataSizeInBytes(comp) == 0.0 ) ).collect(Collectors.toList());
}
I am still reading code examples about Java 8 and using lambda. I am convinced it can help a lot to write better code, increase productivity and reduce bugs. If you are writing analysis plugins for AADL, I would definitively recommend to at list have a look at the tutorial.