Programming Fundamentals - PowerPoint PPT Presentation

Loading...

PPT – Programming Fundamentals PowerPoint presentation | free to download - id: 5c8589-MTdkN



Loading


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation
Title:

Programming Fundamentals

Description:

Programming Fundamentals – PowerPoint PPT presentation

Number of Views:300
Avg rating:3.0/5.0
Slides: 303
Provided by: gyanFrag
Learn more at: http://gyan.fragnel.ac.in
Category:

less

Write a Comment
User Comments (0)
Transcript and Presenter's Notes

Title: Programming Fundamentals


1
Programming Fundamentals
2
Software Life Cycle
  • History
  • The "waterfall model", documented in 1970 by
    Royce was the first publicly documented life
    cycle model. The model was developed to help cope
    with the increasing complexity of aerospace
    products. The waterfall model followed a
    documentation driven paradigm. The next
    revolutionary new look at the development
    lifecycle was the "spiral model", presented by
    Boehm in 1985. The spiral model is focused on
    risk management.

3
Software Life Cycle
  • DEFINITION
  • System Development Life Cycle (SDLC) is the
    overall process of developing information systems
    through a multistep process from investigation of
    initial requirements through analysis, design,
    implementation and maintenance. There are many
    different models and methodologies, but each
    generally consists of a series of defined steps
    or stages.

4
Software Life Cycle
  • Why use Software Models?
  • Once upon a time, software development consisted
    of a programmer writing code to solve a problem
    or automate a procedure. Nowadays, systems are so
    big and complex that teams of architects,
    analysts, programmers, testers and users must
    work together to create the millions of lines of
    custom-written code that drive our enterprises

5
Software Life Cycle
  • Why use Software Models?
  • To manage this, a number of system development
    life cycle (SDLC) models have been created
    waterfall, fountain, spiral, build and fix, rapid
    prototyping, incremental, and synchronize and
    stabilize.
  • The oldest of these, and the best known, is the
    waterfall a sequence of stages in which the
    output of each stage becomes the input for the
    next.

6
Software Life Cycle
  • Why use Software Models?
  • These stages can be characterized and divided up
    in different ways, including the following
  • Project planning, feasibility study Establishes
    a high-level view of the intended project and
    determines its goals.
  • Systems analysis, requirements definition
    Refines project goals into defined functions and
    operation of the intended application. Analyzes
    end-user information needs.
  • Systems design Describes desired features and
    operations in detail, including screen layouts,
    business rules, process diagrams, pseudocode and
    other documentation.

7
Software Life Cycle
  • Why use Software Models?
  • These stages can be characterized and divided up
    in different ways, including the following
  • Implementation The real code is written here.
  • Integration and testing Brings all the pieces
    together into a special testing environment, then
    checks for errors, bugs and interoperability.
  • Acceptance, installation, deployment The final
    stage of initial development, where the software
    is put into production and runs actual business.
  • Maintenance What happens during the rest of the
    software's life changes, correction, additions,
    moves to a different computing platform and more.
    This, the least glamorous and perhaps most
    important step of all, goes on seemingly forever.

8
Software Life Cycle
  • Why use Software Models?
  • But It Doesn't Work!
  • The waterfall model is well understood, but it's
    not as useful as it once was. In a 1991
    Information Center Quarterly article, Larry Runge
    says that SDLC "works very well when we are
    automating the activities of clerks and
    accountants. It doesn't work nearly as well, if
    at all, when building systems for knowledge
    workers -- people at help desks, experts trying
    to solve problems, or executives trying to lead
    their company into the Fortune 100."

9
Software Life Cycle
  • Why use Software Models?
  • But It Doesn't Work!
  • Another problem is that the waterfall model
    assumes that the only role for users is in
    specifying requirements, and that all
    requirements can be specified in advance.
    Unfortunately, requirements grow and change
    throughout the process and beyond, calling for
    considerable feedback and iterative consultation.
    Thus many other SDLC models have been developed.
  • The fountain model recognizes that although some
    activities can't start before others -- such as
    you need a design before you can start coding --
    there's a considerable overlap of activities
    throughout the development cycle.

10
Software Life Cycle
  • Why use Software Models?
  • But It Doesn't Work!
  • The spiral model emphasizes the need to go back
    and reiterate earlier stages a number of times as
    the project progresses. It's actually a series of
    short waterfall cycles, each producing an early
    prototype representing a part of the entire
    project. This approach helps demonstrate a proof
    of concept early in the cycle, and it more
    accurately reflects the disorderly, even chaotic
    evolution of technology.
  • Build and fix is the crudest of the methods.
    Write some code, then keep modifying it until the
    customer is happy. Without planning, this is very
    open-ended and can by risky.

11
Software Life Cycle
  • Why use Software Models?
  • But It Doesn't Work!
  • In the rapid prototyping (sometimes called rapid
    application development) model, initial emphasis
    is on creating a prototype that looks and acts
    like the desired product in order to test its
    usefulness. The prototype is an essential part of
    the requirements determination phase, and may be
    created using tools different from those used for
    the final product. Once the prototype is
    approved, it is discarded and the "real" software
    is written.
  • The incremental model divides the product into
    builds, where sections of the project are created
    and tested separately. This approach will likely
    find errors in user requirements quickly, since
    user feedback is solicited for each stage and
    because code is tested sooner after it's written.

