0% found this document useful (0 votes)
13 views87 pages

Coding Standards

Uploaded by

janko.juratovic
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views87 pages

Coding Standards

Uploaded by

janko.juratovic
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INDEX

Purpose and Scope ..................................................Error! Bookmark not defined.


List of Rules and Guidelines .................................................................................... 2
Good Programming Practice .................................................................................... 6
Structure of source files ..................................................................................... 6
High-quality code structures, program flow control and naming conventions ........ 11
Comments ...................................................................................................... 11
Quality of Service ................................................................................................. 13
Program flow .................................................................................................. 14
Management of resources ................................................................................ 16
Logging .......................................................................................................... 16
Security .............................................................................................................. 20
Java.................................................................................................................... 30
Source files organisation and structure .............................................................. 30
Naming conventions ........................................................................................ 31
Formatting...................................................................................................... 33
Code constructs and programming practice ....................................................... 37
JavaScript ........................................................................................................... 39
Formatting...................................................................................................... 39
Code constructs and programming practice ....................................................... 42
HTML/JSP ........................................................................................................... 49
CSS .................................................................................................................... 54
XML .................................................................................................................... 58
General design ................................................................................................ 59
Components of the XML ................................................................................... 60
Representation of XML instances ...................................................................... 60
C# ...................................................................................................................... 61
Groovy ................................................................................................................ 77
Temporary and Final Regulations ..............................Error! Bookmark not defined.
Referential Documents ......................................................................................... 85
Appendices.......................................................................................................... 85
Camel case Definition ...................................................................................... 85
List of Rules and Guidelines
Good Programming Practice

ITCS-GPP-01 Source files are encoded in UTF-8 ............................................................. 6


ITCS-GPP-02 Official language in all source files is International English .......................... 7
ITCS-GPP-03 Use of personal and company names is not allowed ................................... 7
ITCS-GPP-04 Inappropriate language is not allowed ....................................................... 8
ITCS-GPP-05 Use of horizontal whitespace .................................................................... 9
ITCS-GPP-06 Use of vertical whitespace ........................................................................ 9
ITCS-GPP-07 Use of special escape sequences ............................................................ 10
ITCS-GPP-08 Use of non-ASCII characters................................................................... 10
ITCS-GPP-09 Proper use of line wrapping .................................................................... 10
ITCS-GPP-10 One statement per line .......................................................................... 11
ITCS-GPP-11 Copyright information are mandatory ...................................................... 11
ITCS-GPP-12 Use documentation comments to describe each source code component.... 11
ITCS-GPP-13 Documentation comment should describe the code component completely 12
ITCS-GPP-14 Proper use of inline comments................................................................ 12
ITCS-GPP-15 End of line and mid-line comments are not allowed .................................. 12
ITCS-GPP-16 Commented code is not allowed ............................................................. 13
ITCS-GPP-17 Use of tracking comments is discouraged ................................................ 13

Quality of Service

ITCS-QOS-01 Give all loops a fixed upper bound .......................................................... 14


ITCS-QOS-02 Implement maximum depth in all recursive methods ................................ 14
ITCS-QOS-03 Do not chain multiple recursive methods ................................................. 14
ITCS-QOS-04 Protect loop control code from exceptions in inner code............................ 14
ITCS-QOS-05 Do not spawn threads manually .............................................................. 15
ITCS-QOS-06 Limit the size of all arrays and collections ................................................ 16
ITCS-QOS-07 Use weak references when handling large datasets .................................. 16
ITCS-QOS-08 Use least invasive method to access external resources ............................ 16
ITCS-QOS-09 Release all resources as soon as they are consumed ................................ 16
ITCS-QOS-10 Ensure that all resources get released ..................................................... 16
ITCS-QOS-11 Allow runtime configuration changes ....................................................... 16
ITCS-QOS-12 Use established tools to perform the logging............................................ 16
ITCS-QOS-13 Log generously and consistently ............................................................. 16
ITCS-QOS-14 Use proper log level ............................................................................... 17
ITCS-QOS-15 Each logging statement should contain both data and description.............. 18
ITCS-QOS-16 Avoid any code with possible side-effects in logging statement.................. 19
ITCS-QOS-17 Make log messages easy to read and easy to parse .................................. 19
ITCS-QOS-18 Watch out for external systems .............................................................. 19

Security

ITCS-SEC-01 Perform proper input validation .............................................................. 20


ITCS-SEC-02 Perform proper output encoding ............................................................. 20
ITCS-SEC-03 Authentication and password management .............................................. 21
ITCS-SEC-04 Session management ............................................................................. 23
ITCS-SEC-05 Access control ....................................................................................... 24
ITCS-SEC-06 Cryptographic practices .......................................................................... 25
ITCS-SEC-07 Error handling and logging ..................................................................... 25
ITCS-SEC-08 Data protection ..................................................................................... 26
ITCS-SEC-09 Communication security ......................................................................... 26
ITCS-SEC-10 System configuration ............................................................................. 27
ITCS-SEC-11 Database security .................................................................................. 28
ITCS-SEC-12 File management................................................................................... 28
ITCS-SEC-13 Memory management ............................................................................ 29
ITCS-SEC-14 General secure coding practices .............................................................. 29

Java

ITCS-JAV-01 File name same as class name ............................................................... 30


ITCS-JAV-02 Proper file structure............................................................................... 30
ITCS-JAV-03 Wildcard import statements are not allowed ............................................ 30
ITCS-JAV-04 Exactly one top-level class declaration is allowed ..................................... 31
ITCS-JAV-05 Order class members logically ................................................................ 31
ITCS-JAV-06 Never split overloaded methods ............................................................. 31
ITCS-JAV-07 Use only ASCII letters, digits and underscores in identifiers ...................... 31
ITCS-JAV-08 Package names – use lowercase ............................................................. 31
ITCS-JAV-09 Class names – use UpperCamelCase ....................................................... 31
ITCS-JAV-10 Method names – use lowerCamelCase .................................................... 31
ITCS-JAV-11 Constant names – use CONSTANT_CASE ................................................ 32
ITCS-JAV-12 Non-constant field names – use lowerCamelCase ..................................... 32
ITCS-JAV-13 Parameter names – use lowerCamelCase ................................................ 32
ITCS-JAV-14 Local variable names – use lowerCamelCase ........................................... 32
ITCS-JAV-15 Use braces even where optional ............................................................. 33
ITCS-JAV-16 Use K&R braces formatting .................................................................... 33
ITCS-JAV-17 Put comment in each empty block .......................................................... 33
ITCS-JAV-18 Use of vertical whitespace...................................................................... 34
ITCS-JAV-19 Use of horizontal whitespace .................................................................. 34
ITCS-JAV-20 Horizontal alignment is never required .................................................... 35
ITCS-JAV-21 Grouping parentheses are recommended ................................................ 35
ITCS-JAV-22 Line breaks in enum classes are optional ................................................. 36
ITCS-JAV-23 Declare one variable per declaration ....................................................... 36
ITCS-JAV-24 Declare when needed, initialize as soon as possible ................................. 36
ITCS-JAV-25 Array initializers can be block-like ........................................................... 36
ITCS-JAV-26 C-style array declarations are not allowed ............................................... 36
ITCS-JAV-27 Proper use of switch statement .............................................................. 37
ITCS-JAV-28 Proper formatting of annotations ............................................................ 37
ITCS-JAV-29 Proper order of modifiers ....................................................................... 38
ITCS-JAV-30 Use uppercase numeric suffixes.............................................................. 38
ITCS-JAV-31 Always use @Override ........................................................................... 38

Javascript

ITCS-JSC-01 Declare all variables with ‘var’ ................................................................ 39


