druid icon indicating copy to clipboard operation
druid copied to clipboard

[DISCUSS] Code generation for commonly implemented basic methods

Open jihoonson opened this issue 7 years ago • 23 comments

I recently found a bug in ArrayOfDoublesSketchAggregatorFactory .equals() (fixed in https://github.com/apache/incubator-druid/pull/8326) which made me think that we may need a better way to implement and maintain them. equals(), hashCode() and toString() are very commonly used functions and not easy to catch a mistake if ppl write them manually. To avoid mistakes, I usually use the code generation function of Intellij. This function is good but is not enough to automatically maintain those implementations on code changes.

The Lombok is a library to address this kind of use case. It can automatically generate codes of equals(), hashCode(), and toString() at compile time so that we can expect the implementations are always up to date. Also, they are programmatically generated and it's safer than human codes.

I also find the Lombok library useful when the builder pattern is useful. It provides an annotation called @Builder which automatically generates a builder implementation for a class. This could be very useful to maintain the test codes for user-facing configuration classes. For example, I have added a couple of new configurations to ParallelIndexTuningConfig which also required to fix all places calling the constructor of the class. With the builder, I think we can reduce the required changes which could reduce the PR size.

The downside of using a library such as Lombok is the build time might be longer since it needs to generate more source codes. But I still think it would be worth to take it.

If we go with this way, I think we can start with equals(), hashCode() and toString() methods and gradually change those implementations with Lombok annotations (like 10 classes in each PR). Probably we need unit tests as well if those methods of a class only take account into only a subset of variables defined in that class.

Welcome any thoughts.

jihoonson avatar Aug 16 '19 22:08 jihoonson

I've also seen instances where new fields are added to classes but one or more of equals(), hashCode(), or toString() were not updated to account for the new field. Adding tests to catch these kinds of errors is not very productive, so using lombok to automatically generate methods like these is helpful. I also find lombok useful to generating getter/setters for DTOs, for similar reasons.

The lombok builder generator is very useful and will make the code more readable in places like this:

           new IndexTuningConfig(
                null,
                10000,
                10,
                null,
                null,
                null,
                null,
                null,
                null,
                indexSpec,
                null,
                3,
                false,
                null,
                null,
                null,
                null,
                null,
                null,
                null
            )

It's also possible to easily ignore the lombok-generated methods from code coverage, making the code coverage reports more useful.

Some possible drawbacks of using lombok:

  • Slower IDE performance (since it has to delombok the code to index it)
  • "Missing" code for IDEs/editors without lombok plugins (although most of the popular IDEs, like Eclipse and IntelliJ, do have support)
  • Debugging/callstacks do not match the source code

Overall, I think the advantages of lombok outweigh its drawbacks. If we do start using lombok, however, I think we should add its experimental features to the forbidden apis list.

ccaominh avatar Aug 16 '19 22:08 ccaominh

This seems an interesting idea, but we have to be very careful when doing and reviewing this to make sure we don't lose any purposeful omissions or customizations done for performance reasons. I'm thinking of things like this where a large or expensive to work with field is left out of all of those things on purpose. It might be very hard spot all of these if they are not documented, so this is potentially risky in that regard.

clintropolis avatar Aug 16 '19 22:08 clintropolis

@ccaominh @clintropolis thank you for the comments.

I'm thinking of things like this where a large or expensive to work with field is left out of all of those things on purpose.

This is a very good point. I guess this could be one of the reasons why we should change only a few classes per PR.

jihoonson avatar Aug 16 '19 22:08 jihoonson

Another example, where standard equals is not used for performance reasons is here, there might be more. So perhaps Lombok can be used or not on a case by case basis.

surekhasaharan avatar Aug 16 '19 22:08 surekhasaharan

You can control what fields will be only considered in equals() and hashCode() (https://projectlombok.org/features/EqualsAndHashCode). I think you can do the same thing for toString().

jihoonson avatar Aug 16 '19 22:08 jihoonson

IMHO, That is too magical. When I look at the source code, I want to know what is actually running ... e.g. if there is a stack trace from production server with line numbers for files inside druid source code etc, I would look at the source code that is checked in whereas actual code running is the rewrite from Lambok. That would add another variable to debugging equation for me to wonder is it possible that code generated by Lambok is buggy in some way. also, this is confusing for debuggers.

When I am browsing through the source code and there is a line say... xx.equals(yy) and I tell the IDE to goto the place where equals(..) is defined, it would take me to wrong place most likely. (Same goes for other things generated e.g. getters/setters etc)

OTOH It might be good to have something that can catch such issues and fail the build so that we can go fix it by writing/ide-generating that code manually.

himanshug avatar Aug 16 '19 23:08 himanshug

Some (Java) alternatives to lombok to generate boilerplate with less magic are AutoValue and Immutables.

ccaominh avatar Aug 17 '19 00:08 ccaominh

Prev. discussion about AutoValue: #4125

leventov avatar Aug 18 '19 10:08 leventov

I read through https://github.com/google/auto/blob/master/value/userguide/index.md and AutoValue does sound relatively better considering it generates new classes. there would be some bunch of annotations needed to make json serde of those objects work,and also probably you need to define constructor with json annotations in the abstract class . anyways, my first impression is that it could be made to work. there is a warning mentioned, "Be careful that you don't accidentally pass parameters to the generated constructor in the wrong order. You must ensure that your tests are sufficient to catch any field ordering problem." tells that you still need to carefully unit test or else someone just changing ordering of getters in abstract class could introduce silent bugs.

himanshug avatar Aug 19 '19 23:08 himanshug

I would vote +2 for Lombok. People who haven't used Lombok usually assume that it's too much magic and that it makes it hard to debug. In my experience this has not been the case. Lombok makes it easy to delombok methods if you want to debug that piece through a single click in the IDE, and the methods are usually so simple and boilerplate that there really should be no bugs in it. I would trust automatically generated code that is tested by tons of people using it over manually added code by a developer who might miss a field in the equals or hashcode method.

Lombok also does take you to the right place when you step through the code (to the relevant Lombok annotation).

In fact, I find that Lombok makes debugging easier by reducing boilerplate in code so you don't have to worry about it and makes the code much easier to understand and maintain.

jnaous avatar Oct 25 '19 18:10 jnaous

I believe the issue with the debugging here is not the debugging with IDE but the debugging with your brain based on the stack trace. It will be still not good enough if we want to delombok first to see the real line number. I also believe the benefits @jnaous mentioned can be applied to other code generation tools in general, not only for lombok. I didn't have a time to look at AutoValue and Immutables. Will take a look soon.

jihoonson avatar Oct 25 '19 20:10 jihoonson

Adding tests to catch these kinds of errors is not very productive

I've run in to this problem as well - EqualsVerifier has been pretty effective in catching these types of errors and takes almost no time to write - https://jqno.nl/equalsverifier/

@Test
public void equalsContract() {
    EqualsVerifier.forClass(Foo.class).verify();
}

suneet-s avatar Oct 25 '19 20:10 suneet-s

Another bug that could have been prevented by auto-generating equals/hashCode/toString: https://github.com/apache/incubator-druid/issues/8866

ccaominh avatar Nov 15 '19 01:11 ccaominh

@jihoon, I'm curious if you've had experience trying out something like Lombok. I have never heard complaints about difficulty debugging from the people who have worked with it. @suneet @chi, please chime in if you have heard otherwise.

On Thu, Nov 14, 2019, 5:26 PM Chi Cao Minh [email protected] wrote:

Another bug that could have been prevented by auto-generating equals/hashCode/toString: #8866 https://github.com/apache/incubator-druid/issues/8866

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/apache/incubator-druid/issues/8328?email_source=notifications&email_token=AAPSYCSSCF5J7TC27B5YZ4DQTX3D3A5CNFSM4IMNGLOKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEED6UYY#issuecomment-554166883, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAPSYCWG4LMXTHDKRKVUVY3QTX3D3ANCNFSM4IMNGLOA .

jnaous avatar Nov 17 '19 03:11 jnaous

I used lombok in my previous company. I had a pretty good experience with that because I was involved in a medium-sized project and the code generation was pretty convenient and useful for that size of project. However, it was still sometimes annoying since it makes the IDE slower and I had to delombok for debugging. I would think this will be more emphasized with a big project like Druid.

I still didn't have time to check other libraries. @jnaous what is your rationale for using lombok other than others? What is the benefit we can get with lombok particularly?

jihoonson avatar Nov 17 '19 05:11 jihoonson

I like Lombok vs others because it hides boilerplate and reduces the amount of code to maintain. Generally, if you assume that the boilerplate generated by Lombok is correct (99.9% of cases) then it reduces the cognitive load needed to debug issues and allows you to more quickly find the actual sources of issues. It also reduces the effort of updating code when you add a field.

That said, I would only advocate it for straightforward objects (like immutable data objects used for serialization) and for real boilerplate, nothing too fancy.

On Sat, Nov 16, 2019 at 9:27 PM Jihoon Son [email protected] wrote:

I used lombok in my previous company. I had a pretty good experience with that because I was involved in a medium-sized project and the code generation was pretty convenient and useful for that size of project. However, it was still sometimes annoying since it makes the IDE slower and I had to delombok for debugging. I would think this will be more emphasized with a big project like Druid.

I still didn't have time to check other libraries. @jnaous https://github.com/jnaous what is your rationale for using lombok other than others? What is the benefit we can get with lombok particularly?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/apache/incubator-druid/issues/8328?email_source=notifications&email_token=AAPSYCW4RYNEYS32LLBD55TQUDI57A5CNFSM4IMNGLOKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEEICQMI#issuecomment-554706993, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAPSYCUPXHXYKFK2C25FM4DQUDI57ANCNFSM4IMNGLOA .

jnaous avatar Nov 17 '19 19:11 jnaous

I've never had to debug code generated by lombok, because it's always used for very simple code - hashCode&equals, trivial getters & setters, Constructors and Builders. And in my experience, I haven't seen the IDE slow down significantly because annotation processing was enabled for lombok.

There are some fancy features in lombok - like SneakyThrows that I think we should not use except within the test folder.

suneet-s avatar Nov 18 '19 16:11 suneet-s

This issue has been marked as stale due to 280 days of inactivity. It will be closed in 4 weeks if no further activity occurs. If this issue is still relevant, please simply write any comment. Even if closed, you can still revive the issue at any time or discuss it on the [email protected] list. Thank you for your contributions.

stale[bot] avatar Aug 29 '20 16:08 stale[bot]

Thanks for the reminder stalebot!

Does anyone want to try out using lombok so we don't need to keep adding EqualsVerifier tests for every class? I'm happy to be the first guinea pig in my next PR. We'd have to update the dev environment setup docs, but I think lombok would make the codebase nicer to read because you'd only have to read code that's interesting.

suneet-s avatar Aug 31 '20 16:08 suneet-s

This issue is no longer marked as stale.

stale[bot] avatar Aug 31 '20 16:08 stale[bot]