12
Software Life Cycle
  • Why use Software Models?
  • Big Time, Real Time
  • The synchronize and stabilize method combines the
    advantages of the spiral model with technology
    for overseeing and managing source code.
  • This method allows many teams to work efficiently
    in parallel. This approach was defined by David
    Yoffie of Harvard University and Michael Cusumano
    of MIT.
  • They studied how Microsoft Corp. developed
    Internet Explorer and Netscape Communications
    Corp. developed Communicator, finding common
    threads in the ways the two companies worked.
  • For example, both companies did a nightly
    compilation (called a build) of the entire
    project, bringing together all the current
    components.

13
Software Life Cycle
  • Why use Software Models?
  • Big Time, Real Time
  • They established release dates and expended
    considerable effort to stabilize the code before
    it was released.
  • The companies did an alpha release for internal
    testing one or more beta releases (usually
    feature-complete) for wider testing outside the
    company, and finally a release candidate leading
    to a gold master, which was released to
    manufacturing. At some point before each release,
    specifications would be frozen and the remaining
    time spent on fixing bugs.

14
Software Life Cycle
  • Methods
  • Life cycle models describe the interrelationships
    between software development phases. The common
    life cycle models are
  • spiral model
  • waterfall model
  • throwaway prototyping model
  • evolutionary prototyping model
  • incremental/iterative development
  • reusable software model
  • automated software synthesis

15
Software Life Cycle
  • Methods
  • Life cycle models describe the interrelationships
    between software development phases. The common
    life cycle models are
  • spiral model
  • waterfall model
  • throwaway prototyping model
  • evolutionary prototyping model
  • incremental/iterative development
  • reusable software model
  • automated software synthesis

16
Software Life Cycle
  • Methods
  • Because the life cycle steps are described in
    very general terms, the models are adaptable and
    their implementation details will vary among
    different organizations.
  • The spiral model is the most general.
  • Most life cycle models can in fact be derived as
    special instances of the spiral model.
  • Organizations may mix and match different life
    cycle models to develop a model more tailored to
    their products and capabilities.

17
Software Life Cycle
  • Learn
  • A software life cycle model depicts the
    significant phases or activities of a software
    project from conception until the product is
    retired. It specifies the relationships between
    project phases, including transition criteria,
    feedback mechanisms, milestones, baselines,
    reviews, and deliverables.
  • Typically, a life cycle model addresses the
    following phases of a software project
    requirements phase, design phase, implementation,
    integration, testing, operations and maintenance.
  • Much of the motivation behind utilizing a life
    cycle model is to provide structure to avoid the
    problems of the "undisciplined hacker".

18
Software Life Cycle
  • Spiral Model
  • The spiral model is the most generic of the
    models. Most life cycle models can be derived as
    special cases of the spiral model.
  • The spiral uses a risk management approach to
    software development.

19
Software Life Cycle
  • Spiral Model
  • Some advantages of the spiral model are
  • defers elaboration of low risk software elements
  • incorporates prototyping as a risk reduction
    strategy
  • gives an early focus to reusable software
  • accommodates life-cycle evolution, growth, and
    requirement changes
  • incorporates software quality objectives into the
    product
  • focus on early error detection and design flaws
  • sets completion criteria for each project
    activity to answer the question "How much is
    enough?"
  • uses identical approaches for development and
    maintenance
  • can be used for hardware-software system
    development

20
Software Life Cycle
  • Waterfall Model
  • The least flexible and most obsolete of the life
    cycle models.
  • Well suited to projects that has low risk in the
    areas of user interface and performance
    requirements, but high risk in budget and
    schedule predictability and control.

21
Software Life Cycle
  • Throwaway Prototyping Model
  • Useful in "proof of concept" or situations where
    requirements and user's needs are unclear or
    poorly specified.
  • The approach is to construct a quick and dirty
    partial implementation of the system during or
    before the requirements phase.

22
Software Life Cycle
  • Evolutionary Prototyping Model
  • Use in projects that have low risk in such areas
    as losing budget, schedule predictability and
    control, large-system integration problems, or
    coping with information sclerosis, but high risk
    in user interface design.

23
Software Life Cycle
  • Incremental/iterative Development
  • The process for constructing several partial
    deliverables, each having incrementally more
    functionality.

24
Software Life Cycle
  • Automated Software Synthesis
  • This process relies on tools to transform
    requirements into operational code. Formal
    requirements are created and maintained using
    specification tools.
  • This is an active research area, and practical
    tools for this approach are yet to be developed.

25
Software Life Cycle
  • Automated Software Synthesis
  • This process relies on tools to transform
    requirements into operational code. Formal
    requirements are created and maintained using
    specification tools.
  • This is an active research area, and practical
    tools for this approach are yet to be developed.

26
What Is Programming?
  • Simply put, programming is the process of
    creating a set of instructions for the computer
    to follow.
  • These instructions are written in a language or
    languages which people can understand, and then
    "compiled" (literally, translated) into machine
    language, or interpreted by the computer from
    reading a script. HTML is a programming language,
    as are Javascript and VBScript.
  • The "syntax" of a programming language consists
    of the various language elements, conventions,
    and operators that are used to write the
    instructions.

