TheClassic
TheClassic

Reputation: 1044

Avoiding method with multiple identical typed parameters

I want to avoid passing multiple identically typed parameters into my method to avoid the potential to misorder the parameters. For example:

void createBook(String publisher, String illustrator, String author)

My instinct is to create 3 new types extending String, so that I can have parameters Publisher, Illustrator, and Author, which can be constructed and used as Strings. However, this isn't possible since String is final.

How can I achieve the Clean Code that I desire in the simplest manner? It seems like overkill to have to implement a base class that provides a constructor and .toString for each of these.

Upvotes: 2

Views: 186

Answers (2)

Onur A.
Onur A.

Reputation: 3017

Named parameters are not supported in Java but you can either use a little trick or make a builder-type class like below.

1-Little trick;

String publisher; String illustrator; String author;
createBook(publisher="...", illustrator="...", author="...");

2-Builder class;

Based on your method name I named class as Book

public class Book {
  public static class Builder {
    public Book build() {
      return new Book(this);
    }

    public Builder setPublisher(String publisher) {
      this.publisher = publisher;
      return this;
    }

    public Builder setIllustrator(String illustrator) {
      this. illustrator = illustrator;
      return this;
    }

    public Builder setAuthor(String author) {
      this.author = author;
      return this;
    }

     private String publisher;
     private String illustrator;
     private String author;
  }

  public static Builder builder() {
      return new Builder();
  }

  private Book(Builder builder) {
    publisher = builder.publisher;
    illustrator = builder.illustrator;
    author = builder.author;
  }

  private String publisher;
  private String illustrator;
  private String author;
}

Then you can use it like this

Book book = Book.builder()
    .setPublisher("JohnThePublisher")
    .setIllustrator("JohnTheIllustrator")
    .setAuthor("JohnTheAuthor")
    .build();

Upvotes: 1

davidxxx
davidxxx

Reputation: 131346

Create a Book class and make the method accept an instance of Book :

void createBook(Book book)

To avoid the same problem of parameters with the same type in the Book constructor, you could use a builder or a setter approach.

Setter approach :

Book book = new Book();
book.setPublisher(...);
book.setIllustrator(...);
book.setAuthor(...);

Builder approach :

Book book = new BookBuilder().withPublisher(...)
                             .withIllustrator(...)
                             .withAuthor(...)
                             .build();

The Builder approach is more verbose to achieve but note that it also provides clearer client code and make completely sense if the object is designed to be immutable. It makes it always consistent and thread safe.

Upvotes: 5

Related Questions