How to avoid deprecation warnings when #SuppressWarnings("deprecation") doesn't work? - java

We have a Java project. We enable -Xlint (enable warnings) and -Werror (treat warning as error) flags for javac, to make sure our code is warning-free. Recently we decide to deprecate a class. The problem is in some cases #SuppressWarnings("deprecation") will not suppress the deprecation warning at all, resulting in build failure. Below is a list of use cases that I ran into:
Imported in other non-deprecated classes.
Imported in other deprecated classes.
Parent class.
Type parameter. For example
#SuppressWarnings("deprecation")
public class Foo extends Bar<DeprecatedClass>
{ ... }
However, this one has no warning even without suppress:
#Deprecated
public class DeprecatedClass extends Bar<DeprecatedClass>
{ ... }
AFAIK, there is no syntax for annotating imports, so for case 1 and 2 our solution is to either import * or avoid importing. For case 3 and 4, both Java 6 and 7 do not suppress the warning. Java 8 will correctly suppress it (maybe a bug is fixed). So far no solution for this.
Unfortunately, we have to support Java 6, 7 and 8 at this point. Is there way to deal with the problem? It is a road block for our Java API evolution.
ADDENDUM
Many people ask why do we still use the deprecated class in our own codebase. The reason is that the project is a library, supporting many different clients. When introducing new replacement API, we have to first deprecate our old API, keep it in our codebase, wait for all clients to migrate then remove it. There are three common use cases:
We deprecate class Foo and Bar, where Foo extends Bar. This is the case 2 and 3 in my question.
We deprecate class Foo and Bar, where Foo extends Collection<Bar>. This is the case 2 and 4.
We must keep all test code for class Foo and Bar. The test code imports these classes. This is the case 1.
Why keep the test? Don't forget that if a serious bug (e.g. memory leak, security issue) is discovered, and the clients can't easily migrate to the new version, we still need to provide bug fix to the old API. And all changes must be tested.
I feel our situation should be fairly common in software library development and API evolution. Surprisingly it took Java such long time (until Java 8) to fix the bug.

I'm sorry to say that I don't have a solution to the problem you're facing, though as you've observed, there has been some progress. We've been trying to get rid of all the Java compilation warnings in the JDK itself, and this has been a long, difficult process. During JDK 8 development in 2011 I helped kick off the warnings cleanup effort and I later co-presented a JavaOne talk (slides and audio) on the subject.
More recently, my colleage Joe Darcy has continued the warnings cleanup work and has worked through the different warnings categories and has finally reached deprecation warnings. As you noted, there have been some bugs in the compiler's handling of suppression of deprecation warnings, such as JDK-6480588 which was fixed in JDK 8. Unfortunately, it is still not possible in JDK 8 to suppress warnings on imports of deprecated items. This bug, JDK-8032211, was fixed quite recently in our JDK 9 development line. In fact, we're still tuning up the handling of the #Deprecated annotation. For example, bug JDK-6481080 clarifies that attempting to use #Deprecated in a package-info.java file does not in fact deprecate the package; this bug was fixed just last week. And there is more work to be done but it's somewhat speculative at this point.
The JDK is facing similar problems to yours, in that we have to maintain deprecated APIs for clients that are still using them. But since we use and implement such APIs internally, we have a lot of deprecation warnings to suppress. As of this writing, in our JDK 9 development line, we still have not been able to compile the system without deprecation warnings. As a result, the javac options for lint warnings are still:
-Xlint:all,-deprecation
You will probably have to disable deprecation warnings in your compilation as well, especially if you are still building on JDK 6. I don't see a way around it at this point.
One final note on one of your deprecation cases:
#Deprecated
public class DeprecatedClass extends Bar<DeprecatedClass> { ... }
This does not issue a deprecation warning, nor should it. The Java Language Specification, section 9.6.4.6, specifies that deprecation warnings are not issued if the use of a deprecated entity is within an entity that is itself deprecated.

Consider using -Xmaxwarns, you can control how many warnings before stop.
Or try collect the number of warnings and fail the integration process, not compiling.
For example: https://issues.apache.org/jira/browse/HADOOP-11252.
Every code commit to the hadoop project need to pass the automated CI and it give -1 for increase number of warnings.