ITCS-JSC-02 Proper use of semicolons ....................................................................... 39
ITCS-JSC-03 Multiline string literals are not allowed .................................................... 40
ITCS-JSC-04 Proper use of curly braces ..................................................................... 40
ITCS-JSC-05 Proper use of Array and Object initializers ............................................... 41
ITCS-JSC-06 Use single quotes for string literals ......................................................... 41
ITCS-JSC-07 Use proper casing for names of the code elements .................................. 42
ITCS-JSC-08 Comments ............................................................................................ 42
ITCS-JSC-09 Use of nested functions is encouraged .................................................... 42
ITCS-JSC-10 Proper use of loops ............................................................................... 43
ITCS-JSC-11 Do not use associative arrays ................................................................. 43
ITCS-JSC-12 Use Array and Object literals instead of Array and Object constructors ...... 44
ITCS-JSC-13 Avoid ‘eval’ ........................................................................................... 44
ITCS-JSC-14 Do not modify prototypes of builtin objects ............................................. 45
ITCS-JSC-15 Proper use of equality............................................................................ 45
ITCS-JSC-16 Type checking....................................................................................... 45
ITCS-JSC-17 Switch Statements ................................................................................ 49
ITCS-JSC-18 Avoid unnecessary Boolean operators to evaluate the truthiness ............... 46
ITCS-JSC-19 Proper handling of ‘this’ for later invocation ............................................. 47
ITCS-JSC-20 Cache and reuse selectors ..................................................................... 47
ITCS-JSC-21 Do not use inline event handlers ............................................................ 48
ITCS-JSC-22 Unbind all event handlers before binding the same handlers again ............ 48
ITCS-JSC-23 Use event delegation ............................................................................. 48
ITCS-JSC-24 Closure................................................................................................. 49

HTML/JSP

ITCS-HTM-01 Proper formatting .................................................................................. 49


ITCS-HTM-02 Always use DOCTYPE ............................................................................ 49
ITCS-HTM-03 Use of IE compatibility mode .................................................................. 50
ITCS-HTM-04 Character Encoding ............................................................................... 50
ITCS-HTM-05 Add title element................................................................................... 50
ITCS-HTM-06 Omit type attribute for CSS .................................................................... 50
ITCS-HTM-07 Omit type attribute for JavaScript ........................................................... 51
ITCS-HTM-08 Don't mix tags for CSS and JavaScript ..................................................... 51
ITCS-HTM-09 Use lower case element and attribute names ........................................... 52
ITCS-HTM-10 Close All HTML Elements........................................................................ 52
ITCS-HTM-11 Close Empty HTML Elements .................................................................. 52
ITCS-HTM-12 Always define image size ....................................................................... 53
ITCS-HTM-13 Boolean attributes are allowed ............................................................... 53
ITCS-HTM-14 Write one list item per line ..................................................................... 53
ITCS-HTM-15 Escape specific characters ...................................................................... 54
ITCS-HTM-16 All attributes should be quoted ............................................................... 54
ITCS-HTM-17 Minimize use of IFRAMEs ....................................................................... 54
ITCS-HTM-18 Use of Custom data attributes ................................................................ 54
ITCS-HTM-19 Don’t use tables for page layout ............................................................. 54

CSS

ITCS-CSS-01 General coding principles ....................................................................... 54


ITCS-CSS-02 Follow the recommended formatting of a ruleset ..................................... 55
ITCS-CSS-03 Don’t use @import ................................................................................ 55
ITCS-CSS-04 Don’t qualify ID rules with tag names or classes ...................................... 56
ITCS-CSS-05 Avoid the descendant selector ................................................................ 56
ITCS-CSS-06 Use Pixels instead of Ems ...................................................................... 57
ITCS-CSS-07 Images................................................................................................. 57
ITCS-CSS-08 Class Names ......................................................................................... 57
ITCS-CSS-09 Use Specific Classes When Necessary ..................................................... 58

XML

ITCS-XML-01 Attempt to reuse existing XML formats whenever possible ........................ 59


ITCS-XML-02 Document formats should be expressed using W3C XML Schemas............. 59
ITCS-XML-03 Use of namespaces is required ............................................................... 59
ITCS-XML-04 All names and enumerated values need to use lowerCamelCase ................ 60
ITCS-XML-05 Mixed content is not allowed .................................................................. 60
ITCS-XML-06 Use of grouping elements is encouraged ................................................. 60
ITCS-XML-07 Order of attributes should be irrelevant ................................................... 60
ITCS-XML-08 Use no more than 10 attributes per element............................................ 60
ITCS-XML-09 Do not store whitespace-sensitive values in attributes .............................. 60
ITCS-XML-10 Binary data should be Base64 encoded ................................................... 60
ITCS-XML-11 Declare namespaces on the root element ................................................ 60
ITCS-XML-12 Proper use of whitespace ....................................................................... 61
ITCS-XML-13 Use any format for empty elements ........................................................ 61
ITCS-XML-14 Allow both quotes and apostrophes for attribute values ............................ 61
ITCS-XML-15 Proper use of comments ........................................................................ 61

C#

ITCS-CSH-01 Naming Conventions and Style ...................Error! Bookmark not defined.


ITCS-CSH-02 Coding Practices .......................................Error! Bookmark not defined.
ITCS-CSH-03 Project Settings and Project Structure .........Error! Bookmark not defined.
ITCS-CSH-04 [Link] and Web Services ........................Error! Bookmark not defined.
ITCS-CSH-05 Documenting ............................................Error! Bookmark not defined.

Groovy

ITCS-GRV-01 Groovy follows Java coding standards ..................................................... 77


ITCS-GRV-02 No semicolons ....................................................................................... 77
ITCS-GRV-03 Groovy closures do not need to follow K&R braces formatting. .................. 77
ITCS-GRV-04 Return keyword is optional ..................................................................... 77
ITCS-GRV-05 Def and type ......................................................................................... 78
ITCS-GRV-06 Methods and classes are public by default ............................................... 80
ITCS-GRV-07 Omitting parentheses on method calls ..................................................... 80
ITCS-GRV-08 Classes as first-class citizens................................................................... 81
ITCS-GRV-09 Getters and Setters................................................................................ 81
ITCS-GRV-10 Initializing beans with named parameters and the default constructor........ 82
ITCS-GRV-11 Using with() for repeated operations on the same bean ............................ 83
ITCS-GRV-12 Use strong typing in API methods ........................................................... 83

Good Programming Practice


Structure of source files
ITCS-GPP-01 Source files are encoded in UTF-8

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:

• Names of source files,


• Names of all programming language constructs (variables, constants, classes, types,
interfaces, tags…),
• Copyright text,
• Documentation comments,
• Inline comments,
• Log entries,
• Any text within the string content, either in a prose form, or codified for localization
purposes.

Only exceptions to this rule are the localized dictionary files and custom data mapping files.

ITCS-GPP-03 Use of personal and company names is not allowed

Use of personal names and nicknames (either real or imaginary) is not allowed, except:

• In the ‘author’ section of the documentation comment,


• In cases where established algorithm is named after a person.

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.

See below several examples:

Not allowed

1 // do not use personal names as variable names


2 ArrayList madMladen;

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;

ITCS-GPP-04 Inappropriate language is not allowed

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

1 catch (Exception ex) {


2 // who cares
3 }
4
5 if (validationPassed = false) {
6 validationPassed = true; // ha-ha
7 }
8
9 // do not touch, no one knows what could be the side effects
10 clearCache();
11
12 if ([Link]()) {
13 // why??
14 productCount++;
15 }
16
17 if (![Link]("companyName").equalsIgnoreCase("TEVA")) {
18 // No one except Teva uses this, why bother
19 ...
20 }
21
22 if (isMsSql) {
23 // our beloved Microsoft
24 ...
25 }

ITCS-GPP-05 Use of horizontal whitespace

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.

Horizontal whitespace at the end of the line is not allowed.