27
Definitions of algorithm
  • A mathematical relation between an observed
    quantity and a variable used in a step-by-step
    mathematical process to calculate a quantity. In
    the context of remote sensing, algorithms
    generally specify how to determine higher-level
    data products from lower-level source data. For
    example, algorithms prescribe how atmospheric
    temperature and moisture profiles are determined
    from a set of radiation observations originally
    sensed by satellite sounding instruments.
  • is a procedure or formula for solving problems

28
Definitions of algorithm
  • A computer program (or set of programs) which is
    designed to systematically solve a certain kind
    of problem. WSR-88D radars (NEXRAD) employ
    algorithms to analyze radar data and
    automatically determine storm motion, probability
    of hail, VIL, accumulated rainfall, and several
    other parameters
  • A finite set of well-defined rules for the
    solution of a problem in a finite number of
    steps.
  • A set of rules that a search engine uses to rank
    the listings contained within its index, in
    response to a particular query.

29
Definitions of algorithm
  • A computer program (or set of programs) which is
    designed to systematically solve a certain kind
    of problem. WSR-88D radars (NEXRAD) employ
    algorithms to analyze radar data and
    automatically determine storm motion, probability
    of hail, VIL, accumulated rainfall, and several
    other parameters
  • A finite set of well-defined rules for the
    solution of a problem in a finite number of
    steps.
  • A set of rules that a search engine uses to rank
    the listings contained within its index, in
    response to a particular query.

30
Difference between Algorithm Program
  • For small programs there's little value in
    planning - in fact, you'll probably end up
    wasting time.
  • As far as individual algorithms go, it's usually
    best to go with whatever seems the easiest to
    understand and only do more advanced things once
    you know that you need more speed or something
    like that.

31
Difference between Algorithm Program
  • That's a pseudocode implementation of an
    algorithm. You can describe an algorithm in human
    language, in pseudocode or in a programming
    language.
  • create an empty jumble word
  • while the chosen word has letters in it
  • extract a random letter from the chosen word
  • add the random letter to the jumble word

32
Difference between Algorithm Program
  • That's actually longer than just writing the
    algorithm in Python directly, which is why we say
    that Python is executable pseudocode ).
  • Pseudo-code design has IMO little value in Python
    and should stop at a higher level if it's used at
    all. In this example I'd have said this before
    going to Python code
  • randomize letters in word

33
Difference between Algorithm Program
  • By going into too much detail, you've actually
    overlooked the fact that you're recreating
    functionality from the Python standard library
    random.shuffle.
  • If the prog. is like

34
Difference between Algorithm Program
  • Game List
  • list ("GT4",
  • "GTA Sanandreas",
  • "Takken 5")
  • print "My Games "
  • for i in list
  • print i
  • print "\nI've got", len(list), "games."

