Chapter 10: Coding - PowerPoint PPT Presentation

1 / 25
About This Presentation
Title:

Chapter 10: Coding

Description:

The choice of the programming language can be a difficult one. ... and failure to synchronise file storage may cause work to be garbled or lost. ... – PowerPoint PPT presentation

Number of Views:39
Avg rating:3.0/5.0
Slides: 26
Provided by: christop139
Category:

less

Transcript and Presenter's Notes

Title: Chapter 10: Coding


1
Chapter 10 Coding
  • 10.1 Introduction
  • Not to be confused with design !
  • A programmers role is to respect the design
    document
  • Should be a straightforward phase!
  • The choice of the programming language can be a
    difficult one.
  • Care must be taken in the choice of the compiler
    / programming environment
  • 10.2 Abstract Data Type (ADT)
  • See modular design and the notion of information
    hiding.
  • See Data Structures And Algorithm subject.
  • 10.2.1 Information Hiding
  • The decision to use an ADT with information
    hiding must have been taken during design.
  • The choice of ADT must already have been made
    during design.

2
  • At coding time only considerations relating to
    the implementation of the ADT should be looked
    at.
  • Some languages are better suited for ADT
    implementation (e.g. OO languages, Ada, Pascal
    with extensions) than others (e.g. C)

3
  • Example of an ADT and abstract data type in Ada
    95
  • Ada is a strongly typed large superset of Pascal
    incorporating Object Oriented and Concurrent
    Programming
  • E.g. a Stack of Integers date type implemented
    using an array
  • Max constant 100
  • S array (1..Max) of Integer
  • Top Integer range 0 .. Max
  • We would also need a number of subprograms
  • procedure PushX(X Integer) is
  • begin
  • Top Top 1
  • S(Top) X
  • end Push
  • function Pop return Integer is
  • begin
  • Top Top - 1

4
  • The above is a typical implementation in simple
    block structured language (e.g. C, Pascal)
  • Giving access to the subprograms Push and Pop
    also gives direct access to the stack via the
    variables S and Top
  • In effect, an undisciplined programmer could use
    S and Top directly without referring to Push and
    Pop
  • We have no information hiding here, the integrity
    of the stack cannot be ensured in traditional
    programming languages such as C or Pascal
  • Better is to enforce information hiding and put a
    'wall' around our stack and specify a proper
    interface for it. In Ada it means using a Package
    (in an OO programming language it means using a
    class).
  • Here is our stack interface
  • package Stack is
  • procedure Push(X Integer)
  • function Pop return Integer
  • end Stack
  • This interface is visible from the rest of the
    application (outside the Stack package)

5
  • Of course we must also provide the internals of
    the Stack package
  • package body Stack is
  • Max constant 100
  • S array (1..Max) of Integer
  • Top Integer range 0 .. Max
  • procedure PushX(X Integer) is
  • begin
  • Top Top 1
  • S(Top) X
  • end Push
  • function Pop return Integer is
  • begin
  • Top Top - 1
  • return S(top 1)
  • end Pop
  • begin

6
  • The way the stack is implemented is hidden from
    the outside this is the notion of information
    hiding.
  • This approach has many benefits
  • reduces complexity (local to the package)
  • easier to test (one package at a time)
  • easier to debug (no error propagation)
  • easier to maintain (as long as the interface
    remains unchanged we can change the internals of
    a package without having to change anything else)
  • more logical (who cares how the stack is
    implemented?)
  • For medium to large projects using information
    hiding is a necessity.
  • You can only "pretend" to do the same thing in C.
  • In Java or C, all attributes should declared as
    private to the class, and a clear public
    interface must be provided.

7
  • 10.2.2 More Abstract
  • Imagine that as well as a stack of integers our
    application also needs a stack of medical
    records, of personal records of different sizes
    etc.
  • It would be tiresome and less reliable to define
    3 similar modules (packages in Ada) one for each
    type of stack.

8
  • Some programming languages allow the definition
    of really abstract data types.
  • Templates in C
  • Generics in Ada
  • In our Ada example
  • generic
  • Max Integer
  • type Item is private
  • package Stack is
  • procedure Push(X Item)
  • function Pop return Item
  • end Stack
  • package body Stack is
  • S array (1..Max) of Item
  • Top Integer range 0 .. Max
  • ... etc. as before but with
  • ... Integer replaced by Item
  • end Stack
  • We can now use this truly Abstract Data Type for
    all our stacks of a particular size and type
  • package Stk1 is new Stack(100, Integer)