Other use of horizontal whitespace is language-specific and defined with specific rules
further in this document.

ITCS-GPP-06 Use of vertical whitespace

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.

Line ending is mandatory on the last line of the source file.

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.

Use of more than one empty line as a separator is not allowed.

ITCS-GPP-07 Use of special escape sequences

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.

ITCS-GPP-08 Use of non-ASCII characters

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.

In the Unicode escape case, use of an explanatory comment is encouraged.

ITCS-GPP-09 Proper use of line wrapping

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.

Wrap these long lines:

• 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:

• Indent wrapped lines more than the standard indentation width


• Ending of each wrapped line part must clearly show that it is has a wrapped part (for
example, when concatenating strings, put the plus sign at the end of the line; when
wrapping method parameters, put the comma at the end of the line).

ITCS-GPP-10 One statement per line

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.

High-quality code structures, program flow control and


naming conventions
Use generally acclaimed design principles, guidelines and best practices when designing the
software components. It is implicitly assumed to follow them and no extract of these rules is
currently in the scope of the document.

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.

ITCS-GPP-12 Use documentation comments to describe each source code


component

Each component of the source code should be described by using language-specific


documentation comments, regardless of the visibility modifier (public, protected, private…).
This include:

• 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.

ITCS-GPP-13 Documentation comment should describe the code component


completely

Each code component (class, interface, method…) should be described completely in a single
documentation comment block. The comment should include:

• The description, purpose and intended use of the component,


• The general functionality of the component,
• Constraints and restrictions when using a component,
• Results of the component execution, including the changes of the application state,
• Any consequences and side-effects.

Do not split these in multiple documentation and inline comments.

ITCS-GPP-14 Proper use of inline comments

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:

• To describe the purpose of the local variable,


• To give a ‘caption’ to the block of code to increase the readability,
• To describe reasons for any nontrivial branching or a loop,
• To describe reasons for using chosen datatype or algorithm,
• To describe additional debugging information,
• To warn to any security-sensitive functionality,
• And wherever there is a need for additional explanation of the code.

Use descriptive variable names and clean programming style and avoid to write comments
that restate what is already visible from the code itself.

ITCS-GPP-15 End of line and mid-line comments are not allowed

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.

ITCS-GPP-17 Use of tracking comments is discouraged

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:

• Minimizing the possibility of the occurrence of an adverse event,


• Minimizing the scope of the effect of an adverse event,
• Minimizing the time needed for the (automatic or manual) recovery upon an adverse
event,
• Conducting quality forensic work upon an adverse event or a performance
degradation,
• Minimizing the required (planned or unplanned) downtime of the system.
Program flow
ITCS-QOS-01 Give all loops a fixed upper bound

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.

ITCS-QOS-02 Implement maximum depth in all recursive methods

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.

ITCS-QOS-03 Do not chain multiple recursive methods

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).

ITCS-QOS-04 Protect loop control code from exceptions in inner code

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

1 public void refreshProfiles() {


2 for (ProfileBean pb : [Link]()) {
3 try {
4 [Link](); // throws DfException
5 } catch (DfException ex) {
6 [Link]().error("Error refreshing profile" + [Link]() +
": " + [Link]());
7 //break, continue, or rethrow; depending on the desired outcome
8 }
9 }
10 }
Bad – the exception is caught outside of the loop, you don’t know which profile is causing the
exception

1 public void refreshProfiles() {


2 try {
3 for (ProfileBean pb : [Link]()) {
4 [Link](); // throws DfException
5 }
6 } catch (DfException ex) {
7 [Link]().error("Error refreshing profiles: " + [Link]());
8 }
9 }

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

1 public void refreshProfiles() throws DfException {


2 for (ProfileBean pb : [Link]()) {
3 [Link](); // throws DfException
4 }
5 }
6
7 // ... far far away
8
9 public void initDocument() {
10 try {
11 // lots of code
12 refreshProfiles();
13 // lots of code
14 } catch (DfException ex) {
15 [Link]().error("Error initializing doc: " + [Link]());
16 }
17 }

ITCS-QOS-05 Do not spawn threads manually

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.

ITCS-QOS-07 Use weak references when handling large datasets

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.

ITCS-QOS-08 Use least invasive method to access external resources

As the title says. If you only need to read the document, open it with read privileges.

ITCS-QOS-09 Release all resources as soon as they are consumed

If the resource needs to be released manually (close the stream, remove the lock, close the
collection…), do it as soon as possible.

ITCS-QOS-10 Ensure that all resources get released

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

ITCS-QOS-11 Allow runtime configuration changes

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.

ITCS-QOS-13 Log generously and consistently

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.

ITCS-QOS-14 Use proper log level

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.

Follow these recommendations to decide on the proper log level:

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:

• Critical resource unavailable (database, interfaced system …),


• Any unhandled application error (NPE!),
• Unhandled configuration errors (for example: unknown object type),
• Mission critical use case cannot be continued.

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:

• Business event has occurred (for example: document has been


created/promoted/deleted/updated),
• Configuration change has been performed (for example: profile has been changed),
• Scheduled job has started/finished,
• Interaction with connected system has occurred,
• Application state has been changed (application started/terminated; configuration
cache reloaded; server joined the cluster…).
TRACE – details of the business process execution and all changes of the application state
should be logged with trace level. System specialists should be able to understand TRACE
messages and find out the details of the application execution. This level will often be
enabled in the productive application use, especially during execution of mission-critical
processes. Use trace level for:

• All milestones of the business process,


• Deviations from the happy path of the process execution,
• Values of input, output and intermediate parameters,
• Data exchanged with external systems (see ITCS-QOS-18 ),
• Use of resources,
• Internally handled exceptions.

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:

• Changes of the local variables,


• Iterations of the internal loops,
• Internal milestones (especially in multithreaded code),
• Watchdog loops and timers,
• Any other internal event that can alter the state of the application.

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.

Exception to this rule is logging of input/output/intermediate parameter values in the TRACE


level when large number of parameters is present. To increase readability, each parameter
value can be logged in a separate log message.

Bad – no data that show context is present

1 [Link]("New document has been created");

Bad – no description is present


1 [Link]([Link]());

Bad – description and data are separated in multiple messages

1 [Link]("New document has been created");


2 [Link]("object_name = " + objectName);
3 [Link]("profile_id = " + profileId);

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 + ")");

ITCS-QOS-16 Avoid any code with possible side-effects in logging statement

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.

Do not log the content of the collection directly.

ITCS-QOS-17 Make log messages easy to read and easy to parse

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).

ITCS-QOS-18 Watch out for external systems

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

• Conduct all data validation on a trusted system (e.g., The server)


• Identify all data sources and classify them into trusted and untrusted. Validate all
data from untrusted sources (e.g., Databases, file streams, etc.)
• There should be a centralized input validation routine for the application
• Specify proper character sets, such as UTF-8, for all sources of input
• Encode data to a common character set before validating (Canonicalize)
• All validation failures should result in input rejection
• Determine if the system supports UTF-8 extended character sets and if so, validate
after UTF-8 decoding is completed
• Validate all client provided data before processing, including all parameters, URLs and
HTTP header content (e.g. Cookie names and values). Be sure to include automated
post backs from JavaScript, Flash or other embedded code
• Verify that header values in both requests and responses contain only ASCII
characters
• Validate data from redirects (An attacker may submit malicious content directly to the
target of the redirect, thus circumventing application logic and any validation
performed before the redirect)
• Validate for expected data types
• Validate data range
• Validate data length
• Validate all input against a "white" list of allowed characters, whenever possible
• If any potentially hazardous characters must be allowed as input, be sure that you
implement additional controls like output encoding, secure task specific APIs and
accounting for the utilization of that data throughout the application . Examples of
common hazardous characters include: < > " ' % ( ) & + \ \' \"
• If your standard validation routine cannot address the following inputs, then they
should be checked discretely
o Check for null bytes (%00)
o Check for new line characters (%0d, %0a, \r, \n)
o Check for “dot-dot-slash" (../ or ..\) path alterations characters. In cases
where UTF-8 extended character set encoding is supported, address alternate
representation like: %c0%ae%c0%ae/ (Utilize canonicalization to address double
encoding or other forms of obfuscation attacks)

