2 回答

TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
if (actualFileSize <= Long.parseLong(emailFileSizeLimit)) {
file = null;
}
return new Email(from, recipient, title,emailContent, null, file);
1)重構(gòu)。如果您認(rèn)為參數(shù)過(guò)多,您可以將該方法分成更小的、可管理的方法。
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 中提供參數(shù)并將其作為請(qǐng)求/響應(yīng)傳遞到整個(gè)鏈中,在需要時(shí)使用您需要的元素。當(dāng)您需要?jiǎng)?chuàng)建時(shí),您可以添加更多屬性。您通過(guò) setter 提供它們并在需要時(shí)傳遞
3) 建造者。您在類中完成了在完成操作后返回自身的邏輯。您可以通過(guò)對(duì)同一類調(diào)用不同的操作并返回結(jié)果來(lái)執(zhí)行下一個(gè)操作。
Mail mail = mailBuilder.addName(name).add(stuff).compile(); // will call constructor inside
4) 工廠
讓工廠包含所有方法并讓它決定調(diào)用什么方法。它可以是靜態(tài)的或托管的
factory.createBasicMail(name);
factory.createFileMail(name, file);
ps:為了您的心理健康,請(qǐng)使用 Lombok

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
這似乎很適合Builder 模式,在那里您需要以精心設(shè)計(jì)的方式構(gòu)造一個(gè)新對(duì)象:
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();
添加回答
舉報(bào)