The Nitty and the Gritty - PowerPoint PPT Presentation

1 / 38
About This Presentation
Title:

The Nitty and the Gritty

Description:

The Nitty and the Gritty. CS130 Lecture 7. CS130 Prof Majumdar ... Example: IDEs (Eclipse), debug tools, Frameworks: J2EE, .NET, Spring, Ruby on Rails ... – PowerPoint PPT presentation

Number of Views:200
Avg rating:3.0/5.0
Slides: 39
Provided by: csU5
Category:
Tags: gritty | ides | nitty

less

Transcript and Presenter's Notes

Title: The Nitty and the Gritty


1
The Nitty and the Gritty
  • CS130 Lecture 7

2
Where we Are
  • Started with requirements
  • Progressively digging deeper
  • Specifications What to build
  • Design How to build
  • Architecture Detailed plan for the design
  • Design Patterns More detailed plans
  • Today Code level details
  • A VERY brief survey from McConnells Code
    Complete

3
Where will we go Next?
  • Next few lectures will be on testing/debugging
  • Current practice as well as current research in
    testing/software quality
  • One of the most exciting directions in software
    engineering research!

4
Code Level Decisions
  • Programming Language
  • Programming Conventions
  • Not required by language, but often crucial
  • Examples All executables will have version
    option
  • Variable naming conventions
  • Programming Tools and Frameworks
  • Example IDEs (Eclipse), debug tools,
  • Frameworks J2EE, .NET, Spring, Ruby on Rails

5
Designing Your Software
  • Key Challenge Manage Complexity
  • Essential Problems (underlying problem is hard
    or ill-defined) vs Accidental Problems
    (language does not have particular features)
  • Goal Modularize essential complexity
  • How?
  • Stratification (abstract layers)
  • Loose coupling
  • Extensibility and reusability
  • Portability
  • No formula heuristic process

Design Patterns
6
Design Heuristics
  • Find a real-world analogy for objects
  • Encapsulate details, hide information
  • Makes programs easier to modify
  • Pattern example?
  • Isolate areas likely to change
  • Pattern example?

7
Working Classes
  • Class Cohesive collection of data and routines
    that share a responsibility
  • And let you
  • ignore the rest of the program when looking at
    class implementation
  • Ignore class implementation when looking at use
  • Based on Abstract Data Types
  • Hide implementation details, localize effect of
    changes

8
Good Abstractions
  • Consistent level of abstraction
  • Eg dont mix several responsibilities
  • Understand the abstraction from the problem
    viewpoint
  • Enforce interfaces
  • Limit accessibility to methods/members
  • Dont let client depend on assumptions beyond
    interface
  • Eg hash table client should not assume ordering
    of values

9
Routines
  • Aka methods, functions, subroutines
  • Routines reduce complexity
  • Introduce understandable abstraction
  • Avoid duplicate code
  • Simple routines are good
  • Dont be shy of writing small ones

10
Routine Cohesion
  • How closely its operations are related
  • Functional cohesion (best)
  • Routine does one thing only
  • Sequential cohesion
  • Operations share data and must be done in
    sequence
  • Bad design
  • Procedural cohesion
  • Routine exists only to sequence operations
  • Coincidental cohesion no cohesion

11
Naming Conventions
  • short digression Naming conventions in
    McConnells book is spread over several sections
    7.3 routines, 10 variables, 12.7 constants,
    12.9 types. I dont like that.
  • No universal naming convention
  • But projects need naming conventions
  • To let you concentrate on more important things
  • Compensate for some language weaknesses
  • Emphasize relationships otherwise missed

12
Typical Naming Conventions
  • Routines verb (OO languages) or verbObject
    (non-OO)
  • Opposites used precisely min/max, open/close
  • Give Boolean variables logical names
  • Status_ok or Status_not_found (rather than
    status, or status_error)
  • Many more conventions, project specific
    conventions

13
Possible Things to Identify viaNaming Conventions
  • Types vs Variables vs Constants
  • Ex Constants in ALL_CAPS
  • i,j integer indices, p pointer, s string
  • Globals vs Locals vs Members
  • Inputs, Outputs, InputOutputs

14
Naming Conventions Example
  • General Advice
  • Name should accurately describe the named entity
  • E.g. bpp ? bytes_per_page
  • Names should be specific
  • E.g. do_work ? compute_bytes_per_page
  • Names should relate to problem, not solution
  • E.g. two_to_the_bits ? bytes_per_page
  • Names should have right length
  • Typically, lt 20 chars, small scope names can be
    small (i, x),
  • Others larger

15
Naming Conventions More
  • bytesPerPage vs bytes_per_page
  • Surprising how much time is lost!
  • Consistency is important!!
  • Bottom Line Favor read-time convenience over
    write-time convenience

16
Bad Names
  • Visual puns si10 vs silo
  • Inside jokes revenge_on_joe
  • similar sounding cownt, count
  • Similar names, different work
  • aBufLength, a BufferLength
  • Similar work, different names
  • inputLength, il

17
Defensive Programming
  • Write code so that bugs are easier to catch and
    fix
  • Not a substitute for good design principles!
  • Basic Idea Dont trust the external world

