Comp 468 Lecture Slide Chapter 06 (Coding)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

Chapter 6

Coding

Prepared by: Marta G. (MSc.)


1
Contents
 Introduction: coding
 Programming Principles & Guidelines
◦ Common coding errors
◦ Some Programming Practices
◦ Coding Standards
 Coding process
◦ An Incremental Coding Process
◦ Test Driven Development
◦ Pair Programming
 Verification
◦ Code Inspections
◦ Unit Testing
◦ Static Analysis
◦ Formal Verification
◦ Proving techniques
Coding

 Coding is one of the important, critical and interesting phase of


software development life cycle.
 The goal of the coding or programming activity is to implement
the design in the best possible manner.
 Coding affects testing and maintenance profoundly
◦ As testing and maintenance costs are high, the aim of coding
activity should be to write code that reduces these costs
 Hence, goal should not be to reduce coding cost, but testing and
maintenance cost,
◦ i.e. make the job of tester and maintainer easier

3
Programming Principles & Guidelines
 The main goal of the programmer is to write simple and easy to
read programs with few bugs in it.
 Good programming (producing correct and simple programs)
is a practice independent of the target programming language,
◦ Although well-structured programming languages make the
programmer's job simpler.

4
Coding guidelines
 The following are some representative coding guidelines
✓Do not use a coding style that is too clever or too difficult to
understand.
✓Do not use an identifier for multiple purposes.
✓The code should be well-documented.
✓The length of any function should not exceed 10 source lines
✓Do not use goto statements

5
Common Coding Errors

Syntax errors
 Computer languages have their own specialized grammar
rules. When these rules aren’t followed a syntax error
prevents the application from running.
 Missing semicolons, extra brackets, misspelt instructions,
and misplaced capitals are all examples of a syntax coding
error.
 Syntax errors are among the easiest to find and fix. This is
because your compiler will often give you the location of
the error.
Common Coding Errors….
Logic errors
▪ The hardest type of coding error to locate and fix is the logic
error.
▪ There are no crashes or helpful highlighting to point out the
problem. Instead, the program runs successfully. But behaving
unexpectedly or failing to produce the desired output.
▪ To avoid logic errors, make sure to break your code down into
small, manageable chunks, and test each piece separately before
moving on to the next.
▪ In fact, a logic error caused by miscalculations between American
and English units caused NASA to lose a spacecraft in 1999.
Common Coding Errors….

Runtime errors
 These bugs occur when the code “won’t play nice” with
another computer, even if it worked perfectly fine on the
developer’s own computer.
 This make the application appear unreliable or even
completely broken.
Common Coding Errors….
Compilation errors
 Compilation, the process of converting a high-level
programming language into a lower-level language, takes
place so that the computer can better understand the
language.
 Compilation errors occur when the computer is not able to
make the conversion reliably. This prevents the software
from being launched or tested.
 The best way to avoid a compilation error is to run the
compiler often to get early feedback.so that, you would be
able to spot the errors sooner.
Common Coding Errors….

Semantic errors
 Are mistakes in the meaning of the code.
 For example, you can use the wrong variable name or call
a function with the wrong arguments.
 One way to avoid semantic errors is to use clear,
descriptive variable and function names.
 It is also a good idea to use a linter, which is a tool that
checks your code for semantic errors and other style issues.
Cont..

Memory Leaks
 A Memory Leak is a situation where there are objects
present in the heap that are no longer used, but the
garbage collector is unable to remove them from
memory, and therefore, they're unnecessarily maintained.
 Occurs frequently in the languages which do not have
automatic garbage collection (c, c++)

11
Common Coding Errors…

NULL Dereferencing
 Refers to the act of trying to access or dereference an object
reference that has a null value
 In other word it Occurs when we access a location that points to
NULL
 Improper initialization and missing the initialization in different paths
leads to the NULL reference error

12
Common Coding Errors

Accessing uninitialized memory


 Is the error of accessing uninitialized memory
 Often occurs if data is initialized in most cases, but most cases do