ITCS-SEC-02 Perform proper output encoding

• Conduct all encoding on a trusted system (e.g., The server)


• Utilize a standard, tested routine for each type of outbound encoding
• Contextually output encode all data returned to the client that originated outside the
application's trust boundary. HTML entity encoding is one example, but does not
work in all cases
• Encode all characters unless they are known to be safe for the intended interpreter
• Contextually sanitize all output of un-trusted data to queries for SQL, XML, and LDAP
• Sanitize all output of un-trusted data to operating system commands

ITCS-SEC-03 Authentication and password management

• 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

ITCS-SEC-05 Access control

• 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

ITCS-SEC-06 Cryptographic practices

• 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

ITCS-SEC-07 Error handling and logging

• Do not disclose sensitive information in error responses, including system details,


session identifiers or account information
• Use error handlers that do not display debugging or stack trace information
• Implement generic error messages and use custom error pages
• The application should handle application errors and not rely on the server
configuration
• Properly free allocated memory when error conditions occur
• Error handling logic associated with security controls should deny access by default
• All logging controls should be implemented on a trusted system (e.g., The server)
• Logging controls should support both success and failure of specified security events
• Ensure logs contain important log event data
• Ensure log entries that include un-trusted data will not execute as code in the
intended log viewing interface or software
• Restrict access to logs to only authorized individuals
• Utilize a master routine for all logging operations
• Do not store sensitive information in logs, including unnecessary system details,
session identifiers or passwords
• Ensure that a mechanism exists to conduct log analysis
• Log all input validation failures
• Log all authentication attempts, especially failures
• Log all access control failures
• Log all apparent tampering events, including unexpected changes to state data
• Log attempts to connect with invalid or expired session tokens
• Log all system exceptions
• Log all administrative functions, including changes to the security configuration
settings
• Log all backend TLS connection failures
• Log cryptographic module failures
• Use a cryptographic hash function to validate log entry integrity

ITCS-SEC-08 Data protection

• 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

ITCS-SEC-09 Communication security

• 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

ITCS-SEC-10 System configuration

• 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

ITCS-SEC-11 Database security

• Use strongly typed parameterized queries


• Utilize input validation and output encoding and be sure to address meta characters.
If these fail, do not run the database command
• Ensure that variables are strongly typed
• The application should use the lowest possible level of privilege when accessing the
database
• Use secure credentials for database access
• Connection strings should not be hard coded within the application. Connection
strings should be stored in a separate configuration file on a trusted system and they
should be encrypted.
• Use stored procedures to abstract data access and allow for the removal of
permissions to the base tables in the database
• Close the connection as soon as possible
• Remove or change all default database administrative passwords. Utilize strong
passwords/phrases or implement multi-factor authentication
• Turn off all unnecessary database functionality (e.g., unnecessary stored procedures
or services, utility packages, install only the minimum set of features and options
required (surface area reduction))
• Remove unnecessary default vendor content (e.g., sample schemas)
• Disable any default accounts that are not required to support business requirements
• The application should connect to the database with different credentials for every
trust distinction (e.g., user, read-only user, guest, administrators)

ITCS-SEC-12 File management

• 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

ITCS-SEC-13 Memory management

• Utilize input and output control for un-trusted data


• Double check that the buffer is as large as specified
• When using functions that accept a number of bytes to copy, such as strncpy(), be
aware that if the destination buffer size is equal to the source buffer size, it may not
NULL-terminate the string
• Check buffer boundaries if calling the function in a loop and make sure there is no
danger of writing past the allocated space
• Truncate all input strings to a reasonable length before passing them to the copy and
concatenation functions
• Specifically close resources, don’t rely on garbage collection. (e.g., connection
objects, file handles, etc.)
• Use non-executable stacks when available
• Avoid the use of known vulnerable functions (e.g., printf, strcat, strcpy etc.)
• Properly free allocated memory upon the completion of functions and at all exit
points

ITCS-SEC-14 General secure coding practices

• 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.

ITCS-JAV-02 Proper file structure

A source file consists of, in order:

1. Copyright information
2. Package statement
3. Import statements
4. Exactly one top-level class

Exactly one blank line separates each section that is present.

ITCS-JAV-03 Wildcard import statements are not allowed

Wildcard import statements are not allowed.


ITCS-JAV-04 Exactly one top-level class declaration is allowed

Each top-level class resides in a source file of its own.

ITCS-JAV-05 Order class members logically

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.

ITCS-JAV-06 Never split overloaded methods

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+.

ITCS-JAV-08 Package names – use lowercase

Package names are all lowercase, with consecutive words simply concatenated together (no
underscores). For example, [Link], not [Link] or
[Link].deep_space.

ITCS-JAV-09 Class names – use UpperCamelCase

Class names are written in UpperCamelCase.

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).

ITCS-JAV-10 Method names – use lowerCamelCase

Method names are written in lowerCamelCase.

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:

Constants and not constants

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"};

ITCS-JAV-12 Non-constant field names – use lowerCamelCase

Non-constant field names (static or otherwise) are written in lowerCamelCase. These names
are typically nouns or noun phrases. For example, computedValues or index.

ITCS-JAV-13 Parameter names – use lowerCamelCase

Parameter names are written in lowerCamelCase. One-character parameter names should be


avoided.

ITCS-JAV-14 Local variable names – use lowerCamelCase

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.

ITCS-JAV-16 Use K&R braces formatting

Braces follow the Kernighan and Ritchie style ("Egyptian brackets") for nonempty blocks and
block-like constructs:

• No line break before the opening brace.


• Line break after the opening brace.
• Line break before the closing brace.
• Line break after the closing brace if that brace terminates a statement or the body of
a method, constructor or named class. For example, there is no line break after the
brace if it is followed by else or a comma.

Example:

Good – proper braces formatting

1 return new MyClass() {


2 @Override
3 public void method() {
4 if (condition()) {
5 try {
6 something();
7 } catch (ProblemException e) {
8 recover();
9 }
10 } else {
11 somethingElse();
12 }
13 }
14 };

ITCS-JAV-17 Put comment in each empty block

If there are no statements within pair of braces, put an inline comment describing the
purpose of an empty block.

Bad – empty block without comment

1 public class ProfileBean implements IBean {


2 @Override
3 public void init() { }
4 ...
5 }

Good – empty block commented

1 public class ProfileBean implements IBean {


2 @Override
3 public void init() {
4 // there’s nothing to initialize for the profile bean
5 }
6 ...
7 }

ITCS-JAV-18 Use of vertical whitespace

Follow general guidelines defined in ITCS-GPP-06 Additionally, single blank line appears:

• Between consecutive members (or initializers) of a class: fields, constructors,


methods, nested classes, static initializers, instance initializers.
• Within method bodies, as needed to create logical groupings of statements.
• Optionally before the first member or after the last member of the class (neither
encouraged nor discouraged).

ITCS-JAV-19 Use of horizontal whitespace

Follow general guidelines defined in ITCS-GPP-05

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

ITCS-JAV-20 Horizontal alignment is never required

Terminology Note: Horizontal alignment is the practice of adding a variable number of


additional spaces in your code with the goal of making certain tokens appear directly below
certain other tokens on previous lines.

This practice is permitted, but is never required. It is not even required to maintain
horizontal alignment in places where it was already used.

Here is an example without alignment, then using alignment:

