我需要你的建议。就软件工程(可读性、可用性)而言,哪种方式最好
我有对象人
public class Person {
private String name;
private String surname;
public Person(String name, String surname) {
super();
this.name = name;
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
我有方法savePerson。
第一种方法是在初始化对象之前将请求参数设置为变量。
public void handle(Map<String, Object> map, HttpServletRequest request) throws Exception {
String name = request.getParameter("name");
String surname = request.getParameter("surname");
Person person = new Person(name, surname);
personService.savePerson(person);
}
第二种方法是设置请求参数,将它们设置为构造函数参数。
public void handle(Map<String, Object> map, HttpServletRequest request) throws Exception {
Person person = new Person(request.getParameter("name"), request.getParameter("surname"));
personService.savePerson(person);
}
最佳答案
您必须考虑到编译器将您的操作转换为某种经过稍微优化的二进制版本。 您的第二个版本可读性较差,但只有一行代码。 编译器会为你做,所以你可以根据你的写作风格选择你的版本。 如果你要和其他人分享你的代码,第一种方法可能是最好的,因为它更简单,而且在执行效率相同的场景下,它可以成为你的判别式。
关于java - 将请求参数设置为对象的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45582989/