fbpx
Wikipedia

Boilerplate code

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.[1]

The need for boilerplate can be reduced through high-level mechanisms such as metaprogramming (which has the computer automatically write the needed boilerplate code or insert it at compile time), convention over configuration (which provides good default values, reducing the need to specify program details in every project) and model-driven engineering (which uses models and model-to-code generators, eliminating the need for manual boilerplate code).

Origin Edit

The term arose from the newspaper business. Columns and other pieces that were distributed by print syndicates were sent to subscribing newspapers in the form of prepared printing plates. Because of their resemblance to the metal plates used in the making of boilers, they became known as "boiler plates", and their resulting text—"boilerplate text". As the stories that were distributed by boiler plates were usually "fillers" rather than "serious" news, the term became synonymous with unoriginal, repeated text.[2][3]

A related term is bookkeeping code, referring to code that is not part of the business logic but is interleaved with it in order to keep data structures updated or handle secondary aspects of the program.

Preamble Edit

One form of boilerplate consists of declarations which, while not part of the program logic or the language's essential syntax, are added to the start of a source file as a matter of custom. The following Perl 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 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 Edit

In Java 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 class representing a pet, almost all the code is boilerplate except for the declarations of Pet, name, and owner:

Java Edit

public class Pet {  private String name;  private Person owner;  public Pet(String name, Person owner) {  this.name = name;  this.owner = owner;  }  public String getName() {  return name;  }  public void setName(String name) {  this.name = name;  }  public Person getOwner() {  return owner;  }  public void setOwner(Person owner) {  this.owner = owner;  } } 

Most of the boilerplate in this example exists to fulfill requirements of JavaBeans. If the variables name and owner were declared as public, the accessor and mutator methods would not be needed.

In Java 14, record classes were added to fight with this issue.[4][5][6]

To reduce the amount of boilerplate, many frameworks have been developed, e.g. Lombok for Java.[7] The same code as above is auto-generated by Lombok using Java annotations, which is a form of metaprogramming:

@AllArgsConstructor @Getter @Setter public class Pet {  private String name;  private Person owner; } 

Scala Edit

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# Edit

Or in C# using Automatic Properties with compiler generated backing fields:

public class Pet {  public string Name { get; set; }  public Person Owner { get; set; } } 

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 Edit

In addition to declarations, methods 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 subroutines in procedural languages in general.[8]

HTML Edit

In HTML, the following boilerplate is used as a basic empty template and is present in most web pages:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Test</title> </head> <body> </body> </html> 

The WHATWG HTML Living Standard defines that the <html>, <head> and <body> tags may be safely omitted under most circumstances.[9] The <meta charset="UTF-8"> 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.[10] Google's HTML/CSS style guide recommends that all optional tags be omitted,[11] resulting in much less boilerplate. The World Wide Web Consortium states that element <title> must not be empty:[12]

<!DOCTYPE html> <title>Test</title> 

Python Edit

In Python, 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 Edit

References Edit

  1. ^ Lämmel, Ralf; Jones, Simon Peyton (2003). "Scrap your boilerplate: a practical design pattern for generic programming". Proceedings of the 2003 ACM SIGPLAN International Workshop on Types in Languages Design and Implementation. TLDI '03. New York: ACM. pp. 26–37. doi:10.1145/604174.604179. ISBN 9781581136494. S2CID 9472305.
  2. ^ "Boilerplate". Dictionary.com. Retrieved 2018-01-27.
  3. ^ "Boilerplate". Merriam-Webster. Retrieved 2018-01-27.
  4. ^ "Record Classes". docs.oracle.com.
  5. ^ "JEP 395: Record". openjdk.org.
  6. ^ Evans, Ben (2020-11-01). "Records Come to Java". blogs.oracle.com.
  7. ^ Frankel, Nicolas (2009-12-07). "Lombok reduces your boilerplate code". DZone.com. Retrieved 2017-08-02.
  8. ^ Martin Velez; Dong Qiu; You Zhou; Earl T. Barr; Zhendong Su (5 Feb 2015). "On the Lexical Distinguishability of Source Code [was: A Study of "Wheat" and "Chaff" in Source Code]". arXiv:1502.01410 [cs].
  9. ^ "HTML Standard - The HTML syntax - Optional tags". WHATWG. 2017-05-05. Retrieved 2017-05-05.
  10. ^ "Is the charset meta tag required with HTML5?". stackoverflow.com. Retrieved 2017-05-05.
  11. ^ "Google HTML/CSS Style Guide". google.github.io. Retrieved 2017-05-05.
  12. ^ "HTML page has non-empty title". www.w3.org. Retrieved 22 July 2021.

