Coding Standards
Coding Standards
Quality of Service
Security
Java
Javascript
HTML/JSP
CSS
XML
C#
Groovy
All source and configuration files must be encoded in UTF-8 Unicode encoding. Use of the
BOM (Byte Order Mask) is encouraged, but its use may be overridden by the requirements of
the used tool or technology.
ITCS-GPP-02 Official language in all source files is International English
Any text or text-like construct in either the source or the configuration file needs to be
written in international English1. This includes:
Only exceptions to this rule are the localized dictionary files and custom data mapping files.
Use of personal names and nicknames (either real or imaginary) is not allowed, except:
For the use of personal initials in the inline comments, see rule ITCS-GPP-17
Use of the owner company names is allowed in the copyright section and as part of the
package/namespace name only.
Use of the client’s company name is not allowed in the source code. Use of client’s company
name is allowed in client-specific configuration files.
Use of other company names, product names, brands and trademarks is allowed only in
places where the functionality uses or depends on the products, standards or protocols
produced by said company.
Not allowed
1 “English is the international language. Or, should I say, broken English is the international language” –Akira
Nambara, International Herald Tribune, 28 Sept. 1987.
3
4 // do not use personal names in comments
5 status = WARNING; //according to Horak
6
7 // ofcourse it’s ours, we implemented it – avoid owner company names
8 [Link];
9
10 // name the class after the functionality, not after the client who uses it
11 [Link] us;
12
13 // same goes for the variables
14 if (isFromKrka) ...
15
16 // EMA does not have a proprietary standard, they use AS1
17 [Link] client;
18
19 // unprofessional, not allowed
20 [Link]().warning("Ogi 46: no profile defined")
21 String separator = "BetterCallSaul";
Proper naming
1 // name the class after the functionality, not after the client who uses it
2 [Link] us;
3
4 // EMA does not have a proprietary standard, they use AS1
5 [Link].As1GatewayClient client;
6
7 // Use of proprietary formats or technologies
8 AdobePdfReader reader;
9 MsOfficePublisher publisher;
Inappropriate language is strictly prohibited in all places in the source code (including
variable names, comments, log entries, string content…). As a rule of thumb, do not place in
source code any text that you wouldn’t use in a recorded audio session or an e-mail
exchange with the client. Following (incomplete) list gives hints what not to use:
• Profanity,
• Slang,
• Text that you know is not true,
• Text that disrespects our clients, our competitors or owners of tool and technologies
that are being used,
• Text that disrespects own company and coworkers,
• Text that shows your own ignorance or incompetence,
• Text that, if disclosed, could have any negative impact on own company or the client.
Some subtle, but inappropriate comments are given below as examples:
Inappropriate comments
The tab character HT (U+0009) should be used for line indenting. The indenting sequence of
tab characters can be used at the beginning of the line only, directly followed by a first non-
whitespace character.
Apart from line indenting, the space character (U+0020) is the only allowed horizontal
whitespace character. All other whitespace characters (including the tab character HT –
U+0009) can be used as part of string literals only, and should be properly escaped.
Other use of horizontal whitespace is language-specific and defined with specific rules
further in this document.
Microsoft Windows newline convention is to be used for line endings in all source files: CR
(U+000D) character, followed by LF (U+000A) character. Use of either of the characters
independently, as well as use of any other vertical whitespace character, is allowed string
literals only. Use of any vertical whitespace character as part of a string literal should be
properly escaped.
Empty lines should be used to logically separate functional blocks of code. Language-specific
rules are given further in the document. In general, blocks with more than 20 lines of code
(excluding comments) should not be used.
For any character that has a special escape sequence (\t, \\, \"…), that sequence is used
rather than the corresponding Unicode escape (e.g. \u000a). Octal escape (e.g. \012) should
never be used.
Non-printable and whitespace characters are always escaped (see ITCS-GPP-05 , ITCS-GPP-
06 ). For the remaining non-ASCII characters, either the actual Unicode character or the
equivalent Unicode escape is used, depending only on which makes the code easier to read
and understand.
Any line shorter than 120 characters must not be wrapped. Lines that exceed 120 characters
have to be wrapped in situations described below. All other lines should not be wrapped,
even if they exceed 120 characters.
• Method declaration and method call having more than one parameter – if wrapped,
write each method parameter, including the first one, in a separate line. Do not split
single parameter into multiple lines.
• Concatenation of string literals – if wrapped, put each part of the string literal in a
separate line.
• Prepopulated collections – can be formatted in block-like constructs.
• Documentation and inline comments – wrap comments not to exceed the 120
characters limit.
Wrapped lines should be easily recognizable. To achieve this. Comply with following two
rules:
Each statement is followed by a line break. Do not put more than one statement in one line,
no matter how simple and short these statements are.
Comments
ITCS-GPP-11 Copyright information are mandatory
Include the properly formatted copyright information at the beginning of each source and
configuration file. Copyright information should be consistent and defined for each software
development project.
• Functions,
• Interfaces,
• Classes,
• Constructors,
• Method definitions within interfaces,
• Abstract method definitions within abstract classes,
• Methods (both base and inherited),
• Class member variables,
• Constants,
• Method arguments and return values,
• Thrown exceptions.
Interfaces, classes, constructors and methods are usually described with the multiline block
comments. Member variables, arguments, return values and exceptions can be described
with a single-line comment.
This rule does not apply to the local variables used within the method body and to the inner
anonymous classes.
Each code component (class, interface, method…) should be described completely in a single
documentation comment block. The comment should include:
Use inline comments to describe internals of the code and the reasons behind decisions
made when the code was written or updated. Do not use inline comments to describe
general functionality (see ITCS-GPP-13 above).
The amount of inline comments depends on the complexity and the nature of the
functionality. Following points give suggestions where the inline comments should be used:
Use descriptive variable names and clean programming style and avoid to write comments
that restate what is already visible from the code itself.
Always put comment in a separate line. Combining the comment with the executable code in
a single line is not allowed.
ITCS-GPP-16 Commented code is not allowed
Do not leave commented code within the source file when committing. Leverage the code
versioning system to track the code changes instead.
Use proper inline comments to demonstrate that a certain code must not be there instead of
simply commenting it out.
Source code repository and issue tracking system are primary systems to track the changes
in the code and to describe the reasons for the changes. Use of inline comments to track
code changes is discouraged. Rather, insert a new (or update the existing)
documentation/inline comment describing the intent of the change and the newly developed
functionality. If you still need to use the tracking comments, follow these rules:
• Each tracking comment must include the ID from the issue tracking system.
• A tracking comment may contain the initials, trigram or name of the developer.
• A tracking comment may contain the date of the inclusion.
• Restrict use of tracking comments to small code changes and unusual scenarios
• Treat all tracking comments as a personal and temporary aid (for example, to help
you with porting the changes to another branch). No officially approved procedure
will depend on existence of inline tracking comments.
• You are encouraged to remove all previous tracking comments within the scope of
the code that you are changing.
Quality of Service
This chapter aggregates the rules, recommendations and best practices to assure the high
quality of service, including:
It must be possible to prove statically that the loop cannot exceed a pre-set upper bound on
the number of iterations. Use sensible limit defaults and always implement the functionality
to enable reconfiguration of the default limits.
Only exceptions to this rule are loops in non-user threads that are meant to be
nonterminating – for example, in a queue scheduler. In those special cases, the reverse rule,
ITCS-QOS-04 must be applied.
Prevent stack overflow errors by implementing a recursion depth limiter, which will prevent
unbounded recursive calls. (E.g. maximum virtual document depth, maximum XML node
nesting depth…)
Use sensible limit defaults and always implement the functionality to enable reconfiguration
of the default limits.
If you are to implement a recursive algorithm, do so within a single recursive method. Avoid
implementing the recursive algorithm by chaining multiple methods in a recursive chain
(method A calls the method B, method B calls the method A).
Any exception thrown within a body of the loop needs to be caught and handled within the
loop body. Apply this rule on the deepest level in nested loops.
Good – the exception is caught in the loop and logged with enough details
Very bad – the exception has bubbled up without proper handling, you don’t even know that refresh
of a profile is the cause of the exception
Thread management should not be part of the application code. Do not create, run or
destroy threads manually. Rather, use the higher-level functionalities and frameworks
available for each language. These functionalities include thread pools, executor frameworks,
workers, futures, blocking queues…
Management of resources
ITCS-QOS-06 Limit the size of all arrays and collections
Prevent out of memory errors by implementing the size limiter on all arrays and collections
that could otherwise grow uncontrollably. Use sensible limit defaults and always implement
the functionality to reconfigure the default limits.
Use weak object references that will be garbage collected even when still in use to prevent
the out of memory errors. Implement a sensible fallback functionality if such situation
occurs.
As the title says. If you only need to read the document, open it with read privileges.
If the resource needs to be released manually (close the stream, remove the lock, close the
collection…), do it as soon as possible.
Ensure that all code paths, including exceptions, always end up releasing all opened
resources to prevent resource leakage. Leverage the existence of dedicated code constructs,
such as finally blocks in Java or using blocks in C#.
Parameter values that are read from the configuration files should not be treated as
constants. Rather, use a getter methods to read the value each time it is accessed.
Logging
ITCS-QOS-12 Use established tools to perform the logging
Establish the logging tools used on each project and use only them. Do not log in the
console directly.
Application logs are the primary place to look for information on the current and past
statuses of the application, user activities in the application and to troubleshoot any
problems that interrupt normal application behavior.
Log each relevant application execution information, do it in concise and consistent manner
and use proper logging level. Further standards in this chapter give best practices for
constructing the quality log messages.
Each log message should be logged by using proper log level. The primary set of logging
levels is: ERROR, WARNING, INFO, TRACE and DEBUG. Some of the logging levels may
be split into multiple levels to yield a finer separation. Similarly, additional logging categories
can be introduced to be used to log specific categories of events (such as QUERY or
LOGININFO). Each of the additionally introduced log levels must fall within one of the
primary levels.
ERROR – something terribly wrong has happened, that must be investigated immediately.
No system can tolerate items logged on this level. Use error log level for:
WARNING – the process can be continued, but take extra caution. The application can
tolerate warning messages, but they should always be justified and examined. Use warning
log level for:
• Obvious problems where workaround exists (for example: data unavailable, using
cached values)
• Attentions to potential problems and suggestions (for example: application running in
debug mode; admin password is not encrypted …)
• Handled configuration errors (for example: missing dictionary entry)
INFO – an atomic business process or transaction has finished, or the state of the
application has been changed significantly. An administrator or an advanced user should be
able to understand INFO messages and quickly find out what the application is doing. Try to
keep INFO log messages concise and put as much information into a single message (pay
attention to ITCS-QOS-15 and ITCS-QOS-17 ). Use info log level for:
DEBUG – very detailed information, intended only for the development. Use this level to log
information required during development, testing and troubleshooting of specific scenarios.
Plan that this log level will be disabled shortly after the start of productive use of the
application. Use debug level for:
ITCS-QOS-15 Each logging statement should contain both data and description
Whenever applicable, a log message should include all necessary data to describe the
context of the log message. Additionally, no log message can contain only the data, without
the message description. Do not separate log messages into one that shows only description,
and the other that shows the data. However, it is allowed to log similar message twice – with
less details in the INFO level and with more details in the TRACE level.
Good
1 [Link]("New document '" + objectName + "' has been created with profile "
+ profileId);
2
3 //or
4
5 [Link]("New document created (object_name = '" + objectName + "',
profile_id = " + profileId + ")");
Do not use getters that can lead to null-pointer exceptions or implicit casts to strings within
log statements.
Do not use getters that can result in on-demand object initialization or the ones that change
the state of the application.
Each log statement should be easily understandable to appropriate person (see ITCS-QOS-14
). On the other hand, ensure that log messages can be easily filtered with standard
techniques (such as regular expressions).
If you communicate with an external system, consider logging every piece of data that
comes out from your application and gets in.
Security
ITCS-SEC-01 Perform proper input validation
• Require authentication for all pages and resources, except those specifically intended
to be public
• All authentication controls must be enforced on a trusted system (e.g., The server)
• Establish and utilize standard, tested, authentication services whenever possible
• Use a centralized implementation for all authentication controls, including libraries
that call external authentication services
• authentication logic from the resource being requested and use redirection to and
from the centralized authentication control
• All authentication controls should fail securely
• All administrative and account management functions must be at least as secure as
the primary authentication mechanism
• If your application manages a credential store, it should ensure that only
cryptographically strong one-way salted hashes of passwords are stored and that the
table/file that stores the passwords and keys is write-able only by the application.
(Do not use the MD5 algorithm if it can be avoided)
• Password hashing must be implemented on a trusted system (e.g., The server).
• Validate the authentication data only on completion of all data input, especially for
sequential authentication implementations
• Authentication failure responses should not indicate which part of the authentication
data was incorrect. For example, instead of "Invalid username" or "Invalid password",
just use "Invalid username and/or password" for both. Error responses must be truly
identical in both display and source code
• Utilize authentication for connections to external systems that involve sensitive
information or functions
• Authentication credentials for accessing services external to the application should be
encrypted and stored in a protected location on a trusted system (e.g., The server).
The source code is NOT a secure location
• Use only HTTP POST requests to transmit authentication credentials
• Only send non-temporary passwords over an encrypted connection or as encrypted
data, such as in an encrypted email. Temporary passwords associated with email
resets may be an exception
• Enforce password complexity requirements established by policy or regulation.
Authentication credentials should be sufficient to withstand attacks that are typical of
the threats in the deployed environment. (e.g., requiring the use of alphabetic as well
as numeric and/or special characters)
• Enforce password length requirements established by policy or regulation. Eight
characters is commonly used, but 16 is better or consider the use of multi-word pass
phrases
• Password entry should be obscured on the user's screen. (e.g., on web forms use the
input type "password")
• Enforce account disabling after an established number of invalid login attempts (e.g.,
five attempts is common). The account must be disabled for a period of time
sufficient to discourage brute force guessing of credentials, but not so long as to
allow for a denial-of-service attack to be performed
• Password reset and changing operations require the same level of controls as
account creation and authentication.
• Password reset questions should support sufficiently random answers. (e.g., "favorite
book" is a bad question because “The Bible” is a very common answer)
• If using email based resets, only send email to a pre-registered address with a
temporary link/password
• Temporary passwords and links should have a short expiration time
• Enforce the changing of temporary passwords on the next use
• Notify users when a password reset occurs
• Prevent password re-use
• Passwords should be at least one day old before they can be changed, to prevent
attacks on password re-use
• Enforce password changes based on requirements established in policy or regulation.
Critical systems may require more frequent changes. The time between resets must
be administratively controlled
• Disable "remember me" functionality for password fields
• The last use (successful or unsuccessful) of a user account should be reported to the
user at their next successful login
• Implement monitoring to identify attacks against multiple user accounts, utilizing the
same password. This attack pattern is used to bypass standard lockouts, when user
IDs can be harvested or guessed
• Change all vendor-supplied default passwords and user IDs or disable the associated
accounts
• Re-authenticate users prior to performing critical operations
• Use Multi-Factor Authentication for highly sensitive or high value transactional
accounts
• If using third party code for authentication, inspect the code carefully to ensure it is
not affected by any malicious code
ITCS-SEC-04 Session management
• Use the server or framework’s session management controls. The application should
only recognize these session identifiers as valid
• Session identifier creation must always be done on a trusted system (e.g., The
server)
• Session management controls should use well vetted algorithms that ensure
sufficiently random session identifiers
• Set the domain and path for cookies containing authenticated session identifiers to an
appropriately restricted value for the site
• Logout functionality should fully terminate the associated session or connection
• Logout functionality should be available from all pages protected by authorization
• Establish a session inactivity timeout that is as short as possible, based on balancing
risk and business functional requirements. In most cases it should be no more than
several hours
• Disallow persistent logins and enforce periodic session terminations, even when the
session is active. Especially for applications supporting rich network connections or
connecting to critical systems. Termination times should support business
requirements and the user should receive sufficient notification to mitigate negative
impacts
• If a session was established before login, close that session and establish a new
session after a successful login
• Generate a new session identifier on any re-authentication
• Do not allow concurrent logins with the same user ID
• Do not expose session identifiers in URLs, error messages or logs. Session identifiers
should only be located in the HTTP cookie header. For example, do not pass session
identifiers as GET parameters
• Protect server side session data from unauthorized access, by other users of the
server, by implementing appropriate access controls on the server
• Generate a new session identifier and deactivate the old one periodically. (This can
mitigate certain session hijacking scenarios where the original identifier was
compromised)
• Generate a new session identifier if the connection security changes from HTTP to
HTTPS, as can occur during authentication. Within an application, it is recommended
to consistently utilize HTTPS rather than switching between HTTP to HTTPS.
• Supplement standard session management for sensitive server-side operations, like
account management, by utilizing per-session strong random tokens or parameters.
This method can be used to prevent Cross Site Request Forgery attacks
• Supplement standard session management for highly sensitive or critical operations
by utilizing per-request, as opposed to per-session, strong random tokens or
parameters
• Set the "secure" attribute for cookies transmitted over an TLS connection
• Set cookies with the HttpOnly attribute, unless you specifically require client-side
scripts within your application to read or set a cookie's value
• Use only trusted system objects, e.g. server side session objects, for making access
authorization decisions
• Use a single site-wide component to check access authorization. This includes
libraries that call external authorization services
• Access controls should fail securely
• Deny all access if the application cannot access its security configuration information
• authorization controls on every request, including those made by server side scripts,
"includes" and requests from rich client-side technologies like AJAX and Flash
• Segregate privileged logic from other application code
• Restrict access to files or other resources, including those outside the application's
direct control, to only authorized users
• Restrict access to protected URLs to only authorized
• Restrict access to protected functions to only authorized users
• Restrict direct object references to only authorized users
• Restrict access to services to only authorized users
• Restrict access to application data to only authorized users
• Restrict access to user and data attributes and policy information used by access
controls
• Restrict access security-relevant configuration information to only authorized users
• Server side implementation and presentation layer representations of access control
rules must match
• If state data must be stored on the client, use encryption and integrity checking on
the server side to catch state tampering.
• Enforce application logic flows to comply with business rules
• Limit the number of transactions a single user or device can perform in a given period
of time. The transactions/time should be above the actual business requirement, but
low enough to deter automated attacks
• Use the "referer" header as a supplemental check only, it should never be the sole
authorization check, as it is can be spoofed
• If long authenticated sessions are allowed, periodically re-validate a user’s
authorization to ensure that their privileges have not changed and if they have, log
the user out and force them to re-authenticate
• Implement account auditing and enforce the disabling of unused accounts (e.g., After
no more than 30 days from the expiration of an account’s password.)
• The application must support disabling of accounts and terminating sessions when
authorization ceases (e.g., Changes to role, employment status, business process,
etc.)
• Service accounts or accounts supporting connections to or from external systems
should have the least privilege possible
• Create an Access Control Policy to document an application's business rules, data
types and access authorization criteria and/or processes so that access can be
properly provisioned and controlled. This includes identifying access requirements for
both the data and system resources
• All cryptographic functions used to protect secrets from the application user must be
implemented on a trusted system (e.g., The server)
• Protect master secrets from unauthorized access
• Cryptographic modules should fail securely
• All random numbers, random file names, random GUIDs, and random strings should
be generated using the cryptographic module’s approved random number generator
when these random values are intended to be un-guessable
• Cryptographic modules used by the application should be compliant to FIPS 140-2 or
an equivalent standard. (See [Link]
• Establish and utilize a policy and process for how cryptographic keys will be managed
• Implement least privilege, restrict users to only the functionality, data and system
information that is required to perform their tasks
• Protect all cached or temporary copies of sensitive data stored on the server from
unauthorized access and purge those temporary working files a soon as they are no
longer required.
• Encrypt highly sensitive stored information, like authentication verification data, even
on the server side. Always use well vetted algorithms, see "Cryptographic Practices"
for additional guidance
• Protect server-side source-code from being downloaded by a user
• Do not store passwords, connection strings or other sensitive information in clear text
or in any non-cryptographically secure manner on the client side. This includes
embedding in insecure formats like: MS viewstate, Adobe flash or compiled code
• Remove comments in user accessible production code that may reveal backend
system or other sensitive information
• Remove unnecessary application and system documentation as this can reveal useful
information to attackers
• Do not include sensitive information in HTTP GET request parameters
• Disable auto complete features on forms expected to contain sensitive information,
including authentication
• Disable client side caching on pages containing sensitive information. Cache-Control:
no-store, may be used in conjunction with the HTTP header control "Pragma: no-
cache", which is less effective, but is HTTP/1.0 backward compatible
• The application should support the removal of sensitive data when that data is no
longer required. (e.g. personal information or certain financial data)
• Implement appropriate access controls for sensitive data stored on the server. This
includes cached data, temporary files and data that should be accessible only by
specific system users
• Implement encryption for the transmission of all sensitive information. This should
include TLS for protecting the connection and may be supplemented by discrete
encryption of sensitive files or non-HTTP based connections
• TLS certificates should be valid and have the correct domain name, not be expired,
and be installed with intermediate certificates when required
• Failed TLS connections should not fall back to an insecure connection
• Utilize TLS connections for all content requiring authenticated access and for all other
sensitive information
• Utilize TLS for connections to external systems that involve sensitive information or
functions
• Utilize a single standard TLS implementation that is configured appropriately
• Specify character encodings for all connections
• Filter parameters containing sensitive information from the HTTP referer, when
linking to external sites
• Ensure servers, frameworks and system components are running the latest approved
version
• Ensure servers, frameworks and system components have all patches issued for the
version in use
• Turn off directory listings
• Restrict the web server, process and service accounts to the least privileges possible
• When exceptions occur, fail securely
• Remove all unnecessary functionality and files
• Remove test code or any functionality not intended for production, prior to
deployment
• Prevent disclosure of your directory structure in the [Link] file by placing
directories not intended for public indexing into an isolated parent directory. Then
"Disallow" that entire parent directory in the [Link] file rather than Disallowing
each individual directory
• Define which HTTP methods, Get or Post, the application will support and whether it
will be handled differently in different pages in the application
• Disable unnecessary HTTP methods, such as WebDAV extensions. If an extended
HTTP method that supports file handling is required, utilize a well-vetted
authentication mechanism
• If the web server handles both HTTP 1.0 and 1.1, ensure that both are configured in
a similar manor or insure that you understand any difference that may exist (e.g.
handling of extended HTTP methods)
• Remove unnecessary information from HTTP response headers related to the OS,
web-server version and application frameworks
• The security configuration store for the application should be able to be output in
human readable form to support auditing
• Implement an asset management system and register system components and
software in it
• Isolate development environments from the production network and provide access
only to authorized development and test groups. Development environments are
often configured less securely than production environments and attackers may use
this difference to discover shared weaknesses or as an avenue for exploitation
• Implement a software change control system to manage and record changes to the
code both in development and production
• Do not pass user supplied data directly to any dynamic include function
• Require authentication before allowing a file to be uploaded
• Limit the type of files that can be uploaded to only those types that are needed for
business purposes
• Validate uploaded files are the expected type by checking file headers. Checking for
file type by extension alone is not sufficient
• Do not save files in the same web context as the application. Files should either go to
the content server or in the database
• Prevent or restrict the uploading of any file that may be interpreted by the web
server.
• Turn off execution privileges on file upload directories
• Implement safe uploading in UNIX by mounting the targeted file directory as a logical
drive using the associated path or the chrooted environment
• When referencing existing files, use a white list of allowed file names and types.
Validate the value of the parameter being passed and if it does not match one of the
expected values, either reject it or use a hard coded default file value for the content
instead
• Do not pass user supplied data into a dynamic redirect. If this must be allowed, then
the redirect should accept only validated, relative path URLs
• Do not pass directory or file paths, use index values mapped to pre-defined list of
paths
• Never send the absolute file path to the client
• Ensure application files and resources are read-only
• Scan user uploaded files for viruses and malware
• Use tested and approved managed code rather than creating new unmanaged code
for common tasks
• Utilize task specific built-in APIs to conduct operating system tasks. Do not allow the
application to issue commands directly to the Operating System, especially through
the use of application initiated command shells
• Use checksums or hashes to verify the integrity of interpreted code, libraries,
executables, and configuration files
• Utilize locking to prevent multiple simultaneous requests or use a synchronization
mechanism to prevent race conditions
• Protect shared variables and resources from inappropriate concurrent access
• Explicitly initialize all your variables and other data stores, either during declaration or
just before the first usage
• In cases where the application must run with elevated privileges, raise privileges as
late as possible, and drop them as soon as possible
• Avoid calculation errors by understanding your programming language's underlying
representation and how it interacts with numeric calculation. Pay close attention to
byte size discrepancies, precision, signed/unsigned distinctions, truncation,
conversion and casting between types, "not-a-number" calculations, and how your
language handles numbers that are too large or too small for its underlying
representation
• Do not pass user supplied data to any dynamic execution function
• Restrict users from generating new code or altering existing code
• Review all secondary applications, third party code and libraries to determine
business necessity and validate safe functionality, as these can introduce new
vulnerabilities
• Implement safe updating. If the application will utilize automatic updates, then use
cryptographic signatures for your code and ensure your download clients verify those
signatures. Use encrypted channels to transfer the code from the host server
Java
Source files organisation and structure
ITCS-JAV-01 File name same as class name
The source file name consists of the case-sensitive name of the top-level class it contains,
plus the .java extension.
1. Copyright information
2. Package statement
3. Import statements
4. Exactly one top-level class
The ordering of the members of a class can have a great effect on learnability, but there is
no single correct recipe for how to do it. Different classes may order their members
differently.
What is important is that each class order its members in some logical order, which its
maintainer could explain if asked. For example, new methods are not just habitually added
to the end of the class, as that would yield "chronological by date added" ordering, which is
not a logical ordering.
When a class has multiple constructors, or multiple methods with the same name, these
appear sequentially, with no intervening members.
Naming conventions
ITCS-JAV-07 Use only ASCII letters, digits and underscores in identifiers
Identifiers use only ASCII letters and digits, and in some cases, underscores. Thus each valid
identifier name is matched by the regular expression \w+.
Package names are all lowercase, with consecutive words simply concatenated together (no
underscores). For example, [Link], not [Link] or
[Link].deep_space.
Class names are typically nouns or noun phrases. For example, Character or ImmutableList.
Interface names may also be nouns or noun phrases (for example, List), but may
sometimes be adjectives or adjective phrases instead (for example, Readable).
Method names are typically verbs or verb phrases. For example, sendMessage or stop.
ITCS-JAV-11 Constant names – use CONSTANT_CASE
Constant names use CONSTANT_CASE: all uppercase letters, with words separated by
underscores. But what is a constant, exactly?
Every constant is a static final field, but not all static final fields are constants. Before
choosing constant case, consider whether the field really feels like a constant. For example,
if any of that instance's observable state can change, it is almost certainly not a constant.
Merely intending to never mutate the object is generally not enough. Examples:
1 // Constants
2 static final int NUMBER = 5;
3 static final ImmutableList<String> NAMES = [Link]("Ed", "Ann");
4 static final Joiner COMMA_JOINER = [Link](','); // Joiner is immutable
5 static final SomeMutableType[] EMPTY_ARRAY = {};
6 enum SomeEnum { ENUM_CONSTANT }
7
8 // Not constants
9 static String nonFinal = "non-final";
10 final String nonStatic = "non-static";
11 static final Set<String> mutableCollection = new HashSet<String>();
12 static final ImmutableSet<MutableType> mutElems = [Link](mutable);
13 static final Logger logger = [Link]([Link]());
14 static final String[] nonEmptyArray = {"these", "can", "change"};
Non-constant field names (static or otherwise) are written in lowerCamelCase. These names
are typically nouns or noun phrases. For example, computedValues or index.
Local variable names are written in lowerCamelCase, and can be abbreviated more liberally
than other types of names. However, one-character names should be avoided, except for
temporary and looping variables.
Even when final and immutable, local variables are not considered to be constants, and
should not be styled as constants.
Formatting
ITCS-JAV-15 Use braces even where optional
Braces are used with if, else, for, do and while statements, even when the body is empty
or contains only a single statement.
Braces follow the Kernighan and Ritchie style ("Egyptian brackets") for nonempty blocks and
block-like constructs:
Example:
If there are no statements within pair of braces, put an inline comment describing the
purpose of an empty block.
Follow general guidelines defined in ITCS-GPP-06 Additionally, single blank line appears:
Additionally, beyond where required by the language or other style rules, and apart from
literals, comments and Javadoc, a single ASCII space also appears in the following
places only.
1. Separating any reserved word, such as if, for or catch, from an open parenthesis (
that follows it on that line
2. Separating any reserved word, such as else or catch, from a closing curly brace }
that precedes it on that line
3. Before any open curly brace ({), with two exceptions:
o @SomeAnnotation({a, b}) (no space is used)
o String[][] x = {{"foo"}}; (no space is required between {{, by item 8
below)
4. On both sides of any binary or ternary operator. This also applies to the following
"operator-like" symbols:
o the ampersand in a conjunctive type bound: <T extends Foo & Bar>
o the colon (:) in an enhanced for ("foreach") statement
5. After ,:; or the closing parenthesis ) of a cast
6. On both sides of the double slash (//) that begins an end-of-line comment. Here,
multiple spaces are allowed, but not required.
7. Between the type and variable of a declaration: List<String> list
8. Optional just inside both braces of an array initializer
o new int[] {5, 6} and new int[] { 5, 6 } are both valid
This practice is permitted, but is never required. It is not even required to maintain
horizontal alignment in places where it was already used.
Rationale: Alignment can aid readability, but it creates problems for future maintenance.
Consider a future change that needs to touch just one line. This change may leave the
formerly-pleasing formatting mangled, and that is allowed. More often it prompts the coder
(perhaps you) to adjust whitespace on nearby lines as well, possibly triggering a cascading
series of reformattings. That one-line change now has a "blast radius." This can at worst
result in pointless busywork, but at best it still corrupts version history information, slows
down reviewers and exacerbates merge conflicts.
Optional grouping parentheses are omitted only when there is no reasonable chance the
code will be misinterpreted without them, nor would they have made the code easier to
read. It is not reasonable to assume that every reader has the entire Java operator
precedence table memorized.
Good – use grouping parentheses
After each comma that follows an enum constant, a line-break is optional. All other rules for
formatting classes apply.
Every variable declaration (field or local) declares only one variable: declarations such as int
a, b; are not used.
Local variables are not habitually declared at the start of their containing block or block-like
construct. Instead, local variables are declared close to the point they are first used (within
reason), to minimize their scope. Local variable declarations typically have initializers, or are
initialized immediately after declaration.
The square brackets form a part of the type, not the variable: String[] args, not String
args[].
Code constructs and programming practice
ITCS-JAV-27 Proper use of switch statement
Terminology Note: Inside the braces of a switch block are one or more statement groups.
Each statement group consists of one or more switch labels (either case FOO: or default:),
followed by one or more statements.
As with any other block, the contents of a switch block are indented. After a switch label, a
newline appears, and the indentation level is increased, exactly as if a block were being
opened. The following switch label returns to the previous indentation level, as if a block had
been closed.
Within a switch block, each statement group either terminates abruptly (with a break,
continue, return or thrown exception), or is marked with a comment to indicate that
execution will or might continue into the next statement group. This special comment is not
required in the last statement group of the switch block.
Each switch statement includes a default statement group, even if it contains no code.
1 switch (input) {
2 case 1:
3 case 2:
4 prepareOneOrTwo();
5 // fall through
6 case 3:
7 handleOneTwoOrThree();
8 break;
9 default:
10 handleLargeNumber(input);
11 }
1 @Override
2 @Nullable
3 public String getNameIfPresent() { ... }
As an exception, a single parameterless annotation may instead appear together with the
first line of the signature:
Annotations applying to a field also appear immediately after the documentation block, but in
this case, multiple annotations (possibly parameterized) may be listed on the same line:
Class and member modifiers, when present, appear in the order recommended by the Java
Language Specification:
public protected private abstract static final transient volatile synchronized
native strictfp
long-valued integer literals use an uppercase L suffix, never lowercase (to avoid confusion
with the digit 1). For example, 3000000000L rather than 3000000000l.
A method is marked with the @Override annotation whenever it is legal. This includes a class
method overriding a superclass method, a class method implementing an interface method,
and an interface method respecifying a superinterface method.
JavaScript
Formatting
ITCS-JSC-01 Declare all variables with ‘var’
Each function should begin with a single comma-delimited var statement that declares any
local variables necessary. If a function does not declare a variable using var, that variable
can leak into an outer scope (which is frequently the global scope, a worst-case scenario),
and can unwittingly refer to and modify that data.
Assignments within the var statement should be listed on individual lines, while declarations
can be grouped on a single line. Any additional lines should be indented with an additional
tab. Objects and functions that occupy more than a handful of lines should be assigned
outside of the var statement, to avoid over-indentation.
1 var k, m, length,
2 value = 'some value';
Always use semicolons. Semicolons should be included at the end of function expressions,
but not at the end of function declarations.
1 var myString = 'A rather long string of English text, an error message \
2 actually that just keeps going and going -- an error \
3 message to make the Energizer bunny blush (right through \
4 those Schwarzenegger shades)! Where was I? Oh yes, \
5 you\'ve got an error and all the extraneous whitespace is \
6 just gravy. Have a nice day.';
1 var myString = 'A rather long string of English text, an error message ' +
2 'actually that just keeps going and going -- an error ' +
3 'message to make the Energizer bunny blush (right through ' +
4 'those Schwarzenegger shades)! Where was I? Oh yes, ' +
5 'you\'ve got an error and all the extraneous whitespace is ' +
6 'just gravy. Have a nice day.';
Because of implicit semicolon insertion, always start your curly braces on the same line as
whatever they're opening. Also if/else/for/while/try always span multiple lines which
encourages readability. For example:
Bad
1 if(condition) doSomething();
2
3 while(condition) iterating++;
4
5 for(var i=0;i<100;i++) someIterativeFn();
Good
1 if (condition) {
2 // ...
3 } else {
4 // ...
5 }
6
7 while (condition) {
8 // statements
9 }
10
11 for (var i = 0; i < 100; i++) {
12 // statements
13 }
Single-line array and object initializers are allowed when they fit on a line:
Single-line initializers
Multiline array initializers and object initializers are indented with a tab, with the braces on
their own line, just like blocks.
Block initializers
1 // Object initializer.
2 var inset = {
3 top: 10,
4 right: 20,
5 bottom: 15,
6 left: 12
7 };
Prefer ' over ". For consistency single-quotes are preferred to double-quotes. This is helpful
when creating strings that include HTML
ITCS-JSC-07 Use proper casing for names of the code elements
Use camelCase for function, method and variable names, UpperCamelCase for constructors
and enums and CONTSTANT_CASE for constants (for the definition of the camel case, see
section 13.1):
• functionNamesLikeThis;
• variableNamesLikeThis;
• ConstructorNamesLikeThis;
• EnumNamesLikeThis;
• methodNamesLikeThis;
• CONSTANTS_LIKE_THIS;
ITCS-JSC-08 Comments
Comments come before the code to which they refer, and should always be preceded by a
blank line. Capitalize the first letter of the comment, and include a period at the end when
writing full sentences. There must be a single space between the comment token (//) and
the comment text.
1 someStatement();
2
3 // Explanation of something complex on the next line
4 doSomething();
1 /*
2 This is a comment that is long enough to warrant being stretched
3 over the span of multiple lines.
4 */
Nested functions can be very useful, for example in the creation of continuations and for the
task of hiding helper functions. Feel free to use them.
ITCS-JSC-10 Proper use of loops
Use for-in loop only for iterating over keys in an object/map/hash. for-in loops are often
incorrectly used to loop over the elements in an Array. This is however very error prone
because it does not loop from 0 to length - 1 but over all the present keys in the object and
its prototype chain.
Never use Array as a map/hash/associative array. If you need a map/hash use Object
instead of Array in these cases because the features that you want are actually features of
Object and not of Array.
ITCS-JSC-12 Use Array and Object literals instead of Array and Object
constructors
The eval() function in JavaScript is a way to run arbitrary code at run-time. In almost all
cases, eval should never be used. eval() makes for confusing semantics and is dangerous
to use if the string being eval()'d contains user input.
Bad – If the result was modified to include malicious JavaScript code, if we use eval then that code will
be executed
Strict equality checks (===) must be used in favour of abstract equality checks (==). The only
exception is when checking for both undefined and null by way of null.
1 var a = 'word1';
2 bar b = 'word2';
3
4 if (a == b) {
5 // do something
6 }
1 var a = 'word1';
2 bar b = 'word2';
3
4 if (a === b) {
5 // do something
6 }
1 // String:
2 if (typeof object === 'string') …
3
4 // Number:
5 if (typeof object === 'number') …
6
7 // Boolean:
8 if (typeof object === 'boolean') …
9
10 // Object:
11 if (typeof object === 'object') …
12
13 // Array:
14 if ([Link](object)) …
15
16 // null:
17 if (object === null) …
18
19 // null or undefined:
20 if (object == null) …
21
22 // undefined (Global Variables):
23 if (typeof variable === 'undefined') …
24
25 // undefined (Local Variables):
26 if (variable === undefined) …
27
28 // undefined (Properties):
29 if ([Link] === undefined) …
Take advantage of built-in capabilities and avoid unnecessary Boolean operators to evaluate
truthiness or falseness. Use following examples as a guide:
Conditional evaluation
Beyond the generally well known use cases of call and apply, always prefer .bind(this) or
a functional equivalent, for creating BoundFunction definitions for later invocation.
Alternately, aliasing can be used. When using aliasing use self as an identifier.
Always cache selectors when accessing or setting multiple properties on the same object.
Bad – Improper use of abstract equality check
Inline event handlers allows only one event listener to be attached and lead to poorly
organized code.
1 [Link]('click', function() {
2 [Link]('test');
3 }, false);
ITCS-JSC-21 Unbind all event handlers before binding the same handlers again
Always make sure you are unbinding event handlers before binding the same handler again.
When handling DOM events, you can improve the efficiency and performance of your script
by attaching an event to a single parent element instead of attaching events to every
element. This is called event delegation. Event delegation takes advantage of event bubbling
to assign a single event handler to manage all the events of a particular type.
ITCS-JSC-23 Closure
Avoid leakage of variables from or to other modules by wrapping files in a closure. This gives
the contained code its own scope.
HTML/JSP
ITCS-HTM-01 Proper formatting
Follow general formatting guidelines listed in chapter 2.1. Nested HTML elements should be
indented once.
Keep the amount of Java code within JSP files to a minimum. Any Java code should be
written by following the guidelines listed in chapter 4.
The usage of switch statements is generally discouraged, but can be useful when there are a
large number of cases – especially when multiple cases can be handled by the same block,
or fall-through logic (the default case) can be leveraged.
A proper Doctype which triggers standards mode in your browser should always be used.
Quirks mode should always be avoided.
1 <html>
2 ...
3 </html>
4
5 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
6 "[Link]
1 <!DOCTYPE html>
2 <html>
3 ...
4 </html>
ITCS-HTM-03 Use of IE compatibility mode
Internet Explorer supports the use of a document compatibility <meta> tag to specify what
version of IE the page should be rendered as. If needed, instruct IE to use the latest
supported mode with edge mode.
IE edge mode
All markup should be delivered as UTF-8, as it’s the most friendly for internationalization.
Don’t use legacy character encoding format. Specify the encoding meta tag at the top of all
meta tags.
Bad
Good
The <title> element is required in HTML5. Make the title as meaningful as possible
Per HTML5 spec, typically there is no need to specify a type when including CSS files as
text/css is the default.
Bad
1 <style type="text/css">
2 ...
3 </style>
Good
1 <style>
2 ...
3 </style>
Per HTML5 spec, typically there is no need to specify a type when including JavaScript files
as text/javascript is the default.
Bad
1 <script type="text/javascript">
2 ...
3 </script>
Good
1 <script>
2 ...
3 </script>
Good
Bad
1 <SECTION>
2 <p CLASS="header">This is a paragraph.</p>
3 </SECTION>
Good
1 <section>
2 <p class="header">This is a paragraph.</p>
3 </section>
Bad
1 <section>
2 <p>This is a paragraph.
3 <p>This is a paragraph.
4 </section>
Good
1 <section>
2 <p>This is a paragraph.</p>
3 <p>This is a paragraph.</p>
4 </section>
It’s recommended to always close empty HTML elements. The forward slash should have
exactly one space preceding it.
Bad
1 <meta charset="utf-8">
2 …
3 <br>
Good
Always define image size. It improves performance and reduces flickering because the
browser can reserve space for images before they are loaded.
A boolean attribute is one that needs no declared value. XHTML required you to declare a
value, but HTML5 has no such requirement.
Bad
1 <ul>
2 <li>General</li><li>The root Element</li><li>Sections</li>...
3 </ul>
Good
1 <ul>
2 <li>General</li>
3 <li>The root Element</li>
4 <li>Sections</li>
5 ...
6 </ul>
Escape &, <, >, " and ' with named character references.
The HTML5 specification defines quotes around attributes as optional. For consistency with
attributes that accept whitespace, all attributes should be quoted. Use double quote to quote
attribute values.
Iframes are the most costly elements to add to a given page. They block the page from
firing the onload event until they are complete.
CSS
ITCS-CSS-01 General coding principles
Ruleset anatomy
1 [selector] {
2 [property]: [value];
3 [<--declaration--->]
4 }
5
6 .foo, .foo-bar,
7 .baz {
8 display: block;
9 background-color: green;
10 color: red;
11 }
Compared to <link>s, @import is slower, adds extra page requests, and can cause other
unforeseen problems. Avoid them and instead opt for an alternate approach and include
multiple <link> elements.
1 <style>
2 @import url("[Link]");
3 </style>
Good – use <link>
If a rule has an ID selector as its key selector, don’t add the tag name to the rule. Since IDs
are unique, adding a tag name would slow down the matching process needlessly.
Bad
1 button#backButton {…}
2
3 .menu-left#newMenuIcon {…}
Good
1 #backButton {…}
2
3 #newMenuIcon {…}
The descendant selector is the most expensive selector in CSS. It is dreadfully expensive—
especially if the selector is in the Tag or Universal Category.
Bad
1 .treecell-header {…}
Use px unit of measurement to define font size, because it offers absolute control over text.
All major browsers support text resizing of pixel units and/or full-page zooming so pixels
sizing is preferred. Additionally, unit-less line-height is preferred because it does not inherit a
percentage value of its parent element, but instead is based on a multiplier of the font-size.
Bad
1 #selector {
2 font-size: 0.813em;
3 line-height: 1.25em;
4 }
Good
1 #selector {
2 font-size: 13px;
3 line-height: 1.5; /* 13 * 1.5 = 19.5 ~ rounds to 20px */
4 }
ITCS-CSS-07 Images
You should never be using spacer images. Use CSS sprites generously. They make hover
states easy and improve page load time.
Class names (or values) should be modular and should pertain to content within an element,
not appearance, as much as possible (if a visual appearance changes, class name should still
make sense). These values should be written in such a way that they resemble the syntax of
the CSS language. Accordingly, class names should be all lowercase and should use hyphen
delimiters. Prefix classes based on the closest parent or base class.
Bad
1 .Big_Red_Box { ... }
Good
1 .alert-message { ... }
There are times when a CSS selector is so long and specific that it no longer makes sense. It
creates a performance lag and is strenuous to manage. In this case, using a class alone is
advised. While applying a class to the targeted element may create more code within HTML,
it will allow the code to render faster and will remove any managing obstacles.
For example, if an <em> element is nested within an <h1> element inside of an <aside>
element, and all of that is nested within a <section> element, the selector might look
something like aside h1 em. Should the <em> element ever be moved out of the <h1>
element the styles will no longer apply. A better, more flexible selector would use a class,
such as text-offset, to target the <em> element.
Bad
Good
1 .text-offset { ... }
XML
This chapter provides a set of guidelines for general use when designing new XML document
formats, but also when manually writing instances of the XML documents based on the
existing format. The guidelines should be applied to new designs, and are not intended to
force retroactive changes in existing designs.
Rules and guides that follow are meant for the design of XML that is to be consumed by
machines rather than human beings. They are not applicable to formats such as XHTML or
some other rich-text format.
General design
ITCS-XML-01 Attempt to reuse existing XML formats whenever possible
Attempt to reuse existing XML formats whenever possible, especially those which allow
extensions. Creating an entirely new format should be done only with care and
consideration.
If you are reusing or extending an existing format, make sensible use of the prescribed
elements and attributes, especially any which are required. Don't completely repurpose
them, but do try to see how they might be used in creative ways if the vanilla semantics
aren't suitable. As a last resort when an element or attribute is required by the format but is
not appropriate for your use case, use some fixed string as its value.
When extending formats, use the implicit style of the existing format, even if it contradicts
this guide.
All newly created XML document formats should be expressed by using the W3C XML
Schema. Schemas should use the “Venetian Blind” style (schemas may also use the “Russian
Doll” style if they are short and simple).
If required, additional Schematron business and validation rules can be embedded to the
schema appinfo sections.
DTDs may also be provided for compatibility with existing products, tools or users.
Attribute names should not be in a namespace unless they are drawn from a foreign
document type or are meant to be used in foreign document types.
Namespace prefixes should be short, but single-letter prefixes should not be used. Prefixes
should contain only lower-case ASCII letters.
Components of the XML
ITCS-XML-04 All names and enumerated values need to use lowerCamelCase
Names of all elements, attributes and all enumerated values need to use lowerCamelCase, as
defined in chapter 13.1. Maximum allowed name length is 25 characters.
All elements must contain either nothing, character content, or child elements. Mixed
content must not be used (remember, textual format are not covered by this rule).
XML elements that wrap repeating child elements should be used where suitable. By using
such approach, functionalities of many text editors to collapse/expand an XML element can
be leveraged to hide sections of XML files.
Document formats must not depend on the order of attributes in a start-tag. Ordering of
XML attributes is not part of the XML Infoset and some parsers disregard the ordering.
Elements should not be overloaded with too many attributes. Instead, use child elements to
encapsulate closely related attributes.
Attributes must not be used to hold values in which line breaks are significant. Such line
breaks are converted to spaces by conformant XML parsers.
Binary data MUST NOT be included directly as-is in XML documents, but must be encoded
using Base64 encoding. The line breaks required by Base64 may be omitted.
An attribute named xsi:type with value xs:base64Binary may be attached to this element to
signal that the Base64 format is in use.
Well-known prefixes such as html: (for XHTML) and xs: (for XML Schema) should be used
for standard namespaces.
Redundant whitespace in a tag should not be used. Use one space before each attribute in
a start-tag; if the start tag is too long, the space may be replaced by a newline.
Documents may be pretty-printed using 2-space indentation for child elements. Elements
that contain character content should not be wrapped.
If comments are used, they should appear only in the document prolog or in elements that
contain child elements. If pretty-printing is required, pretty-print comments like elements,
but with line wrapping. Comments should not appear in elements that contain character
content.
C#
ITCS-CSH-01 Naming Conventions and Style
• Use Pascal casing for type and method names and constants:
• Use camel casing for local variable names and method arguments.
1 int number;
2
3 void MyMethod(int someNumber)
4 {}
Interfaces
1 interface IMyInterface
2 {...}
• Prefix private member variables with m_. Use Pascal casing for the rest of a member
variable name following the m_.
• With generics, use capital letters for types. Reserve suffixing Type when dealing with
the .NET type Type.
Avoid
Correct
• Use meaningful namespaces such as the product name or the company name.
• Avoid fully qualified type names. Use the using statement instead.
• Avoid putting a using statement inside a namespace.
• Group all framework namespaces together and put custom or third-party namespaces
underneath.
Namespaces
1 using System;
2 using [Link];
3 using [Link];
4 using [Link];
5 using MyCompany;
6 using MyControls;
Delegates
• Maintain strict indentation. Do not use tabs or nonstandard indentation, such as one
space. Recommended values are three or four spaces, and the value should be
uniformed across.
• All member variables should be declared at the top, with one line separating them
from the properties or methods.
Member variables
File naming
1 //In [Link]
2 public partial class MyClass
3 {...}
4
5 //In [Link]
6 public partial class MyClass
7 {...}
Good
Bad
Good
Bad
Assert
1 using [Link];
2 object GetObject()
3 {...}
4 object someObject = GetObject();
5 [Link](someObject != null);
Re-throw
1 catch(Exception exception)
2 {
3 [Link]([Link]);
4 throw; //Same as throw exception;
5 }
Good
Bad
Bad
• Avoid function calls in Boolean conditional statements. Assign into local variables and
check on them.
Good
1 bool ok = IsEverythingOK();
2 if (ok)
3 {...}
Bad
1 if (IsEverythingOK())
2 {...}
Array initialization
Defensive cast
Event accessors
Interface support
1 SomeType obj1;
2 IMyInterface obj2;
3
4 /* Some code to initialize obj1, then: */
5 obj2 = obj1 as IMyInterface;
6
7 if (obj2 != null)
8 {
9 obj2.Method1();
10 }
11 else
12 {
13 //Handle error in expected interface
14 }
• Never hardcode strings that will be presented to end users. Use resources instead.
• Never hardcode strings that might change based on deployment such as connection
strings.
• Use [Link] instead of "".
• When building a long string, use StringBuilder, not string.
• Avoid providing methods on structures.
o Parameterized constructors are encouraged.
o Can overload operators.
• Always provide a static constructor when providing static member variables.
• Do not use late-binding invocation when early-binding is possible.
• Use application logging and tracing.
• Never use goto unless in a switch statement fall-through.
• Always have a default case in a switch statement that asserts.
Default case
• Do not use this reference unless invoking another constructor from within a
constructor.
• Do not use the base word to access base class members unless you wish to resolve a
conflict with a subclasses member of the same name or when invoking a base class
constructor.
• Avoid explicit code exclusion of method calls (#if…#endif). Use conditional methods
instead:
Conditional methods
• Avoid casting to and from [Link] in code that uses generics. Use constraints
or the as operator instead:
Good
Bad
1 class MyClass<T>
2 {
3 void SomeMethod(T t)
4 {
5 object temp = t;
6 SomeClass obj = (SomeClass)temp;
7 }
8 }
Good
Bad
Conditional methods
1 <?xml version="1.0"?>
2 <configuration>
3 <startup>
4 <supportedRuntime version="v2.0.5500.0"/>
5 <supportedRuntime version="v1.1.5000.0"/>
6 </startup>
7 </configuration>
• Avoid putting code in ASPX files of [Link]. All code should be in the code beside
partial class.
• Code in code beside partial class of [Link] should call other components rather
than contain direct business logic.
• Always check a session variable for null before accessing it.
• In transactional pages or web services, always store session in SQL server.
• Avoid setting the Auto-Postback property of server controls in [Link] to True.
• Turn on Smart Navigation for [Link] pages.
• Strive to provide interfaces for web services. See Appendix A of Programming .NET
Components 2nd Edition.
• Always provide namespace and service description for web services.
• Always provide a description for web methods.
• When adding a web service reference, provide meaningful name for the location.
• In both [Link] pages and web services, wrap a session variables in a local
property. Only that property is allowed to access the session variable, and the rest of
the code uses the property, not the session variable.
• Always modify client-side web service wrapper class to support cookies, since you
have no way of knowing whether the service uses Session state or not.
ITCS-CSH-05 Documenting
• Keep comments simple. Provide just enough information so that others can
understand your code.
• Write the documentation before you write the code. This way you will see if the
method name suits the code. Write the algorithm you intend to implement in small
comments and then go and implement those comments. This will show in early stage
if the algorithm is good or not.
• Document every parameter if it's not obvious what it means. For example, this
parameter doesn't need an explanation: int height.
• When you go against a standard, document it. All standards, except for this one, can
be broken. If you do so, you must document why you broke the standard, the
potential implications of breaking the standard, and any conditions that may/must
occur before the standard can be applied to this situation.
• For example, if you choose to change some commonly used algorithm by implicating
some condition document it.
• Indent comment at the same level of indentation as the code you are documenting.
• All comments should pass spell checking. Misspelled comments indicate sloppy
development.
• Avoid comments that explain the obvious. Code should be self-explanatory. Good
code with readable variable and method names should not require comments.
• Document only operational assumptions, algorithm insights and so on.
• Avoid method-level documentation.
o Use extensive external documentation for API documentation.
o Use method-level comments only as tool tips for other developers.
Groovy
ITCS-GRV-01 Groovy follows Java coding standards
Groovy is Javas younger sibling, so it follows all coding style rules from chapter "Java" of this
guide. Exceptions from Java style rules are noted in this chapter.
ITCS-GRV-02 No semicolons
We are using idiomatic approach to Groovy coding. Semicolons are optional in Groovy and
we don't use them.
A closure in Groovy is an open, anonymous, block of code that can take arguments, return a
value and be assigned to a variable. For better readability closure braces don’t need to follow
ITCS-JAV-16 style rule when they are contain just one line.
Good
1 [Link] { println it }
Avoid
1 [Link] {
2 println it
3 }
The last expression evaluated in the body of a method can be returned without necessitating
the return keyword. Especially for short methods and for closures, it’s nicer to omit it for
brevity. Methods should follow ITCS-JAV-16 style rule.
Good
1 String toString() {
2 "a server"
3 }
Avoid
1 String toString() {
2 return "a server"
3 }
This doesn't look too good when you're using a variable, and see it visually twice on two
rows:
Avoid
1 def props() {
2 def m1 = [a: 1, b: 2]
3 m2 = [Link] { k, v -> v % 2 == 0 }
4 m2.c = 3
5 m2
6 }
Good
1 def props() {
2 def m1 = [a: 1, b: 2]
3 m2 = [Link] { k, v -> v % 2 == 0 }
4 m2.c = 3
5 return m2
6 }
Good
But def is redundant here. So make a choice, either use def or a type.
Avoid
When defining a method with untyped parameters, you can use def but it’s not needed, so
we omit them.
Good
Avoid
Another place where def is redundant and should be avoided is when defining constructors.
Good
1 class MyClass {
2 MyClass() {
3 // some code...
4 }
5 }
Avoid
1 class MyClass {
2 def MyClass() {
3 // some code...
4 }
5 }
By default, Groovy considers classes and methods public. So you don’t have to use the public
modifier everywhere something is public. Only if it’s not public, you should put a visibility
modifier.
Good
1 class Server {
2 String toString() {
3 "a server"
}
}
Avoid
Groovy allows you to omit the parentheses for top-level expressions so you should not use
them.
Good
1 println "Hello"
2 method a, b
Avoid
1 println("Hello")
2 method(a, b)
When a closure is the last parameter of a method call, like when using Groovy’s each{}
iteration mechanism, you should can put the closure outside the closing parentheses and
omit the parentheses.
Good
1 [Link] { println it }
Avoid
1 [Link]( { println it } )
2 [Link](){ println it }
The .class suffix is not needed in Groovy, a bit like in Java’s instanceof.
Good
Avoid
In Groovy, a getters and setters form what we call a "property", and offers a shortcut
notation for accessing and setting such properties. So instead of the Java-way of calling
getters / setters, you can use a field-like access notation:
Good
1 [Link] == SERVER_TYPE_NAME
2 [Link] = "something"
Avoid
1 [Link]().getName() == SERVER_TYPE_NAME
2 [Link]("something")
When writing your beans in Groovy, often called POGOs (Plain Old Groovy Objects), you
don’t have to create the field and getter / setter yourself, but let the Groovy compiler do it
for you.
Good
1 class Person {
2 String name
3 }
Avoid
1 class Person {
2 private String name
3 String getName() { return name }
4 void setName(String name) { [Link] = name }
5 }
As you can see, a free standing 'field' without modifier visibility actually makes the Groovy
compiler to generate a private field and a getter and setter for you.
Although the compiler creates the usual getter/setter logic, if you wish to do anything
additional or different in those getters/setters, you’re free to still provide them, and the
compiler will use your logic, instead of the default generated one.
Instead of setting each setter in subsequent statements you can use named parameters with
the default constructor (first the constructor is called, then the setters are called in the
sequence in which they are specified in the map).
Good
1 class Server {
2 String name
3 Cluster cluster
4 }
5
6 def server = new Server(name: "Obelix", cluster: aCluster)
Avoid
1 class Server {
2 String name
3 Cluster cluster
4 }
5
6 def server = new Server()
7 [Link] = "Obelix"
8 [Link] = aCluster
Good
1 [Link] {
2 name = [Link]
3 status = status
4 sessionCount = 3
5 start()
6 stop()
7 }
Avoid
1 [Link] = [Link]
2 [Link] = status
3 [Link] = 3
4 [Link]()
5 [Link]()
Groovy lets you decide whether you use explicit strong typing, or when you use def.
Whenever the code you’re writing is going to be used by others as a public API, you should
always favor the use of strong typing, it helps making the contract stronger, avoids possible
passed arguments type mistakes, gives better documentation, and also helps the IDE with
code completion.
Whenever the code is for your use only, like private methods then you’re more free to decide
when to use strong type or not.
Referential Documents
[1] G. J. Holzmann, "The Power of 10: Rules for Developing Safety-Critical Code,"
NASA/JPL Laboratory for Reliable Software, 2006.
[3] M. Howard and D. LeBlanc, Writing Secure Code, Second Edition, Redmond: Microsoft
Press, 2002.
[4] "Style guides for Google-originated open-source projects," 2015. [Online]. Available:
[Link]
[5] The Open Web Application Security Project, "OWASP Secure Coding Practices Quick
Reference Guide," OWASP Foundation, 2010.
[9] T. Nurkiewicz, "10 Tips for Proper Application Logging," [Online]. Available:
[Link]
Appendices
Camel case Definition
Camel case is the practice of writing compound words or phrases such that each word or
abbreviation begins with a capital letter and that the space between words is omitted. Camel
case may start with a capital or with a lowercase letter. The former is called the
UpperCamelCase, while the latter is called the lowerCamelCase. UpperCamelCase may also
be referred to as the PascalCase.
Sometimes there is more than one reasonable way to convert an English phrase into camel
case, such as when acronyms or unusual constructs like "MedDRA", "eCTD" or "NeeS" are
present. To improve predictability, following (nearly) deterministic scheme must be used.
1. Convert the phrase to plain ASCII and remove any apostrophes. For example,
"Müller's algorithm" might become "Muellers algorithm".
2. Divide this result into words, splitting on spaces and any remaining punctuation
(typically hyphens).
• If any word already has a conventional camel case appearance in common
usage, split it into its constituent parts (e.g. “YouTube” becomes You Tube).
Note that this practice is not applied on any acronyms.
• Some words are ambiguously hyphenated in the English language. For
example “nonempty” and “non-empty” are both correct, so both approaches,
to split and not to split, are likewise correct.
3. Now lowercase everything (including acronyms), then uppercase only the first
character of:
• Each word, to yield UpperCamelCase, or
• Each word except the first, to yield lowerCamelCase
4. Finally, join all the words in to a single identifier
Note that the casing of original words is almost entirely disregarded. Following table shows
several examples: