programming notes sep05

Upload: jawahar

Post on 31-May-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 Programming Notes Sep05

    1/27

    Programming Notes & Advice

    Todd Littell

    22SEP05

  • 8/14/2019 Programming Notes Sep05

    2/27

    Basic Coding Practices

  • 8/14/2019 Programming Notes Sep05

    3/27

    Maintain State Locally//////////// Bad C

    int count = 0;void countTokens(){

    while ()++count;

    }

    //////////// Bad Javapublic class TokenCount{

    public int count;public String token;

    }

    //////////// Good C

    int countTokens(){

    int count = 0while ()

    ++count;return count;

    }//////////// Good Javapublic class TokenCount{

    private int count;private String token;

    public int getCount() { return count; }public void setCount(int cnt){ this.count = cnt; }

    }

  • 8/14/2019 Programming Notes Sep05

    4/27

    Maintain State Locally (2)//////////// Bad C

    typedef struct {int count;char *token;

    } TokenCount;TokenCount tcArray[1000];int tcArraySize = 1000;

    int indexOfToken(char *token)

    {for (int i = 0; i < tcArraySize; i++)

    if (!strcmp(tcArray[i], token))return i;

    return -1;}

    //////////// Good C

    typedef struct {int count;char *token;

    } TokenCount;static TokenCount tcArray[1000];static int tcArraySize = 1000;

    int indexOfToken(TokenCount *array, int

    arraySize, char *token){

    for (int i = 0; i < arraySize; i++)if (!strcmp(array[i], token))

    return i;return -1;

    }

    int main(){int k = indexOfToken(tcArray, tcArraySize,

    argv[1]);}

    Note: Always keep data as local and private as possible. In C++/Java, use private keyword; in Cuse static keyword for any globals. Note #2: Only have globals at the highest level of your program, ifat all.

  • 8/14/2019 Programming Notes Sep05

    5/27

    Be Careful of Side-Effects

    //////////// Bad Javavoid dumpValidAddresses(Set addrSet)

    {

    Iterator it = addrSet.iterator();

    while (it.hasNext())

    {

    Address addr = (Address)it.next();

    if (addr.getCity() == null || addr.getState() ==null)

    it.remove();

    else

    System.out.println(Address: + addr);

    }

    }//////////// Bad C++

    void myProc(Address arr[], int &num)

    {

    for (; num >= 0; --num) ;

    }

    //////////// Good Javavoid dumpValidAddresses(Set addrSet)

    {

    Iterator it = addrSet.iterator();

    while (it.hasNext())

    {

    Address addr = (Address)it.next();

    if (addr.getCity() != null && addr.getState() !=null)

    System.out.println(Address: + addr);

    }

    }

    //////////// Good C++

    void myProc(Address arr[], int num)

    {

    for (; num >= 0; --num) ;

    }

  • 8/14/2019 Programming Notes Sep05

    6/27

    Maintain Consistent Style//////////// Bad C (inconsistent naming)

    void cutBreadHorizontally();void cut_bread_vertically();

    //////////// Bad C (inconsistent naming)

    void cut_bread_horizontally();

    void vertically_cut_bread();

    void cut_bread_with_diagonal();

    //////////// Bad C (inconsistent typing)

    short countTokens();

    void printTokenCount(int count, char *token);

    //////////// Bad C (inconsistent signatures)

    int indexOf(char c, int start);

    int indexOf(int start, char *str);

    //////////// Good C (consistent naming)

    void cutBreadHorizontally();void cutBreadVertically();

    //////////// Good C (consistent naming)

    void cut_bread_horizontally();

    void cut_bread_vertically();

    void cut_bread_diagonally();

    //////////// Good C (consistent typing)

    int countTokens();

    void printTokenCount(int count, char *token);

    // Or

    typedef int count_t;count_t countTokens();

    void printTokenCount(count_t count, );

    //////////// Good C (consistent signatures)

    int indexOf(char c, int start);

    int indexOfchar *str, int start);

  • 8/14/2019 Programming Notes Sep05

    7/27

    Comment when needed//////////// Bad C

    int foo(int *a, int b){

    char *c = (char*)malloc(b);

    int d, e, f=0;

    for (d = 0; d < b; d++)

    {

    if (c[d]) continue;c[d] = 1;

    for (e=a[d]; e-d; e=a[e], c[d]++)

    c[e] = 1;

    f = (c[d] > f? c[d] : f);

    }

    free(c); return f;

    }

    //////////// Good C

    int maxCycleLength(int array[], int sz){

    // visited[] will store 1 if visited; else 0.

    char *visited = (char*)malloc(sz);

    int i, j, max=0;

    for (i = 0; i < sz; i++) // for each array member

    {if (visited[i]) // if visited then skip

    continue;

    visited[i] = 1;

    // for each member in cycle,

    // update visited count.

    for (j=array[i]; j != i; j = array[j], visited[i]++)visited[j] = 1;

    max = (visited[i] > max? visited[i] : max);

    }

    free(visited); return max;

    }

  • 8/14/2019 Programming Notes Sep05

    8/27

    Be Defensive!//////////// Bad C

    int foo(TokenCount *tcArray, int tcArraySize) {for (int i = 0; i < tcArraySize; i++){

    printf( %s %d\n, tcArray[i].token,tcArray[i].count);

    }

    return 0;}

    //////////// Bad Javavoid foo(TokenCount tcArray[]) {

    for (int i = 0; i < tcArray.length; i++) ;}

    //////////// Good C

    #define NO_ERR 0

    #define ERR_INVALID_ARGS -1

    int foo(TokenCount *tcArray, int tcArraySize) {

    if (tcArray == NULL || tcArraySize < 0)

    return ERR_INVALID_ARGS;

    for (int i = 0; i < tcArraySize; i++)

    {

    if (tcArrray[i].name == NULL)

    continue;

    printf( %s %d\n, tcArray[i].token,tcArray[i].count);

    }

    return NO_ERR;

    }//////////// Good Java

    void foo(TokenCount tcArray[]) {

    if (tcArray == null)

    throw new IllegalArgumentException(foo());

    for (int i = 0; i < tcArray.length; i++) ;

    }

  • 8/14/2019 Programming Notes Sep05

    9/27

    Maintain Orthogonality

    //////////// Bad Cvoid searchAndReplace(char *string, char

    oldChr, char newChr);

    //////////// Bad C++

    class DataFileConverter {

    void convert(char *oldFilename, char*newFilename);

    };

    //////////// Bad Java

    class TimerStack {

    void pushCurrentTime();

    Time popTime();}

    class Car {

    boolean startCarAndDriveToStore();

    }

    //////////// Good Cint find(char *string, int pos, char oldChr);

    void replace(char *string, int pos, char newChr);

    //////////// Better C++

    class DataFileConverter {

    void convert(FILE *oldFile, FILE *newFile);void convert(int oldfd, int newfd);

    };

    //////////// Good Java

    class TimerStack {

    void pushTime(Time currTime);

    Time popTime();

    }

    class Car {

    boolean startEngine();

    boolean driveToLocation(Locationdestination);

    }

  • 8/14/2019 Programming Notes Sep05

    10/27

    Think: Reusability

    If a function (method) is more than 30 lines of code, then refactor it!

    If a file contains more than 300-400 lines of code, then refactor it!

    Be able to describe thepurpose of your function in one sentence, and thepurpose of your class(or file) in one paragraph. If it seems complex to you (the programmer) then it is too complex andneeds refactoring.

    WHY?

  • 8/14/2019 Programming Notes Sep05

    11/27

    Be Resource Conscious

    Example #1:

    void foo(char *mystring)

    {

    char *tmpbuf =

    (char*)malloc((strlen(mystring)+1)*sizeof(char));

    // processing happens.

    free(tmpbuf);

    }

    File *gl_infile; // Global input file ptr.

    char *gl_proc_buf; // Global procing buf.

    void init(char *infilename) {

    gl_infile = fopen(infilename, r); // opens inputfile.

    gl_proc_buf = malloc(200);

    }

    void finish() {

    fclose(gl_infile);

    free(gl_proc_buf);

    }

    int main() {

    init(argv[1]);

    // Main processing loop

    finish();

    }

    If an object (or function) opens (or allocates or reserves) a resource, then the same

    object (or function) should release it.

  • 8/14/2019 Programming Notes Sep05

    12/27

    Quick Review Know your language!

    It is possible to write a bad (or good) program in any language. Some simplepractices can go a long way.

    Keep variables (state) as local (private) as possible. Reduces dependencies.

    Maintain a consistent style; not just naming/indentation, but also in how you code.

    Stay away from side-effects, and be explicit about any mutators you may have (i.e. infunction name & in comments).

    Keep your code modular; 30 lines/function; 300 lines/file. KISS.

    Be defensive, not offensive. Increase level of error checking.

    Use common idioms & practices. For example, for defining constants, macros, testingcode, assertion code, etc.

  • 8/14/2019 Programming Notes Sep05

    13/27

    Language Basics

  • 8/14/2019 Programming Notes Sep05

    14/27

    Review of Address Space

    Global Data

    Stack

    Executable Code Text Segment

    Data Segment

    Stack Segment

    Heap

    Unix/Linux Address Space

  • 8/14/2019 Programming Notes Sep05

    15/27

    C Language A level above assembly.

    Still remains the underlying model behind many other languages.

    Procedural language withpass-by-value argument passing.

    Comes with powerful pre-processor (e.g. #include, #define, #if, #ifdef, etc.).

    Separate declarations in header files (.h) from definitions in (.c) source files.

    Pointer arithmetic is not only supported; its encouraged.

    Typing is weaklyenforced; especially with primitives. Anything can be cast into

    anything else, basically.

    Functions can be passed as arguments. Powerful!

    Review variable scope & duration. Review address space partitioning.

  • 8/14/2019 Programming Notes Sep05

    16/27

  • 8/14/2019 Programming Notes Sep05

    17/27

  • 8/14/2019 Programming Notes Sep05

    18/27

  • 8/14/2019 Programming Notes Sep05

    19/27

    Java Language An interpreted, portable Object-Oriented language, withpass-by-value argument passing.

    C++ look-a-like, but Smalltalk semantics.

    Variable are either primitives orobject references! All objects are allocated on heap. Onlyprimitives & references are on stack.

    All methods are virtual(all the time)!

    Built-in garbage collector & memory manager.

    Declaration is not separated from definition. Both go in one source file (.java).

    Pointer arithmetic does not exist, which makes for safer code.

    Typing is stronglyenforced.

    Built-in multi-threading support.

    Review variable scope & duration. Review address space partitioning.

  • 8/14/2019 Programming Notes Sep05

    20/27

    Common Java Idioms Use interface to define constants:

    public interface ProgConstsIF { public final static String DFLT_TMP_PATH = /tmp; }

    Throw RuntimeException for very common exceptions; else define and throw yourown app exception (that is not derived from RuntimeException).

    When the construction & initialization of an object is complex, then a factory methodis often used.

    Example: javax.xml.parsers.DocumentBuilder.parse(InputStream is) :org.w3c.dom.Document;

    Introspection is used often: Example: void foo(Object o) { if (o instanceof String) }

    You must override hashCode() iff you override equals().

  • 8/14/2019 Programming Notes Sep05

    21/27

    I/O Comparison

    Classes:Reader

    Writer

    Classes:

    BufferedReader

    BufferedWriter

    Classes:

    StreamTokenizer

    PrintWriter

    Java

    strm.get()

    strm.put()

    strm.read()

    strm.write()

    strm.get()

    strm.put()

    strm.read()

    strm.write()

    Overloaded>

    C++

    read()/getc()

    write()/putc()

    fread()/fgets()

    fwrite()/fputs()

    fprintf()

    fscanf()

    C

    UnbufferedBuffered-

    Unformatted

    Buffered-

    Formatted

  • 8/14/2019 Programming Notes Sep05

    22/27

    Collections Comparison

    java.util:

    BitSet

    stl:

    vector

    bitset

    Bit Vector

    java.util:

    Map

    HashMap

    TreeMap

    stl:

    map

    multimap

    Map

    java.util:

    Set

    HashSet

    TreeSet

    java.util:

    List

    ArrayList

    LinkedList

    Java

    stl:

    set

    multiset

    stl:

    vector

    list

    C++

    SetList

    Note 1: The C++ Standard Template Library is iterator-based, while the Java Utilsare collection-based. Note 2: that Apache Common Collections are commonly usedas an extension. Note 3: the STL doesnt have a hash table.

  • 8/14/2019 Programming Notes Sep05

    23/27

    Design Basics

  • 8/14/2019 Programming Notes Sep05

    24/27

    Common Design Principles Design top-down, build bottom-up.

    Design with layers. Layer N can only call functions/objects in layer N-1.

    Design-by-Contract (aka Interface). Think of objects first in terms of their interface what they do not how they are built. Use ABCs or interfaces often.

    Design with composition, not inheritance. Compose objects with aggregation, notinheritance. Rules for inheriting B from A: An instance of B object will always be an instance of an A object.

    A B object is a special kind-of an A object.

    Never inherit for convenience (e.g. Stack inheriting from Vector is wrong!).

    Use roles idiom to handle multiple types, or types that can change over time.

    Use design patterns such as Composite, Factory, Strategy, Template, Visitor,Adaptor, Singleton to simplify your code (reference). Also, Manager paradigm.

    Class hierarchies tend to be flat, not deep. Common practice in C++ is to add a Rootclass. (Not much method overriding actually happens).

    http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/
  • 8/14/2019 Programming Notes Sep05

    25/27

    Common Design Principles (2) KISS

    Do not intertwine object (data) behavior with application behavior.

    Example:

    class Car { boolean startEngine();

    boolean driveToLocation(Location destination);

    class DriveStategies { boolean driveCarToStore();

    boolean driveCarToGasStation(); }

    Weak coupling via Observer-Observable or a Semantic Event subsystem.

  • 8/14/2019 Programming Notes Sep05

    26/27

    Design PracticesHOW TO ACTUALLY BUILD A DESIGN?

    Data Models: A data model such as an Entity Relationship (ER) diagram or Extended EntityRelationship (EER) is still very common. Why? Because RDBMS still dominate as the persistent storage.

    How? Use pencil & paper, or whiteboard, or Visio, or software.

    Notations: Crows foot, Chen, homegrown.

    Object Models: An object model encapsulates objects & class hierarchies. Most commonnotation: Unified Modeling Language (UML). Why? Because OO Programming Languages (OOPL) dominate software field.

    How? Use pencil & paper, or whiteboard, or Visio, or software (Poseidon, Rational Rose, etc).

    Notations: UML has taken over. OMT was predecessor in many ways.

    UML is a Swiss Army knife many views supported for different stakeholders.

    Architectural Designs: This can be as simple as a napkin sketch, or as complete as a full-blownUML model. Architectural designs are evaluated by design principles. Why? Any large software system needs a clear, consistent design.

    How? Whatever works!

    Notations: If not done in UML, then can be whatever conveys the essence of the design.

    Food for thought: A good Software Architect will make $200-300K per year, plus fringe, plus publicity, plusstocks, etc.

    http://www.gentleware.com/http://www.gentleware.com/http://www.gentleware.com/
  • 8/14/2019 Programming Notes Sep05

    27/27

    Superb Books & References Online e-Books/References:

    The Art of Unix Programming, by Eric Raymond. Thinking in Java/C++, by Bruce Eckel.

    C++ FAQ Lite

    General Programming Books:

    Code Complete, by Steve McConnell.

    Writing Solid Code, Steve Maguire.

    Introductory C++ Books: C++ How to Program, Deitel & Deitel. (Great b/c it teaches very good many OO concepts).

    C++ FAQs, Cline, et al.

    Great Unix Book:

    Advanced Programming in the Unix Environment, Richard Stevens. (aka The Bible)

    Software Engineering Books:

    Instant UML, Muller. Object-Oriented Methods, Graham. (General OO methodology/technology survey).

    Patterns in Java, Mark Grand. (esp. volumes 1-2).

    Advanced Object-Oriented Analysis and Design using UML, Odell.

    http://www.faqs.org/docs/artu/http://www.janiry.com/bruce-eckel/http://www.parashift.com/c++-faq-lite/http://www.amazon.com/exec/obidos/tg/detail/-/0735619670/qid=1127256511/sr=8-2/ref=pd_bbs_2/102-1470680-6609765?v=glance&s=books&n=507846http://www.amazon.com/exec/obidos/tg/detail/-/1556155514/qid=1127308531/sr=2-1/ref=pd_bbs_b_2_1/102-1470680-6609765?v=glance&s=bookshttp://www.deitel.com/books/cpphtp5/http://www.amazon.com/exec/obidos/ASIN/0201309831/102-1470680-6609765http://www.amazon.com/exec/obidos/tg/detail/-/0201563177/102-1470680-6609765?v=glancehttp://www.amazon.com/exec/obidos/tg/detail/-/1861000871/qid=1127309178/sr=2-1/ref=pd_bbs_b_2_1/102-1470680-6609765?v=glance&s=bookshttp://www.amazon.com/exec/obidos/tg/detail/-/020161913X/qid=1127309103/sr=1-1/ref=sr_1_1/102-1470680-6609765?v=glance&s=bookshttp://www.amazon.com/exec/obidos/tg/detail/-/0471227293/qid=1127309301/sr=2-1/ref=pd_bbs_b_2_1/102-1470680-6609765?v=glance&s=bookshttp://www.amazon.com/exec/obidos/tg/detail/-/052164819X/qid=1127309429/sr=1-1/ref=sr_1_1/102-1470680-6609765?v=glance&s=bookshttp://www.amazon.com/exec/obidos/tg/detail/-/052164819X/qid=1127309429/sr=1-1/ref=sr_1_1/102-1470680-6609765?v=glance&s=bookshttp://www.amazon.com/exec/obidos/tg/detail/-/0471227293/qid=1127309301/sr=2-1/ref=pd_bbs_b_2_1/102-1470680-6609765?v=glance&s=bookshttp://www.amazon.com/exec/obidos/tg/detail/-/020161913X/qid=1127309103/sr=1-1/ref=sr_1_1/102-1470680-6609765?v=glance&s=bookshttp://www.amazon.com/exec/obidos/tg/detail/-/1861000871/qid=1127309178/sr=2-1/ref=pd_bbs_b_2_1/102-1470680-6609765?v=glance&s=bookshttp://www.amazon.com/exec/obidos/tg/detail/-/0201563177/102-1470680-6609765?v=glancehttp://www.amazon.com/exec/obidos/ASIN/0201309831/102-1470680-6609765http://www.deitel.com/books/cpphtp5/http://www.amazon.com/exec/obidos/tg/detail/-/1556155514/qid=1127308531/sr=2-1/ref=pd_bbs_b_2_1/102-1470680-6609765?v=glance&s=bookshttp://www.amazon.com/exec/obidos/tg/detail/-/0735619670/qid=1127256511/sr=8-2/ref=pd_bbs_2/102-1470680-6609765?v=glance&s=books&n=507846http://www.parashift.com/c++-faq-lite/http://www.parashift.com/c++-faq-lite/http://www.janiry.com/bruce-eckel/http://www.faqs.org/docs/artu/