Good – no horizontal alignment

1 private int x; // this is fine


2 private Color color; // this too

Bad – with horizontal alignment

1 private int x; // permitted, but future edits


2 private Color color; // may leave it unaligned

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.

ITCS-JAV-21 Grouping parentheses are recommended

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

1 int weightedAverage = ((x * 0.7) + (y * 1.3)) / 2;

ITCS-JAV-22 Line breaks in enum classes are optional

After each comma that follows an enum constant, a line-break is optional. All other rules for
formatting classes apply.

Good – enum declaration

1 private enum Roles { AUTHOR, REVIEWER, APPROVER, COORDINATOR }

ITCS-JAV-23 Declare one variable per declaration

Every variable declaration (field or local) declares only one variable: declarations such as int
a, b; are not used.

ITCS-JAV-24 Declare when needed, initialize as soon as possible

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.

ITCS-JAV-25 Array initializers can be block-like

Any array initializer may optionally be formatted as if it were a "block-like construct."

ITCS-JAV-26 C-style array declarations are not allowed

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.

Good – proper switch statement

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 }

ITCS-JAV-28 Proper formatting of annotations

Annotations applying to a class, method or constructor appear immediately after the


documentation block, and each annotation is listed on a line of its own (that is, one
annotation per line):

Good – class/method/constructor annotations

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:

Good – single parameterless class/method/constructor annotation

1 @Override public int hashCode() { ... }

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:

Good – field annotations

1 @Partial @Mock DataLoader loader;

ITCS-JAV-29 Proper order of modifiers

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

ITCS-JAV-30 Use uppercase numeric suffixes

long-valued integer literals use an uppercase L suffix, never lowercase (to avoid confusion
with the digit 1). For example, 3000000000L rather than 3000000000l.

ITCS-JAV-31 Always use @Override

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.

Bad – invalid declaration of variables

1 var foo = true;


2 var bar = false;
3 var a;
4 var b;
5 var c;

Good – valid declaration of variables

1 var k, m, length,
2 value = 'some value';

ITCS-JSC-02 Proper use of semicolons

Always use semicolons. Semicolons should be included at the end of function expressions,
but not at the end of function declarations.

Bad – function expression without semicolon

1 var somthing = function() {


2 return true;
3 } // no semicolon here.
Good – function expression with semicolon

1 var something = function() {


2 return true;
3 }; // semicolon here.

ITCS-JSC-03 Multiline string literals are not allowed

Bad – whitespace after the slash will result in tricky errors

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.';

Good – use string concatenation instead

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.';

ITCS-JSC-04 Proper use of curly braces

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 }

ITCS-JSC-05 Proper use of Array and Object initializers

Single-line array and object initializers are allowed when they fit on a line:

Single-line initializers

1 var arr = [1, 2, 3]; // No space after [ or before ].


2 var obj = {a: 1, b: 2, c: 3}; // No space after { or before }.

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 };

ITCS-JSC-06 Use single quotes for string literals

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;

Private properties and methods should be named with a trailing underscore.

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.

Single line comments

1 someStatement();
2
3 // Explanation of something complex on the next line
4 doSomething();

Multi-line comments should be used for long comments

1 /*
2 This is a comment that is long enough to warrant being stretched
3 over the span of multiple lines.
4 */

Code constructs and programming practice


ITCS-JSC-09 Use of nested functions is encouraged

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.

Bad – invalid use of for-in loop

1 for (var key in some_array) {


2 [Link](some_array[key]);
3 }

Good – proper use of for and for-in loops

1 // iterating over array


2 var length = some_array.length;
3
4 for (var i = 0; i < length; i++) {
5 [Link](some_array[i]);
6 }
7
8 // iterating over object properties
9 for (var key in some_object) {
10 if (some_object.hasOwnProperty(key)) {
11 [Link](some_object[key]);
12 }
13 }

ITCS-JSC-11 Do not use associative arrays

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.

Bad – improper use of Array

1 var associative_array = [];


2 associative_array['one'] = 'Lorem';
3 associative_array['two'] = 'Ipsum';
4
5 // associative_array.length will return 0.
Good – use of Object for maps/hash

1 var map = {};


2 map['one'] = 'Lorem';
3 map['two'] = 'Ipsum';

ITCS-JSC-12 Use Array and Object literals instead of Array and Object
constructors

Bad – do not use array and object constructors

1 var array1 = new Array();


2 var array2 = new Array(1, 2, 3);
3
4 var object1 = new Object();
5 var object2 = new Object();
6 object2.a = 0;
7 object2.b = 'some text';

Good – use array and object literals

1 var array1 = [];


2 var array2 = [1, 2, 3];
3
4 var object1 = {};
5 var object2 = {
6 a: 0,
7 b: 'some text'
8 };

ITCS-JSC-13 Avoid ‘eval’

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

1 var serverResult = '{"name":"Alice",email":"looking_glass@[Link]"}';


2
3 var userInfo = eval(serverResult);
4 var email = userInfo['email'];
Good – With [Link], invalid JSON (including all executable JavaScript) will cause an exception to
be thrown

1 var serverResult = '{"name":"Alice",email":"looking_glass@[Link]"}';


2
3 var userInfo = [Link](serverResult);
4 var email = userInfo['email'];

ITCS-JSC-14 Do not modify prototypes of builtin objects

Modifying built-ins like [Link] and [Link] are strictly forbidden.

ITCS-JSC-15 Proper use of equality

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.

Bad – Improper use of abstract equality check

1 var a = 'word1';
2 bar b = 'word2';
3
4 if (a == b) {
5 // do something
6 }

Good – Proper use of strict equality check

1 var a = 'word1';
2 bar b = 'word2';
3
4 if (a === b) {
5 // do something
6 }

ITCS-JSC-16 Type checking

These are the preferred ways of checking the type of an object:


Type checking

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) …

ITCS-JSC-17 Avoid unnecessary Boolean operators to evaluate the truthiness

Take advantage of built-in capabilities and avoid unnecessary Boolean operators to evaluate
truthiness or falseness. Use following examples as a guide:

Conditional evaluation

1 // When only evaluationg that an array has length,


2 // instead of this:
3 if ([Link] > 0) ...
4
5 // ...evaluate truthiness, like this:
6 if ([Link]) ...
7
8 // When only evaluating that an array is empty,
9 // instead of this:
10 if ([Link] === 0) ...
11
12 // ...evaluate truthiness, like this:
13 if (![Link]) ...
14
15 // When only evaluating that a string is not empty,
16 // instead of this:
17 if (string !== '') ...
18
19 // ...evaluate truthiness, like this:
20 if (string) ...
21
22 // When only evaluating that a string _is_ empty,
23 // instead of this:
24 if (string === '') ...
25
26 // ...evaluate falsy-ness, like this:
27 if (!string) ...
28
29 // When only evaluating that a reference is true,
30 // instead of this:
31 if (foo === true) ...
32
33 // ...evaluate like you mean it, take advantage of built in capabilities:
34 if (foo) ...

ITCS-JSC-18 Proper handling of ‘this’ for later invocation

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.

Example of use of bind and aliasing

1 // use of bind() method


