Is it good to upgrade to MapStruct from ModelMapper? - mapstruct

Currently we are using ModelMapper in our project. However in the site i see there are lot of likes for MapStruct.
Not sure the differences and whether we need to really go for an upgrade.
What are the differences between ModelMapper and MapStruct ?
Thanks.

(Project lead of MapStruct here, so naturally I am biased)
I have not used ModelMapper before. However, the projects are quite different in the way they are doing the mapping. I believe that ModelMapper is based on reflection and performs the mapping during runtime. Whereas MapStruct is a code generator which generates the mapping code (java classes) during compilation time.
So naturally if you are worried about performance then MapStruct is the clear choice. There is this independent Java Object Mapper Benchmark that benchmarks different frameworks.
The code that is generated by MapStruct is human readable code which is easy to debug and there is no reflection in it.
There are a lot of built-in conversions.
You get notified during compilation time if something could not be mapped and you would be responsible to providing such mappings so MapStruct can use them.
There are also IDE plugins:
* IntelliJ plug-in: helps when editing mapper interfaces via auto-completion, go to referenced properties, refactoring support etc.
* Eclipse plug-in avaible: has quickfixes and auto-completions which are very helpful when designing mapper interfaces

Related

External DSL for CRUD code generation for multiple frameworks

I am developing a general purpose CRUD code generator application. The idea is that codes/files (model, controller, view) for common insert, update, list, delete etc. operations will be automatically generated from model definition (like the definition used in Grails). But the generated code can be for any framework, e.g. Play (Scala or Java version) or Django or Grails or whatever framework user wants to use it for, even AngularJs. That is, same model definition can be used for generating code for any framework.
My question is, what can I use for this task - Scala or Groovy or some DSL specialized tools like Xtext?
This seems like a good case for a DSL. A DSL can be summed up as the following 3 elements:
Abstract Syntax: the concepts of your DSL. Here you want to specify CRUD applications.
Concrete Syntax(es): a way to materialize your Abstract Syntax. As a programmer, the first thought is often text-based syntaxes, but you could also use a graphical or tree-like syntax, or even simply a GUI with text fields and checkboxes.
Semantics: the meanings of your DSL. Here you want to generate code.
I'll now suggest some solutions which are based on Java and come from the Eclipse Modeling ecosystem.
Eclipse EMF implements standards for the definition of so-called "metamodels" (basically abstract syntaxes). In the Eclipse world, EMF is the base for a lot of tooling.
Assuming you have an EMF metamodel, textual syntaxes can be specified using Eclipse Xtext, and graphical syntaxes using Eclipse Sirius. Note that you can also develop your own GUI in Java and create your model using the EMF Java APIs. Also note that Xtext can create your metamodel for you based on the grammar you want for your text-based syntax. This is nice if you don't want to dive too deep into EMF it self (thus steps 1 and 2 are one and the same).
Eclipse Acceleo provides a template language specifically designed to generate text, including code. Once again, you can also write your code generator using plain Java, or any JVM-based language thanks to the EMF Java APIs. If you use Xtext, there is also a facility for including an Xtend-based code generator alonside your syntax.

Scala Metaprogramming at Runtime

