Presentation is loading. Please wait.

Presentation is loading. Please wait.

INSE - Lecture 10 Programming practice & style u Control constructs u Layout & Names u Initialization.

Similar presentations

Presentation on theme: "INSE - Lecture 10 Programming practice & style u Control constructs u Layout & Names u Initialization."— Presentation transcript:

1 INSE - Lecture 10 Programming practice & style u Control constructs u Layout & Names u Initialization

2 To bear in mind while “ coding ” A key target is readability of the code, because that leads to u understandability; and u learnability.

3 Control Constructs "Those things in the language that determine in which order instructions are obeyed."

4 Control constructs - sub-topics: u “ Stucturedness ” u Linear sequence ("too obvious" - and not much to say anyway); u Loop constructs; u Choice constructs ( if, case / switch, etc.); u Subroutine constructs (?recursive); u Labels and goto ("unstructured"); u Other? (e.g. error-handling; parallelism...)

5 What does “ structured ” mean? 1960's - “ programs must be 'structured'. ” (With at least two inconsistent definitions of the term!) 1970's -(1) “ What's that? ” -- please define it better! (2) It's a straitjacket. -- what forms of structure do we really want? (3) "The 60's doctrine is fine for beginners."

6 Example: u input, skipping spaces, buffering non- spaces: the first character can be either space or non- space: stop at end of input. u Can this be made structured? u Not a chance!

7 “ Structured ” loop constructs u These are “ natural ” loop constructs for many applications, but there are situations where the need goes beyond either of these … e.g....

8 Another “ natural ” loop need: u “ Copy characters from an input file to an output file, up to (but excluding output of) the first ’. ” (Assume there will be a ’ before end of file.)

9 Copy up to but excluding … u That “ naturally ” calls for the flow diagram on the left. u This flow diagram is of a “ N-and-a-half-loop ”. u Note that it is structured in the sense of “ one entry, one exit ”.

10 Coding that in (say) Java - try 1 do // read C if (C!= ’ ) // write C while(C!= ’ ); u The duplicated condition makes it hard to understand u Testing the condition twice each time round the loop is inefficient u Prone to mis- maintenance?

11 Coding that in (say) Java - try 2 // read C while(C!= ’ ) { // write C // read C } u More understand- able? u Safe? u What if the “ read ” is many lines of code? - a maintenance problem...

