Technical Writing - Definition of Bad and Good Code



Similar documents
Code Refactoring and Defects

CS 241 Data Organization Coding Standards

Software Engineering Techniques

The Rules 1. One level of indentation per method 2. Don t use the ELSE keyword 3. Wrap all primitives and Strings

PL / SQL Basics. Chapter 3

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

No no-argument constructor. No default constructor found

CS 111 Classes I 1. Software Organization View to this point:

1 The Java Virtual Machine

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

System Security Fundamentals

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

The programming language C. sws1 1

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Data Structure with C

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Good FORTRAN Programs

The C Programming Language course syllabus associate level

Moving from CS 61A Scheme to CS 61B Java

Developing for the App Store. (Legacy)

Syntax Check of Embedded SQL in C++ with Proto

Chapter 5. Recursion. Data Structures and Algorithms in Java

Stacks. Linear data structures

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Format string exploitation on windows Using Immunity Debugger / Python. By Abysssec Inc

7.1 Our Current Model

ECE 341 Coding Standard

LINKED DATA STRUCTURES

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

1 Abstract Data Types Information Hiding

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

DATA STRUCTURE - STACK

Secure Programming with Static Analysis. Jacob West

INFORMATION MANAGEMENT AND WHY IT MATTERS. CIO Research Report 2014

Chapter 7D The Java Virtual Machine