not get covered
 Array index out of bounds, care needs to be taken to see that the
array index values are not negative and do not exceed their
bounds
 Arithmetic exceptions, include errors like divide by zero and
floating point exceptions
 Illegal use of & instead of &&, arises if non short circuit logic
(like & or |) is used instead of short circuit logic (&& or ||)

13
Some Programming Practices
 Control constructs: Use only a few structured constructs (rather
than using a large no of constructs)
 Goto: Use them sparingly, and only when the alternatives are
worse
 Information hiding: Use information hiding
 User-defined types: use these to make the programs easier to
read
 Nesting: Avoid heavy nesting of if-then-else; if disjoint nesting
can be avoided
 Module size: Should not be too large – generally means low
cohesion

14
Some Programming Practices…

 Module interface: make it simple


 Robustness: Handle exceptional situations
 Side effects: Avoid them, where possible
 Empty catch block: always have some default action
rather than empty
 Empty if, while: bad practice
 Correlated parameters: Should check for compatibility

15
Coding Standards Eg: for java
 Naming conventions
◦ Package name should be in lower case (mypackage)
◦ Type names should be nouns and start with uppercase (Day,
DateOfBirth,…)
◦ Variable names should be nouns in lowercase; variables with large
scope should have long names; loop iterators should be i, j, k…
◦ Const names should be all caps
◦ Method names should be verbs starting with lower case (e.g.
getValue())
◦ Prefix is should be used for Boolean methods

16
Coding Standards…

 Files: There are conventions on how files should be named, and


what files should contain, such that a reader can get some idea
about what the file contains.
◦ Source files should have .java extension
◦ Each file should contain one outer class and the name should
be same as file
◦ Line length should be limited to less than 80 columns and
special characters should be avoided. If the line is longer, it
should be continued and the continuation should be made very
clear.

17
Coding Standards…
 Statements
◦ Variables should be initialized where declared in the smallest
possible scope
◦ Declare related variables together; unrelated variables should
be declared separately
◦ Class variables should never be declared public
◦ Loop variables should be initialized just before the loop
◦ Avoid
 Using break and continue in loops
 Avoid executable statements in conditionals
 Avoid using the do… while construct

18
Coding Standards…
 Commenting and layout
◦ Single line comments for a block should be aligned with the code
block
◦ There should be comments for all major variables explaining
what they represent
◦ A comment block should start with a line with just
 /* and end with a line with */
 Layout guidelines focus on how a program should be indented, how
it should use blank lines, white spaces, etc. to make it more easily
readable.
◦ Indentation guidelines are sometimes provided for each type of
programming construct.

19
Coding Process

 Coding starts when specifications for modules from design is


available
 Usually modules are assigned to programmers for coding
 In top-down development, top level modules are developed first;
in bottom-up lower levels modules are developed first.
 For coding, developers use different processes; We now look at
some processes that developers use during coding, or that have
been suggested.

20
An Incremental Coding Process
 The process followed by many developers is;
◦ write the code for the currently assigned module, and when
done,
 perform unit testing on it and fix the bugs found.
 Then the code is checked in the project repository to make it
available to others in the project.
 It is better to do this incrementally: write code for part of
functionality, then test it and fix it, then proceed by adding
further functionality to the code, which is then tested again.
◦ I.e. code is built for a module by coders incrementally

21
22
Test Driven Development
 This coding process changes the order of activities in
coding
 In test driven development, programmer first writes the
test scripts and then writes the code to pass the test
cases in the script.
 A test case or test script is a set of conditions or
variable under which the tester determines whether the
software satisfies requirements and functions properly.
 A test case is a single executable test which a tester
carries out.
 The process of developing test cases can also help find
problems in the requirements or design of an application.

23
Test Driven Development …
 This is done incrementally
 Is a relatively new approach, and is a part of the
extreme programming (XP)
 Responsibility to ensure that all functionality is on test
case design, not coding.