Normally, when you deprecate class, you don't want anybody to use it in later versions. Also, YOUR codebase should stop using deprecated class too. It looks strange, when you say everybody not to use MySuperDeprecatedUtil class but continue using it in your codebase.
If you need to use your MySuperDeprecatedUtil class in some other class - you should mark class where you use it as #Deprecated - every class that used deprecated code should be either deprecated, or would produce compilation warnings, or should be removed, or should stop using deprecated code.
If you can't stop using your class - maybe it's too early to deprecate it?
In my practice, when I want to deprecate some class, I create replacement class e.g. MySuperFreshUtil. Switch all classess using MySuperDeprecatedUtil to MySuperFresh util preserving interfaces where possible(if not possible - use FQCN and mark method as deprecated). Mark MySuperDeprecatedUtil as #Deprecated and add comment which class and how should be used instead. Then I commit this changes in single changelist.

Related

Compatibility of a Java runtime retention annotation in previous Java versions

I want to use the #FunctionalInterface from Java 8 in my code, but I want to be able to use the generated class files with Java 6. I think then that I should the source version to 1.8, and the target version to 1.6.
I would be using #FunctionalInterface just for documentation, but I note that it has #Retention(RetentionPolicy.RUNTIME). If no one ever uses that annotation, will it cause problems?
If someone iterates over the annotations of my object at runtime, will it cause a missing class exception? But if that is true, how is it that how Google Guava can declare the JSR 305 annotation dependency to have a Maven <scope> of provided, which means annotations such as javax.annotation.Nonnull are missing at runtime, too, in Guava, without causing problems?
Let me ask it another way: if I use Google Guava in my project but don't include a JSR 305 dependency, do I really risk some error if I use reflection on the code? If so, what error will occur? If no error will occur, then analogously can I use the #FunctionalInterface annotation in source compiled with Java version 1.8 yet targeted to version 1.6 without any risk of runtime errors, even using reflection?
I think then that I should [set] the source version to 1.8, and the target version to 1.6.
Actually, it is not possible to compile Java source files of newer source versions for older JVM target versions. Oracles and OpenJDKs javac will reject a compilation attempt where the -source version is higher than the -target version. (However, I couldn't find a specification denying it, even the manual doesn't mention that). The sole idea of javacs cross-compiling feature is that you can compile your old e.g. 1.6 Java files still for the old 1.6 JVM even when you are using a newer JDK for compilation.
The issue you are describing is the sort of reason for this. Since Java is using a sort of lazy dependency loading, the compiler can't guarantee that there will be an appropriated class at runtime for all the dependencies. This also applies to the standard library.
However, there are (unofficial) tools to compile the newer source idioms or byte code to older byte code versions. But that doesn't go for the standard library. If you wanna use newer classes, you have to provide them on your own. For this purpose, there exist some back ports for specific parts of the standard library.
Specifically about your annotation question:
I was not able to find any reliable specification to what should/might happen if the JVM encounters an annotated construct for which it could not retrieve the class file (I searched the Java virtual machine specification SE 8). However, I found a somewhat related reference in the Java language specification SE 8:
An annotation is a marker which associates information with a program construct, but has no effect at run time.
From JLS 9.7
This statement rather indicates that an annotation (present or not) should not have an influence on the execution of a JVM. Therefore, a exception (such as NoClassDefFoundError) because of a missing annotation were rather against this.
Finally, though the answers of this question, I found even more specific statements:
An annotation that is present in the binary form may or may not be available at run time via the reflection libraries of the Java SE platform.
From JLS 9.6.4.2
And
Adding or removing annotations has no effect on the correct linkage of the binary representations of programs in the Java programming language.
From JLS 13.5.7
This quite clearly states that missing annotations will not cause an error, but instead will be just ignored if examined by reflection.
And if you deliver a class annotated with a Java 1.8 standard library annotation, and it will be (somehow) executed on e.g. Java 1.6 JVM where that annotation is just not present, then this specifications denies that any error is generated.
This is also supported by the following test which I wrote: (notice the usage of reflection)
#TestAnno
public class Test {
public static void main(String[] args) {
Annotation[] annos = Test.class.getAnnotations();
for (Annotation a : annos) {
System.out.println(a);
}
}
}
#Retention(RetentionPolicy.RUNTIME)
#interface TestAnno {
}
If compiled, it yields a Test.class and a TestAnno.class. When executed the program outputs:
#TestAnno()
Because that is the one annotation applied to Test. Now, if the TestAnno.class is removed without any modifications to Test.class (which refers to TestAnno with LTestAnno; sequence in the byte code) and Test is executed again, it just does not output anything. So my JVM is indeed ignoring the missing annotation and does not generate any error or exception (Tested with a OpenJDK version 1.8.0_131 on Linux).
As with any class loading situation, if the class isn't needed (or rather, doesn't need to be loaded), it doesn't matter if the class doesn't exist at runtime. Runtime annotations normally have the same problem, since if they're retained at runtime, it usually means that there's logic based on them, meaning their classes are loaded too.
But #FunctionalInterface doesn't have runtime logic, so...
Why does #FunctionalInterface have a RUNTIME retention? Apparently not for any particularly compelling reason, just a side effect of it also being #Documented annotation.
So if you want to make sure there are no potential problems if someone (or some tool more likely (I don't mean a "tool", like a co-worker)) decides to enumerate the annotations in your classes, I guess you'd need to remove the annotations at pre-processing.

Eclipse source code warnings

Below you can see an image of the source code (in eclipse) where the warnings are occurring. I am new to this, and am therefore unaware of how to solve this.
Source code image
Thanks
Andrew
Your example of warnings is related to usage of deprecated classes.
If you have the need to use that deprecated class (for a big reason) in that case you can add this:
#SuppressWarnings( "deprecation" )
That will remove the warnings.
But, ... Here is big but...
You should to avoid usage of deprecated classes/methods because of every part which is marked as deprecated is marked as deprecated for a reason. For example, some code (method, class, etc) is marked as deprecated because it is planned to be removed, have better solution, works non-predictive or some other reason.
From other side, everything what is annotated as #Deprecated have to discourage all the programmers using it and try to implement his replacement or another solution.
Like Felix mentioned, hover over those "warnings/messages" and it will show you a hint.
In this case, you are calling a deprecated class:
https://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html

What would be happen if used lot of #SuppressWarnings in my java file?

In my application lot of warnings are coming. For removing that warnings I'm using #SuppressWarnings annotations, anything would be happen in my code if I used several suppress warning annotations.
The #SuppressWarnings annotation does not change anything to the way your code works. The only thing it does is not make your compiler or IDE complain about specific warnings.
If you feel you need to use #SuppressWarnings a lot, then you should take a close look at why you get those warnings. It's a sign that you might be doing things incorrectly - you get warnings for a reason.
The #SuppressWarnings annotation disables certain compiler warnings. In this case, the warning about deprecated code ("deprecation") and unused local variables or unused private methods ("unused"). This article explains the possible values.
Depends on what warnings you are suppressing. If they are related to APIs that available only in new versions, your app will crash on older versions. Some warnings on the other hand are informational and point to common causes of bugs, so it really depends on what warning you are suppressing.
If you mean will my project break? or will it run slower most probably the answer is no. You can be fine suppressing warnings if they are trivial and you understand what are they signaling you and why are they there.
For example, an unused variable warning. Maybe you have defined it and plan to use in the near future, but the warning annoys you. Although I strongly suggest you to use a Source Code Version Control System like Git/Mercurial so you can safely delete code and recover a few days later.
But always check every warning you're suppressing: they are there for a purpose. For example, deprecated warnings: maybe your code runs fine, but in the next version of the JVM that deprecated method/class may have disappeared.
Always understand what you're doing

Is there an automatic way to generate a list of interface changes?

I am developing/maintaining a Java library, and would like to keep track of backwards-incompatible changes between releases. This list could contain changes in class declarations, method signatures etc.
For example, if I (accidentally) changed a constructor by adding a parameter, then I would like to have it included in the list and be warned about the change.
// before
public MyCar(String name) { ... }
// after (some accidental change)
public MyCar(String name, long mileage) { ... }
// an application using my library depending on this constructor would be broken
// when it updates to the new version
Is there an automated way to generate this list? It feels like something that IntelliJ or Gradle should be able to do.
My team has tried reviewing pull requests and maintaining a CHANGELOG manually (which seems to be a common approach), but that's prone to human errors. I seek an automated way that can ideally be part of the build system.
I've always maintained the compatibility list manually but sometimes I forget something.
A quick look around shows several open source libraries but they haven't had new versions released in nearly 10 years. So I don't know if they would work with new Java 7 or 8 features.
Note: I've never used any of these!
CLIRR - apache project used by some other apache projects to show what has changed (example output from apache commons-lang here. last updated in 2005 doesn't even build with Maven 2 (or 3)
JDiff javadoc doclet comparator. Might support Java 5. Last updated in 2008
Japitools - apparently was used by the GNU Classpath project to compare their APIs for signature compatibility with different versions of the Sun Java class libraries. Doesn't look like it's been updated since 2006
There's a better way to do it.
Preserve backwards compatibility for a time by annotating your methods with #Deprecated, and indicate when they'll be unsupported. Then add the #deprecated piece to your Javadoc and that will automatically generate a list of deprecated features that the end user needs to care about.
This has the added benefit of allowing you to introduce when a feature was introduced (#since), and when a feature will be removed, without having to fuss too much with a lot of other tools.
Since you've added a more concrete code example, I'll add one more note: those sorts of changes...are the result of a conscious design decision, and it brings to the forefront two issues:
Regression testing (as in, a test should have caught this)
Ease of transition into the newer API (as in, if I need to suddenly give a new parameter to this to gain functionality, isn't it a new thing rather than it being attached to the old, legacy thing?)
Those issues can't be teased away with any conventional tools; that requires an earnest conversation about the amount of time it takes to transition from one API to another. If you find that you need to introduce new functionality to the core, then you had better make darn certain that hasn't broken the legacy case.
This is what it means to have an API - you have to have the older version lurking around for a while.

Is it safe to use Project Lombok? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In case you don't know Project Lombok helps with some of the annoyances of Java with stuff like generating getters and setters with annotations and even simple JavaBean like generation with #Data. It could really help me, especially in 50 different event objects where you have up to 7 different fields that need to be constructed and hidden with getters. I could remove almost a thousand lines of code with this.
However, I'm worried that in the long run, it will be a regretful decision. Flamewars will erupt in the ##Java Freenode channel when I mention it, providing code snippets will confuse possible helpers, people will complain about missing JavaDoc, and future commiters might just remove it all anyway. I would really enjoy the positive, but I'm worried about the negative.
So: Is it safe to use Lombok on any project, small or large? Are the positive effects worth the negatives?
TL; DR:
Yes, it's pretty safe to use and I'd recommend using it. (May 2022)
Original Answer
Just started using Lombok today. So far I like it, but one drawback I didn't see mentioned was refactoring support.
If you have a class annotated with #Data, it will generate the getters and setters for you based on the field names. If you use one of those getters in another class, then decide the field is poorly named, it will not find usages of those getters and setters and replace the old name with the new name.
I would imagine this would have to be done via an IDE plug-in and not via Lombok.
UPDATE (Jan 22 '13)
After using Lombok for 3 months, I still recommend it for most projects. I did, however, find another drawback that is similar to the one listed above.
If you have a class, say MyCompoundObject.java that has 2 members, both annotated with #Delegate, say myWidgets and myGadgets, when you call myCompoundObject.getThingies() from another class, it's impossible to know if it's delegating to the Widget or Gadget because you can no longer jump to source within the IDE.
Using the Eclipse "Generate Delegate Methods..." provides you with the same functionality, is just as quick and provides source jumping. The downside is it clutters your source with boilerplate code that take the focus off the important stuff.
UPDATE 2 (Feb 26 '13)
After 5 months, we're still using Lombok, but I have some other annoyances. The lack of a declared getter & setter can get annoying at times when you are trying to familiarize yourself with new code.
For example, if I see a method called getDynamicCols() but I don't know what it's about, I have some extra hurdles to jump to determine the purpose of this method. Some of the hurdles are Lombok, some are the lack of a Lombok smart plugin. Hurdles include:
Lack of JavaDocs. If I javadoc the field, I would hope the getter and setter would inherit that javadoc through the Lombok compilation step.
Jump to method definition jumps me to the class, but not the property that generated the getter. This is a plugin issue.
Obviously you are not able to set a breakpoint in a getter/setter unless you generate or code the method.
NOTE: This Reference Search is not an issue as I first thought it was. You do need to be using a perspective that enables the Outline view though. Not a problem for most developers. My problem was I am using Mylyn which was filtering my Outline view, so I didn't see the methods. Lack of References search. If I want to see who's calling getDynamicCols(args...), I have to generate or code the setter to be able to search for references.
UPDATE 3 (Mar 7 '13)
Learning to use the various ways of doing things in Eclipse I guess. You can actually set a conditional breakpoint (BP) on a Lombok generated method. Using the Outline view, you can right-click the method to Toggle Method Breakpoint. Then when you hit the BP, you can use the debugging Variables view to see what the generated method named the parameters (usually the same as the field name) and finally, use the Breakpoints view to right-click the BP and select Breakpoint Properties... to add a condition. Nice.
UPDATE 4 (Aug 16 '13)
Netbeans doesn't like it when you update your Lombok dependencies in your Maven pom. The project still compiles, but files get flagged for having compilation errors because it can't see the methods Lombok is creating. Clearing the Netbeans cache resolves the issue. Not sure if there is a "Clean Project" option like there is in Eclipse. Minor issue, but wanted to make it known.
UPDATE 5 (Jan 17 '14)
Lombok doesn't always play nice with Groovy, or at least the groovy-eclipse-compiler. You might have to downgrade your version of the compiler.
Maven Groovy and Java + Lombok
UPDATE 6 (Jun 26 '14)
A word of warning. Lombok is slightly addictive and if you work on a project where you can't use it for some reason, it will annoy the piss out of you. You may be better off just never using it at all.
UPDATE 7 (Jul 23 '14)
This is a bit of an interesting update because it directly addresses the safety of adopting Lombok that the OP asked about.
As of v1.14, the #Delegate annotation has been demoted to an Experimental status. The details are documented on their site (Lombok Delegate Docs).
The thing is, if you were using this feature, your backout options are limited. I see the options as:
Manually remove #Delegate annotations and generate/handcode the delegate code. This is a little harder if you were using attributes within the annotation.
Delombok the files that have the #Delegate annotation and maybe add back in the annotations that you do want.
Never update Lombok or maintain a fork (or live with using experiential features).
Delombok your entire project and stop using Lombok.
As far as I can tell, Delombok doesn't have an option to remove a subset of annotations; it's all or nothing at least for the context of a single file. I opened a ticket to request this feature with Delombok flags, but I wouldn't expect that in the near future.
UPDATE 8 (Oct 20 '14)
If it's an option for you, Groovy offers most of the same benefits of Lombok, plus a boat load of other features, including #Delegate. If you think you'll have a hard time selling the idea to the powers that be, take a look at the #CompileStatic or #TypeChecked annotation to see if that can help your cause. In fact, the primary focus of the Groovy 2.0 release was static safety.
UPDATE 9 (Sep 1 '15)
Lombok is still being actively maintained and enhanced, which bodes well to the safety level of adoption. The #Builder annotations is one of my favorite new features.
UPDATE 10 (Nov 17 '15)
This may not seem directly related to the OP's question, but worth sharing. If you're looking for tools to help you reduce the amount of boilerplate code you write, you can also check out Google Auto - in particular AutoValue. If you look at their slide deck, the list Lombok as a possible solution to the problem they are trying to solve. The cons they list for Lombok are:
The inserted code is invisible (you can't "see" the the methods it generates) [ed note - actually you can, but it just requires a decompiler]
The compiler hacks are non-standard and fragile
"In our view, your code is no longer really Java"
I'm not sure how much I agree with their evaluation. And given the cons of AutoValue that are documented in the slides, I'll be sticking with Lombok (if Groovy is not an option).
UPDATE 11 (Feb 8 '16)
I found out Spring Roo has some similar annotations. I was a little surprised to find out Roo is still a thing and finding documentation for the annotations is a bit rough. Removal also doesn't look as easy as de-lombok. Lombok seems like the safer choice.
UPDATE 12 (Feb 17 '16)
While trying to come up with justifications for why it's safe to bring in Lombok for the project I'm currently working on, I found a piece of gold that was added with v1.14 - The Configuration System! This is means you can configure a project to dis-allow certain features that your team deems unsafe or undesirable. Better yet, it can also create directory specific config with different settings. This is AWESOME.
UPDATE 13 (Oct 4 '16)
If this kind of thing matters to you, Oliver Gierke felt it was safe to add Lombok to Spring Data Rest.
UPDATE 14 (Sep 26 '17)
As pointed out by #gavenkoa in the comments on the OPs question, JDK9 compiler support isn't yet available (Issue #985). It also sounds like it's not going to be an easy fix for the Lombok team to get around.
UPDATE 15 (Mar 26 '18)
The Lombok changelog indicates as of v1.16.20 "Compiling lombok on JDK1.9 is now possible" even though #985 is still open.
Changes to accommodate JDK9, however, necessitated some breaking changes; all isolated to changes in config defaults. It's a little concerning that they introduced breaking changes, but the version only bumped the "Incremental" version number (going from v1.16.18 to v1.16.20). Since this post was about the safety, if you had a yarn/npm like build system that automatically upgraded to the latest incremental version, you might be in for a rude awakening.
UPDATE 16 (Jan 9 '19)
It seems the JDK9 issues have been resolved and Lombok works with JDK10, and even JDK11 as far as I can tell.
One thing I noticed though that was concerning from a safety aspect is the fact that the change log going from v1.18.2 to v1.18.4 lists two items as BREAKING CHANGE!? I'm not sure how a breaking change happens in a semver "patch" update. Could be an issue if you use a tool that auto-updates patch versions.
UPDATE 17 (Mar 17 '21)
There is some drama unfolding between the Lombok developers and an OpenJDK developer around JDK 16. The JDK developers argue that Lombok is taking advantage of unpublished JDK internals via loopholes the JDK team would like to close, but have intentionally left open for various reasons.
They have stated their concern (about the safety of Lombok) as such:
All access to internals will remain available as before, provided that
the client application explicitly allows it, acknowledging that it is
knowingly taking on any maintenance (or security) issue this might
entail.
While Lombok might think they're deceiving OpenJDK, all they're doing
is announcing that it is their intention to deceive their own users.
There may come a day soon where Lombok will not be able to find any more creative solutions around the JDK's security restrictions. Even if they do, the safety of using Lombok in your project may be in question.
UPDATE 18 (May 11 '22)
A recent comment asked for a summary, so I put that at the top.
The short answer is it's perfectly safe to use and I'd highly recommend using it if we're writing Java code.
Given that support for JDK 17 has been out for awhile and was released less than a month after the JDK was officially released, the safety of Lombok sticking around is high. And you can always de-lombok if you need to.
As a consultant, I get to see how a lot of different companies write code. Every client I've had for the past 5 years has used Lombok. These have all been Fortune 1000 companies. It speeds development and makes it less error prone.
That said, you still need to keep up on the latest features of the JDK. Consider using the Java record keyword to make your objects immutable instead of some Lombok feature. Use Lombok where it makes sense. Use the Lombok config options to prevent usage of it in ways you don't agree with.
So unless something major happens, this will probably be my last update to this answer. Thanks for all the votes. I'm glad it helps.
It sounds like you've already decided that Project Lombok gives you significant technical advantages for your proposed new project. (To be clear from the start, I have no particular views on Project Lombok, one way or the other.)
Before you use Project Lombok (or any other game-changing technology) in some project (open source or other wise), you need to make sure that the project stake holders agree to this. This includes the developers, and any important users (e.g. formal or informal sponsors).
You mention these potential issues:
Flamewars will erupt in the ##Java Freenode channel when I mention it,
Easy. Ignore / don't participate in the flamewars, or simply refrain from mentioning Lombok.
providing code snippets will confuse possible helpers,
If the project strategy is to use Lombok, then the possible helpers will need to get used to it.
people will complain about missing JavaDoc,
That is their problem. Nobody in their right mind tries to rigidly apply their organization's source code / documentation rules to third-party open source software. The project team should be free to set project source code / documentation standards that are appropriate to the technology being used.
(FOLLOWUP - The Lombok developers recognize that not generating javadoc comments for synthesized getter and setter methods is an issue. If this is a major problem for your project(s), then one alternative is to create and submit a Lombok patch to address this.)
and future commiters might just remove it all anyway.
That's not on! If the agreed project strategy is to use Lombok, then commiters who gratuitously de-Lombok the code should be chastised, and if necessary have their commit rights withdrawn.
Of course, this assumes that you've got buy-in from the stakeholders ... including the developers. And it assumes that you are prepared to argue your cause, and appropriately handle the inevitable dissenting voices.
Go ahead and use Lombok, you can if necessary "delombok" your code afterwards http://projectlombok.org/features/delombok.html
Personally (and therefore subjectively) I've found that using Lombok makes my code more expressive about what I'm trying to achieve when compared to IDE/own implementations of intricate methods such as hashcode & equals.
When using
#EqualsAndHashCode(callSuper = false, of = { "field1", "field2", "field3" })
it's much easier to keep Equals & HashCode consistent and keep track of which fields are evaluated, than any IDE/own implementation. This is especially true when you're still adding / removing fields regularly.
The same goes for the #ToString annotation and its parameters which clearly communicate the desired behavior regarding included / excluded fields, usage of getters or field access and wether or not to call super.toString().
And again by annotating an entire class with #Getter or #Setter(AccessLevel.NONE) (and optionally overriding any divergent methods) it's immediately clear what methods will be available for the fields.
The benefits go on and on..
In my mind it's not about reducing code, but about clearly communicating what you desire to achieve, rather than having to figure it out from Javadoc or implementations. The reduced code just makes it easier to spot any divergent-method implementations.
I read some opinions about the Lombok and actually I'm using it in some projects.
Well, in the first contact with Lombok I had a bad impression. After some weeks, I started to like it. But after some months I figure out a lot of tiny problems using it. So, my final impression about Lombok is not so positive.
My reasons to think in this way:
IDE plugin dependency. The IDE support for Lombok is through plugins. Even working good in most part of the time, you are always a hostage from this plugins to be maintained in the future releases of the IDEs and even the language version (Java 10+ will accelerate the development of the language). For example, I tried to update from Intellij IDEA 2017.3 to 2018.1 and I couldn't do that because there was some problem on the actual lombok plugin version and I needed to wait the plugin be updated... This also is a problem if you would like to use a more alternative IDE that don't have any Lombok plugin support.
'Find usages' problem.. Using Lombok you don't see the generated getter, setter, constructor, builder methods and etc. So, if you are planning to find out where these methods are being used in your project by your IDE, you can't do this only looking for the class that owns this hidden methods.
So easy that the developers don't care to break the encapsulation. I know that it's not really a problem from Lombok. But I saw a bigger tendency from the developers to not control anymore what methods needs to be visible or not. So, many times they are just copying and pasting #Getter #Setter #Builder #AllArgsConstructor #NoArgsConstructor annotations block without thinking what methods the class really need to be exposed.
Builder Obssession ©. I invented this name (get off, Martin Fowler). Jokes apart, a Builder is so easy to create that even when a class have only two parameters the developers prefer to use #Builder instead of constructor or a static constructor method. Sometimes they even try to create a Builder inside the lombok Builder, creating weird situations like MyClass.builder().name("Name").build().create().
Barriers when refactoring. If you are using, for example, a #AllArgsConstructor and need to add one more parameter on the constructor, the IDE can't help you to add this extra parameter in all places (mostly, tests) that are instantiating the class.
Mixing Lombok with concrete methods. You can't use Lombok in all scenarios to create a getter/setter/etc. So, you will see these two approaches mixed in your code. You get used to this after some time, but feels like a hack on the language.
Like another answer said, if you are angry about the Java verbosity and use Lombok to deal with it, try Kotlin.
Lombok is great, but...
Lombok breaks the rules of annotation processing, in that it doesn't generate new source files. This means it cant be used with another annotation processors if they expect the getters/setters or whatever else to exist.
Annotation processing runs in a series of rounds. In each round, each one gets a turn to run. If any new java files are found after the round is completed, another round begins. In this way, the order of annotation processors doesn't matter if they only generate new files. Since lombok doesn't generate any new files, no new rounds are started so some AP that relies on lombok code don't run as expected. This was a huge source of pain for me while using mapstruct, and delombok-ing isn't a useful option since it destroys your line numbers in logs.
I eventually hacked a build script to work with both lombok and mapstruct. But I want to drop lombok due to how hacky it is -- in this project at least. I use lombok all the time in other stuff.
Update to specifically mapstruct+lombok: the two libraries work out of the box with each other nowadays. The problem will still exist for other annotation processors though.
There are long-term maintenance risks as well. First, I'd recommend reading about how Lombok actually works, e.g. some answers from its developers here.
The official site also contains a list of downsides, including this quote from Reinier Zwitserloot:
It's a total hack. Using non-public API. Presumptuous casting (knowing
that an annotation processor running in javac will get an instance of
JavacAnnotationProcessor, which is the internal implementation of
AnnotationProcessor (an interface), which so happens to have a couple
of extra methods that are used to get at the live AST).
On eclipse, it's arguably worse (and yet more robust) - a java agent
is used to inject code into the eclipse grammar and parser class,
which is of course entirely non-public API and totally off limits.
If you could do what lombok does with standard API, I would have done
it that way, but you can't. Still, for what its worth, I developed the
eclipse plugin for eclipse v3.5 running on java 1.6, and without
making any changes it worked on eclipse v3.4 running on java 1.5 as
well, so it's not completely fragile.
As a summary, while Lombok may save you some development time, if there is a non-backwards compatible javac update (e.g. a vulnerability mitigation) Lombok might get you stuck with an old version of Java while the developers scramble to update their usage of those internal APIs. Whether this is a serious risk obviously depends on the project.
I know I'm late, but I can't resist the temptation: anybody liking Lombok should also have a look at Scala. Many good ideas that you find in Lombok are part of the Scala language.
On your question: it's definitely easier to get your developers trying Lombok than Scala. Give it a try and if they like it, try Scala.
Just as a disclaimer: I like Java, too!
I have used Lombok in almost all my projects for one year but unfortunately removed it. In the beginning it was a very clean way of development but setting up the development environment for new team members is not very easy and straightforward. When it became a headache I just removed it. But it is a good work and needs some more simplicity to setting up.
My take on Lombok is that it merely provides shortcuts for writing bolilerplate Java code.
When it comes to using shortcuts for writing bolilerplate Java code, I would rely on such features provided by IDE -- like in Eclipse, we can go to menu Source > Generate Getters and Setters for generating getters and setters.
I would not rely on a library like Lombok for this:
It pollutes your code with an indirection layer of alternative syntax (read #Getter, #Setter, etc. annotations). Rather than learning an alternative syntax for Java, I would switch to any other language that natively provides Lombok like syntax.
Lombok requires the use of a Lombok supported IDE to work with your code. This dependency introduces a considerable risk for any non-trivial project. Does the open source Lombok project have enough resources to keep providing support for different versions of a wide range of Java IDE's available?
Does the open source Lombok project have enough resources to keep providing support for newer versions of Java that will be coming in future?
I also feel nervous that Lombok may introduce compatibility issues with widely used frameworks/libraries (like Spring, Hibernate, Jackson, JUnit, Mockito) that work with your byte code at runtime.
All in all I would not prefer to "spice up" my Java with Lombok.
When I showed the project to my team the enthusiasm was high, so I think you should not be afraid of team response.
As far as ROI, it is a snap to integrate, and requires no code change in its basic form. (just adding a single annotation to your class)
And last, if you change your mind, you can run the unlombok, or let your IDE create these setters, getters, and ctors, (which I think no one will ask for once they see how clear your pojo becomes)
Wanted to use lombok's #ToString but soon faced random compile errors on project rebuild in Intellij IDEA. Had to hit compile several times before incremental compilation could complete with success.
Tried both lombok 1.12.2 and 0.9.3 with Intellij IDEA 12.1.6 and 13.0 without any lombok plugin under jdk 1.6.0_39 and 1.6.0_45.
Had to manually copy generated methods from delomboked source and put lombok on hold until better times.
Update
The problem happens only with parallel compile enabled.
Filed an issue:
https://github.com/rzwitserloot/lombok/issues/648
Update
mplushnikov commented on 30 Jan 2016:
Newer version of Intellij
doesn't have such issues anymore. I think it can be closed here.
Update
I would highly recommend to switch from Java+Lombok to Kotlin if possible.
As it has resolved from the ground up all Java issues that Lombok tries to work around.
I have encountered a problem with Lombok and Jackson CSV, when I marshalized my object (java bean) to a CSV file, columns where duplicated, then I removed Lombok's #Data annotation and marshalizing worked fine.
I haven't tried using Lombok yet - it is/was next on my list, but it sounds as if Java 8 has caused significant problems for it, and remedial work was still in progress as of a week ago. My source for that is https://code.google.com/p/projectlombok/issues/detail?id=451 .

Categories