300 likes | 904 Views
Programming Fundamentals. ECE573: Data Structures and Algorithms Electrical and Computer Engineering Dept. Rutgers University http://www.cs.rutgers.edu/~vchinni/dsa/. Course Overview. Objective To teach you how to program efficiently Prerequisites
E N D
Programming Fundamentals ECE573: Data Structures and Algorithms Electrical and Computer Engineering Dept. Rutgers University http://www.cs.rutgers.edu/~vchinni/dsa/
Course Overview • Objective • To teach you how to program efficiently • Prerequisites • You know the basics of programming in C, C++ or Java • Can write, debug and run simple programs in C/C++/Java, and • Have some simple understanding of object-oriented design
What is a Good Program? • Run correctly • Run in accordance with the specifications • Run efficiently • In minimum time? • Other constraints: Memory use? • How? Use appropriate data structures and algorithms • Algorithm: A precisely specified procedure for solving a problem • Easy to read and understand • Easy to debug • Easy to modify (easy to maintain) • Portability? Focus Software Engineering Building large SW systems Reliable & easy to maintain
Programming Strategies • Modularity • Decompose a program into suitable small modules • Test them before incorporating them into larger modules • Management is simpler • How to partition a large task? Abstraction A high level views of objects or functions Enables us to forget about low level details and concentrate on problems at hand
Example • Truck Manufacturer • Computer to control engine operation Load Sensors Computer CPU Sensor interface Fuel Control Engine Speed Interrupt Handler Memory Air Flow Pedal Position I/O Interface ROM Clock Air Temperature SW
Example • Truck Manufacturer • Computer to control engine operation Load Sensors Computer CPU Sensor interface Fuel Control Engine Speed Interrupt Handler Memory Air Flow Pedal Position I/O Interface ROM Clock Air Temperature “When the accelerator pedal is 50% depressed, air and fuel valves should be opened until the engine speed reaches 2500 rpm”
Example • Transportation Company • Abstract view of a truck • Just a means of transporting goods from point A to point B in the min time allowed by the road traffic etc. • Specifications? • “The truck, when laden with 10 tonnes, shall need no more than 2 Gallons of fuel to travel100 miles when traveling at 60mph” • How it is achieved is irrelevant. Does not matter whether there is a control computer or other gadgets.
Types of Abstraction • Functional Abstraction • Specify a function for a module, i.e., • “This module will sort the items in its input stream into ascending order based on an ordering rule for the items and place them on its output stream” • Structural Abstraction • Known as Object Orientation • Construct software models of the behavior of real world items • Truck manufacturer: • To analyze performance of his vehicle, employs SW model of the control computer • He is only concerned with external behavior of the computer
Objects • Abstract Data Types • Collection of data structure and a collection of functions or procedures which operate on the data structure • Functions & Procedures Methods • Data structure and its methods Class • Instance of a class Object • Objects represent objects in the real world and appear in programs as variables of a type defined by the class • OO additional: Inheritance etc. • Object orientation is a design methodology! • Possible: OO programs using C, Pascal etc. • C++ provide additional compiler support for OO design • This support must be provided by the programmer in non-OO languages OO Terminology
Example: Collections • Collections may be organized in many ways • May use different program structures to represent them • Yet, from an abstract point of view common operations may include • Create Create a new collection • Add Add a new item to a collection • Delete Delete an item from a collection • Find Find an item matching some criterion in the collection • Destroy Destroy the collection
Constructors and Destructors • Constructors and destructors • The create and destroy methods –often called constructors and destructors-often implemented for any abstract data type • Specific applications may require additional methods: • Ex: join two collections • “One of the aims of good program design would be to ensure that additional requirements are easily handled”
Data Structure • Name of a data type – type of objects that belong to the collection class; • typedef struct collection_struct * collection We are defining pointer to a structure We have not specified details of the attributes of the structure We will be able to substitute different data structures for the actual implementation of the collection We can declare objects of type collection
Methods • collection ConsCollection (int max_items, int item_size) • void AddToCollection (collection c, void *item) • void DeleteFromCollection ( collection c, void * itme); • void * FindInCollection (collection c, void *key); • C is not exactly the safest programming language in the sense of the support it provides for the engineering of quality software • As we assumed that our collection object is a pointer to a structure, we assume the object which belongs to the collection are also represented by pointers to data structures • Void * will match any pointer • Void * highlights the deficiencies of C: it doesn’t provide the capability to create generic objects.
Pre- and Post-conditions • Formal specification requires pre- and post-conditions • It is a contract between the object and its client • Pre-conditions: State of the program which the client guarantees will be true before calling any method • Post-conditions: State of the program that the object’s method will guarantee to create for you when it returns • C provides NO FORMAL SUPPORT for this • Use assert function • Express pre-and post conditions as comments with the method definition
Assert: man pages • NAME assert - program verification • SYNOPSIS #include <assert.h> assert(expression) • DESCRIPTION assert() is a macro that indicates expression is expected to be true at this point in the program. If expression is false (0), it displays a diagnostic message on the standard output and exits.
/* Specification for Collection */ typedef struct t_Collection *Collection; Collection ConsCollection( int max_items, int item_size ); /* Construct a new Collection Pre-condition: max_items > 0 Post-condition: returns a pointer to an empty Collection */ void AddToCollection( Collection c, void *item ); /* Add an item to a Collection Pre-condition: (c is a Collection created by a call to ConsCollection) && (existing item count < max_items) && (item != NULL) Post-condition: item has been added to c */
void DeleteFromCollection( Collection c, void *item ); /* Delete an item from a Collection Pre-condition: (c is a Collection created by a call to ConsCollection) && (existing item count >= 1) && (item != NULL) Post-condition: item has been deleted from c */ void *FindInCollection( Collection c, void *key ); /* Find an item in a Collection Pre-condition: c is a Collection created by a call to ConsCollection key != NULL Post-condition: returns an item identified by key if one exists, otherwise returns NULL */
More formal pre- and post-conditions • No duplicates: items with same key cannot be added to the collection
/* Specification of a collection which contains unique items only; Assumes that the items of which the collection is composed supply an ItemKey method which returns the pointer to an identifying key for the item */ typedef struct u_collection_struct *u_collection; u_collection ConsUCollection( int max_items ); /* Construct a new collection Pre-condition: None Post-condition: returns a pointer to an empty collection */ void AddToUCollection( u_collection c, void *item ); /* Add an item to a collection Pre-condition: (c was created by a call to ConsUCollection) && (item != NULL) && (FindInUCollection(c, ItemKey(item))==NULL) Post-condition: FindInUCollection(c, ItemKey(item)) != NULL */
void DeleteFromUCollection( u_collection c, void *item ); /* Delete an item from a collection Pre-condition: (c was created by a call to ConsUCollection) && (item != NULL) && (FindInUCollection(c, ItemKey(item)) != NULL) Post-condition: FindInUCollection(c, ItemKey(item)) == NULL */ void *FindInUCollection( u_collection c, void *key ); /* Find an item in a collection Pre-condition: c is a collection created by a call to ConsCollection key != NULL Post-condition: returns an item identified by key if one exists, otherwise returns NULL */
C conventions • .h file • Specifications which a user or client of the object needs to see – are normally placed in this file with .h suffix to its name • For the collection, we would place the specs in files called collection.h and Ucollection.h • Use Cs #include facility to import them into programs which needed to use them. • .c file • The implementation or body of the class is placed in a file with a .c suffix
Error Handling • Unexpected program failures are a disaster • If an error is fatal i.e., if the program cannot sensibly continue, then the program must be able to “die gracefully” • Inform its user why it died, and • Save as much of the program state as possible • What is an error? • Careful specification of each software component is a requirement • Pre-conditions of a method will specify the states of a system which a method is able to process specify all the acceptable input states • Post-conditions of a method specify the result of processing each acceptable input • Divide the responsibility of the errors
Processing Errors Error to be processed by the constructor for a dynamically allocated object X ConsX( .... ) { X x = malloc( sizeof(struct t_X) ); if ( x == NULL ) { printf("Insuff mem\n"); exit( 1 ); } else ..... } What is the problem?
Processing Errors.. • Error message is cryptic • Little help in locating the cause of the error • At least be “Insuff Mem for X” • Program will simply exit • possibly leaving the system in some unstable, partially updated state • What if the code is built into elaborate GUI program with no provision for “standard output”? • We may have used the code in embedded processor with no way to process an output stream of characters • Use of exit assumes the presence of higher level program such as Unix shell to process the error code • General rule: I/O is non-portable! • Functions like printf will produce error messages on terminal, but where will the messages go if running a GUI program like Netscape
C • Programming – Basics • Input and Output • Structures (Arrays, Pointers, Self-references, Table lookup, typedef, Unions, bit fields etc) • Pointers and arrays • Functions and program structure • Control flow (if-else, loops, break, switch, continue, goto etc) • Types, operators, and expressions Challengers Call by value? External variables? Conditional expression Recursion Initialization Pointers to functions Command-line arguments Register variables Error handling – stderr Formats: Scanf Functions as a data type?
C • Know what is Unix and what is ANSI C • Libraries • <stdio.h>, <string.h>, <math.h>, <stdlib.h>, <assert.h>, <signal.h>,<time.h>, <ctype.h> • Programming- Subtleties • Conversions • Expressions • Declarations • Scope • Preprocessing
C++ • Dynamic memory allocation • Operator: new, delete • Classes • Operator overloading • Exception handling • Friends and protected Class members • #ifndef, #define, and #endif statements
Debugging • Test run produces a result different from the one expected • Some thing wrong with the program • Determine the cause and correct the discrepancy Debugging • How to design test data? HOW TO DEBUG • Logical reasoning • Program trace • Isolate the suspect and trace this part • Debugger • Dos and don’ts • Do not correct errors by creating exceptions • Correcting an error should not create other errors • Incremental testing and debugging • To test multi function program, • begin testing single function that is independent • Introduce other functions one at a time
SW Guidelines • Coding Style • Header files, Comments • Naming variables • Indentation • Compilation • Makefile • Execution • Environment, shell, path • Debugger • Submission Refer to the “Guidelines for Programming Homeworks” document available on the course web page
Next Time • Computational Complexity & Program Performance • Cormen: Chapter 1, 2, 3, 4.1-4.3 • Terminology from Chapters 5 & 6 • Student Talk…Who? To be announced TA and Demo Lab