Hard coding (also hard-coding or hardcoding) is the software development practice of embedding data directly into the
source code
In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the wo ...
of a
program
Program, programme, programmer, or programming may refer to:
Business and management
* Program management, the process of managing several related projects
* Time management
* Program, a part of planning
Arts and entertainment Audio
* Progra ...
or other executable object, as opposed to obtaining the data from external sources or generating it at
runtime. Hard-coded data typically can only be modified by editing the source code and
recompiling the executable, although it can be changed in
memory
Memory is the faculty of the mind by which data or information is encoded, stored, and retrieved when needed. It is the retention of information over time for the purpose of influencing future action. If past events could not be remembered, ...
or on disk using a
debugger
A debugger or debugging tool is a computer program used to software testing, test and debugging, debug other programs (the "target" program). The main use of a debugger is to run the target program under controlled conditions that permit the pr ...
or
hex editor
A hex editor (or ''binary file editor'' or ''byte editor'') is a computer program that allows for manipulation of the fundamental binary data that constitutes a computer file. The name 'hex' comes from ' hexadecimal', a standard numerical format f ...
. Data that are hard-coded is best for unchanging pieces of information, such as
physical constants
A physical constant, sometimes fundamental physical constant or universal constant, is a physical quantity that is generally believed to be both universal in nature and have constant value in time. It is contrasted with a mathematical constant, ...
,
version numbers and static text elements.
Softcoded data, on the other hand, encode arbitrary information through
user input
In computing, input/output (I/O, or informally io or IO) is the communication between an information processing system, such as a computer, and the outside world, possibly a human or another information processing system. Information, Inputs are ...
,
text files
A text file (sometimes spelled textfile; an old alternative name is flatfile) is a kind of computer file that is structured as a sequence of lines of electronic text. A text file exists stored as data within a computer file system. In operat ...
,
INI files, HTTP server responses, configuration files, preprocessor macros, external constants, databases, command-line arguments, and are determined at runtime.
Overview
Hard coding requires the program's source code to be changed any time the input data or desired format changes, when it might be more convenient to the end user to change the detail by some means outside the program.
Hard coding is often required, but can also be considered an
anti-pattern
An anti-pattern in software engineering, project management, and business processes is a common response to a recurring problem that is usually ineffective and risks being highly counterproductive. The term, coined in 1995 by computer programmer An ...
.
Programmers may not have a dynamic user interface solution for the end user worked out but must still deliver the feature or release the program. This is usually temporary but does resolve, in a short term sense, the pressure to deliver the code. Later, softcoding is done to allow a user to pass on parameters that give the end user a way to modify the results or outcome.
The term "hard-coded" was initially used as an analogy to hardwiring circuits - and was meant to convey the inflexibility which results from its usage within software design and implementation.
In the context of run-time extensible
collaborative development environment
A collaborative development environment (CDE) is an online meeting space where a software development project's stakeholders can work together, no matter what time zone or region they are in, to discuss, document, and produce project deliverables. ...
s such as
MUD
A MUD (; originally multi-user dungeon, with later variants multi-user dimension and multi-user domain) is a Multiplayer video game, multiplayer Time-keeping systems in games#Real-time, real-time virtual world, usually Text-based game, text-bas ...
s, hardcoding also refers to developing the core engine of the system responsible for low-level tasks and executing
scripts
Script may refer to:
Writing systems
* Script, a distinctive writing system, based on a repertoire of specific elements or symbols, or that repertoire
* Script (styles of handwriting)
** Script typeface, a typeface with characteristics of handw ...
, as opposed to softcoding which is developing the high-level scripts that get interpreted by the system at
runtime, with values from external sources, such as
text files
A text file (sometimes spelled textfile; an old alternative name is flatfile) is a kind of computer file that is structured as a sequence of lines of electronic text. A text file exists stored as data within a computer file system. In operat ...
,
INI files, preprocessor
macros, external constants,
database
In computing, a database is an organized collection of data stored and accessed electronically. Small databases can be stored on a file system, while large databases are hosted on computer clusters or cloud storage. The design of databases sp ...
s,
command-line
A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invoking executables and pro ...
arguments,
HTTP
The Hypertext Transfer Protocol (HTTP) is an application layer protocol in the Internet protocol suite model for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web, ...
server
Server may refer to:
Computing
*Server (computing), a computer program or a device that provides functionality for other programs or devices, called clients
Role
* Waiting staff, those who work at a restaurant or a bar attending customers and su ...
responses,
configuration file
In computing, configuration files (commonly known simply as config files) are computer file, files used to configure the Parameter (computer programming), parameters and Initialization (programming), initial settings for some computer programs. T ...
s, and
user input
In computing, input/output (I/O, or informally io or IO) is the communication between an information processing system, such as a computer, and the outside world, possibly a human or another information processing system. Information, Inputs are ...
. In this case, the term is not pejorative and refers to general development, rather than specifically embedding output data.
Hardcoding and backdoors
Hardcoding credentials is a popular way of creating a
backdoor
A back door is a door in the rear of a building. Back door may also refer to:
Arts and media
* Back Door (jazz trio), a British group
* Porta dos Fundos (literally “Back Door” in Portuguese) Brazilian comedy YouTube channel.
* Works so title ...
. Hardcoded credentials are usually not visible in configuration files or the output of account-enumeration commands and cannot be easily changed or bypassed by users. If discovered, a user might be able to disable such a backdoor by modifying and rebuilding the program from its
source code
In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the wo ...
(
if source is publicly available),
decompiling, or
reverse-engineering
Reverse engineering (also known as backwards engineering or back engineering) is a process or method through which one attempts to understand through deductive reasoning how a previously made device, process, system, or piece of software accompli ...
software
Software is a set of computer programs and associated documentation and data. This is in contrast to hardware, from which the system is built and which actually performs the work.
At the lowest programming level, executable code consists ...
,
directly editing the program's
binary code
A binary code represents text, computer processor instructions, or any other data using a two-symbol system. The two-symbol system used is often "0" and "1" from the binary number system. The binary code assigns a pattern of binary digits, also ...
, or instituting an integrity check (such as digital signatures, anti-tamper, and
anti-cheat
Cheating in online games is the subversion of the rules or mechanics of online video games to gain an unfair advantage over other players, generally with the use of third-party software. What constitutes cheating is dependent on the game in ...
) to prevent the unexpected access, but such actions are often prohibited by an
end-user license agreement
An end-user license agreement or EULA () is a legal contract between a software supplier and a customer or end-user, generally made available to the customer via a retailer acting as an intermediary. A EULA specifies in detail the rights and restr ...
.
Hardcoding and DRM
As a
digital rights management
Digital rights management (DRM) is the management of legal access to digital content. Various tools or technological protection measures (TPM) such as access control technologies can restrict the use of proprietary hardware and copyrighted works. ...
measure, software developers may hardcode a unique
serial number
A serial number is a unique identifier assigned incrementally or sequentially to an item, to ''uniquely'' identify it.
Serial numbers need not be strictly numerical. They may contain letters and other typographical symbols, or may consist enti ...
directly into a program. Or it is common to hardcode a
public key
Public-key cryptography, or asymmetric cryptography, is the field of cryptographic systems that use pairs of related keys. Each key pair consists of a public key and a corresponding private key. Key pairs are generated with cryptographic al ...
, creating the DRM for which it is infeasible to create a keygen.
On the opposite case, a software
cracker may hard-code a valid serial number to the program or even prevent the executable from asking the user for it, allowing unauthorized copies to be redistributed without the need of entering a valid number, thus sharing the same key for every copy, if one has been hard-coded.
Fixed installation path
If a Windows program is programmed to assume it is always installed to C:\Program Files\Appname and someone tries to install it to a different drive for space or organizational reasons, it may fail to install or to run after installation. This problem might not be identified in the testing process, since the average user installs to the default drive and directory and testing might not include the option of changing the installation directory. However it is advisable for programmers and developers not to fix the installation path of a program, since the default installation path depends on the operating system, OS version, and
sysadmin
A system administrator, or sysadmin, or admin is a person who is responsible for the upkeep, configuration, and reliable operation of computer systems, especially multi-user computers, such as servers. The system administrator seeks to ensu ...
decisions. For example, many installations of
Microsoft Windows
Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for serv ...
use
drive C: as their primary
hard disk
A hard disk drive (HDD), hard disk, hard drive, or fixed disk is an electro-mechanical data storage device that stores and retrieves digital data using magnetic storage with one or more rigid rapidly rotating platters coated with magnet ...
, but this is not guaranteed.
There was a similar issue with
microprocessor
A microprocessor is a computer processor where the data processing logic and control is included on a single integrated circuit, or a small number of integrated circuits. The microprocessor contains the arithmetic, logic, and control circu ...
s in early computers, which
started execution at a fixed
address
An address is a collection of information, presented in a mostly fixed format, used to give the location of a building, apartment, or other structure or a plot of land, generally using political boundaries and street names as references, along ...
in memory.
Startup disk
Some "
copy-protected" programs look for a particular file on a floppy disk or flash drive on startup to verify that they are not unauthorized copies. If the computer is replaced by a newer machine, which doesn't have a floppy drive, the program that requires it now can't be run, since the floppy disk can't be inserted.
This last example shows why hard-coding may turn out to be impractical even when it seems at the time that it would work completely. In the 1980s and 1990s the great majority of PCs were fitted with at least one floppy drive, but floppy drives later fell out of use. A program hard-coded in that manner 15 years ago could face problems if not updated.
Special folders
Some Windows operating systems have so called ''
Special Folders
On Microsoft Windows, a special folder is a folder that is presented to the user through an interface as an abstract concept instead of an absolute folder path. (The synonymous term shell folder is sometimes used instead.) Special folders make ...
'' which organize files logically on the hard disk. There are problems that can arise involving hard coding:
Profile path
Some Windows programs hard code the profile path to developer-defined locations such as
C:\Documents and Settings\''Username''
. This is the path for the vast majority of
Windows 2000
Windows 2000 is a major release of the Windows NT operating system developed by Microsoft and oriented towards businesses. It was the direct successor to Windows NT 4.0, and was Software release life cycle#Release to manufacturing (RTM), releas ...
or above, but this would cause an error if the profile is stored on a network or otherwise relocated. The proper way to get it is to call the
GetUserProfileDirectory
function or to resolve the
%userprofile%
environment variable. Another assumption that developers often make is assuming that the profile is located on a local hard disk.
My Documents folder path
Some Windows programs hardcode the path to
My Documents
My Documents is the commonly recognized name of a special folder in Microsoft Windows (starting with Windows Vista, it is called Documents only, and the actual name of the folder might be different when the language of the installed copy of Wi ...
as
''ProfilePath''\My Documents
. These programs would work on machines running the English version, but on
localized versions of Windows this folder normally has a different name. For example, in Italian versions the
My Documents
folder is named ''Documenti''.
My Documents
may also have been relocated using Folder Redirection in Group Policy in Windows 2000 or above. The proper way to get it is to call the
SHGetFolderPath
function.
Solution
An indirect reference, such as a variable inside the program called "FileName", could be expanded by accessing a "browse for file" dialogue window, and the program code would not have to be changed if the file moved.
Hard coding is especially problematic in preparing the software for translation to other languages.
In many cases, a single hard-coded value, such as an array size, may appear several times within the source code of a program. This would be a
magic number. This may commonly cause a program bug if some of the appearances of the value are modified, but not all of them. Such a bug is hard to find and may remain in the program for a long time. A similar problem may occur if the same hard-coded value is used for more than one parameter value, e.g. an array of 6 elements and a minimum input string length of 6. A programmer may mistakenly change all instances of the value (often using an editor's search-and-replace facility) without checking the code to see how each instance is used. Both situations are avoided by defining
constants, which associate names with the values, and using the names of the constants for each appearance within the code.
One important case of hard coding is when strings are placed directly into the file, which forces translators to edit the source code to translate a program. (There is a tool called
gettext
In computing, gettext is an internationalization and localization (i18n and l10n) system commonly used for writing multilingual programs on Unix-like computer operating systems. One of the main benefits of gettext is that it separates programmi ...
that permits strings to be left in files, but lets translators translate them without changing the source code; it effectively de-hard codes the strings.)
Hard coding in competitions
In computing competitions such as the
International Olympiad in Informatics
The International Olympiad in Informatics (IOI) is an annual competitive programming and one of the International Science Olympiads for secondary school students. It is the second largest science olympiad, after International Mathematical Olympi ...
, contestants are required to write a program with specific input-output pattern according to the requirement of the questions.
In rare cases where the possible number of inputs is small enough, a contestant might consider using an approach that maps all possible inputs to their correct outputs. This program would be considered a hard-coded solution as opposed to an
algorithm
In mathematics and computer science, an algorithm () is a finite sequence of rigorous instructions, typically used to solve a class of specific Computational problem, problems or to perform a computation. Algorithms are used as specificat ...
ic one (even though the hard-coded program might be the output of an algorithmic program).
See also
*
Firmware
In computing, firmware is a specific class of computer software that provides the low-level control for a device's specific hardware. Firmware, such as the BIOS of a personal computer, may contain basic functions of a device, and may provide h ...
*
Closed-source software
Proprietary software is software that is deemed within the free and open-source software to be non-free because its creator, publisher, or other rightsholder or rightsholder partner exercises a legal monopoly afforded by modern copyright and in ...
*
Self-modifying code
In computer science, self-modifying code (SMC) is code that alters its own instructions while it is executing – usually to reduce the instruction path length and improve performance or simply to reduce otherwise repetitively similar code, ...
References
{{reflist
Anti-patterns