18
Example Whats Wrong?
  • int a(int arr, int n, int i)
  • return ai
  • int a(int arr, int n, int i)
  • assert(0lt i i lt n)
  • return ai

19
Whats Wrong?
  • x (struct foo )malloc()
  • x-gta 0
  • Better
  • x (struct foo )malloc()
  • If(x NULL)
  • handle error
  • x-gta 0

20
Whats Wrong?
  • s inputString()
  • Printf(s)
  • What if s has format characters?
  • e.g
  • S n?
  • Look up n ?

21
Whats Wrong?
  • S SELECT pwd FROM Table WHERE name
  • Name inputString()
  • Query S Name
  • Execute(Query)
  • SQL Injection Attack
  • What if Name is
  • Foo 1 1
  • Or
  • Foo DELETE Table
  • Similar issues in cross site scripting

22
Whats Wrong?
  • Lock()
  • If(error condition)
  • return
  • Unlock()
  • Return
  • On error condition, lock is not released
  • Lead to deadlock

23
What can you do?
  • Input Validation
  • Taint analysis make sure input data always
    passes through validator
  • Assertions
  • Contracts (pre- and post-conditions)
  • Static Analysis

24
Refactoring
  • Myth Coding can proceed linearly, ie written
    once, tested, and forgotten.
  • Reality Various upstream issues change, code
    evolves substantially during initial development

25
Refactoring
  • Change internal structure, not observable
    behavior, in order to make code easier to
    understand and modify
  • Motivated by projects that evolve during
    construction
  • Agile/XP development

26
When to Refactor?
  • Duplicate Code
  • Unused code
  • Awkward API
  • Poorly encapsulated classes
  • God class
  • Class that does little
  • Routines grouped together that shouldnt be
  • Too long routine, too many parameters
  • Often called smells Martin Fowler

27
Refactoring Techniques
  • General principles
  • DRY Dont repeat yourself
  • (Copy and paste is a design error)
  • Do refactorings one at a time
  • Be prepared to undo
  • Keep refactorings small
  • Organize
  • TEST

28
Techniques
  • Replace code with routine
  • Encapsulate data (eg introduce class)
  • Rework routine to avoid duplication
  • Change values to references and vice versa
  • Pull a routine up to superclass
  • Push a routine to subclass
  • Move routine from interface
  • Add inheritance/delegation
  • Centralize access to data

29
Refactor Gradually
  • As you go rather than all at once

30
Code Tuning
  • Performance often conflicts with other design
    goals
  • Example of design pattern that can reduce
    performance?
  • Many patterns introduce indirection
  • Factories, Strategies,
  • Indirection is costly

31
Code Tuning
  • Question to ask Are you sure you want to
    sacrifice design for performance?
  • Answer is no most of the time
  • Other things you can do
  • Change platform (HW, OS, language)
  • Algorithmic improvements
  • 80-20 rule (80 of execution in 20 of code)
  • Amdahls Law

32
Why Not to Optimize
  • Is it really a bottleneck?
  • Programmer intuitions often poor
  • You can waste work unnecessarily optimizing code
  • Best to optimize later, when bottlenecks can be
    identified better (ideally, through profiling)
  • Ideal flow Iterate
  • Measure to find biggest bottlenecks
  • Tune code to address it
  • Measure result discard if it didnt help
  • Repeat

33
Ok, You really want to Tune
  • Standard tuning strategies
  • Stop testing when you find the answer
  • Order tests by frequency
  • Substitute table lookups for complicated
    computations
  • Put busiest loop on the inside
  • Caching
  • Loop unswitching, jamming, unrolling (these are
    often done well by compilers)
  • Parallelize (for multicores) but not easy
  • As compilers get better, some advice gets
    obsolete

34
Internationalization and Localization
  • I18n and L10n
  • Adapt software to different languages and
    regional differences
  • Why? Want access to different regional markets
    without major changes in code
  • How do you design software so that you can
    convert all messages, time/date formats, etc from
    one language/region to another?
  • Example Date format US MM/DD/YY, Europe
    DD/MM/YY

35
I18n, L10n
  • What to change
  • Alphabets/scripts Most systems use Unicode
    standard to resolve character encoding issues
  • Language translation Normal and error messages,
    menu titles,
  • Currency, weights and measures, ID numbers,
    telephone numbers,
  • Number formats (decimal point vs comma,
    positioning)

36
Whats Done?
  • Place text in resource strings which are loaded
    during program execution as needed
  • Resource strings translated into various
    languages
  • No code change required, only point to a
    different locale to load appropriate strings
  • See e.g. GNU gettext
  • Difficulties
  • Have to keep parallel versions of the strings
    consistent through project lifetime
  • Some other details (direction of writing) not so
    easy, and may be solved using compilation time
    switches

37
More Info
  • IBM globalization (g11n) web site
  • http//www-01.ibm.com/software/globalization/index
    .jsp
  • Microsoft globalization website
  • http//msdn.microsoft.com/en-us/goglobal/bb688110.
    aspx
  • Java
  • http//java.sun.com/developer/technicalArticles/In
    tl/IntlIntro/

38
Administrative Items
  • Project 3 (design review) due Monday
  • HW 2 is up (due Wednesday)
  • Tell me what each group is up to?
Write a Comment
User Comments (0)
About PowerShow.com