2 var showDataVar = [Link](user);
3
4 // use of aliasing
5 var someObject = {
6 processItem: function(item) { // some code },
7 someMethod: function() {
8 var self = this;
9
10 ['1', '2'].forEach(function(item) {
11 [Link](item);
12 });
13 }
14 };

ITCS-JSC-19 Cache and reuse selectors

Always cache selectors when accessing or setting multiple properties on the same object.
Bad – Improper use of abstract equality check

1 [Link]('element1').value = 'some value';


2 [Link]('element1').[Link] = 'black';
3 [Link]('element1').[Link] = 'white';

Good – Proper use of strict equality check

1 var element1 = [Link]('element1');


2 [Link] = 'some value';
3 [Link] = 'black';
4 [Link] = 'white';

ITCS-JSC-20 Do not use inline event handlers

Inline event handlers allows only one event listener to be attached and lead to poorly
organized code.

Bad – inline event handlers

1 <a href="[Link]" onclick="callSomeFunction();"/>

Good – proper use of event listeners

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.

ITCS-JSC-22 Use event delegation

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.

ITCS-JSC-24 Switch Statements

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.

ITCS-HTM-02 Always use DOCTYPE

A proper Doctype which triggers standards mode in your browser should always be used.
Quirks mode should always be avoided.

Bad – DOCTYPE invalid or missing

1 <html>
2 ...
3 </html>
4
5 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
6 "[Link]

Good – use of proper DOCTYPE

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

1 <meta http-equiv="X-UA-Compatible" content="IE=Edge" />

ITCS-HTM-04 Character Encoding

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

1 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Good

1 <meta charset="UTF-8" />

ITCS-HTM-05 Add title element

The <title> element is required in HTML5. Make the title as meaningful as possible

ITCS-HTM-06 Omit type attribute for CSS

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>

ITCS-HTM-07 Omit type attribute for JavaScript

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>

ITCS-HTM-08 Don't mix tags for CSS and JavaScript

Put all CSS links before the script tags.


Bad

1 <script src="/js/[Link]" />


2 <link href="/css/[Link]" rel="stylesheet" />
3 <script src="/js/[Link]" />

Good

1 <link href="/css/[Link]" rel="stylesheet" />


2 <script src="/js/[Link]" />
3 <script src="/js/[Link]" />
ITCS-HTM-09 Use lower case element and attribute names

It’s recommended to always use lowercase element and attribute names.

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>

ITCS-HTM-10 Close All HTML Elements

It’s recommended to always close HTML elements.

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>

ITCS-HTM-11 Close Empty HTML Elements

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

1 <meta charset="utf-8" />


2 …
3 <br />

ITCS-HTM-12 Always define image size

Always define image size. It improves performance and reduces flickering because the
browser can reserve space for images before they are loaded.

Define the image size

1 <img src="[Link]" style="width: 128px; height: 128px;" />

ITCS-HTM-13 Boolean attributes are allowed

A boolean attribute is one that needs no declared value. XHTML required you to declare a
value, but HTML5 has no such requirement.

Attributes without declared value

1 <input type="text" disabled>


2 …
3 <select>
4 <option value="1" selected>1</option>
5 </select>

ITCS-HTM-14 Write one list item per line

Put each list item in a separate line.

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>

ITCS-HTM-15 Escape specific characters

Escape &, <, >, " and ' with named character references.

ITCS-HTM-16 All attributes should be quoted

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.

ITCS-HTM-17 Minimize use of IFRAMEs

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.

ITCS-HTM-18 Use of Custom data attributes

Store custom data in data- attributes.

ITCS-HTM-19 Don’t use tables for page layout

Tables shouldn't be used for page layout.

CSS
ITCS-CSS-01 General coding principles

Follow these general principles when working with CSS files:


• Add CSS through external files, minimizing the # of files, if possible. It should always
be in the HEAD of the document.
• Don't include styles inline in the document, either in a style tag or on the elements.
It's harder to track down style rules.
• Elements that occur only once inside a document should use IDs, otherwise, use
classes.
• Select what you want explicitly, rather than relying on circumstance or coincidence.
• Write selectors for reusability, so that you can work more efficiently and reduce
waste and repetition.
• Do not nest selectors unnecessarily, because this will increase specificity and affect
where else you can use your styles.
• Do not qualify selectors unnecessarily, as this will impact the number of different
elements you can apply styles to.
• Keep selectors as short as possible, in order to keep specificity down and
performance up.

ITCS-CSS-02 Follow the recommended formatting of a ruleset

Be consistent in formatting and use following ruleset anatomy:

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 }

ITCS-CSS-03 Don’t use @import

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.

Bad – don’t use @import

1 <style>
2 @import url("[Link]");
3 </style>
Good – use <link>

1 <link rel="stylesheet" href="[Link]">

ITCS-CSS-04 Don’t qualify ID rules with tag names or classes

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 {…}

ITCS-CSS-05 Avoid the descendant selector

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 treehead treerow treecell {…}

Better, but still bad

1 treehead > treerow > treecell {…}


Good

1 .treecell-header {…}

ITCS-CSS-06 Use Pixels instead of Ems

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.

ITCS-CSS-08 Class Names

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 { ... }

ITCS-CSS-09 Use Specific Classes When Necessary

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

1 section aside h1 em { ... }

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.

ITCS-XML-02 Document formats should be expressed using W3C XML Schemas

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.

ITCS-XML-03 Use of namespaces is required

Element names must be in a namespace, except when extending pre-existing document


types that do not use namespaces. A default namespace should be used.

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.

ITCS-XML-05 Mixed content is not allowed

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).

ITCS-XML-06 Use of grouping elements is encouraged

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.

ITCS-XML-07 Order of attributes should be irrelevant

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.

ITCS-XML-08 Use no more than 10 attributes per element

Elements should not be overloaded with too many attributes. Instead, use child elements to
encapsulate closely related attributes.

ITCS-XML-09 Do not store whitespace-sensitive values in 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.

ITCS-XML-10 Binary data should be Base64 encoded

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.

Representation of XML instances


ITCS-XML-11 Declare namespaces on the root element

Namespaces should be declared in the root element of a document wherever possible.


The mapping of namespace URIs to prefixes should remain constant throughout the
document, and should also be used in documentation of the design.

Well-known prefixes such as html: (for XHTML) and xs: (for XML Schema) should be used
for standard namespaces.

ITCS-XML-12 Proper use of whitespace

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.

ITCS-XML-13 Use any format for empty elements

Empty elements may be expressed as empty tags or a start-tag immediately followed by an


end-tag. No distinction should be made between these two formats by any application.

ITCS-XML-14 Allow both quotes and apostrophes for attribute values

Attribute values may be surrounded with either quotation marks or apostrophes.


Specifications must not require or forbid the use of either form. &apos; and &quot; may be
freely used to escape each type of quote.

ITCS-XML-15 Proper use of comments

Comments must not be used to carry real data.

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.

Comments should have whitespace following <!-- and preceding -->.

C#
ITCS-CSH-01 Naming Conventions and Style

• Use Pascal casing for type and method names and constants:

Pascal casing for types, methods and constants

1 public class SomeClass


2 {
3 const int DefaultSize = 100;
4
5 public SomeMethod()
6 {}
7 }

• Use camel casing for local variable names and method arguments.

Camel casing for local variables and arguments

1 int number;
2
3 void MyMethod(int someNumber)
4 {}

• Prefix interface names with I

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_.

Private member variables

1 public class SomeClass


2 {
3 private int m_Number;
4 }

• Suffix custom attribute classes with Attribute.


