How to bypass non-existent default arguments in Java / How to use method overloading with may fields?

216 views Asked by At

I know there are no default arguments for methods in Java and this can be remedied by using method overloading like in this question.

However, I have a class with around twenty fields and I should be able to create that class with any combination of the fields:

import java.util.Date;

public class RequestBodyGenerator {
    private Integer length;
    private String author;
    private String title;
    private Long descriptionId;
    private Long productId;
    private Integer yearMin;
    private Integer yearMax;
    private Long publisherId;
    private String publisher;
    private String ean13;
    private String imageFilter;
    private String image;
    private Date createdFrom;
    private Date createdFromTime;
    private Date createdTo;
    private Date createdToTime;
    private Date shopSellFrom;
    private Date shopSellFromTime;
    private Date shopSellTo;
    private Date shopSellToTime;
    private Integer minPrice;
    private Integer maxPrice;
    private String moreInfo;
    private String storagePlace;
    private String creator;
    private String orderBy;
    private Boolean __checkbox_needImage;

}

This class shall create the body of a http request, so whichever fields the constructor gets will have a value in the request body, the others should be an empty string. It is possible that there is only one field, lets say I give in a "title" field, all the other fields are empty, but it may happen that I will give value to 10+ fields.

My problem could be solved by using an empty string as a default argument, but this is not working in Java. If I wrote a constructor for each possible case I would end up writing hundreds of them, so this is obviously not the way to go.

1

There are 1 answers

0
handris On

Using the build pattern, first suggested by khelwood, was the solution to my problem.