Coding Techniques: Dept of CSE 5 Sem
Coding Techniques: Dept of CSE 5 Sem
Coding Techniques: Dept of CSE 5 Sem
Introduction
Superior coding techniques and programming practices are hallmarks of a professional
programmer. The bulk of programming consists of making a large number of small choices
while attempting to solve a larger set of problems. How wisely those choices are made depends
largely upon the programmer's skill and expertise.
This document addresses some fundamental coding techniques and provides a collection
of coding practices from which to learn. The coding techniques are primarily those that improve
the readability and maintainability of code, whereas the programming practices are mostly
performance enhancements.
The readability of source code has a direct impact on how well a developer comprehends
a software system. Code maintainability refers to how easily that software system can be
changed to add new features, modify existing features, fix bugs, or improve performance.
Although readability and maintainability are the result of many factors, one particular facet of
software development upon which all developers have an influence is coding technique. The
easiest method to ensure that a team of developers will yield quality code is to establish a coding
standard, which is then enforced at routine code reviews.
Programming Practices
Experienced developers follow numerous programming practices or rules of thumb, which
typically derived from hard-learned lessons. The practices listed below are not all-inclusive, and
should not be used without due consideration. Veteran programmers deviate from these practices
on occasion, but not without careful consideration of the potential repercussions. Using the best
programming practice in the wrong context can cause more harm than good.
To conserve resources, be selective in the choice of data type to ensure the size of a
variable is not excessively large.
Keep the lifetime of variables as short as possible when the variables represent a finite
resource for which there may be contention, such as a database connection.
Keep the scope of variables as small as possible to avoid confusion and to ensure
maintainability. Also, when maintaining legacy source code, the potential for
inadvertently breaking other parts of the code can be minimized if variable scope is
limited.
Use variables and routines for one and only one purpose. In addition, avoid creating
multipurpose routines that perform a variety of unrelated functions.
When writing classes, avoid the use of public variables. Instead, use procedures to
provide a layer of encapsulation and also to allow an opportunity to validate value
changes.
When using objects pooled by MTS, acquire resources as late as possible and release
them as soon as possible. As such, you should create objects as late as possible, and
destroy them as early as possible to free resources.
When using objects that are not being pooled by MTS, it is necessary to examine the
expense of the object creation and the level of contention for resources to determine when
resources should be acquired and released.
Information Hiding
Information hiding for programmers is executed to prevent system design change. If
design decisions are hidden, certain program code cannot be modified or changed. Information
hiding is usually done for internally changeable code, which is sometimes especially designed
not to be exposed. Such stored and derived data is not expounded upon, most generally. Change
resilience of classes and ease of use by client objects are two byproducts of hidden data.
Reduced costs: Coding guidelines are beneficial in reducing the cost incurred on the software
project. This is possible since coding guidelines help in detecting errors in the early stages of
the software development.
Reduced complexity: The written software code can be either simple or complex. Generally, it
is observed that a complex segment of software code is more susceptible to errors than a
segment containing a simple software code. This is because a complex software code reduces
readability as well as understand ability. In addition, the complex software code may be
inefficient in functioning and use of resources.
Reduced hidden costs: Coding guidelines, if adhered to in a proper manner, help to achieve a
high-quality software code. The software quality determines the efficiency of the software.
Software quality is the degree to which user requirements are accomplished in the software
along with conformity to standards.
Code reuse: Using coding guidelines, software developers are able to write a code that is more
robust and create individual modules of the software code. The reason for making separate
code segment is to enable reusability of the modules used in the software.
Structured programming
is a programming paradigm aimed at improving the clarity, quality, and development time of
a computer program by making extensive use of subroutines, block structures, for and while
loopsin contrast to using simple tests and jumps such as the go to statement, which could lead
to "spaghetti code" that is difficult to follow and maintain.
It emerged in the late 1950s with the appearance of the ALGOL 58 and ALGOL 60
programming languages,[1] with the latter including support for block structures. Contributing
factors to its popularity and widespread acceptance, at first in academia and later among
practitioners, include the discovery of what is now known as the structured program theorem in
1966,[2] and the publication of the influential "Go To Statement Considered Harmful" open letter
in 1968 by Dutch computer scientist Edsger W. Dijkstra, who coined the term "structured
programming".
Structured programming is most frequently used with deviations that allow for clearer
programs in some particular cases, such as when exception handling has to be performed.
Control structures
"Sequence"; ordered statements or subroutines executed in sequence.
"Selection"; one or a number of statements is executed depending on the state of the
program. This is usually expressed with keywords such as if..then..else..endif.
"Iteration"; a statement or block is executed until the program reaches a certain state, or
operations have been applied to every element of a collection. This is usually expressed
with keywords such as while, repeat, for or do..until. Often it is recommended that each
loop should only have one entry point (and in the original structural programming, also
only one exit point, and a few languages enforce this).
"Recursion"; a statement is executed by repeatedly calling itself until termination
conditions are met. While similar in practice to iterative loops, recursive loops may be
more computationally efficient, and are implemented differently as a cascading stack.
Code Review
Code review is systematic examination (often known as peer review) of computer source
code. It is intended to find and fix mistakes overlooked in the initial development phase,
improving both the overall quality of software and the developers skills.
The main goals of code review are:
To spot and fix defects early in the process.
Better-shared understanding of the code base as team members learn from each other
Helps to maintain a level of consistency in design and implementation.
Helps to identify common defects across the team thus reducing rework.
Builds confidence of stakeholders about technical quality of the execution.
Uniformity in understanding will help interchangeability of team members in case of
non-availability of any one of them.
A different perspective. Another set of eyes adds objectivity. Similar to the reason for
separating your coding and testing teams, peer reviews provide the distance needed to
recognize problems.
Coding Standards
General coding standards pertain to how the developer writes code. The SISEPG has
come up with a small set of items it feels should be followed regardless of the programming
language being used.
Indentation
Proper and consistent indentation is important in producing easy to read and maintainable
programs. Indentation should be used to:
Emphasize the body of a control statement such as a loop or a select statement
Emphasize the body of a conditional statement
Emphasize a new scope block
A minimum of 3 spaces shall be used to indent. Generally, indenting by three or four
spaces is considered to be adequate. Once the programmer chooses the number of spaces to
indent by, then it is important that this indentation amount be consistently applied throughout the
program
Inline Comments
Inline comments explaining the functioning of the subroutine or key aspects of the
algorithm shall be frequently used. See section 4.0 for guidance on the usage of inline
comments.
Pair programming
Pair programming is an agile software development technique in which two
programmers work together at one workstation. One, the driver, writes code while the other, the
observer or navigator,[1] reviews each line of code as it is typed in. The two programmers switch
roles frequently.
While reviewing, the observer also considers the "strategic" direction of the work, coming up
with ideas for improvements and likely future problems to address. This frees the driver to focus
all of their attention on the "tactical" aspects of completing the current task, using the observer as
a safety net and guide
Pairing variations
Expertexpert
Expertexpert pairing may seem to be the obvious choice for the highest productivity and
can produce great results, but it often yields little insight into new ways to solve
problems, as both parties are unlikely to question established practices.[2]
Expertnovice
Expertnovice pairing creates many opportunities for the expert to mentor the novice.
This pairing can also introduce new ideas, as the novice is more likely to question
established practices. The expert, now required to explain established practices, is also
more likely to question them. However, in this pairing, an intimidated novice may
passively "watch the master" and hesitate to participate meaningfully. Also, some experts
may not have the patience needed to allow constructive novice participation.[11]
Novicenovice
Novicenovice pairing can produce results significantly better than two novices working
independently, although, this practice is generally discouraged
Code Inspection
Code Inspection is the most formal type of review, which is a kind of static testing to
avoid the defect multiplication at a later stage.
The main purpose of code inspection is to find defects and it can also spot any process
improvement if any.
An inspection report lists the findings, which include metrics that can be used to aid
improvements to the process as well as correcting defects in the document under review.
Preparation before the meeting is essential, which includes reading of any source documents to
ensure consistency.
Inspections are often led by a trained moderator, who is not the author of the code.
The inspection process is the most formal type of review based on rules and checklists and makes
use of entry and exit criteria.
It usually involves peer examination of the code and each one has a defined set of roles.
After the meeting, a formal follow-up process is used to ensure that corrective action is completed
in a timely manner.
Where Code Inspection fits in
hierarchies may be rearranged to be more logical and helpful, and perhaps to benefit from
recognized design patterns.
Unit testing
Intuitively, one can view a unit as the smallest testable part of an application. In
procedural programming, a unit could be an entire module, but it is more commonly an
individual function or procedure. In object-oriented programming, a unit is often an entire
interface, such as a class, but could be an individual method.[2] Unit tests are short code
fragments[3] created by programmers or occasionally by white box testers during the
development process. It forms the basis for component testing.[4]
Ideally, each test case is independent from the others. Substitutes such as method stubs,
mock objects,[5] fakes, and test harnesses can be used to assist testing a module in isolation. Unit
tests are typically written and run by software developers to ensure that code meets its design and
behaves as intended.
Because some classes may have references to other classes, testing a class can frequently
spill over into testing another class. A common example of this is classes that depend on a
database: in order to test the class, the tester often writes code that interacts with the database.
This is a mistake, because a unit test should usually not go outside of its own class boundary, and
especially should not cross such process/network boundaries because this can introduce
unacceptable performance problems to the unit test-suite.