【问题标题】:Clean code - how to break a method that returns String干净的代码 - 如何打破返回字符串的方法
【发布时间】:2019-09-23 22:15:41
【问题描述】:

我有以下方法(因为太长而拆分):

private String replacePlaceholders(IncidentFullDTO incident, String text) {
        text = replacePlaceholdersPL(incident, text);
        text = replacePlaceholdersENG(incident, text);
        text = replaceAdministratorProcessor(incident, text);
        text = replaceRateSummary(incident, text);
        return text;
    }

每个方法(如 replacePlaceholdersPL)都会返回一个新的“文本”。所有这些方法都非常相似。示例:

    private String replacePlaceholdersPL(AAA incident, String text) {
            if (text.equals(PlaceholdersEnum.CURRENT_DATE.getPlaceholder())) {
                text = text.replace(PlaceholdersEnum.CURRENT_DATE.getPlaceholder(), getCurrentDate());
            } else if (...) {
                text = text.replace(PlaceholdersEnum.DATE_TIME_START_INCIDENT.getPlaceholder(), formatDate(incident.getIncidentDate()));
} else if(...) {}
} else if(...) {}...

如何用干净的代码原则编写这段代码?当前一个方法更改“文本”变量时,我想拆分这段代码,以免不必要地调用所有这些方法,如 replacePlaceholdersENG……我从 docx 文件中获取“文本”变量,我想用另一个替换这个文本文本值

【问题讨论】:

  • 听起来像是Code Review 的问题。不过,您需要一个更完整的示例。
  • 噢,我不知道代码审查网站...非常感谢
  • 从您的代码看来,您有不同类型的文本,并且在不知道其类型的情况下很难将其清理干净,您可能需要为每个组创建类型,例如 LanguageText、SummaryText 然后您可以应用您的转换而无需重复自己

标签: java coding-style clean-architecture


【解决方案1】:

不确定您所说的简洁代码原则是什么意思,但您可以创建一个类并将事件和文本设置为实例变量。每个函数调用都会有更新的文本。

class PlaceHolder {

 Incident incident;
 String text;

 public PlaceHolder(Incident incident, String text){
   this.incident = incident;
   this.text = text;
 }

 public String getResult() {
   replaceA();
   replaceB();
   ....
   return this.text;
 }

 public void replaceA(){}
 ....
}

【讨论】:

猜你喜欢
  • 2021-04-20
  • 1970-01-01
  • 2017-04-26
  • 2010-11-14
  • 2020-04-09
  • 2023-01-17
  • 1970-01-01
  • 1970-01-01
  • 2012-08-02
相关资源
最近更新 更多