Coding Techniques: Dept of CSE 5 Sem

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Coding

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.

Coding Techniques and Programming Practice


Coding Techniques
Coding techniques incorporate many facets of software development and, although they
usually have no impact on the functionality of the application, they contribute to an improved
comprehension of source code. For the purpose of this document, all forms of source code are
considered, including programming, scripting, markup, and query languages.
The coding techniques defined here are not proposed to form an inflexible set of coding
standards. Rather, they are meant to serve as a guide for developing a coding standard for a
Specific software project
The coding techniques are divided into three sections:
Names
Comments
Format

Dept of CSE 5th sem Page 1


Coding

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.

Dept of CSE 5th sem Page 2


Coding

Implementing Coding Guidelines


If coding guidelines are used in a proper manner, errors can be detected at the time of
writing the software code. Such detection in early stages helps in increasing the performance of
the software as well as reducing the additional and unplanned costs of correcting and removing
errors. Moreover, if a well-defined coding guideline is applied, the program yields a software
system that is easy to comprehend and maintain. Some of the coding guidelines that are followed
in a programming language are listed below.
All the codes should be properly commented before being submitted to the review team.
All curly braces should start from a new line.
All class names should start with the abbreviation of each group. For example, AA and CM can
be used instead of academic administration and course management, respectively.
Errors should be mentioned in the following format: [error code]: [explanation]. For example,
0102: null pointer exception, where 0102 indicates the error code and null pointer exception is
the name of the error.
Every 'if statement should be followed by a curly braces even if there exists only a single
statement.
Every file should contain information about the author of the file, modification date, and
version information.
Advantages of Coding Guidelines
Coding guidelines supplement the language standard by defining acceptable and
unacceptable usage of the programming language used. Acceptable usage avoids troublesome
situations while unacceptable usage is conducive to errors or leads to misunderstanding of the
written code. Properly implemented coding guidelines help the developer to limit program
complexity, establish the basis for code review, and guard against compiler and common
programming errors. Other advantages associated with coding guidelines are listed below and
depicted.
Increased efficiency: Coding guidelines can be used effectively to save time spent on gathering
unnecessary details. These guidelines increase the efficiency of the software team while the
software development phase is carried out..

Dept of CSE 5th sem Page 3


Coding

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

Dept of CSE 5th sem Page 4


Coding

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.

Dept of CSE 5th sem Page 5


Coding

Pride/reward. Recognition of coding prowess is a significant reward for many


programmers.
Team cohesiveness. Working together helps draw team members closer. It also provides
a brief respite from the isolation that coding often brings.
The main areas a reviewer is focusing on are as follows:
General Unit Testing
Comment and Coding Conventions
Error Handling
Resource Leaks
Thread Safety
Control Structures
Performance
Functionality
Security

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

Dept of CSE 5th sem Page 6


Coding

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

Dept of CSE 5th sem Page 7


Coding

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

Test-driven development (TDD)


is a software development process that relies on the repetition of a very short
development cycle: Requirements are turned into very specific test cases, then the software is
improved to pass the new tests, only. This is opposed to software development that allows
software to be added that is not proven to meet requirements.

Dept of CSE 5th sem Page 8


Coding

Test-driven development cycle


1. Add a test
In test-driven development, each new feature begins with writing a test. Write a test that
defines a function or improvements of a function, which should be very succinct. To write a test,
the developer must clearly understand the feature's specification and requirements. The
developer can accomplish this through use cases and user stories to cover the requirements and
exception conditions, and can write the test in whatever testing framework is appropriate to the
software environment.
2. Run all tests and see if the new test fails
This validates that the test harness is working correctly, shows that the new test does not
pass without requiring new code because the required behavior already exists, and it rules out the
possibility that the new test is flawed and will always pass. The new test should fail for the
expected reason. This step increases the developer's confidence in the new test.
3. Write the code
The next step is to write some code that causes the test to pass. The new code written at
this stage is not perfect and may, for example, pass the test in an inelegant way. That is
acceptable because it will be improved and honed in Step 5.
At this point, the only purpose of the written code is to pass the test. The programmer must not
write code that is beyond the functionality that the test checks.
4. Run tests
If all test cases now pass, the programmer can be confident that the new code meets the
test requirements, and does not break or degrade any existing features. If they do not, the new
code must be adjusted until they do.
5. Refactor code
The growing code base must be cleaned up regularly during test-driven development.
New code can be moved from where it was convenient for passing a test to where it more
logically belongs. Duplication must be removed. Object, class, module, variable and method
names should clearly represent their current purpose and use, as extra functionality is added..
They benefit from being split and their parts carefully named to improve readability and
maintainability, which will be increasingly valuable later in the software lifecycle. Inheritance

Dept of CSE 5th sem Page 9


Coding

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.

Dept of CSE 5th sem Page 10

You might also like