Coding
The coding is the process of transforming the design of a system into a computer language
format. This coding phase of software development is concerned with software translating
design specification into the source code. It is necessary to write source code & internal
documentation so that conformance of the code to its specification can be easily verified.
Coding is done by the coder or programmers who are independent people than the designer.
The goal is not to reduce the effort and cost of the coding phase, but to cut to the cost of a later
stage. The cost of testing and maintenance can be significantly reduced with efficient coding.
Goals of Coding
1. To translate the design of system into a computer language format: The coding is
the process of transforming the design of a system into a computer language format,
which can be executed by a computer and that perform tasks as specified by the design
of operation during the design phase.
2. To reduce the cost of later phases: The cost of testing and maintenance can be
significantly reduced with efficient coding.
3. Making the program more readable: Program should be easy to read and understand.
It increases code understanding having readability and understandability as a clear
objective of the coding activity can itself help in producing more maintainable software.
Structured Programming
In structured programming, we sub-divide the whole program into small modules so that the
program becomes easy to understand. The purpose of structured programming is to linearize
control flow through a computer program so that the execution sequence follows the sequence
in which the code is written. The dynamic structure of the program than resemble the static
structure of the program. This enhances the readability, testability, and modifiability of the
program. This linear flow of control can be managed by restricting the set of allowed
applications construct to a single entry, single exit formats.
We use structured programming because it allows the programmer to understand the program
easily. If a program consists of thousands of instructions and an error occurs then it is
complicated to find that error in the whole program, but in structured programming, we can
easily detect the error and then go to that location and correct it. This saves a lot of time.
Structured programming (SP) is a technique devised to improve the reliability and
clarity of programs. In SP, control of program flow is restricted to three structures,
sequence, IF THEN ELSE, and DO WHILE, or to a structure derivable from a
combination of the basic three. Thus, a structured program does not need to use GO
TOs or branches (unless it is written in a language that does not have statement
forms corresponding to the SP structures, in which case, GO TOs may be used to
simulate the structures). The result is a program built of modules that are highly
independent of each other. In turn, this allows a programmer to be more confident
that the code contains fewer logic errors and will be easier to debug and change in
the future. However, SP may be less efficient than an unstructured counterpart.
Another disadvantage is the relative difficulty of using SP with a language that
doesn’t support it.
Coding Standards and Guidelines
.
Writing an efficient software code requires a thorough knowledge of programming.
This knowledge can be implemented by following a coding style which comprises
several guidelines that help in writing the software code efficiently and with minimum
errors. These guidelines, known as coding guidelines, are used to implement
individual programming language constructs, comments, formatting, and so on. These
guidelines, if followed, help in preventing errors, controlling the complexity of the
program, and increasing the readability and understandability of the program.
Coding guidelines should state how to deal with the existing code when the software
incorporates it or when maintenance is performed.
Since there are numerous programming languages for writing software codes, each
having different features and capabilities, coding style guidelines differ from one
language to another. However, there are some basic guidelines which are followed in
all programming languages. These include naming conventions, commenting
conventions, and formatting conventions.
There are certain rules for naming variables, functions and methods in the software
code. These naming conventions help software; developers in understanding the use of
a particular variable or function. The guidelines used to assign a name to any variable,
function, and method are listed below.
• All the variables, functions, and methods should be assigned names that make the
code more understandable to the reader. By using meaningful names, the code
can be self-explanatory, thus, minimizing the effort of writing comments for
variables. For example, if two variables are required to refer to ‘sales tax’ and
‘income tax’, they should be assigned names such as ‘sales Tax’ and ‘income Tax’.
• For names, a full description in a commonly spoken language (for example,
English) should be used. In addition, the use of abbreviations should be avoided.
For example, variable names like ‘contact Number’ and ‘address’ should be used
instead of ‘cno’ and ‘add’.
• Short and clear names should be assigned in place of long names. For ‘example,
‘multiply The Two Numbers’ can be shortened to ‘multiply Numbers’ as it is clear
and short enough to be expressed in reasonable length.
In every programming language, there is a different naming convention for variables
and constants in the software code. The commonly used conventions for naming
variables and constants are listed in Table.
Table Naming Conventions for Variables and Constants
Variable Naming Conventions Constant Naming Conventions
The variable names should be in camel All the names of constants should be in
case letters starting with a lower case upper case. In case the name of
letter. For example, use ‘total Amount’ constant is too long, it should be
instead of ‘Total Amount’. separated by an underscore. For
example, sales tax rate should be
written as ‘SALES_TAX_RATE’.
The temporary storage variables that The use of literal should be avoided.
are restricted to a segment of code Literal numbers such as ’15’used in the
should be short. For example, the software code confuses the reader.
variable ‘temp’ can be used for a These numbers are counted as integers
temporary variable. It is important to and result in wrong output of the
note that a single temporary variable program. However, the numbers ‘0’
should not be reused in the same and ‘1’ can be used as constants.
program. For example, variables ‘i’, j’, or
‘k’ are declared while using loops.
The use of numbers in naming
variables should be avoided. For
example, ‘first Number’ should be used
instead of ‘number1’.
As with variables and constants, there are some guidelines that should be followed
while naming functions in the software code. These conventions are listed below.
• The names of functions should be meaningful and should describe the purpose of
the function with clarity and briefness. Like variables, the names should be self-
explanatory so that no additional description about the task of that function is
required.
• The function name should begin with a verb. For example, the verb ‘display’ can be
used for the function that displays the output on the screen. In case the verb itself
is not descriptive, an additional noun or adjective can be used with the verb. For
example, the function name ‘add Marks’ should be used to clarify the function and
its purpose.
• In case the function returns a Boolean value, the helping verbs ‘is’ and ‘has’ should
be used as prefixes for the function name. For example, the function name ‘is
Deposited’ or ‘has Deposited’ should be used for functions that return true or false
values.
Comments are helpful in proper understanding of the code segment used in program.
Commenting conventions should be used efficiently to make the code easy to grasp.
Generally, two types of commenting conventions are used: file header comments and
trailing comments.
File header comments are useful in providing information related to a file as a whole
and comprise identification information such as date of creation, Dame of the creator,
and a brief description of the software code.
Trailing comments are used to provide explanation of a single line of code. These
comments are used to clarify the complex code. These also specify the function of the
abbreviated variable names that are not clear. In some languages, trailing comments
are used with the help of a double slash (//). The commenting conventions that are
commonly followed in the software code are listed below.
• Comments should not be used to include information that is clearly
understandable from the software.
• Comments should be used with important segments of code and code segments
that are difficult to understand.
• Comments should be separated from the code to enhance readability of the
software code.
Formatting (way of arranging a program in order to enhance readability) consists of
indentation, alignment, and use of white spaces in the program. Consistency plays an
important role while formatting a program in an organized way. A program with
consistent formatting makes the code easier to read and understand. The commonly
used formatting conventions are listed below.
• Indentation: This refers to one or more spaces left at the beginning of statements
in the program. Indentation is useful in making the code easily readable. However,
the spaces used for indentation should be followed in the entire program.
o Indentation should be used to highlight a nested block. Some nested
blocks can be made with the help of ‘if-else’ and ‘do-while’ loops.
o Indentation is required if the statement is large enough to fit in a single
line.
o Indentation should be consistent at the beginning and at the end of the
braces in the program.
• White spaces: These improve readability by minimizing the compactness of the
code. Some of the guidelines for proper usage of spaces within the code are listed
below.
• There should be a space after placing a comma between two function arguments.
• There should be no space between a function name and parenthesis.
• There should be spaces to align the operators vertically to emphasize program
structure and semantics.
Modern Programming Language Features
Readability: A good high-level language will allow programs to be written in some methods
that resemble a quite-English description of the underlying functions. The coding may be done
in an essentially self-documenting way.
Portability: High-level languages, being virtually machine-independent, should be easy to
develop portable software.
Generality: Most high-level languages allow the writing of a vast collection of programs, thus
relieving the programmer of the need to develop into an expert in many diverse languages.
Brevity: Language should have the ability to implement the algorithm with less amount of code.
Programs mean in high-level languages are often significantly shorter than their low-level
equivalents.
Error checking: A programmer is likely to make many errors in the development of a computer
program. Many high-level languages invoke a lot of bugs checking both at compile-time and
run-time.
Cost: The ultimate cost of a programming language is a task of many of its characteristics.
Quick translation: It should permit quick translation.
Efficiency: It should authorize the creation of an efficient object code.
Modularity: It is desirable that programs can be developed in the language as several
separately compiled modules, with the appropriate structure for ensuring self-consistency
among these modules.
Widely available: Language should be widely available, and it should be feasible to provide
translators for all the major machines and all the primary operating systems.
A coding standard lists several rules to be followed during coding, such as the way variables are
to be named, the way the code is to be laid out, error return conventions, etc.
Type Checking
Type checking is the process of verifying and enforcing the constraints of types, and it can
occur either at compile time (i.e. statically) or at runtime (i.e. dynamically). Type checking is all
about ensuring that the program is type-safe, meaning that the possibility of type errors is kept
to a minimum. A type error is an erroneous program behavior in which an operation occurs on
a particular data type that it’s not meant to occur on. This could be a situation where an
operation is performed on an integer with the intent that it is a float, or even something such as
adding a string and an integer together:
When a program is considered not type-safe, there is no single standard course of action that
happens upon reaching a type error. Many programming languages throw type errors
which halt the runtime or compilation of the program, while other languages have built-in safety
features to handle a type error and continue running . the process of type checking is a
necessity.
Type checking is a program analysis that verifies something about the types that are used in
the program.
The purpose of type checking is to guarantee type safety.
Type checking could happen at compile-time or at run-time.
There is two types of type checking:
1. Static type checking
2. Dynamic type checking
Static Type Checking
A language is statically-typed if the type of a variable is known at compile time instead of at
runtime. Common examples of statically-typed languages include Ada, C, C++, C#, JADE, Java,
Fortran, Haskell, ML, Pascal, and Scala.
The big benefit of static type checking is that it allows many type errors to be caught early in the
development cycle. Static type checkers evaluate only the type information that can be
determined at compile time, but are able to verify that the checked conditions hold for all
possible executions of the program, which eliminates the need to repeat type checks every time
the program is executed.
for example, in Java
int age = 20;
It is performed at compile time.
Dynamic Type Checking
Dynamic type checking is the process of verifying the type safety of a program at runtime.
Common dynamically-typed languages include Groovy, JavaScript, Lisp, Lua, Objective-C, PHP,
Prolog, Python, Ruby, Smalltalk and Tcl.
Most type-safe languages include some form of dynamic type checking, even if they also have a
static type checker. In contrast to static type checking, dynamic type checking may cause a
program to fail at runtime due to type errors. Dynamic type checking typically results in less
optimized code than does static type checking; it also includes the possibility of runtime type
errors and forces runtime checks to occur for every execution of the program (instead of just at
compile-time).
For example, in Python
age = 20;
It is performed at run time.
User-Defined DataTypes
The data types that are defined by the user are called the derived datatype or user-
defined derived data type.
• Class
• Structure
• Union
• Enumeration
• Typedef defined DataType
1. Class: The building block of all Object-Oriented programming is a Class. It is a user-
defined data type, which holds its own data members and member functions, which can be
accessed and used by creating an instance of that class. A class is like a blueprint for an
object.
Syntax:
Example:
#include <bits/stdc++.h>
using namespace std;
class Geeks {
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname()
{
cout << "Geekname is: " << geekname;
}
};
int main()
{
// Declare an object of class geeks
Geeks obj1;
// accessing data member
[Link] = "GeeksForGeeks";
// accessing member function
[Link]();
return 0;
}
Output:
Geekname is: GeeksForGeeks
2. Structure: A structure is a user defined data type. A structure creates a data type that can
be used to group items of possibly different types into a single type.
Syntax:
struct address {
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
3. Union: Like Structures, union is a user defined data type. In union, all members share the
same memory location. For example in the following C program, both x and y share the
same location. If we change x, we can see the changes being reflected in y.
#include <iostream>
using namespace std;
// Declaration of union is same as the structures
union test {
int x, y;
};
int main()
{
// A union variable t
union test t;
// t.y also gets value 2
t.x = 2;
cout << "After making x = 2:"
<< endl
<< "x = " << t.x
<< ", y = " << t.y
<< endl;
// t.x is also updated to 10
t.y = 10;
cout << "After making Y = 10:"
<< endl
<< "x = " << t.x
<< ", y = " << t.y
<< endl;
return 0;
}
4. Output:
5. After making x = 2:
6. x = 2, y = 2
7. After making Y = 10:
8. x = 10, y = 10
[Link]: Enumeration (or enum) is a user defined data type in C. It is mainly used to
assign names to integral constants, the names make a program easy to read and maintain.
Syntax:
enum State {Working = 1, Failed = 0};
// Program to demonstrate working
// of enum in C++
#include <iostream>
using namespace std;
enum week { Mon,
Tue,
Wed,
Thur,
Fri,
Sat,
Sun };
int main()
{
enum week day;
day = Wed;
cout << day;
return 0;
}
Output:
2
[Link] : C++ allows you to define explicitly new data type names by using the keyword
typedef. Using typedef does not actually create a new data class, rather it defines a name for
an existing type. This can increase the portability(the ability of a program to be used across
different types of machines.
Syntax:
typedef type name;
Example:
// C++ program to demonstrate typedef
#include <iostream>
using namespace std;
// After this line BYTE can be used
// in place of unsigned char
typedef unsigned char BYTE;
int main()
{
BYTE b1, b2;
b1 = 'c';
cout << " " << b1;
return 0;
}
Output:
Data Abstraction
Data abstraction is one of the most essential and important feature of object oriented
programming. Abstraction means displaying only essential information and hiding the
details. Data abstraction refers to providing only essential information about the data to
the outside world, hiding the background details or implementation.
Consider a real life example of a man driving a car. The man only knows that pressing
the accelerators will increase the speed of car or applying brakes will stop the car but he
does not know about how on pressing accelerator the speed is actually increasing, he
does not know about the inner mechanism of the car or the implementation of
accelerator, brakes etc in the car. This is what abstraction is.
Exception Handling
Exceptions are run-time anomalies or abnormal conditions that a program encounters
during its execution. There are two types of exceptions
try: represents a block of code that can throw an exception.
catch: represents a block of code that is executed when a particular exception is thrown.
throw: Used to throw an exception. Also used to list the exceptions that a function throws,
but doesn’t handle itself.
Following are main advantages of exception handling over traditional error handling.
1) Separation of Error Handling code from Normal Code: In traditional error handling
codes, there are always if else conditions to handle errors. These conditions and the
code to handle errors get mixed up with the normal flow. This makes the code less
readable and maintainable. With try catch blocks, the code for error handling becomes
separate from the normal flow.
2) Functions/Methods can handle any exceptions they choose: A function can throw many
exceptions, but may choose to handle some of them. The other exceptions which are
thrown, but not caught can be handled by caller. If the caller chooses not to catch them,
then the exceptions are handled by caller of the caller.
3) Grouping of Error Types: both basic types and objects can be thrown as exception.
We can create a hierarchy of exception objects, group exceptions in namespaces or
classes, categorize them according to types.
Concurrency Mechanism
Concurrency is the execution of the multiple instruction sequences at the same time.
It happens in the operating system when there are several process threads running in
parallel. The running process threads always communicate with each other through
shared memory or message passing. Concurrency results in sharing of resources result
in problems like deadlocks and resources starvation.
It helps in techniques like coordinating execution of processes, memory allocation and
execution scheduling for maximizing throughput.
Principles of Concurrency :
Both interleaved and overlapped processes can be viewed as examples of concurrent
processes, they both present the same problems.
The relative speed of execution cannot be predicted. It depends on the following:
• The activities of other processes
• The way operating system handles interrupts
• The scheduling policies of the operating system
Problems in Concurrency :
• Sharing global resources –
Sharing of global resources safely is difficult. If two processes both make use of a
global variable and both perform read and write on that variable, then the order iin
which various read and write are executed is critical.
• Optimal allocation of resources –
It is difficult for the operating system to manage the allocation of resources
optimally.
• Locating programming errors –
It is very difficult to locate a programming error because reports are usually not
reproducible.
• Locking the channel –
It may be inefficient for the operating system to simply lock the channel and
prevents its use by other processes.