DEV Community

Discussion on: your ways of writting lots of duplicate / similar code

Collapse
 
idanarye profile image
Idan Arye

This is a controversial opinion (and sadly - I'm not being ironic here...) but I do believe that developers are allowed to add their own layers of abstraction. Knowing where to put that layer, of course, is the main problem - but as a rule of thumb you usually want a single source of truth - or as close to "single" as you can reasonably manage.

Since the Java classes will be the most painful to auto-generate, I'd make them that source. You want to add annotations on their fields:

public class Person {
    @Caption("First Name")
    private String firstName;

    @Caption("Last Name")
    private String lastName;

    @Caption("Phone")
    @InputPattern("###-###-####")
    private String phone;

    @Caption("Company")
    @Autocomplete
    private Company company

    // ...
}

Of course - these annotations are just examples - you'll need to figure the ones you need to customize your fields.

You'll then use reflection to read these annotations and generate the SQL queries, HTML templates, TypeScript interfaces and everything else you can auto-generate from them.

The most important thing is to know where to stop. You can't auto-generate everything, and trying to do so will lead to too complicated annotations and too complex code for processing them.