I'm building a tool that will receive unpredictable data structure, and I want to generate case class to accomplish the structure of the received data.
I'm trying to figure out if it's possible to generate case class at runtime? This structure will be know only at runtime.
It's something similar to what macro does, but in runtime.
I've found this project on the internet
mars
Which is very close to what I want to do ,but I couldn't find if it was successful of not.
Another way of doing it is generate the code, compile and put the result in the classpath, like IScala is doing to use the code in an iterative way. But I don't think that this will scale.
Does anybody has already done something like runtime code generation?
This question was also posted in scala-user mailing list
UPDATE: (as per the comments)
If all you want is throw-away code generated at runtime to be fed into to a library that cannot work with just lists and maps, and not code to be stored and used later, it would make sense to look for solutions to this problem for Java or JVM. That is, unless the library requires some Scala specific features not available to vanilla JVM bytecode (Scala adds some extras to the bytecode, which Java code doesn't need/have).
what is the benefit of generating statically typed code dynamically? as opposed to using a dynamic data structure.
I would not attempt that at all. Just use a structure such as nested lists and maps.
Runtime code generation is one of the purposes of the Mars Project. Mars is under development, at the moment there is no release version. Mars requires its own toolchain to expand macros at runtime and should use several features unique to scala.meta (http://scalameta.org/), for example, AST interpretation and AST persistence. Currently we are working on ASTs typechecking in scala-reflect, required for runtime macros expansion.

What's the scala alternative to runtime-preserved annotations

I just realized I cannot have annotations in scala, that are preserved and analyzed at runtime. I also checked this question, but I didn't quite get it what are the alternatives.
DI - an answer mentions that there is no need for DI framework in scala. While that might be the case on a basic level (although I didn't quite like that example; what's the idiomatic way of handling DI?), Java DI frameworks like spring are pretty advanced and handle many things like scheduled jobs, caching, managed persistence, etc, all through annotations, and sometimes - custom ones.
ORM - I'll admit I haven't tried any native scala ORM, but from what I see in squeryl, it also makes some use of annotations, meaning they are unavoidable?
any serialization tool - how do you idiomatically customize serialization output to JSON/XML/...?
Web service frameworks - how do you define (in code) the mappings, headers, etc. for RESTful or SOAP services?
Scala users need to have a hybrid scala/java (for the annotations) project in order to use these facilities that are coming from Java?
And are the native scala alternatives for meta-data nicer than annotations? I'm not yet fully into the scala mode of thinking, and therefore most of the examples look ugly to me, compared to using annotations, so please try to be extra convincing :)
Actually, Scala does have runtime-retained annotations. The difference is that they are not stored as Java annotations but are instead encoded inside the contents of binary ScalaSignature annotation (which, by itself, is a runtime-retained Java annotation).
So, Scala annotations can be retrieved at runtime, but instead of using Java reflection, one must use Scala reflection:
class Awesome extends StaticAnnotation
#Awesome
class AwesomeClass
import scala.reflect.runtime.universe._
val clazz = classOf[AwesomeClass]
val mirror = runtimeMirror(clazz.getClassLoader)
val symbol = mirror.classSymbol(clazz)
println(symbol.annotations) // prints 'List(Awesome)'
Unfortunately, Scala reflection is still marked as experimental and is actually unstable at this point (SI-6240 or SI-6826 are examples of quite serious issues). Nevertheless, it seems like the most straightforward replacement for Java reflection and annotations in the long term.
As for now, one has to use Java annotations which I think is still a nice solution.
Regarding frameworks and libraries for DI/ORM/WS/serialization - Scala still doesn't seem to be mature in this area, at least not as Java is. There are plenty of ongoing projects targeting these problems, some of them are already really nice, others are still in development. To name a few that come to my mind: Squeryl, Slick, Spray, Pickling.
Also, Scala has some advanced features that often make annotations unneccessary. Typeclasses (implemented with implicit parameters) are probably good example of that.

Scala and Aspects

Scala and Aspects can be used together? Are there benefits in this case?
Thanks
Scala is just like java, if you mean for example spring-like AOP I'm sure that annotations work either in scala or in java.
On the other hand, the fact that Scala has closures (and java doesn't) makes AOP less interesting.
In fact the Scala IDE for Eclipse uses Aspects (because the JDT assumes Java):
From Scala Support in Eclipse - Monkey-patching the JDT for fun and profit?, p16 by Miles Sabin
AspectJ and Equinox Aspects
A collection of aspects is effectively a patch
AspectJ was used to retrofit the desired extensibility features to the JDT and expose them via public API
The key modification:
The JDT's CompilationUnit is the entry point to it's internal model, but it assumes Java source
An aspect can turn its constructor into a factory method
So the answer is Yes, it is possible. I have to agree with Pablo that it's less attractive than in Java.
Fakod has some examples for AspectJ here
Real-World Scala: Managing Cross-Cutting Concerns using Mixin Composition and AOP

Project Lombok vs. Eclipse templates / code generation

Does Project Lombok offer any benefit compared to code templates / code generation in Eclipse? Are there any downsides (apart from including the .jar)?.
One advantage of Lombok is that once you've annotated a class with, say, the #Data annotation, you never need to regenerate the code when you make changes. For example, if you add a new field, #Data would automatically include that field in the equals, hashCode and toString methods. You'd need to manually make that change when using Eclipse generated methods. Some of the time, you may prefer the manual control but for most cases, I expect not.
The advantage of Lombok is that the code isn't actually there - i.e. classes are much more readable and are not cluttered.
Advantages:
Very easy to use
Classes are much cleaner ('no boilerplate code'),especially
'struct'-like inner classes shrink to a bare minimum:
#Data
private class AttrValue {
private String attribute;
private MyType value;
}
This will create both getters and setters, a toString(), and correct hash() / equals() methods including both variables.
The variant with #Value creates an immutable structure (no setters, all fields final).
No need to generate/remove code when you change fields (getters, setters, toString, hash, equals)
No interference with hand-coded methods: just add you own specific setter to the class where needed. Lombok skips this and generates everything else
Disadvantages:
No name refactoring, yet: renaming value above will not (yet) rename getValue() and setValue()
May slows down ecplise slightly
toString output not as nice as, for instance, ToStringBuilder from apache commons
Very few come to mind:
it is based on annotation, so no good for legacy project still in pre-Java5 (delombok can help). Actually, it requires using the javac v1.6 compiler.
it still have limitations regarding multiple constructors
The dependency issue is not to be overlooked though, but you have excluded it from your question.
Eclipse EMF offers some features which are very handy which Lombock does not yet support:
Powerful notification mechanims to get informed about changes in your instances
Generic API without java reflection. Access and modify instances without a strong reference to the type
Command und API based editing
Cross references between models: Create and load model trees and EMF handles the loading by creating a proxy for the cross reference. This saves memory and boost performance in huge domain trees
And much more...