• Suffix custom exception classes with Exception.
• Name methods using verb-object pair, such as ShowDialog().
• Methods with return values should have a name describing the value returned, such
as GetObjectState().
• Local variables should be declared as close as possible to their first use.
• Use descriptive variable names.
o Avoid single character variable names, such as i or t. Use index or temp
instead.
o Do not abbreviate words (such as num instead of number).
• This naming convention can be relaxed for several specific types of local variable:
o Streams (“in” or “out” are usually used)
o Loop counters (single letters can be used, most often “i”, “j” and “k”)
o Exceptions (“e” or “ex” are usually used for generic exception)
• Fields that are collections (e.g. vectors, arrays) should be given names that are plural
to indicate that they represent multiple values.
• Avoid names that sound like sentences, like NumberOfRecords, rather use RecordNumber.
• Names of the methods must describe what their purpose is. If you can't describe it in
the name, it's a badly written function. For example, GetItem should only get the item
not create it as well, for that purpose rather use ProvideItem. Use the verb Safe where
there is no way the method could throw an exception, like SafeDeleteItem.
• Do not duplicate a reserved keyword, for example: int string = 2;
• “Name hiding” (declaring local variable with same name as one of the classes’ fields,
or a parameter name) should be avoided. Exception to this can occur in setters and
constructors.
• Do not use underscore in class names.
• Even though Microsoft suggests using Hungarian notation for static members, do not
use Hungarian notation or names that describe identifiers type related to specific
language! Stick to the meaning of the identifier, not its type. Not all languages have
the same types so doubleValue could mean one thing in C# and other in VB, choose
rather a generic name like value. The only exceptions are the visual web or standard
controls. For them, you should use the abbreviated type name suffix, for example:
txtName, lblCompany and chkDeleteFiles.
• Always use C# predefined types rather than the aliases in the System namespace.
For example:

• object NOT Object


• string NOT String
• int NOT Int32

• With generics, use capital letters for types. Reserve suffixing Type when dealing with
the .NET type Type.

Avoid

1 public class LinkedList<KeyType,DataType>


2 {...}

Correct

1 public class LinkedList<K,T>


2 {...}

• 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;

• Use delegate inference instead of explicit delegate instantiation.

Delegates

1 delegate void SomeDelegate();


2 public void SomeMethod()
3 {...}
4
5 SomeDelegate someDelegate = SomeMethod;
6

• 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

1 public class MyClass


2 {
3 int m_Number;
4 string m_Name;
5
6 public void SomeMethod1()
7 {}
8
9 public void SomeMethod2()
10 {}
11 }

• A file name should reflect the class it contains.


• When using partial types and allocating a part per file, name each file after the logical
part that part plays. For example:

File naming

1 //In [Link]
2 public partial class MyClass
3 {...}
4
5 //In [Link]
6 public partial class MyClass
7 {...}

• Always place an open curly brace ({) in a new line.


• With anonymous methods, mimic the code layout of a regular method, aligned with
the anonymous delegate declaration. (complies with placing an open curly brace in a
new line):

Good

1 public void InvokeMethod()


2 {
3 SomeDelegate someDelegate = delegate(string name)
4 {
5 [Link](name);
6 };
7 someDelegate("Juval");
8 }

Bad

1 public void InvokeMethod()


2 {
3 SomeDelegate someDelegate = delegate(string
4 name){[Link](name);};
5 someDelegate("Juval");
}
• Use empty parentheses on parameter-less anonymous methods. Omit the
parentheses only if the anonymous method could have been used on any delegate:

Good

1 SomeDelegate someDelegate1 = delegate()


2 {
3 [Link]("Hello");
4 };

Bad

1 SomeDelegate someDelegate1 = delegate


2 {
3 [Link]("Hello");
4 };

ITCS-CSH-02 Coding Practices

• Avoid putting multiple classes in a single file.


• Unit Tests: Every method you write should be tested. The best way is to provide a
small testing method or a whole class that simulate a working environment and than
call the method. Name these classes starting with "Test". If you change the method,
you must test it again.
• Every line of code should be walked through in a “white box” testing manner.
• A single file should contribute types to only a single namespace. Avoid having
multiple namespaces in the same file.
• Avoid files with more than 500 lines (excluding machine-generated code).
• Avoid methods with more than 25 lines.
• Avoid methods with more than 5 arguments. Use structures for passing multiple
arguments.
• Lines should not exceed 80 characters.
• Do not manually edit any machine-generated code.
o If modifying machine generated code, modify the format and style to match
this coding standard.
o Use partial classes whenever possible to factor out the maintained portions.
• With the exception of zero and one, never hard-code a numeric value; always declare
a constant instead.
• Use the const directive only on natural constants such as the number of days of the
week.
• Avoid using const on read-only variables. For that, use the readonly directive.

Const vs. readonly


1 public class MyClass
2 {
3 public const int DaysInWeek = 7;
4 public readonly int Number;
5
6 public MyClass(int someValue)
7 {
8 Number = someValue;
9 }
10 }

• Assert every assumption.

Assert

1 using [Link];
2 object GetObject()
3 {...}
4 object someObject = GetObject();
5 [Link](someObject != null);

• Catch only exceptions for which you have explicit handling.


• In a catch statement that throws an exception, always throw the original exception
(or another exception constructed from the original exception) to maintain the stack
location of the original error:

Re-throw

1 catch(Exception exception)
2 {
3 [Link]([Link]);
4 throw; //Same as throw exception;
5 }

• Avoid error code as method return values.


• Avoid defining custom exception classes.
• When defining custom exceptions:
o Derive the custom exception from Exception.
o Provide custom serialization.
• Avoid multiple Main() methods in a single assembly.
• Make only the most necessary types public, mark others as internal.
• Avoid friend assemblies, as they increase inter-assembly coupling.
• Avoid code that relies on an assembly running from a particular location.
• Minimize code in application assemblies (EXE client assemblies). Use class libraries
instead to contain business logic.

• Avoid providing explicit values for enums.

Good

1 public enum Color


2 {
3 Red, Green, Blue
4 }

Bad

1 public enum Color


2 {
3 Red = 1, Green = 2, Blue = 3
4 }

Avoid specifying a type for an enum.

Bad

1 public enum Color : long


2 {
3 Red, Green, Blue
4 }

• Always use a curly brace scope in an if statement, even if it conditions a single


statement.
• Avoid using the trinary conditional operator.

• 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 {...}

• Always use zero -based arrays.


• Always explicitly initialize an array of reference types using a for loop.

Array initialization

1 const int ArrraySize = 100;


2
3 MyClass[] array = new MyClass[ArrraySize];
4
5 for(int index = 0; index < [Link]; index++)
6 {
7 array[index] = new MyClass();
8 }

• Do not provide public or protected member variables. Use properties instead.


• Avoid using the new inheritance qualifier. Use override instead.
• Always mark public and protected methods as virtual in a non-sealed class.
• Never use unsafe code, except when using interop.
• Avoid explicit casting. Use the as operator to defensively cast to a type.

Defensive cast

1 Dog dog = new GermanShepherd();


2 GermanShepherd shepherd = dog as GermanShepherd;
3 if (shepherd != null)
4 {...}

• Always check a delegate for null before invoking it.


• Do not provide public event member variables. Use event accessors instead.

Event accessors

1 public class MyPublisher


2 {
3 MyDelegate m_SomeEvent;
4 public event MyDelegate SomeEvent
5 {
6 add
7 {
8 m_SomeEvent += value;
9 }
10 remove
11 {
12 m_SomeEvent -= value;
13 }
14 }
15 }

• Avoid defining event-handling delegates. Use EventHandler<T> or


GenericEventHandler instead. GenericEventHandler is defined in Chapter 6 of
Programming .NET Components 2nd Edition.
• Avoid raising events explicitly. Use EventsHelper to publish events defensively.
EventsHelper is presented in Chapter 6-8 of Programming .NET Components 2nd
Edition.
• Always use interfaces. See Chapters 1 and 3 in Programming .NET Components 2nd
Edition.
• Classes and interfaces should have at least 2:1 ratio of methods to properties.
• Avoid interfaces with one member.
• Strive to have three to five members per interface.
• Do not have more than 20 members per interface. Twelve is probably the practical
limit.
• Avoid events as interface members.
• When using abstract classes, offer an interface as well.
• Expose interfaces on class hierarchies.
• Prefer using explicit interface implementation.
• Never assume a type supports an interface. Defensively query for that interface.

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

1 int number = SomeMethod();


2 switch(number)
3 {
4 case 1:
5 [Link]("Case 1:");
6 break;
7 case 2:
8 [Link]("Case 2:");
9 break;
10 default:
11 [Link](false);
12 break;
13 }

• Do not use this reference unless invoking another constructor from within a
constructor.

Proper use of ‘this’

1 public class MyClass


2 {
3 public MyClass(string message)
4 {}
5
6 public MyClass() : this("Hello")
7 {}
8 }

• 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.

Proper use of ‘base’

1 public class Dog


2 {
3 public Dog(string name)
4 {}
5
6 virtual public void Bark(int howLong)
7 {}
8 }
9
10 public class GermanShepherd : Dog
11 {
12 public GermanShepherd(string name): base(name)
13 {}
14
15 override public void Bark(int howLong)
16 {
17 [Link](howLong);
18 }
19 }

• Do not use [Link]().


• Do not rely on HandleCollector.
• Implement Dispose() and Finalize() methods based on the template in Chapter 4 of
Programming .NET Components 2nd Edition.
• Always run code unchecked by default (for the sake of performance), but explicitly in
checked mode for overflow- or underflow-prone operations:

Proper use of ‘checked’

1 int CalcPower(int number,int power)


2 {
3 int result = 1;
4
5 for(int count = 1; count <= power; count++)
6 {
7 checked
8 {
9 result *= number;
10 }
11 }
12 return result;
13 }

• Avoid explicit code exclusion of method calls (#if…#endif). Use conditional methods
instead:

Conditional methods

1 public class MyClass


2 {
3 [Conditional("MySpecialCondition")]
4 public void MyMethod()
5 {}
6 }

• Avoid casting to and from [Link] in code that uses generics. Use constraints
or the as operator instead:

Good

1 class MyClass<T> where T : SomeClass


2 {
3 void SomeMethod(T t)
4 {
5 SomeClass obj = t;
6 }
7 }

Bad

1 class MyClass<T>
2 {
3 void SomeMethod(T t)
4 {
5 object temp = t;
6 SomeClass obj = (SomeClass)temp;
7 }
8 }

• Do not define constraints in generic interfaces. Interface level-constraint can often be


replaced by strong-typing.

Good

1 public interface ICustomerList : IList<Customer>

Bad

1 public interface IList<T> where T : Customer

• Do not define method-specific constraints in interfaces.


• Do not define constraints in delegates.
• If a class or a method offers both generic and non generic flavors, always prefer
using the generics flavor.
• When accessing unmanaged code, you should implement the IDisposable interface to
finalize the unmanaged code or find some other way to maintain resources.
• Do not create instances of visual classes (Forms, Controls) in a thread.
• For singleton classes or the classes that have a default instance make a method called
exactly GetInstance that will return this instance.
• When implementing a generic interface that derived from an equivalent non-generic
interface (such as IEnumerable<T>), use explicit interface implementation on all
methods, and implement the non-generic methods by delegating to the generic ones:

Implementing generic interface

1 class MyCollection<T> : IEnumerable<T>


2 {
3 IEnumerator<T> IEnumerable<T>.GetEnumerator()
4 {...}
5
6 IEnumerator [Link]()
7 {
8 IEnumerable<T> enumerable = this;
9 return [Link]();
10 }
11 }

ITCS-CSH-03 Project Settings and Project Structure

• Always build your project with warning level 4


• Treat warnings as errors in the Release build (note that this is not the default of
Visual Studio). Although it is optional, this standard recommends treating warnings as
errors in Debug builds as well.
• Avoid suppressing specific compiler warnings.
• Always explicitly state your supported runtime versions in the application
configuration file.

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 explicit custom version redirection and binding to CLR assemblies.


• Avoid explicit preprocessor definitions (#define). Use the project settings for defining
conditional compilation constants.
• Do not put any logic inside [Link].
• Do not put any assembly attributes in any file besides [Link].
• Populate all fields in [Link] such as company name, description, and
copyright notice.
• All assembly references in the same solution should use relative path.
• Disallow cyclic references between assemblies.
• Avoid multi-module assemblies.
• Avoid tampering with exception handling using the Exception window
(Debug|Exceptions).
• Strive to use uniform version numbers on all assemblies and clients in the same
logical application (typically a solution). Use the [Link] technique from
Chapter 5 of Programming .NET Components 2nd Edition to automate.

ITCS-CSH-04 [Link] and Web Services

• 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.

Wrapping of the session variables

1 public class Calculator : WebService


2 {
3 int Memory
4 {
5 get
6 {
7 int memory = 0;
8 object state = Session["Memory"];
9 if (state != null)
10 {
11 memory = (int)state;
12 }
13 return memory;
14 }
15
16 set
17 {
18 Session["Memory"] = value;
19 }
20 }
21
22 [WebMethod(EnableSession=true)]
23 public void MemoryReset()
24 {
25 Memory = 0;
26 }
27 }

• 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.

Wrapping of the session variables

1 public class Calculator : SoapHttpClientProtocol


2 {
3 public Calculator()
4 {
5 CookieContainer = new [Link]();
6 Url = ...;
7 }
8 }

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.

ITCS-GRV-03 Groovy closures do not need to follow K&R braces formatting.

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 }

ITCS-GRV-04 Return keyword is optional

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 }

In such case explicitly using return yields better readability.

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 }