24
25
Pair Programming

 Code is written by pair of programmers rather than


individuals
◦ The pair together design algorithms, data structures,
strategies, etc.
◦ One person types the code, the other actively reviews what is
being typed
◦ Errors are pointed out and together solutions are
formulated
◦ Roles are reversed periodically
◦ Special conditions are likely to be dealt with better
and not forgotten
◦ Ownership and accountability issues are also there
26
Source Code Control and Built
 It is a version control system designed to track changes in source
code and other text files during the development of a piece of
software.
 This allows the user to retrieve any of the previous versions of the
original source code and the changes which are stored.
 Eg: GitHub, Git, Bitbucket etc.
 A tool consists of repository, which is a controlled directory
structure
 The repository is the official source for all the code files
 System build is done from the files in the repository only
 Tool typically provides many commands to programmers

27
Verification
 Once a programmer has written the code for a module, it
has to be verified before it is used by others.
 Here we discuss only verification of code written by a
programmer (system verification is discussed in next
chapter-Testing)
 There are many different techniques; key ones – unit
testing, inspection, and program checking
◦ Program checking can also be used at the system level

28
Unit Testing

 Most often unit testing is done by the programmer himself


 It is the most micro-level of testing performed on a software
 It helps developers verify internal design and logic of the
written code
 It can be implemented every time a piece of code is
modified, allowing issues to be resolved as quickly as
possible
 If incremental coding is being done, then complete unit
testing needs to be automated

29
Unit Testing…
 There are tools available to help
◦ They provide the drivers
◦ Test cases are programmed, with outcomes being
checked in them
◦ I.e. unit testing is a script that returns pass/fail

30
Unit Testing…

 Each test case is a method which ends with some assertions


 If assertions hold, the test case pass, otherwise it fails
 Complete execution and evaluation of the test cases is
automated
 For enhancing the test script, additional test cases can be
added easily

31
Example
Code review
 Code review for a model is carried out after the module is
successfully compiled and all the syntax errors have been
eliminated.
 Code reviews are extremely cost-effective strategies for
reduction in coding errors and to produce high quality code.
 The two types of code review techniques are code
inspection and code walk through.

33
Code Walkthroughs
 A few members of the development team are given the code few
days before the walk through meeting to read and understand
code.
 Each member selects some test cases and simulates execution of
the code by hand (i.e. trace execution through each statement
and function execution).
 The main objectives of the walk through are to discover the
algorithmic and logical errors in the code.
 The members note down their findings to discuss these in a walk
through meeting where the coder of the module is present.

34
Cont..
Some of the guidelines of this review technique are:
 The team performing code walk through should not be
either too big or too small. Ideally 3-7 members.
 Discussion should focus on discovery of errors and not
on how to fix the discovered errors.
 In order to foster cooperation and to avoid the feeling
among engineers that they are being evaluated in the
code walk through meeting, managers should not
attend the walk through meetings.

35
Code Inspections
 The main purpose is to find defects and bugs and meeting is led by
trained moderator
 The Inspections are usually held when code has compiled and a few
tests passed
 Checklists are generally used to focus the attention on defects
 Reviewers have checklist to review the work products
 They record the defect and inform the participants to fix those errors
 The defects identified are documented in a logging list or issue log
and a formal follow-up is carried out

36
Classical errors during inspection
 Use of uninitialized variables.
 Jumps into loops.
 Nonterminating loops.
 Incompatible assignments.
 Array indices out of bounds.
 Improper storage allocation and deallocation.
 Mismatches between actual and formal parameter in procedure calls.
 Use of incorrect logical operators or incorrect precedence among
operators.
 Improper modification of loop variables.
 Comparison of equally of floating point variables, etc.
37
Code quality
Three standard facets:
 Toward measuring and achieving these:
◦ Simplicity: Measure and reduce complexity
◦ Modularity: Measure and reduce coupling
◦ Information hiding: Measure and increase cohesion

38
Thank you for your attention!

You might also like