Objectives. Chapter 2: Operating-System Structures. Operating System Services (Cont.) Operating System Services. Operating System Services (Cont.

Chapter 5 Names, Bindings, Type Checking, and Scopes

The course assumes successful completion of CSCI E-50a and CSCI E-50b, i.e. at least two semesters of programming, with a grade of C- or better.

CS106A, Stanford Handout #38. Strings and Chars

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

CS193j, Stanford Handout #10 OOP 3

3rd Edition, June standards/ecma-334.htm.

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

recursion, O(n), linked lists 6/14

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

Computer Programming C++ Classes and Objects 15 th Lecture

TECHNICAL UNIVERSITY OF CRETE DATA STRUCTURES FILE STRUCTURES

So we thought we knew money

Course Title: Software Development

CISC 181 Project 3 Designing Classes for Bank Accounts

Objects for lexical analysis

How To Write Portable Programs In C

Designing and Writing a Program DESIGNING, CODING, AND DOCUMENTING. The Design-Code-Debug Cycle. Divide and Conquer! Documentation is Code

Getting Started with Kanban Paul Klipp

Analysis of a Search Algorithm

Jonathan Worthington Scarborough Linux User Group

Logistics. Software Testing. Logistics. Logistics. Plan for this week. Before we begin. Project. Final exam. Questions?

Module 10. Coding and Testing. Version 2 CSE IIT, Kharagpur

Chapter 1: Key Concepts of Programming and Software Engineering

Chapter 12 Programming Concepts and Languages

What mathematical optimization can, and cannot, do for biologists. Steven Kelk Department of Knowledge Engineering (DKE) Maastricht University, NL

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

Common Data Structures

Stack Allocation. Run-Time Data Structures. Static Structures

Programming in Access VBA

Chapter 7: Software Development Stages Test your knowledge - answers

A deeper look at Inline functions

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

Version control tracks multiple versions. Configuration Management. Version Control. V Software Engineering Lecture 12, Spring 2008

Research Data Management CODING

Lecture 6: Semaphores and Monitors

Linux Driver Devices. Why, When, Which, How?

Lecture 10: Dynamic Memory Allocation 1: Into the jaws of malloc()

Sources: On the Web: Slides will be available on:

3 Hands-on Techniques for Managing Operational Change in HRIS Projects

Semantic Analysis: Types and Type Checking

csce4313 Programming Languages Scanner (pass/fail)

Unit Testing & JUnit

Interpreters and virtual machines. Interpreters. Interpreters. Why interpreters? Tree-based interpreters. Text-based interpreters

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Software development and programming. Software

Buffer Overflows. Code Security: Buffer Overflows. Buffer Overflows are everywhere. 13 Buffer Overflow 12 Nov 2015

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Lessons Learned from Tool Adoption 1

Object Oriented Software Design II

Adapting C++ Exception Handling to an Extended COM Exception Model

Symbol Tables. Introduction

Monitors, Java, Threads and Processes

each college c i C has a capacity q i - the maximum number of students it will admit

Abstraction in Computer Science & Software Engineering: A Pedagogical Perspective

Lecture 9. Semantic Analysis Scoping and Symbol Table

Chapter 24 - Quality Management. Lecture 1. Chapter 24 Quality management

APPROACHES TO SOFTWARE TESTING PROGRAM VERIFICATION AND VALIDATION

british council behaviours

Transcription:

1 Workshop on Distributed Software Management for e-science Day 2 - Software Design Lecture 4 Code Design Basics Geoff Cawood Consultant, EPCC Telephone: +44 131 650 5120 Email: geoffc@epcc.ed.ac.uk 4Low complexity in software the problem of keeping it low as coding progresses 4Bad code: ugly, inefficient, interdependent 4Interdependency major cause of complexity explosion 4Encapsulation a crucial weapon in the fight against complexity low level and high level 4Conclusions Lecture Overview 2

2 Before Coding 4System Design should have ensured the following: 4Reasonable level of detail can t design forever 4High intersection what features there are should be common to a good final item 4High merit low complexity (of what detail we have) low difficulty of use main features of the user interface should have been planned low runtime and space main data structures and algorithms should have been planned 3 4 The Code Design Challenge 4Complexity can explode as detail increases 4 The more code you add, the worse things get the scrambled egg phenomenon bad code starts to appear in the short term it s the easy option get even worse code when you build on top of that 4What s the solution? identify and tackle bad code before it cripples the project 4What is bad code? intersection detail merit

3 What is Bad Code? 4Regardless of whether the code behaves correctly, it can still be bad in a number of ways and lead to scrambled egg 41. Ugliness or sloppiness 42. Inefficiency 43. Interdependency 5 1. Ugly or Sloppy Code 4No comments or poor comments (Day 1) 4Cryptic naming 4Messy layout inconsistent indentation or spacing 4Huge functions more than half a page is probably too long 4Makes it very difficult for anyone else to extend or debug the code 6

4 The Cure 4Decide on coding style guidelines up front 4Can identify problems just by looking at the code 4Tidy it up according to the guidelines 7 4Passing large arguments by value copies the data unnecessarily 4Data duplication same data stored in multiple parts of the program synchronisation overheads 4Poorly designed algorithms e.g. lots more searching than necessary e.g. calculating the same thing repeatedly 2. Inefficient Code 8

5 The Cure 4Identify problems by observing performance and profiling (Day 1) 4Design better algorithms 4Measure improvement 9 4Not all dependencies are bad 3. Interdependent Code if a function calls other functions, that s good! building functions out of lower-level functions keeps bugs down fix the low-level function and all its callers become fixed too 4Nasty dependencies in programs: code dependent on data being in a certain state code dependent implicitly on other code char** buffer = new char*[45]; // Creates an array of 45 string pointers. void printbuffer() { for (int i = 0; i < 45; i++) // Assumes that the size of the array is 45. 10

6 Dependencies 4Nasty dependencies can be very hard to identify by their implicit nature makes them sinister 4Nasty dependencies are very bad for a project a change can cause major ripple effects in the software leads to unreliability makes extension very difficult can destroy your schedule and your project! 4Examples then solutions 11 Dependency Examples 4Convention dependency positive account numbers belong to individuals, negative ones belong to companies get lots of these sprinkled through the code if (order.accountnumber < 0) then else... if you change the convention somewhere, have to change it everywhere conventions may not be obvious (implicit) 12

7 Dependency Examples 4Implementation Dependency dealing with raw data structures introduces dependencies on the current implementation int* rainfallseq; // Array of ints. int raininmarch = rainfallseq[2]; client code depends on the rainfall sequence being an array a real pain if you decide to use a linked list to store the rainfall sequence 13 Dependency Examples 4Behaviour dependency if two functions are expected to have some aspect of their behaviour in common, then that aspect had better stay the same void printnames() { // Print out all the names. for (int i = 0; i < numpeople; i++) { printf( Name is %s \n, names(i)); void printnameandage(int i) { // Print out the name and age of // the person at the argument index. printf( Name is %s \n, names(i)); printf( Age is %d \n, ages(i)); 14

8 Dependencies 4A single dependency on its own may not look very threatening but if you let them proliferate, things go downhill rapidly 4What s the cure? 15 The Cure 4Encapsulation the grouping of related ideas into one unit, which can thereafter be referred to by a single name 4Group related software elements (code and/or data) that have some common purpose or destiny 4Group so that: dependencies are collected together inside encapsulation boundaries dependencies across encapsulation boundaries are minimised 16

9 Some Benefits of Encapsulation 4Small parts are combined into a larger whole which has meaning reduces complexity refer to the whole instead of the parts 4By grouping dependencies inside encapsulation boundaries they become explicit makes them easier to spot and less sinister 4Reduced dependencies across encapsulation boundaries fewer knock-on effects of a code change 17 Low Level Encapsulation 4There are various levels of encapsulation 4Dependency examples seen so far can be cured with low level encapsulation encapsulating a constant into a name encapsulating an idea into a function encapsulating related functions into another function lines of code grouped into a function 18

10 Curing Dependency 4Array example encapsulate the idea of a buffer size with a meaningful name then refer to it explicitly char** buffer = new char*[45]; void printbuffer() { for (int i = 0; i < 45; i++) bufsize = 45 char** buffer = new char*[bufsize]; void printbuffer() { for (int i = 0; i < bufsize; i++) 19 4Convention dependency Curing Dependency positive account numbers belong to individuals, negative ones belong to companies if (order.accountnumber < 0) then else... encapsulate the underlying meaning into a function and refer to it explicitly if (iscompany(order)) then else... 20

11 Curing Dependency 4Implementation Dependency dealing with raw data structures introduces dependencies on the current implementation int* rainfallseq; // Array of ints. int raininmarch = rainfallseq[2]; encapsulate the monthly rainfall concept into a function int* rainfallseq; // Array of ints. int raininmarch = raininmonth(3); int raininmonth(int month) { if (month < 1 or month > 12) then error; return rainfallseq[month - 1]; 21 4Behaviour dependency Curing Dependency void printnames() { // Print out all the names. for (int i = 0; i < numpeople; i++) { printf( Name is %s \n, names(i)); void printnameandage(int i) { // Print out the name and age of // the person at the argument index. printf( Name is %s \n, names(i)); printf( Age is %d \n, ages(i)); as seen earlier, encapsulate the common code into a printname( ) function then call it from both removes code duplication and scope for inconsistency 22

12 Good Low Level Encapsulation 4Naming is important the name of a function should capture the idea being encapsulated the function s comment should capture the programmer s intent 4Avoid dependencies across encapsulation boundaries minimise side-effects of functions or modification of global variables within functions write functions which take arguments rather than reading global variables 23 Code-Data Dependency 4Will low level encapsulation solve all our dependency problems? 4Critically, it doesn t address data protection issues huge source of problems in many programs 4Need higher level encapsulation 24

13 Motivation 4Consider a classic data structure, the stack push pop 4Very useful for bracket matching for example [[[a + b] * 4] + [c * d]] push opening brackets onto the stack pop a bracket each time you discover a closing bracket correct matching if you end with an empty stack 25 Traditional Implementation 4Implemented using an array and a top index array of char stk int top void push(char c) { # Add argument character to the stack. top = top + 1 stk[top] = c char pop() { # Remove top character and return it. if (top < 0) then error char res = stk[top] top = top - 1 return res 26

14 Problems with Public Variables 4What if people are interested in the second-top character? easy, they can just use stk[top - 1] top stk[top - 1] array of char stk 27 Problems with Public Variables 4What if new boy Johnny uses stk[top--] by mistake? stk[top--] top 4He has used the decrement operator (--) so his function will give the right answer (once), but after that the stack is corrupt! 28

15 Problems with Public Variables 4The symptom could appear in one of your functions! 4You may have to go and debug it 4Johnny has messed up your afternoon! 4He hasn t touched a single line of your code, but has still managed to make it misbehave by tampering with public data 29 Too Much Rope 4Why has this waste of time been allowed to happen? 4Programming languages are almost too flexible 4They invite quick dirty hacks to solve small problems quicker to shove in stk[top - 1] than write a function everyone can use 4This approach collapses in larger software complexity becomes unmanageable 4Need to impose additional structure and restrictions 30

16 Private Data 4There is no reason why stk or top should be public to the whole program 4They should be made private to the stack functions make variables accessible only by those functions that have a fundamental right to know about them 4The compiler will complain if an attempt is made to access them from elsewhere Johnny s erroneous modification wouldn t even have compiled 31 Public Interface 4If someone has a legitimate need to know the second-top character, add a function to the public interface char secondtop() { # Return the character which is one below the top one in # the stack, or NULL if there are <=1 characters in the stack. if (top < 1) then return NULL return stk[top - 1] 32

17 High Level Encapsulation 4Means code and data is grouped together into an abstract data type (ADT) 4Data is made private to the functions of the ADT 4Access to the data from outside the ADT is provided via the ADT s public interface functions and data grouped into an ADT 33 Conclusions 4Try to keep complexity low as coding progresses be vigilant against bad code to prevent complexity explosion 4Several types of bad code incorrect code, ugly code, inefficient code, interdependent code 4Interdependency can be the most sinister because of its subtlety and far-reaching effects 4Encapsulation, encapsulation, encapsulation protects against dependencies by making them explicit other benefits: conceptual clarity, reduced scope for bugs etc. low level - grouping lines of code into functions high level - grouping functions and data into ADTs 34

18 References 4For encapsulation and interdependency: Page-Jones, M., Fundamentals of Object-Oriented Design in UML, 2000, Addison-Wesley 35