I am working on an online Library project.
I have created a method name giveBook
that contains more than three parameters.
public void givebook(String bookName, int bookId, String bookAuthor, int bookDayPrice, int bookPrice, String bookTopic){
int idx = this.booksNo - this.availabelbooksNo-1;
this.booksName[idx] = bookName;
this.booksId[idx] = bookId;
this.booksTopic[idx]= bookTopic;
this.booksAuthor[idx] = bookAuthor;
this.booksDayPrice[idx] = bookDayPrice;
this.booksPrice[idx]= bookPrice;
}
It's very confusing for me to work with methods that contain more than three parameters.
Is there an easier way to work with methods that contain more than three parameters
CodePudding user response:
It's not clear what makes it confusing for you to work with such methods but a common problem is that it's quite hard to read, especially if the parameters are of the same type (like int
).
You could Introduce Parameter Object to group related parameters.
The Builder pattern may also help in making the parameters explicit when constructing the object.
Furthermore, you can often decrease the number of arguments by splitting a larger method into a few smaller methods, each one of them focused only on a subset of functionality.
CodePudding user response:
You can insert a newline after each comma :
public void givebook(String bookName,
int bookId,
String bookAuthor,
int bookDayPrice,
int bookPrice,
String bookTopic) {
int idx = this.booksNo - this.availabelbooksNo-1;
this.booksName[idx] = bookName;
this.booksId[idx] = bookId;
this.booksTopic[idx]= bookTopic;
this.booksAuthor[idx] = bookAuthor;
this.booksDayPrice[idx] = bookDayPrice;
this.booksPrice[idx]= bookPrice;
}
Static analyzers such as sonarqube advise using no more than 7 parameters. They suggest that if you need too many parameters, it's a sign that you need to create a class to aggregate the parameters or that your method scope is too broad.
CodePudding user response:
you can use the setters to change the variables of your class, it will take you a few lines but will suit your request Like :
public void setBookName(String bookName){
this.booksName[idx] = bookName;
}