12 Coding that in (say) Java - try 3 boolean stop=false; while(!stop) { // read C if (C== ’ ) stop = true; else // write C } u Obscures the real flow u Longer than it needs to be u Somewhat inefficient

13 Coding that in (say) Java - try 4 do // read C if (C== ’ ) break; // write C while(true); u Understandable, because it “ says what we mean ” by the N-and-a-half flow diagram u Efficient u Hard to mis- maintain

14 Other special loops... u There are other special design situations calling for special control flows … u … the one on the left is a search loop u it ’ s one-entry one-exit. u It ’ s a special case of...

15 ... u … a multi-exit loop u (still “ one entry, one exit ” )

16 An unavoidable goto - even in Ada procedure Sort(X:Arr) is Old : Element; begin > for I in X ’ First+1..X ’ Last loop if X(I-1) > X(I) then Old:=X(I-1); X(I-1):=X; X(I):=Old; goto Restart; end if; end loop; end Sort;

17 Exceptions

18 Another unstructured situation u … when something in the program goes catastrophically wrong … e.g. –arithmetic overflow or underflow; –over-running the bounds of an array or other fixed-size container; –hitting end-of-file but needing more data from the file; –communications line errors... u Especially for reliable programs – we can ’ t let them crash, or run amok!

19 Where to handle the abort? u Often the handling can only be done many levels of call back from the site of the problem. u So any aborting mechanism needs to be (potentially) back to the call, often repeatedly.

20 Traditional solution u Pass some error flag out of each call; u after every call of every procedure test all flags for all possible kinds of abort until a “ handler ” is met for a particular abort...

21 Problems with that solution u How do we guarantee some handler will be met for every possible abort in every possible call sequence? (especially in a compiled program - i.e. impossible to test exhaustively). u In languages without return, how do we abort from the middle of a procedure? u How do with abort without a value from the middle of a function?...

22 In Ada, C++, Java u The languages provide exceptions … u...with statements to “ raise ” (or “ throw ” ) an exception aborting the current set of instructions … u … there is syntax to “ handle ” (or “ catch ” ) particular exceptions … u … when an exception is raised, it is “ propagated ” out of blocks and calls until a handler is found for it.

23 Subroutines... u … or “ subprograms ” u … or “ procedures and functions ” u … or “ PERFORMable paragraphs and sections ” u … or OO “ methods ” u … or...

24 How functions return their results u Some older languages tended to try return function results without any special syntax - –hard to “ spot ” when reading the program; –sometimes made it possible to exit a function without defining a value.

25 In Ada C++ & Java u an explicit “ return ” instruction to define the result; u if execution tries to leave the function ’ s instructions by “ falling off the end ”, then an exception is raised.

26 Recursion u not often needed - but when it is needed, it can make otherwise-nasty code very simple; u easy when you know the trick - –at the place of a recursive call, think of the call as “ seen from the outside ” - just as you would for a call of any other subroutine. u from the programming units, you should know all about it?

27 Backtracking u for “ brute-force search ” programs

28 Example - in “ extended ” Ada for all I in 1..8 loop -- statements which might include -- instructions like success and -- failure end loop; u Backtracking is build into Prolog as the basis of the flow-of-control mechanism.

29 “ Others ” - many! e.g.... u co-routines for pseudo-parallelism: –really only one program counter - but it “ jumps ” between co-routines (usually at controlled places in the source - e.g. semicolons); u parallelism/concurrency: –multiple program counters in a single program, one per process »problems of synchronization »problems of intercommunication »problems of conflict & deadlock

30 A personal conclusion [but one that many other people came to in the 1970 ’ s] u We need adequate programming language constructs: they should give us the ability to state disciplined structures in forms which are –not concealed; and –understandable.

31 Layout I.e. prudent use of u blank lines; u indentation; u blanks within a line; u placement of comments.

32 Purpose of layout LEGIBILITY! 1/ by separation into “ natural units ” - u usually by blank lines; u visible boundaries to the “ natural unit ” remove one uncertainty when thinking about it; u good for different granularities of “ natural unit ”.

33 Purpose of layout … legibility!! 2/ by drawing attention to “ local structure ” : u usually by indentation; u used to help us see where constructs start & end; u also to see which construct.  for     

34 Purpose of layout … legibility!! 3/ by “ phrasing ” within the line: u e.g. by spaces within the line:  =  - the spaces make it very clear that the line represents an assignment.

35 Consistency of layout It helps to have u rules of thumb; u habits; u “ house style ”. Know when to break the rules: e.g. u rule 1: “ one instruction per line ” ; u rule 2: space either side of the assignment operator “ ; u but int OldA=A;A=B;B=OldA;

36 Postscript to “ layout ” Objective: to help the reader u So consistently-applied rules avoid the reader having to adapt to changing style; u But deviations from the rules might be useful to attract the reader ’ s attention. Having a style is more important than exactly what it is … “ Adding layout and comments later ” is false economy.

37 Names u Choosing them for understandability

38 Names... u … should be thoughtfully chosen to be –as short as possible; but also –to say as much as possible. u … we need to find a trade-off between these usually-conflicting objectives. ?standard abbreviations ? ? influence of the programming language? !! inspiration !!

39 Initialization and... u [Avoiding too-obvious bugs … ]

40 General program form u Many programs & program-components are of form –do some setting up; then –do the real work; then –do some wrapping up. u The setting up is easy to forget … –especially uninitialized variables => bugs; –most especially uninitialized pointer variables.

41 Easy to forget... u The setting up is easy to forget … –especially uninitialized variables => bugs; –most especially uninitialized pointer variables. u The wrapping up ( “ finalization ” ) is very easy to forget … –many diverse and subtle forms of this error … »e.g. omitted CLOSEs on some operating systems.

42 After this lecture (1) u look at the loops in your past programming efforts – –how easy to read were they? –how prone to mis-maintenance? u read the notes – especially –for the problems of coding a search loop; –for choice constructs (un-lectured); –for Boehm-Jacopini theorem (un-lectured).

43 After this lecture (2) u From here out, compare constructs in programming languages you meet for their strengths and weaknesses. u think about your past programming efforts - how good was the layout & naming? u do better in future - thoughtfully!! u be more alert for initialization & finalization issues.

44 u © C Lester

Download ppt "INSE - Lecture 10 Programming practice & style u Control constructs u Layout & Names u Initialization."

Similar presentations

Ads by Google