9
  • The Push and Pop subprograms are said to be
    overloaded (different interpretations depending
    on the types of their arguments).
  • This solution is clearly much better than having
    3 times the same code !
  • In effect we have implemented a stack of
    absolutely anything in general that can be
    re-used many times.
  • This technique has many benefits, including
  • economy of effort
  • more reliable
  • re-enforce reuse
  • more logical
  • 10.2.3 Conclusion on ADTs
  • Information hiding and ADTs in general make for
    better programming.
  • It is better style.

10
  • 10.3 Programming Languages
  • From a software engineering point of view some
    programming languages are better than others.
  • A programming language that allows a program to
    do whatever he/she wishes is dangerous.
  • It is important to differentiate between a
    programming language official definition and
    compiler vendors interpretations. E.g. Borland
    C is not compatible with Microsofts C and
    they are both different to the official
    definition of C!!
  • C, because it is a superset of C share many of
    the shortcomings of C.
  • Better languages close to C, include Java and C
    (aka C Sharp).

11
  • 10.3.1 Strong Typing Characteristic
  • Is the ability of a programming language to
    forbid the use of values or variables in improper
    contexts.
  • In a strongly typed language each variable has a
    type and type matching is enforced by the
    compiler. (e.g. "type mismatch" error in Pascal)
  • So for example adding a character and an integer
    together makes no sense in a strongly typed
    language the code will not compile.
  • C is not strongly typed, it is possible to
    configure a C compiler not to complain when type
    mismatch occurs.

12
  • In fact it is possible to compile a C program
    where functions are called with the wrong number
    of arguments !
  • The C philosophy is that programmers know best.
    From a software engineering point of view this
    cannot be assumed we prefer strongly typed
    language such Java, Pascal or Ada.
  • If you are stuck with C
  • set your compiler to give full warnings and
    eliminate those warning from your code
  • always provide the project file or at least
    indicate the compiler's option used to produce
    the executable
  • 10.3.2 User-defined Types
  • Instead of declaring everything as int or float
    define your own types and perform type checking.
  • If you are stuck with C
  • use typedef as much as possible
  • do your own type checking or use an auxiliary tool

13
  • E.g. using C, in
  • typedef float Money
  • typedef int AccountNumber
  • Money total
  • AccountNumber account
  • ...
  • total total account
  • ...
  • There is an obvious type mismatch as adding
    Money with AccountNumber is meaningless. This
    error will not be detected by any C compiler, so
    use an auxiliary tool such as lint (see later).
  • 10.3.3 Abstract Data Type
  • See 10.2.
  • Cannot be enforced in C.
  • Use C, Java, C, Ada or Pascal with extensions
    instead
  • If you are stuck with C
  • be disciplined and respect the spirit of include
    files
  • put comments in your code to indicate how to use
    your ADTs.

14
  • 10.3.4 Run-Time Checking
  • Run-time errors are violations of the language
    definition during execution of a program.
  • For example, array bounds violation or division
    by 0 usually generate a run-time error.
  • Stray pointers are also the cause of many
    run-time errors.
  • Your programs should of course be free of
    run-time errors
  • not always easy to check
  • What happens after a run time error occurs
    depends on your programming language
  • In C release mode typically nothing happens until
    the operating system itself detects the error or
    crashes.
  • In C debug mode the compiler adds run-time
    checking code to catch those errors and generate
    appropriate messages at run-time.
  • Other languages do provide exception handling
    facilities where the programmer can indicate what
    is to be done if a run-time error occurs.

15
  • If you are stuck with C, use defensive
    programming
  • add your own code to e.g. every time you divide
    check the denominator is not zero, check your
    pointers are initialised before using them.
  • 10.3.5 More Defensive Programming
  • Some situations are not supposed to happen at
    run-time (e.g. run-time errors) but can
    nevertheless be checked in your code just in
    case.
  • So
  • add extra code for run-time checks as seen
  • always provide a default case in your switch
    statements (even if it is to log the fact that
    something unexpected has occurred, and carry on
    as normal)
  • use assertions
  • Assertions are specific run-time checks,
    expressed using the values of program variables
    at a particular point in the program.

16
  • e.g.
  • if (door_open speed gt 0)
  • / assertion failure ! /
  • Emergency_stop_luas
  • Log_error(Luas_state)
  • Shut_down_luas
  • The above should never happen, but the expect the
    unexpected principle means that it is covered
    using an assertion which is a kind of defensive
    programming.
  • 10.3.6 C Pre-processor Macros
  • In C pre-processors macros can be used to
  • define constants (useful), e.g. define BUFSIZ
    1023
  • attempt to do information hiding, e.g.
  • define PutItIn(x)
  • (HideItHideIt0(x))
  • So using PutItIn as a function instead of the
    HideIt array means that the way the information
    is stored can be hidden. But this cannot be
    enforced by C compilers.
  • do many complex and clever things (not useful as
    it prevents easy code comprehension during
    maintenance)
  • Most languages do not need pre-processor macros
    the same facilities are instead part of the
    language.

