Create builder with mandatory fields.

106 views
Skip to first unread message

ololoshka

unread,
Dec 6, 2021, 4:36:16 PM12/6/21
to Project Lombok
Create builder with mandatory fields. Without builder you can make
certain fields be mandatory initiated using constructor only. 
Current builder doesn't provide initialization validation but it can be created.
Here I attach ugly first solution that came on my mind:
In this example you are obliged to initialize user name and user age when
you build it. Otherwise you just can't call builder method. 
I believe that such builder will increase code quality. 
Thanks and best regards. 

Jan Materne

unread,
Dec 7, 2021, 1:28:49 AM12/7/21
to project...@googlegroups.com
Wouldnt it be better to combine builder with javax.validation annotations? And I havent tested if Lombok supports that already ... maybe via config file and copyableannotations ...

Jan

--
You received this message because you are subscribed to the Google Groups "Project Lombok" group.
To unsubscribe from this group and stop receiving emails from it, send an email to project-lombo...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/project-lombok/9773c0b5-0e56-443e-9b91-072572e4db5fn%40googlegroups.com.

ololoshka

unread,
Dec 7, 2021, 4:35:52 AM12/7/21
to Project Lombok
Javax annotation is trash in general. But even lombok would support it they wont be compile time safe. 

вторник, 7 декабря 2021 г. в 06:28:49 UTC, Jan:

Michael Berry

unread,
Dec 7, 2021, 4:37:57 AM12/7/21
to project...@googlegroups.com
This has come up quite a bit in the past, there's a good wiki page around it: https://github.com/projectlombok/lombok/wiki/FEATURE-IDEA:-%22Mandatory%22-fields-with-@Builder



--
Thanks,

Michael

Michael Ernst

unread,
Dec 7, 2021, 8:33:40 AM12/7/21
to project...@googlegroups.com
A solution to this problem exists, in the form of a compiler plugin that is compatible with Lombok and that issues a compile-time error if a builder client might fail to set a mandatory field.

The tool is called the Called Methods Checker.  It is distributed as part of the Checker Framework and it has built-in support for Lombok builders.  It does not require you to change your coding style and it does not change the code that Lombok emits.  It does require some programmer-written annotations -- in experiments, about one per 1600 lines of non-comment, non-blank Java code.  The plugin is sound:  if it issues no errors, then your code never fails to supply all mandatory fields.  Like any static analysis tool, it can issue false positive warnings that you suppress with a @SuppressWarnings annotation.  It works best together with the io.freefair.lombok Gradle plugin.

Full disclosure:  I am not the author of the Called Methods Checker, but I did contribute to it.  Please give it a try and submit a bug report if you have any problems.

-Mike

Reply all
Reply to author
Forward
0 new messages