Boilerplate code
   HOME

TheInfoList



OR:

In computer programming, boilerplate code, or simply boilerplate, are sections of code that are repeated in multiple places with little to no variation. When using languages that are considered ''verbose'', the programmer must write a lot of boilerplate code to accomplish only minor functionality. The need for boilerplate can be reduced through high-level mechanisms such as
metaprogramming Metaprogramming is a programming technique in which computer programs have the ability to treat other programs as their data. It means that a program can be designed to read, generate, analyze or transform other programs, and even modify itself ...
(which has the computer automatically write the needed boilerplate code or insert it at
compile time In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled. The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concep ...
),
convention over configuration Convention over configuration (also known as coding by convention) is a software design paradigm used by software frameworks that attempts to decrease the number of decisions that a developer using the framework is required to make without necessa ...
(which provides good default values, reducing the need to specify program details in every project) and
model-driven engineering Model-driven engineering (MDE) is a software development methodology that focuses on creating and exploiting domain models, which are conceptual models of all the topics related to a specific problem. Hence, it highlights and aims at abstract ...
(which uses models and model-to-code generators, eliminating the need for manual boilerplate code).


Origin

The term arose from the
newspaper A newspaper is a periodical publication containing written information about current events and is often typed in black ink with a white or gray background. Newspapers can cover a wide variety of fields such as politics, business, spor ...
business. Columns and other pieces that were distributed by print syndicates were sent to subscribing newspapers in the form of prepared
printing plate Printing is a process for mass reproducing text and images using a master form or template. The earliest non-paper products involving printing include cylinder seals and objects such as the Cyrus Cylinder and the Cylinders of Nabonidus. The ea ...
s. Because of their resemblance to the metal plates used in the making of
boiler A boiler is a closed vessel in which fluid (generally water) is heated. The fluid does not necessarily boil. The heated or vaporized fluid exits the boiler for use in various processes or heating applications, including water heating, central ...
s, they became known as "boiler plates", and their resulting text—"boilerplate text". As the stories that were distributed by boiler plates were usually "
fillers In processed animal foods, a filler is an ingredient added to provide dietary fiber, bulk or some other non-nutritive purpose. Products like corncobs, feathers, soy, cottonseed hulls, peanut hulls, citrus pulp, screening, weeds, straw, and cere ...
" rather than "serious" news, the term became synonymous with unoriginal, repeated text. A related term is ''bookkeeping code'', referring to code that is not part of the
business logic In computer software, business logic or domain logic is the part of the program that encodes the real-world business rules that determine how data can be created, stored, and changed. It is contrasted with the remainder of the software that might ...
but is interleaved with it in order to keep data structures updated or handle secondary aspects of the program.


Preamble

One form of boilerplate consists of declarations which, while not part of the program logic or the language's essential
syntax In linguistics, syntax () is the study of how words and morphemes combine to form larger units such as phrases and sentences. Central concerns of syntax include word order, grammatical relations, hierarchical sentence structure ( constituenc ...
, are added to the start of a source file as a matter of custom. The following
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
example demonstrates boilerplate: #!/usr/bin/perl use warnings; use strict; The first line is a shebang, which identifies the file as a Perl script that can be executed directly on the command line on Unix/Linux systems. The other two are pragmas turning on warnings and strict mode, which are mandated by fashionable Perl programming style. This next example is a C/C++
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
boilerplate, #include guard. #ifndef MYINTERFACE_H #define MYINTERFACE_H ... #endif This checks, and sets up, a global flag to tell the compiler whether the file myinterface.h has already been included. As many interdepending files may be involved in the compilation of a module, this avoids processing the same header multiple times (which would lead to errors due to multiple definitions with the same name).


In Java and similar platforms

In
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
programs, DTO 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 Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
class representing a pet, almost all the code is boilerplate except for the
declaration Declaration may refer to: Arts, entertainment, and media Literature * ''Declaration'' (book), a self-published electronic pamphlet by Michael Hardt and Antonio Negri * ''The Declaration'' (novel), a 2008 children's novel by Gemma Malley Music ...
s of ''Pet'', ''name'', and ''owner'':


Java

public class Pet Most of the boilerplate in this example exists to fulfill requirements of
JavaBeans In computing based on the Java Platform, JavaBeans is a technology developed by Sun Microsystems and released in 1996, as part of JDK 1.1. The 'beans' of JavaBeans are classes that encapsulate one or more objects into a single standardized objec ...
. If the variables name and owner were declared as
public In public relations and communication science, publics are groups of individual people, and the public (a.k.a. the general public) is the totality of such groupings. This is a different concept to the sociology, sociological concept of the ''Öf ...
, the accessor and mutator methods would not be needed. To reduce the amount of boilerplate, many frameworks have been developed, e.g. Lombok for Java. The same code as above is auto-generated by Lombok using Java annotations, which is a form of
metaprogramming Metaprogramming is a programming technique in which computer programs have the ability to treat other programs as their data. It means that a program can be designed to read, generate, analyze or transform other programs, and even modify itself ...
: @AllArgsConstructor @Getter @Setter public class Pet


Scala

In some other programming languages it may be possible to achieve the same thing with less boilerplate, when the language has built-in support for such common constructs. For example, the equivalent of the above Java code can be expressed in Scala using just one line of code: case class Pet(var name: String, var owner: Person)


C#

Or in C# using Automatic
Properties Property is the ownership of land, resources, improvements or other tangible objects, or intellectual property. Property may also refer to: Mathematics * Property (mathematics) Philosophy and science * Property (philosophy), in philosophy an ...
with compiler generated backing fields: public class Pet Starting with C# 9.0 there is an opportunity to use Records which generate classes with Properties automatically: public record Pet(string Name, Person Owner);


Method boilerplate

In addition to declarations,
method Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
s in OOP languages also contribute to the amount of boilerplate. A 2015 study on popular Java projects shows that 60% of methods can be uniquely identified by the occurrence of 4.6% of its tokens, making the remaining 95.4% boilerplate irrelevant to logic. The researchers believe this result would translate to
subroutine In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed. Functions may ...
s in procedural languages in general.


HTML

In
HTML The HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaS ...
, the following boilerplate is used as a basic empty template and is present in most web pages: Test The
WHATWG The Web Hypertext Application Technology Working Group (WHATWG) is a community of people interested in evolving HTML and related technologies. The WHATWG was founded by individuals from Apple Inc., the Mozilla Foundation and Opera Software, l ...
HTML Living Standard defines that the , and tags may be safely omitted under most circumstances. The tag is technically redundant when coming directly from a web server configured to send the character encoding in an HTTP header, though it becomes useful when the HTML response is saved in an .html file, cache, or web archive.
Google Google LLC () is an American Multinational corporation, multinational technology company focusing on Search Engine, search engine technology, online advertising, cloud computing, software, computer software, quantum computing, e-commerce, ar ...
's HTML/CSS style guide recommends that all optional tags be omitted, resulting in much less boilerplate. The
World Wide Web Consortium The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web. Founded in 1994 and led by Tim Berners-Lee, the consortium is made up of member organizations that maintain full-time staff working ...
states that element </code> must not be empty:<ref></ref> <syntaxhighlight lang="html5"> <!DOCTYPE html> <title>Test


Python

In
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
, the following boilerplate code can be used to modify if code can only be executed in or out of a module context. if __name__

'__main__': # Anything placed here will never be executed in a module context. pass if __name__ != '__main__': # Anything placed here will only be executed in a module context. pass


See also

* * * * * * * * * *


References

{{Reflist Source code Computer programming folklore Software engineering folklore Articles with example Java code