我觉得此方法签名太长。有没有更明智或更优雅的方式来重写此内容?
private Email createMail(long actualFileSize, String from, String recipient, String title,
String emailContent, MultipartFile attachment,
File file) {
Email mail = null;
if (actualFileSize <= Long.parseLong(emailFileSizeLimit)) {
mail = new Email(from, recipient, title,emailContent, null, file);
} else mail = new Email(from, recipient, title,emailContent, null, null);
return mail;
}
答案 0 :(得分:0)
tl; dr
if (actualFileSize <= Long.parseLong(emailFileSizeLimit)) {
file = null;
}
return new Email(from, recipient, title,emailContent, null, file);
1)重构。 如果您认为参数太多,可以将该方法划分为较小的,易于管理的方法。
if (actualFileSize <= Long.parseLong(emailFileSizeLimit)) {
file = null;
}
createMail(from, recipient, title,emailContent, null, file);
******
private Email createMail(long actualFileSize, String from, String recipient, String
title, String emailContent, MultipartFile attachment, File file) {
return new Email(from, recipient, title,emailContent, null, file);
}
2)DTO。 您可以在dto中提供参数,并将其作为请求/响应传递到整个链中,并在需要时使用需要的元素。当需要创建时,可以添加更多属性。您可以通过设置员来提供它们,并在需要时通过
3)生成器。 您在类中完成了逻辑,操作完成后将返回自身。您可以通过在同一类上调用不同的操作并返回结果来执行下一操作。
Mail mail = mailBuilder.addName(name).add(stuff).compile(); // will call constructor inside
4)工厂
具有包含所有方法的工厂,并让它决定调用什么方法。它可以是静态的或托管的
factory.createBasicMail(name);
factory.createFileMail(name, file);
ps:为了您的心理健康,请使用龙目岛
答案 1 :(得分:-1)
这似乎很适合Builder pattern,在这里您需要以精心的方式构造一个新对象:
public class EmailBuilder {
private Email mail;
private String from;
private String recipient;
// other properties
public EmailBuilder withFrom(String from) {
this.from = from;
return this;
}
public EmailBuilder withRecipient(String recipient) {
this.recipient = recipient;
return this;
}
public Email send() {
mail = new Email(from, recipient, title,emailContent, null, file);
return mail;
}
}
用法
Email mail = new EmailBuilder()
.withFrom("John Doe")
.withRecipient("Mary Doe")
.with...
.send();