boilerplate, code, this, article, needs, additional, citations, verification, please, help, improve, this, article, adding, citations, reliable, sources, unsourced, material, challenged, removed, find, sources, news, newspapers, books, scholar, jstor, 2017, le. This article needs additional citations for verification Please help improve this article by adding citations to reliable sources Unsourced material may be challenged and removed Find sources Boilerplate code news newspapers books scholar JSTOR May 2017 Learn how and when to remove this template message 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 1 The need for boilerplate can be reduced through high level mechanisms such as metaprogramming which has the computer automatically write the needed boilerplate code or insert it at compile time convention over configuration which provides good default values reducing the need to specify program details in every project and model driven engineering which uses models and model to code generators eliminating the need for manual boilerplate code Contents 1 Origin 2 Preamble 3 In Java and similar platforms 3 1 Java 3 2 Scala 3 3 C 3 4 Method boilerplate 4 HTML 5 Python 6 See also 7 ReferencesOrigin EditFurther information Boilerplate text The term arose from the newspaper business Columns and other pieces that were distributed by print syndicates were sent to subscribing newspapers in the form of prepared printing plates Because of their resemblance to the metal plates used in the making of boilers they became known as boiler plates and their resulting text boilerplate text As the stories that were distributed by boiler plates were usually fillers rather than serious news the term became synonymous with unoriginal repeated text 2 3 A related term is bookkeeping code referring to code that is not part of the business logic but is interleaved with it in order to keep data structures updated or handle secondary aspects of the program Preamble EditOne form of boilerplate consists of declarations which while not part of the program logic or the language s essential syntax are added to the start of a source file as a matter of custom The following Perl 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 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 EditIn Java 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 class representing a pet almost all the code is boilerplate except for the declarations of Pet name and owner Java Edit public class Pet private String name private Person owner public Pet String name Person owner this name name this owner owner public String getName return name public void setName String name this name name public Person getOwner return owner public void setOwner Person owner this owner owner Most of the boilerplate in this example exists to fulfill requirements of JavaBeans If the variables name and owner were declared as public the accessor and mutator methods would not be needed In Java 14 record classes were added to fight with this issue 4 5 6 To reduce the amount of boilerplate many frameworks have been developed e g Lombok for Java 7 The same code as above is auto generated by Lombok using Java annotations which is a form of metaprogramming AllArgsConstructor Getter Setter public class Pet private String name private Person owner Scala Edit 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 Edit Or in C using Automatic Properties with compiler generated backing fields public class Pet public string Name get set public Person Owner get set 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 Edit In addition to declarations methods 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 subroutines in procedural languages in general 8 HTML EditIn HTML the following boilerplate is used as a basic empty template and is present in most web pages lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset UTF 8 gt lt title gt Test lt title gt lt head gt lt body gt lt body gt lt html gt The WHATWG HTML Living Standard defines that the lt html gt lt head gt and lt body gt tags may be safely omitted under most circumstances 9 The lt meta charset UTF 8 gt 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 10 Google s HTML CSS style guide recommends that all optional tags be omitted 11 resulting in much less boilerplate The World Wide Web Consortium states that element lt title gt must not be empty 12 lt DOCTYPE html gt lt title gt Test lt title gt Python EditIn Python 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 passSee also EditDirective programming Language construct that specifies how a compiler should process its input General purpose macro processor Macro processor that is not tied to or integrated with a particular language or piece of software Hello World program Traditional beginners computer program Library computing Collection of non volatile resources used by computer programs Macro computer science Rule for substituting a set input with a set output Preprocessor Program that processes input for another program Scaffold programming Code generation technique or a project generation technique Snippet programming Small region of re usable source code machine code or text Template processor Software designed to combine templates with a data model to produce result documents Web template system System in web publishingReferences Edit Lammel Ralf Jones Simon Peyton 2003 Scrap your boilerplate a practical design pattern for generic programming Proceedings of the 2003 ACM SIGPLAN International Workshop on Types in Languages Design and Implementation TLDI 03 New York ACM pp 26 37 doi 10 1145 604174 604179 ISBN 9781581136494 S2CID 9472305 Boilerplate Dictionary com Retrieved 2018 01 27 Boilerplate Merriam Webster Retrieved 2018 01 27 Record Classes docs oracle com JEP 395 Record openjdk org Evans Ben 2020 11 01 Records Come to Java blogs oracle com Frankel Nicolas 2009 12 07 Lombok reduces your boilerplate code DZone com Retrieved 2017 08 02 Martin Velez Dong Qiu You Zhou Earl T Barr Zhendong Su 5 Feb 2015 On the Lexical Distinguishability of Source Code was A Study of Wheat and Chaff in Source Code arXiv 1502 01410 cs HTML Standard The HTML syntax Optional tags WHATWG 2017 05 05 Retrieved 2017 05 05 Is the charset meta tag required with HTML5 stackoverflow com Retrieved 2017 05 05 Google HTML CSS Style Guide google github io Retrieved 2017 05 05 HTML page has non empty title www w3 org Retrieved 22 July 2021 Retrieved from https en wikipedia org w index php title Boilerplate code amp oldid 1167248749, wikipedia, wiki, book, books, library,

article

, read, download, free, free download, mp3, video, mp4, 3gp, jpg, jpeg, gif, png, picture, music, song, movie, book, game, games.