35
Difference between Algorithm Program
  • add raw_input(\n\nAdd more games ")
  • adding (add)
  • list adding
  • print "Total games are..."
  • print list
  • raw_input("exit.")

36
Difference between Algorithm Program
  • The pseudocode could be something like this
  • list all games
  • show nr. of games
  • get the name of a new game
  • add the new game
  • list all games
  • exit

37
Difference between Algorithm Program
  • If you go into more detail, you'll end up writing
    a long version of the Python code, which kind of
    defeats the purpose of pseudocode.

38
Difference between Algorithm Program
  • Useful advice for algorithm
  • It's more important (at least for larger progams)
    to think about good design in terms of modules,
    classes and functions than in terms of individual
    lines of code. Always stop designing when
    designing becomes as low-level as just writing
    the code.

39
Sequential Algorithm
  • Write an algorithm to find the average marks of a
    students he has obtained in three subjects
  • Step 1 Start
  • Step 2 Accept num1, num2, num3
  • Step 3 sum num1 num2 num3
  • Step 4 avg sum/3
  • Step 5 display avg
  • Step 6 Stop

40
Good Programming Style
  • Consistency
  • One of the hallmarks of good programming style is
    consistency--the fewer surprises, the better.
  • Consistency makes it easier to read the program
    primarily by reducing distractions.
  • But it also helps guide the reader's eyes, for
    example, by being consistent about ordering
    functions or including files to simplify finding
    them in the future.
  • It also makes it easier to deal with other style
    problems by making it easier for the reader to
    get used to them.

41
Good Programming Style
  • Clarity
  • Good style is about making your program clear and
    understandable as well as easily modifiable.
  • When in doubt, choose the most easily understood
    technique for a problem.
  • Remember that whatever you write, you will likely
    have to read at some point after you remember
    exactly what you were thinking.
  • Do your future self a favor and be clear the
    first time.

42
Good Programming Style
  • Whitespace and Formatting
  • Whitespace can set things off and reduce the
    strain on the reader's eyes. Because the compiler
    ignores whitespace, you're free to place things
    anywhere you want and format it however you want.
  • If you choose wisely, this can be a boon.
  • Whitespace comes in several forms, including
    indentation, how you put space around operators,
    how you lay out function ????declarations???, and
    where you place arguments to functions.
  • Of course, this is hardly everything covered by
    whitespace, but it should give you an idea of the
    many places whitespace can be used to improve
    readability.

43
Good Programming Style
  • Whitespace and Formatting
  • Indentation
  • If you don't indent your code, you soon will.
    It's just a natural thing to do because it lets
    you use your eye to quickly pick out the flow of
    control or mistakes in that flow of control.
  • The quick primer on indentation is that you
    should indent every block of code
  • if ( true )
  • // code block

44
Good Programming Style
  • Whitespace and Formatting
  • Brace Styles
  • There are a variety of ways to indent code, and
    many of them are tied to where you place your
    braces. Some people prefer the style used above.
  • Some people prefer the style below
  • if ( true )
  • // code block

45
Good Programming Style
  • Whitespace and Formatting
  • Brace Styles
  • Other styles include
  • if ( true )
  • // code block
  • or even
  • if ( true )
  • // code block

46
Good Programming Style
  • Whitespace and Formatting
  • Brace Styles
  • Any brace style you choose is up to you, although
    I'd recommend using the same brace style as
    everyone else working on your project. At any
    rate, there are arguments for each style. A good
    consideration is to use a brace style that allows
    you to put as much code on a screen at a time,
    but consistency with past practices is probably
    just as important.

47
Good Programming Style
  • Whitespace and Formatting
  • Indentation Depth
  • How far you choose to indent is a matter of
    personal preference--in any case, it's usually
    best to choose an indentation size that's small
    enough to comfortably fit your code on one
    screen.
  • I've found that any indentation width from 2 to 8
    is reasonable and readable, although I've found
    that anything over four spaces for indentation
    can lead to lines that are too long.
  • In general, the best solution to dealing with
    lines that are too long is to reduce the
    complexity of the code or at least to pull out
    some functionality into separate functions.
  • Doing so will reduce the number of levels of
    indentation and can make the code more readable
    (if it is done correctly).

48
Good Programming Style
  • Whitespace and Formatting
  • Tabs vs. Spaces
  • There is something of an argument over whether to
    indent using tabs or spaces.
  • Note that this is not the same as asking whether
    you indent with the spacebar or the tab--most
    people let their editors take care of that
    problem for them (or choose to have tabs expanded
    to spaces).
  • The real issue of tabs vs. spaces is what happens
    when someone else opens your code.
  • Since you can set tabs to take up any number of
    columns, the person opening your code might not
    have the same tabstop width.
  • This can play havoc with otherwise well-formatted
    code. Using only spaces fixes this problem
    because it will always display the same way for
    everyone.

49
Good Programming Style
  • Whitespace and Formatting
  • Tabs vs. Spaces
  • Sometimes a decent code formatter, such as might
    be found in your text editor, can help mitigate
    this problem by reformatting the code.
  • You can also play with your own tab settings to
    display the code correctly (although this is
    obviously annoying).
  • The best solution, if you do decide to use tabs,
    is to be very careful with what you use tabs for.
  • The real problem, in fact, comes up when tabs are
    used not just for indentation but also as a quick
    way of moving four or eight characters to the
    right.

50
Good Programming Style
  • Whitespace and Formatting
  • Tabs vs. Spaces
  • For instance, let's look at the following code
  • if ( a_long_case_number_one_stretching_across_most
    _of_the_screen
  • a_long_case_number_two_also_stretching_across
    _most_of_the_screen )
  • // code

51
Good Programming Style
  • Whitespace and Formatting
  • Tabs vs. Spaces
  • If the second condition had been formatted using
    a tab with a four-space indent followed by a
    space, then when loaded with a tab-width of
    eight, it would look ugly
  • if ( a_long_case_number_one_stretching_across_most
    _of_the_screen a_long_case_number_two_also_stre
    tching_across_most_of_the_screen )
  • // code

52
Good Programming Style
  • Whitespace and Formatting
  • Tabs vs. Spaces
  • If spaces were used for the formatting, it would
    open correctly
  • if ( a_long_case_number_one_stretching_across_most
    _of_the_screen
  • a_long_case_number_two_also_stretching_across
    _most_of_the_screen )
  • // code

53
Good Programming Style
  • Whitespace and Formatting
  • Mis-Use of Whitespace
  • How much white space you use is, to some extent,
    a personal choice. There are some issues to be
    aware of. First, the more your whitespace helps
    emphasize the logic of your program, the better
    you don't want your whitespace to "lie". This
    might not confuse the you-at-this-moment, but it
    can confuse the you-of-the-future or just someone
    else reading your code. What does lying look
    like?
  • if ( true )
  • i
  • j

54
Good Programming Style
  • Whitespace and Formatting
  • Mis-Use of Whitespace
  • The indentation makes it look like both
    statements get executed when the if statement
    executes--but that's not what actually happens.
  • When you're tracking down a bug or syntax error
    in hundreds or thousands of lines of code, you
    may end up doing a visual scan instead of
    checking every line carefully.
  • The easier you make it to scan the code and pick
    out salient details, the faster you can scan
    without making mistakes.

55
Programming Style Writing for Readability
  • Using Functions
  • Unlike prose, where repeating the same word or
    phrase may seem redundant, in programming, it's
    perfectly fine to use the same construction over
    and over again. Of course, you may want to turn a
    repeated chunk of code into a function this is
    even more readable because it gives the block of
    code a descriptive name. (At least you ought to
    make it descriptive!)
  • You can also increase readability by using
    standard functions and data structures (such as
    the STL). Doing so avoids the confusion of
    someone who might ask, "why did you create a new
    function when you had a perfectly good one
    already available?" The problem is that people
    may assume that there's a reason for the new
    function and that it somehow differs from the
    standard version.

56
Programming Style Writing for Readability
  • Using Functions
  • Moreover, by using standard functions you help
    your reader understand the names of the arguments
    to the function. There's much less need to look
    at the function prototype to see what the
    arguments mean, or their order, or whether some
    arguments have default values.

57
Programming Style Writing for Readability
  • Use Appropriate Language Features
  • There are some obvious things to avoid don't use
    a loop as though it were an if statement. Choose
    the right data type for your data if you never
    need decimal places in a number, use an integer.
    If you mean for a value to be unsigned, used an
    unsigned number. When you want to indicate that a
    value should never change, use const to make it
    so.
  • Try to avoid uncommon constructions unless you
    have good reason to use them put another way,
    don't use a feature just because the feature
    exists. One rule of thumb is to avoid do-while
    loops unless you absolutely need one.

58
Programming Style Writing for Readability
  • Use Appropriate Language Features
  • People aren't generally as used to seeing them
    and, in theory, won't process them as well. I've
    never run into this problem myself, but think
    carefully about whether you actually need a
    do-while loop. Similarly, although the ternary
    operator is a great way of expressing some ideas,
    it can also be confusing for programmers who
    don't use it very often.
  • A good rule of thumb is to use it only when
    necessary (for instance, in the initialization
    list of a constructor) and stick with the more
    standard if-else construction for everything
    else. Sure, it'll make your program four lines
    longer, but it'll make it that much easier for
    most people to read.

59
Programming Style Writing for Readability
  • Use Appropriate Language Features
  • There are some less obvious ways of using
    standard features. When you are looping, choose
    carefully between while, do-while, and for.
  • For loops are best when you can fill in each part
    (initialization, conditional, and increment) with
    a fairly short expression. While loops are good
    for watching a sentinel variable whose value can
    be set in multiple places or whose value depends
    on some external event such as a network event.

60
Programming Style Writing for Readability
  • Use Appropriate Language Features
  • While loops are also better when the update step
    isn't really a direct "update" to the control
    variable--for instance, when reading lines from a
    text file, it might more sense to use a while
    loop than a for loop because the control depends
    on the result of the method call, not the value
    of the variable of interest
  • while (fgets(buf, sizeof(buf), fp) ! NULL)
  • / do stuff with buf /

61
Programming Style Writing for Readability
  • Unpack Complex Expressions
  • There's no reason to put everything on a single
    line. If you have a complex calculation with
    multiple steps and levels of parentheses, it can
    be extremely helpful to go from a one-line
    calculation to one that uses temporary variables.
    This gives you two advantages first, it makes it
    easier to follow the expression. Second, you can
    give a distinct name to each intermediate step,
    which can help the reader follow what is
    happening. Often, you'll want to reuse those
    intermediate calcuations anyway. In addition to
    mathematical calculations, this principle also
    applies to nested function calls. The fewer
    events that take place on a single line of code,
    the easier it is to follow exactly what's
    happening.

62
Programming Style Writing for Readability
  • Unpack Complex Expressions
  • Another advantage to unpacking an expression is
    that you can put more comments in-line to explain
    what's going on and why.

63
Programming Style Writing for Readability
  • Avoid Magic Numbers
  • Magic numbers are numbers that appear directly in
    the code without an obvious reason. For instance,
    what does the number 80 in the following
    expression mean?
  • for( int i 0 i lt 80 i )
  • printf( "-" )

64
Programming Style Writing for Readability
  • Avoid Magic Numbers
  • It might be the width of the screen, but it might
    also be the width of a map whose wall is being
    drawn. You just don't know. The best solution is
    to use macros, in C, or constants in C. This
    gives you the chance to descriptively name your
    numbers. Doing so also makes it easier to spot
    the use of a particular number and differentiate
    between numbers with the same value that mean
    different things. Moreover, if you decide you
    need to change a value, you have a single point
    where you can make the change, rather than having
    to sift through your code.

65
Programming Style, Naming Conventions
  • Good naming can make a huge difference in program
    readability. Names like proc1, proc2, and proc3
    mean next-to-nothing, but even apparently decent
    names can be ambiguous.
  • For instance, to name a function that takes two
    ranges and computes the amount of the first that
    lies within the second, names like
    computeRangeWithinRange might sound reasonable.

66
Programming Style, Naming Conventions
  • Unfortunately, this name gives no information
    about the order of arguments to the function.
  • Sometimes this won't be a problem because an
    intelligent IDE should help you determine the
    names of the arguments to the function, but it
    can be confusing when the code is printed, or
    when you try to quickly read through the code.
  • A better name might be computeRangeWithinFirstRang
    e, which at least gives a sense of the order of
    the arguments to the function.

67
Programming Style, Naming Conventions
  • General Naming Conventions
  • It's usually best to choose a consistent set of
    naming convnetions for use throughout your code.
    Naming conventions usually govern things such as
    how you capitalize your variables, classes, and
    functions, whether you include a prefix for
    pointers, static data, or global data, and how
    you indicate that something is a private field of
    a class.

68
Programming Style, Naming Conventions
  • General Naming Conventions
  • There are a lot of common naming conventions for
    classes, functions and objects. Usually these are
    broken into several broad categories c-style
    naming, camelCase, and CamelCase. C-style naming
    separates words in a name using underscores
    this_is_an_identifer. There are two forms of
    camelCase one that begins with a lowercase
    letter and then capitalizes the first letter of
    every ensuing word, and one that capitalizes the
    first letter of every single word.

69
Programming Style, Naming Conventions
  • General Naming Conventions
  • One popular convention is that leading capital
    letter CamelCase is used for the names of structs
    and classes, while normal camelCase is used for
    the names of functions and variables (although
    sometimes variables are written in c-style to
    make the visual separation between functions and
    variables more clear).

70
Programming Style, Naming Conventions
  • General Naming Conventions
  • It can be useful to use prefixes for certain
    types of data to remind you what they are for
    instance, if you have a pointer, prefixing it
    with "p_" tells you that it's a pointer. If you
    see an assignment between a variable starting
    with "p_" and one that doesn't begin with "p_",
    then you immediately know that something fishy is
    going on. It can also be useful to use a prefix
    for global or static variables because each of
    these has a different behavior than a normal
    local variable. In the case of global variables,
    it is especially useful to use a prefix in order
    to prevent naming collisions with local variables
    (which can lead to confusion).

71
Programming Style, Naming Conventions
  • General Naming Conventions
  • Finally, a common convention is to prefix the
    private fields and methods of a class with an
    underscore e.g., _private_data. This can make it
    easier to find out where to look in the body of a
    class for the declaration of a method, and it
    also helps keep straight what you should and
    should not do with a variable. For instance, a
    common rule is to avoid returning non-const
    references to fields of a class from functions
    that are more public than the field. For
    instance, if _age is a private field, then the
    public getAge function probably shouldn't return
    a non-const reference since doing so effectively
    grants write access to the field!

72
Programming Style, Naming Conventions
  • Hungarian Notation
  • Hungarian notation has commonly been associated
    with prefixing variables with information about
    their type--for instance, whether a variable is
    an integer or a double. This is usually not a
    useful thing to do because your IDE will tell you
    the type of a variable, and it can lead to
    bizarre and complicated looking names. The
    original idea behind Hungarian notation, however,
    was more general and useful to create more
    abstract "types" that describe how the variable
    is used rather than how the variable is
    represented. This can be useful for keeping
    pointers and integers from intermixing, but it
    can also be a powerful technique for helping to
    separate concepts that are often used together,
    but that should not be mixed.

73
Programming Style, Naming Conventions
  • Abbrevations
  • Abbreviations are dangerous--vowels are useful
    and can speed up code reading. Resorting to
    abbreviations can be useful when the name itself
    is extremely long because names that are too long
    can be as hard to read as names that are too
    short. When possible, be consistent about using
    particular abbreviations, and restrict yourself
    to using only a small number of them.

74
Programming Style, Naming Conventions
  • Abbrevations
  • Common abbreviations include "itr" for "iterator"
    or "ptr" for pointer. Even names like i, j, and k
    are perfectly fine for loop counter variables
    (primarily because they are so common). Bad
    abbreviations include things like cmptRngFrmRng,
    which at the savings of only a few letters
    eliminates a great deal of readability. If you
    don't like typing long names, look into the
    auto-complete facilities of your text editor. You
    should rarely need to type out a full identifier.
    (In fact, you rarely want to do this typos can
    be incredibly hard to spot.)

75
Programming Style, Naming Conventions
  • Abbrevations
  • Common abbreviations include "itr" for "iterator"
    or "ptr" for pointer. Even names like i, j, and k
    are perfectly fine for loop counter variables
    (primarily because they are so common). Bad
    abbreviations include things like cmptRngFrmRng,
    which at the savings of only a few letters
    eliminates a great deal of readability. If you
    don't like typing long names, look into the
    auto-complete facilities of your text editor. You
    should rarely need to type out a full identifier.
    (In fact, you rarely want to do this typos can
    be incredibly hard to spot.)

76
Procedural and Object-Oriented Programming
  • The first item of business is to identify the 2
    kinds of programming that exist, and how each one
    fits into the overall picture
  • Procedural Programming
  • Object Oriented Programming

77
Procedural Programming
  • Procedural Programming was the first kind of
    programming to develop, and involves a relatively
    simple way of doing things.
  • In procedural programming, the computer is given
    a set of instructions which it executes, and then
    waits for input, which it reacts to by executing
    another set of instructions, and so on.

78
Procedural Programming
  • There are 3 basic elements of procedural
    programming
  • Sequence - The order in which instructions are
    executed is the sequence of the programming. This
    is far more important than it might seem, but
    having things in the proper sequence is
    essential.
  • Selection - If/else conditional statements and
    other forms of selection form the second element.
    This is how a program makes and reacts to
    choices.
  • Iteration - The use of "loops" and other forms
    of repetitive sets of instructions forms the last
    building block of procedural programming.

79
Object Oriented Programming
  • Object Oriented Programming came along later,
    with the advent of multi-tasking operating
    systems such as Windows.
  • In point of fact, procedural programming is at
    the heart of all programming, including
    obect-oriented, but because certain kinds of
    objects have many characteristics in common (such
    as windows, for example), it is more convenient
    to treat them as objects, rather than as sets of
    instructions.

80
Object Oriented Programming
  • An object has properties, methods, and event
    handlers.
  • Properties - Properties of an object are the
    characteristics which define how the object
    behaves. In a web page, for example, the page
    itself has certain properties, which are defined
    in the ltbodygt tag, such as the background color,
    style source page, etc.

81
Object Oriented Programming
  • An object has properties, methods, and event
    handlers.
  • Methods - Methods are actually blocks of
    instructions that can be executed by an object
    itself, and each object has its' own set of
    methods. A simple example of this would be the
    submit() method of a form. When You click on the
    Submit button of a form, or invoke the submit()
    method for a form with a Javascript command, the
    form is submitted using the form's submit()
    method.

82
Object Oriented Programming
  • An object has properties, methods, and event
    handlers.
  • Event Handlers - An "event" is when something
    happens (duh!), either something that the user
    has done, or something the program itself has
    done, or another program has done. The simplest
    example I can think of for an event is using the
    form example above. When you click the "Submit"
    button, you have generated an event, and the
    event handler is the set of instructions which is
    programmed to execute when that event occurs.
    Because of the nature of multi-tasking systems
    like Windows, one is never sure where the next
    event is going to come from, so event handlers
    are designed to react to events in the
    appropriate manner. Each object has its' own
    event handlers, built into the object itself.

83
Object Oriented Programming
  • One last thing that is important to remember
    regarding object-oriented programming
  • It employs procedural programming. In other
    words, an object-oriented program is going to
    contain both object-oriented and procedural code.
  • An event handler, for instance, may simply be a
    procedure that executes when the event occurs.
    This procedure may or may not include
    object-oriented code.

84
Object Oriented Programming
  • The program uses an interface for communicating
    with the user.
  • The interface is a method of the computer talking
    to the user in a way that the user can
    understand, and the user talking back to the
    program in a way that the computer can
    understand. In a web application, the web pages
    themselves comprise the interface.

85
Object Oriented Programming
  • The pages contain information which the user
    reads, and contain active elements, such as
    hyperlinks and forms, that enable the user to
    input instructions to the computer.
  • Think of the interface as something like the old
    Star Trek universal translator It helps the user
    and the computer to communicate, even though they
    think and communicate quite differently.

86
Functions The Basics
  • Why should we make functions in our programs when
    we can just do it all under main?
  • Think for a minute about high-end stereo systems.
    These stereo systems do not come in an all-in-one
    package, but rather come in separate components
    pre-amplifier, amplifier, equalizer, receiver, cd
    player, tape deck, and speakers. The same concept
    applies to programming.
  • Your programs become modularized and much more
    readable if they are broken down into components.

87
Functions The Basics
  • This type of programming is known as top-down
    programming, because we first analyze what needs
    to be broken down into components. Functions
    allow us to create top-down modular programs.
  • Each function consists of a name, a return type,
    and a possible parameter list. This abstract
    definition of a function is known as it's
    interface.

88
Functions The Basics
  • Here are some sample function interfaces
  • char strdup(char s)
  • int add_two_ints(int x, int y)
  • void useless(void)
  • The first function header takes in a pointer to a
    string and outputs a char pointer. The second
    header takes in two integers and returns an int.
    The last header doesn't return anything nor take
    in parameters.

89
Functions The Basics
  • A function can return a single value to its
    caller in a statement using the keyword return.
    The return value must be the same type as the
    return type specified in the function's interface.

90
Functions Prototypes
  • Function prototypes are abstract function
    interfaces. These function declarations have no
    bodies they just have their interfaces.
  • Function prototypes are usually declared at the
    top of a C source file, or in a separate header
    file
  • For example, if you wanted to grab command line
    parameters for your program, you would most
    likely use the function getopt. But since this
    function is not part of ANSI C, you must declare
    the function prototype, or you will get implicit
    declaration warnings when compiling with our
    flags.

91
Functions Prototypes
  • / This section of our program is for Function
    Prototypes /
  • int getopt(int argc, char const argv, const
    char optstring)
  • extern char optarg
  • extern int optind, opterr, optopt

92
Functions Prototypes
  • So if we declared this function prototype in our
    program, we would be telling the compiler
    explicitly what getopt returns and it's parameter
    list.
  • What are those extern variables? Recall that
    extern creates a reference to variables across
    files, or in other words, it creates file global
    scope for those variables in that particular C
    source file.
  • That way we can access these variables that
    getopt modifies directly. More on getopt on the
    next section about Input/Output.

93
Functions Functions as Parameters
  • This is a little more advanced section on
    functions, but is very useful.
  • Take this for example
  • int applyeqn(int F(int), int max, int min)
  • int itmp
  • itmp F(int) min
  • itmp itmp - max
  • return itmp

94
Functions Functions as Parameters
  • What does this function do if we call it with
    applyeqn(square(x), y, z)?
  • What happens is that the int F(int) is a
    reference to the function that is passed in as a
    parameter.
  • Thus inside applyeqn where there is a call to F,
    it actually is a call to square!
  • This is very useful if we have one set function,
    but wish to vary the input according to a
    particular function.

95
Functions Functions as Parameters
  • So if we had a different function called cube we
    could change how we call applyeqn by calling the
    function by applyeqn(cube(x), y, z).

96
Functions The Problem
  • There are four major ways that parameters are
    passed into functions.
  • The two that we should be concerned with are Pass
    by Value and Pass by Reference.
  • In C, all parameters are passed by value.

97
Functions The Problem
  • In simplistic terms, functions in C create
    copies of the passed in variables.
  • These variables remain on the stack for the
    lifetime of the function and then are discarded,
    so they do not affect the inputs!
  • This is important. Let's repeat it again. Passed
    in arguments will remain unchanged.

98
Functions The Problem
  • Let's use this swapping function as an example
  • void swap(int x, int y)
  • int tmp 0
  • tmp x
  • x y
  • y tmp
  • If you were to simply pass in parameters to this
    swapping function that swaps two integers, this
    would fail horribly. You'll just get the same
    values back.

99
Functions The Problem
  • You can circumvent this pass by value limitation
    in C by simulating pass by reference.
  • Pass by reference changes the values that are
    passed in when the function exits.
  • This isn't how C works technically but can be
    thought of in the same fashion.
  • So how do you avoid pass by value side effects?
  • By using pointers and in some cases using macros.

100
The C Preprocessor Overview
  • The C Preprocessor is not part of the compiler,
    but is a separate step in the compilation
    process. In simplistic terms, a C Preprocessor is
    just a text substitution tool.
  • All preprocessor lines begin with .

101
The C Preprocessor Overview
  • The unconditional directives are
  • include - Inserts a particular header from
    another file
  • define - Defines a preprocessor macro
  • undef - Undefines a preprocessor macro

102
The C Preprocessor Overview
  • The conditional directives are
  • ifdef - If this macro is defined
  • ifndef - If this macro is not defined
  • if - Test if a compile time condition is true
  • else - The alternative for if
  • elif - else an if in one statement
  • endif - End preprocessor conditional

103
The C Preprocessor Overview
  • Other directives include
  • - Stringization, replaces a macro parameter
    with a string constant
  • - Token merge, creates a single token from
    two adjacent ones

104
The C Preprocessor Overview
  • Some examples of the above
  • define MAX_ARRAY_LENGTH 20
  • Tells the CPP to replace instances of
    MAX_ARRAY_LENGTH with 20. Use define for
    constants to increase readability. Notice the
    absence of the .

105
The C Preprocessor Overview
  • Some examples of the above
  • include ltstdio.hgt
  • include "mystring.h"
  • Tells the CPP to get stdio.h from System
    Libraries and add the text to this file.
  • The next line tells CPP to get mystring.h from
    the local directory and add the text to the file.
    This is a difference you must take note of.

106
The C Preprocessor Overview
  • Some examples of the above
  • undef MEANING_OF_LIFE
  • define MEANING_OF_LIFE 42
  • Tells the CPP to undefine MEANING_OF_LIFE and
    define it for 42.

107
The C Preprocessor Overview
  • Some examples of the above
  • ifndef IROCK
  • define IROCK "You wish!"
  • endif
  • Tells the CPP to define IROCK only if IROCK
    isn't defined already.

108
The C Preprocessor Overview
  • Some examples of the above
  • ifdef DEBUG
  • / Your debugging statements here /
  • endif
  • Tells the CPP to do the following statements if
    DEBUG is defined. This is useful if you pass the
    -DDEBUG flag to gcc. This will define DEBUG, so
    you can turn debugging on and off on the fly!

109
The C Preprocessor Parameterized Macros
  • One of the powerful functions of the CPP is the
    ability to simulate functions using parameterized
    macros.
  • For example, we might have some code to square a
    number
  • int square(int x)
  • return x x

110
The C Preprocessor Parameterized Macros
  • We can instead rewrite this using a macro
  • define square(x) ((x) (x))
  • First square(x) The left parentheses must
    "cuddle" with the macro identifier.
  • The next thing that should catch your eye are the
    parenthesis surrounding the x's.
  • These are necessary... what if we used this macro
    as square(1 1)?

111
The C Preprocessor Parameterized Macros
  • Imagine if the macro didn't have those
    parentheses?
  • It would become ( 1 1 1 1 ). Instead of our
    desired result of 4, we would get 3.
  • Thus the added parentheses will make the
    expression ( (1 1) (1 1) ).
  • This is a fundamental difference between macros
    and functions. You don't have to worry about this
    with functions, but you must consider this when
    using macros.

112
The C Preprocessor Parameterized Macros
  • Remeber that pass by value vs. pass by reference
    issue earlier? I said that you could go around
    this by using a macro. Here is swap in action
    when using a macro
  • define swap(x, y) int tmp x x y y
    tmp
  • Now we have swapping code that works. Why does
    this work? It's because the CPP just simply
    replaces text. Wherever swap is called, the CPP
    will replace the macro call with
About PowerShow.com