ITCS-GRV-05 Def and type

In Groovy you can use both def and type in declaration.

Good

1 String name = "Frodo"


2 def anotherName = "Bilbo"

But def is redundant here. So make a choice, either use def or a type.

Avoid

1 def String name = "Sauron"

When defining a method with untyped parameters, you can use def but it’s not needed, so
we omit them.

Good

1 void doSomething(param1, param2) {


2 // some code...
3 }

Avoid

1 void doSomething(def param1, def param2) {


2 // some code...
3 }

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 }

ITCS-GRV-06 Methods and classes are public by default

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

1 public class Server {


2 public String toString() {
3 return "a server"
}
}

ITCS-GRV-07 Omitting parentheses on method calls

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 }

ITCS-GRV-08 Classes as first-class citizens

The .class suffix is not needed in Groovy, a bit like in Java’s instanceof.

Good

1 [Link]("${BASE_URI}/[Link]", params, ResourcesResponse)

Avoid

1 [Link](BASE_URI + "/[Link]", params, [Link])

ITCS-GRV-09 Getters and Setters

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.

ITCS-GRV-10 Initializing beans with named parameters and the default


constructor

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

ITCS-GRV-11 Using with() for repeated operations on the same bean

Groovy adds with() method on all objects.

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]()

ITCS-GRV-12 Use strong typing in API methods

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.

[2] S. McConnell, Code Complete: A Practical Handbook of Software Construction, Second


Edition, Redmond: Microsoft Press, 2004.

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

[6] "C# Coding Conventions," Microsoft, [Online]. Available:


[Link]

[7] "Secure Coding Guidelines," Microsoft, [Online]. Available:


[Link]

[8] "The Java EE 6 Tutorial," Oracle, [Online]. Available:


[Link]

[9] T. Nurkiewicz, "10 Tips for Proper Application Logging," [Online]. Available:
[Link]

[10] "Groovy Language Documentation" , Apache, [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.

Beginning with the prose form of the name:

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:

Prose form lowerCamelCase UpperCamelCase Incorrect

XML HTTP request xmlHttpRequest XmlHttpRequest XMLHTTPRequest

new profile ID newProfileId NewProfileId newProfileID

Supports IPv6 supportsIpv6 SupprotsIpv6 supportsIPv6

NeeS publisher neesPublisher NeesPublisher NeeSPublisher

eCTD backbone ectdBackbone EctdBackbone eCTDBackbone

HTML MedDRA browser htmlMeddraBrowser HtmlMeddraBrowser HtmlMedDRABrowser


HtmlMedDraBrowser

YouTube importer youTubeImporter YouTubeImporter youtubeImporter

You might also like