一位同事从未听说过这个词,我也无法给出一个确切的定义。对我来说,这一直是一个“我看到什么就知道什么”的例子。

附带问题,这个词是谁发明的?


当前回答

从维基百科:

在计算机编程中,样板文件是用来描述必须包含在许多地方且很少或没有更改的代码段的术语。它更常用于被认为是冗长的语言,即程序员必须编写大量代码来完成最少的工作。

所以基本上,你可以把样板代码看作是一种编程语言所需要的文本,在你用这种语言编写的程序中经常用到。

现代语言正在尝试减少它,但旧的语言也有特定的类型检查器(例如OCaml有一个类型推断器,它允许您避免在像Java这样更冗长的语言中作为样板代码的太多声明)

其他回答

In practical terms, boilerplate code is the stuff you cut-n-paste all over the place. Often it'll be things like a module header, plus some standard/required declarations (every module must declare a logger, every module must declare variables for its name and revision, etc.) On my current project, we're writing message handlers and they all have the same structure (read a message, validate it, process it) and to eliminate dependencies among the handlers we didn't want to have them all inherit from a base class, so we came up with a boilerplate skeleton. It declared all the routine variables, the standard methods, exception handling framework — all a developer had to do was add the code specific to the message being handled. It would have been quick & easy to use, but then we found out we were getting our message definitions in a spreadsheet (which used a boilerplate format), so we wound up just writing a code generator to emit 90% of the code (including the unit tests).

Joshua Bloch有一个关于API设计的演讲,涵盖了糟糕的API如何使样板代码成为必要。(参考样板文件的第46分钟,今天听这个)

样板代码是指可以反复使用的一段代码。另一方面,任何人都可以说它是一段可重用的代码。

这个词实际上来自钢铁行业。

对于一点历史,根据维基百科:

在19世纪90年代,样板版实际上是铸造或冲压成金属,准备印刷,并分发给美国各地的报纸。直到20世纪50年代,成千上万的报纸从美国最大的供应商西部报业联盟那里收到并使用了这种样板文件。有些公司还以样板文件的形式发布新闻稿,这样它们就必须按书面形式打印出来。

根据维基百科:

In object-oriented programs, classes are often provided with methods for getting and setting instance variables. The definitions of these methods can frequently be regarded as boilerplate. Although the code will vary from one class to another, it is sufficiently stereotypical in structure that it would be better generated automatically than written by hand. For example, in the following Java class representing a pet, almost all the code is boilerplate except for the declarations of Pet, name and owner: public class Pet { private PetName name; private Person owner; public Pet(PetName name, Person owner) { this.name = name; this.owner = owner; } public PetName getName() { return name; } public void setName(PetName name) { this.name = name; } public Person getOwner() { return owner; } public void setOwner(Person owner) { this.owner = owner; } }

从维基百科:

在计算机编程中,样板文件是用来描述必须包含在许多地方且很少或没有更改的代码段的术语。它更常用于被认为是冗长的语言,即程序员必须编写大量代码来完成最少的工作。

所以基本上,你可以把样板代码看作是一种编程语言所需要的文本,在你用这种语言编写的程序中经常用到。

现代语言正在尝试减少它,但旧的语言也有特定的类型检查器(例如OCaml有一个类型推断器,它允许您避免在像Java这样更冗长的语言中作为样板代码的太多声明)

它是可以被许多应用程序/上下文使用的代码,只需很少或没有更改。

样板纸(Boilerplate)起源于20世纪初的钢铁工业。