有哪些避免/处理长方法签名的方法?

感觉这个方法签名太长了。有没有更明智或更优雅的方式来重写这个?


  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;

  }


不负相思意
浏览 229回答 2
2回答

慕工程0101907

if (actualFileSize <= Long.parseLong(emailFileSizeLimit)) {&nbsp; &nbsp; file = null;}return new Email(from, recipient, title,emailContent, null, file);1)重构。如果您认为参数过多,您可以将该方法分成更小的、可管理的方法。if (actualFileSize <= Long.parseLong(emailFileSizeLimit)) {&nbsp; &nbsp; file = null;}createMail(from, recipient, title,emailContent, null, file);******private Email createMail(long actualFileSize, String from, String recipient, String&nbsp;&nbsp; &nbsp; title, String emailContent, MultipartFile attachment, File file) {&nbsp; &nbsp;return new Email(from, recipient, title,emailContent, null, file);}2) DTO。您在 dto 中提供参数并将其作为请求/响应传递到整个链中,在需要时使用您需要的元素。当您需要创建时,您可以添加更多属性。您通过 setter 提供它们并在需要时传递3) 建造者。您在类中完成了在完成操作后返回自身的逻辑。您可以通过对同一类调用不同的操作并返回结果来执行下一个操作。Mail mail = mailBuilder.addName(name).add(stuff).compile(); // will call constructor inside4) 工厂让工厂包含所有方法并让它决定调用什么方法。它可以是静态的或托管的factory.createBasicMail(name);factory.createFileMail(name, file);ps:为了您的心理健康,请使用 Lombok

拉莫斯之舞

这似乎很适合Builder 模式,在那里您需要以精心设计的方式构造一个新对象:public class EmailBuilder {&nbsp; private Email mail;&nbsp; private String from;&nbsp; private String recipient;&nbsp; // other properties&nbsp; public EmailBuilder withFrom(String from) {&nbsp; &nbsp; this.from = from;&nbsp; &nbsp; return this;&nbsp; }&nbsp; public EmailBuilder withRecipient(String recipient) {&nbsp; &nbsp; this.recipient = recipient;&nbsp; &nbsp; return this;&nbsp; }&nbsp; public Email send() {&nbsp; &nbsp; mail = new Email(from, recipient, title,emailContent, null, file);&nbsp; &nbsp; return mail;&nbsp; }}用法Email mail = new EmailBuilder()&nbsp; &nbsp;.withFrom("John Doe")&nbsp; &nbsp;.withRecipient("Mary Doe")&nbsp; &nbsp;.with...&nbsp; &nbsp;.send();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java