什么是样板代码?为什么要避免呢?

what is boiler-plate code? why should it be avoided?

什么是样板代码,为什么这样称呼它? android 的示例:

onCreate(Bundle saveInstance){
    setcontentView(R.layout.m);

    findViewById(R.id.f1);
    findViewById(R.id.f2);
    findViewById(R.id.f3);
    findViewById(R.id.f4);
}

还有哪些例子?为什么我们应该避免样板代码?

样板代码是需要包含在很多地方的重复代码。 wikipedia article on the subject:

很好地解释了起源

Interestingly, the term arose from the newspaper business. Columns and other pieces that were syndicated were sent out to subscribing newspapers in the form of a mat (i.e. a matrix). Once received, boiling lead was poured into this mat to create the plate used to print the piece, hence the name boilerplate. As the article printed on a boilerplate could not be altered, the term came to be used by attorneys to refer to the portions of a contract which did not change through repeated uses in different applications, and finally to language in general which did not change in any document that was used repeatedly for different occasions.

样板代码存在几个问题:

  1. 它很容易出错。您的示例可能很简单,但并非所有样板实例都是如此。在代码包含更多逻辑的情况下,出错的空间更大(=错误)。特别是如果这些块只是从一个地方复制粘贴到另一个地方,但需要一些改动才能工作。
  2. 此外 - 如果您必须更改此逻辑,则很难做到,因为您需要遍历多个地方。
  3. 占用屏幕空间和注意力。阅读更多代码意味着在尝试理解您正在阅读的一段代码时,您需要处理更多的事情。样板代码只是增加了另一种干扰。
  4. 它在最终(通常是编译的)产品中实际占用 space。你更愿意提供什么?一个 1MB 的 JAR 文件还是一个 10MB 的文件?