¿Cómo podrían los métodos tener 3 líneas de largo?

I'm reading a book about Clean coding and there're sample code.

The author says almost all methods could be less than 5 lines long in his book.


Here's a unrefactored code which looks hard to understand.

  public static String testableHtml(
    PageData pageData,
    boolean includeSuiteSetup
  ) throws Exception {
    WikiPage wikiPage = pageData.getWikiPage();
    StringBuffer buffer = new StringBuffer();
    if (pageData.hasAttribute("Test")) {
      if (includeSuiteSetup) {
        WikiPage suiteSetup =
          PageCrawlerImpl.getInheritedPage(
                  SuiteResponder.SUITE_SETUP_NAME, wikiPage
          );
        if (suiteSetup != null) {
          WikiPagePath pagePath =
            suiteSetup.getPageCrawler().getFullPath(suiteSetup);
          String pagePathName = PathParser.render(pagePath);
          buffer.append("!include -setup .")
                .append(pagePathName)
                .append("\n");
        }
      }
      WikiPage setup = 
        PageCrawlerImpl.getInheritedPage("SetUp", wikiPage);
      if (setup != null) {
        WikiPagePath setupPath =
          wikiPage.getPageCrawler().getFullPath(setup);
        String setupPathName = PathParser.render(setupPath);
        buffer.append("!include -setup .")
              .append(setupPathName)
              .append("\n");
      }
    }
    buffer.append(pageData.getContent());
    if (pageData.hasAttribute("Test")) {
      WikiPage teardown = 
        PageCrawlerImpl.getInheritedPage("TearDown", wikiPage);
      if (teardown != null) {
        WikiPagePath tearDownPath =
          wikiPage.getPageCrawler().getFullPath(teardown);
        String tearDownPathName = PathParser.render(tearDownPath);
        buffer.append("\n")
              .append("!include -teardown .")
              .append(tearDownPathName)
              .append("\n");
      }
      if (includeSuiteSetup) {
        WikiPage suiteTeardown =
          PageCrawlerImpl.getInheritedPage(
                  SuiteResponder.SUITE_TEARDOWN_NAME,
                  wikiPage
          );
        if (suiteTeardown != null) {
          WikiPagePath pagePath =
            suiteTeardown.getPageCrawler().getFullPath (suiteTeardown);
          String pagePathName = PathParser.render(pagePath);
          buffer.append("!include -teardown .")
                .append(pagePathName)
                .append("\n");
        }
      }
    }
    pageData.setContent(buffer.toString());
    return pageData.getHtml();
  }

The above code's refactored as below.

 public static String renderPageWithSetupsAndTeardowns(
    PageData pageData, boolean isSuite
  ) throws Exception {
    boolean isTestPage = pageData.hasAttribute("Test");
    if (isTestPage) {
      WikiPage testPage = pageData.getWikiPage();
      StringBuffer newPageContent = new StringBuffer();
      includeSetupPages(testPage, newPageContent, isSuite);
      newPageContent.append(pageData.getContent());
      includeTeardownPages(testPage, newPageContent, isSuite);
      pageData.setContent(newPageContent.toString());
    }
    return pageData.getHtml();
  }

And finally became like this

 public static String renderPageWithSetupsAndTeardowns(
    PageData pageData, boolean isSuite) throws Exception {
    if (isTestPage(pageData))
      includeSetupAndTeardownPages(pageData, isSuite);
    return pageData.getHtml();
  }

I can recognize that the three of codes's been better as it refactored.

Even though it's 3 or 4 lines long, the last method named includeSetupAndTeardownPages(pageData, isSuite) or inner method of it might be longer than 5 lines...

It looks contradictory to me or am I thinking wrongly?

preguntado el 29 de agosto de 12 a las 09:08

Rinse and repeat. If includeSetupAndTeardownPages is longer than 5 lines you can refactor it further until it has less than 5 lines. I don't really agree with that 5 line rule being good code though. -

3 Respuestas

I personally don't think that it makes sense to break a method to 5 lines down. It should make sense:

  • The function could be split it there are some general tasks inside. E.g. an initialization of several modules. There it would make sense to break it so smaller functions which just concerns about one module.
  • Separate code which is used multiple times. E.g. calculating of some date diff or so where you have to check for null values.

To break every method down to just 5 lines is in my opinion bad. So you have to jump thrue the code to see what really happens. Also if that is no topic on modern compiles you have more jumps into your code which could make your code slower... Well maybe just some nano seconds, but out there are also some hard real time problems where this matters.

In general I heard several times (and I think so too) that it is good practice to write no code (function/method) which is longer than the screen. So that you can read the code without scrolling.

Respondido el 31 de enero de 14 a las 18:01

The criterion that clean code should not contain methods longer than 5 lines is not necessarily good.

In my opionion, one should

  • try to encapsule functionalities that are commonly used in many parts of the code / more frequently so you write less lines of code. This makes the code less error-prone and debugging a whole lot easier! Saves a lot of time.
  • combine code that belongs to one logic execution block which makes reading code more comprehensible. A good structure is worth gold, especially when working with big projects!
  • name functions in a way that makes reading code more comprehensible!!!
  • document functions, parameters, variables and code thoroughly, that way you can generate printable documentation easily by using tools such as doxygen. Comes at hand when there are more than just one developer working on your code.

So rather than sticking with a fixed number, go for comprehensibility and structure!

Respondido 29 ago 12, 10:08

I guess the author is breaking 1 method into 2, 3, 4 or more methods to achieve this goal. I don't think that clean code is a code with methods that are less that 5 lines long.

Respondido 29 ago 12, 09:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.