17
  • 10.3.7 Programming Environment and Libraries
  • Nowadays, most programmers use an Integrated
    Development Environment (IDE) rather than line
    command compilers.
  • make sure you spend time learning the environment
  • Also, a good knowledge of the standard libraries
    is necessary
  • C libraries
  • Object-Oriented class library (MFC, JDK etc.)
  • For OO languages repositories of standard classes
    (e.g. for ADTs, Sorting etc.) can be purchased.
  • 10.3.8 Programming Pitfalls
  • Every language has its dangerous or confusing
    features.
  • In C
  • pointers are both confusing and dangerous
  • using instead of
  • assuming the precedence of operators instead of
    using parenthesis for certainty.

18
  • 10.3.9 A Perfect Programming Language?
  • From a software engineering point of view almost
    anything (assembly) but C will be an improvement.
  • Notably, in my order of increasing preference
  • C (too complex, still allows C)
  • Pascal (no modern standard)
  • Ada (not widely used)
  • Java/C
  • In particular Java has the following advantages
  • supports information hiding
  • has large libraries of reusable classes
  • is strongly typed
  • catches run-time errors
  • automatic memory management (garbage collection)
  • portable code
  • If you are stuck with C
  • be disciplined
  • use external checking tools
  • stick to a safer subset (e.g. MISRA C)

19
  • 10.4 Support Tools for Programming
  • Increasingly integrated in powerful programming
    environments
  • 10.4.1 Language Analyser LCLint
  • Targeted for C programs, known as Lint
  • Many variants exists notably Splint (University
    of Virginia, Department of Computer Science
    http//www.splint.org/) free for Linux and
    Windows.
  • Splint is a tool for statically checking C
    programs for security vulnerabilities and coding
    mistakes.
  • Splint does many of the traditional lint checks
    including unused declarations, type
    inconsistencies, use before definition,
    unreachable code, ignored return values,
    execution paths with no return, likely infinite
    loops, and fall through cases.
  • More powerful checks are made possible by
    additional information given in source code
    annotations.

20
  • Annotations are stylized comments that document
    assumptions about functions, variables,
    parameters and types.
  • In addition to the checks specifically enabled by
    annotations, many of the traditional lint checks
    are improved by exploiting this additional
    information.
  • Problems detected by Splint include
  • Dereferencing a possibly null pointer
  • Using possibly undefined storage or returning
    storage that is not properly defined
  • Type mismatches, with greater precision and
    flexibility than provided by C compilers
  • Violations of information hiding
  • Memory management errors including uses of
    dangling references and memory leaks
  • Dangerous aliasing
  • Modifications and global variable uses that are
    inconsistent with specified interfaces
  • Problematic control flow such as likely infinite
    loops, fall through cases or incomplete switches,
    and suspicious statements
  • Buffer overflow vulnerabilities

21
  • Dangerous macro implementations or invocations
  • Violations of customized naming conventions
  • A typical example would be

22
  • Other C language analysers exists for C such as
    PC-List from Gimpel (http//www.gimpel.com/)
    worth checking out if a C program is causing you
    problems.
  • Advice
  • use these tools from the first line of code
    written if you can
  • your code will be more robust if you use them
  • they can save you hours of debugging time
  • 10.4.2 Utilities
  • Simple things like daily backups protected as
    read only are really useful (Windows XP backup
    utility is fine)
  • Grep (Unix) searches allow to quickly find a
    string in many files (useful for variable names
    etc.) e.g.
  • grep tmp_str .c will search all .c files for the
    variable named tmp_str

23
  • Compare files using the diff utility (see above)
  • especially useful to compare a current version
    with a backup version to see what has changed
  • http//www.prestosoft.com/ps.asp?pageedp_examdiff
    pro

24
  • Version-control tools such as the Unix cvs are
    very important for large projects involving many
    programmers
  • extensively used for open-source software
    development (e.g. see Linux)
  • they allows users to keep track of all the
    versions of a file in a central repository and
    retrieve files easily.
  • An alternative to CVS is Subversion (Open Source)
  • Version control comes into its own when more than
    one person is working on a file. Without version
    control, multiple file users face the potential
    problem of conflicting editing and failure to
    synchronise file storage may cause work to be
    garbled or lost.
  • A good editor is http//www.editplus.com/

25
  • 10.5 Conclusion
  • Coding is about respecting the design, this is
    especially true on real projects where many
    programmers will code the same project.
  • Many tools exist to help coding.
  • Programmers should always choose the solution
    that is the cleanest and the simplest.
Write a Comment
User Comments (0)
About PowerShow.com