ucla cs 130 lecture 07
DESCRIPTION
UCLA CS 130 Lecture 07 software engineering classTRANSCRIPT
-
The Nitty and the GrittyCS130 Lecture 7CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Where we AreStarted with requirementsProgressively digging deeperSpecifications: What to buildDesign: How to buildArchitecture: Detailed plan for the designDesign Patterns: More detailed plans
Today: Code level detailsA VERY brief survey from McConnells Code Complete
CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Where will we go Next?Next few lectures will be on testing/debuggingCurrent practice as well as current research in testing/software quality
One of the most exciting directions in software engineering research!
CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Code Level DecisionsProgramming Language
Programming ConventionsNot required by language, but often crucialExamples: All executables will have version optionVariable naming conventions
Programming Tools and FrameworksExample: IDEs (Eclipse), debug tools,Frameworks: J2EE, .NET, Spring, Ruby on Rails
CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Designing Your SoftwareKey Challenge: Manage ComplexityEssential Problems (underlying problem is hard or ill-defined) vs Accidental Problems (language does not have particular features)Goal: Modularize essential complexityHow?Stratification (abstract layers)Loose couplingExtensibility and reusabilityPortabilityNo formula: heuristic processCS130 Prof Majumdar Lecture 7Design Patterns
CS130 Prof Majumdar Lecture 7
-
Design HeuristicsFind a real-world analogy for objects
Encapsulate details, hide informationMakes programs easier to modifyPattern example?
Isolate areas likely to changePattern example?CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Working ClassesClass = Cohesive collection of data and routines that share a responsibilityAnd let you ignore the rest of the program when looking at class implementationIgnore class implementation when looking at useBased on Abstract Data TypesHide implementation details, localize effect of changesCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Good AbstractionsConsistent level of abstractionEg dont mix several responsibilities
Understand the abstraction from the problem viewpoint
Enforce interfacesLimit accessibility to methods/membersDont let client depend on assumptions beyond interfaceEg: hash table client should not assume ordering of valuesCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
RoutinesAka methods, functions, subroutines
Routines reduce complexityIntroduce understandable abstractionAvoid duplicate code
Simple routines are goodDont be shy of writing small onesCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Routine CohesionHow closely its operations are related
Functional cohesion (best)Routine does one thing onlySequential cohesionOperations share data and must be done in sequenceBad design:Procedural cohesionRoutine exists only to sequence operationsCoincidental cohesion = no cohesionCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
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 conventionsTo let you concentrate on more important thingsCompensate for some language weaknessesEmphasize relationships otherwise missedCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Typical Naming ConventionsRoutines: verb (OO languages) or verbObject (non-OO)Opposites used precisely: min/max, open/closeGive Boolean variables logical names:Status_ok or Status_not_found (rather than status, or status_error)
Many more conventions, project specific conventionsCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Possible Things to Identify viaNaming ConventionsTypes vs Variables vs ConstantsEx: Constants in ALL_CAPSi,j integer indices, p pointer, s string
Globals vs Locals vs Members
Inputs, Outputs, InputOutputs
CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
- Naming Conventions ExampleGeneral Advice:Name should accurately describe the named entityE.g.: bpp bytes_per_pageNames should be specificE.g.: do_work compute_bytes_per_pageNames should relate to problem, not solutionE.g.: two_to_the_bits bytes_per_pageNames should have right lengthTypically,
-
Naming Conventions: MorebytesPerPage vs bytes_per_pageSurprising how much time is lost!
Consistency is important!!
Bottom Line: Favor read-time convenience over write-time convenienceCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Bad NamesVisual puns: si10 vs siloInside jokes: revenge_on_joesimilar sounding: cownt, count
Similar names, different work:aBufLength, a BufferLengthSimilar work, different names:inputLength, il
CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Defensive ProgrammingWrite code so that bugs are easier to catch and fix
Not a substitute for good design principles!
Basic Idea: Dont trust the external worldCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
- Example: Whats Wrong?int a(int arr[], int n, int i) { return a[i];}int a(int arr[], int n, int i) { assert(0
-
Whats Wrong?x = (struct foo *)malloc();x->a = 0;CS130 Prof Majumdar Lecture 7Better:x = (struct foo *)malloc();If(x == NULL) { handle error }
x->a = 0;
CS130 Prof Majumdar Lecture 7
-
Whats Wrong?s = inputString();
Printf(s);What if s has format characters?e.g:S = %n?
Look up %n CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Whats Wrong?S = SELECT pwd FROM Table WHERE name = ;
Name = inputString();Query = S ^ Name;
Execute(Query);SQL Injection Attack:
What if Name isFoo || 1 == 1OrFoo ; DELETE Table
Similar issues in cross site scripting
CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Whats Wrong?
Lock();If(error condition) {return;}Unlock();Return;On error condition, lock is not releasedLead to deadlockCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
What can you do?Input ValidationTaint analysis: make sure input data always passes through validatorAssertions
Contracts (pre- and post-conditions)
Static AnalysisCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
RefactoringMyth: Coding can proceed linearly, ie written once, tested, and forgotten.
Reality: Various upstream issues change, code evolves substantially during initial developmentCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
RefactoringChange internal structure, not observable behavior, in order to make code easier to understand and modify
Motivated by projects that evolve during constructionAgile/XP developmentCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
When to Refactor?Duplicate CodeUnused codeAwkward APIPoorly encapsulated classesGod classClass that does littleRoutines grouped together that shouldnt beToo long routine, too many parametersOften called smells [Martin Fowler]CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Refactoring TechniquesGeneral principlesDRY: Dont repeat yourself(Copy and paste is a design error)
Do refactorings one at a timeBe prepared to undoKeep refactorings smallOrganizeTESTCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
TechniquesReplace code with routineEncapsulate data (eg introduce class)Rework routine to avoid duplication
Change values to references and vice versaPull a routine up to superclassPush a routine to subclassMove routine from interfaceAdd inheritance/delegation
Centralize access to dataCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Refactor GraduallyAs you go rather than all at onceCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Code TuningPerformance often conflicts with other design goalsExample of design pattern that can reduce performance?
Many patterns introduce indirectionFactories, Strategies, Indirection is costly
CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Code TuningQuestion 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 improvements80-20 rule (80% of execution in 20% of code)Amdahls LawCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Why Not to OptimizeIs it really a bottleneck?
Programmer intuitions often poorYou can waste work unnecessarily optimizing codeBest to optimize later, when bottlenecks can be identified better (ideally, through profiling)Ideal flow: Iterate:Measure to find biggest bottlenecksTune code to address itMeasure result; discard if it didnt helpRepeat
CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Ok, You really want to TuneStandard tuning strategiesStop testing when you find the answerOrder tests by frequencySubstitute table lookups for complicated computationsPut busiest loop on the insideCachingLoop unswitching, jamming, unrolling (these are often done well by compilers)Parallelize (for multicores) but not easyAs compilers get better, some advice gets obsolete
CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Internationalization and LocalizationI18n and L10n
Adapt software to different languages and regional differencesWhy? 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/YYCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
I18n, L10nWhat to change:Alphabets/scripts: Most systems use Unicode standard to resolve character encoding issuesLanguage translation: Normal and error messages, menu titles, Currency, weights and measures, ID numbers, telephone numbers, Number formats (decimal point vs comma, positioning)CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Whats Done?Place text in resource strings which are loaded during program execution as neededResource strings translated into various languagesNo code change required, only point to a different locale to load appropriate stringsSee e.g. GNU gettextDifficulties: Have to keep parallel versions of the strings consistent through project lifetimeSome other details (direction of writing) not so easy, and may be solved using compilation time switchesCS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
More InfoIBM globalization (g11n) web site:http://www-01.ibm.com/software/globalization/index.jspMicrosoft globalization websitehttp://msdn.microsoft.com/en-us/goglobal/bb688110.aspx
Java:http://java.sun.com/developer/technicalArticles/Intl/IntlIntro/
CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
-
Administrative ItemsProject 3 (design review) due Monday
HW 2 is up (due Wednesday)
Tell me what each group is up to?CS130 Prof Majumdar Lecture 7
CS130 Prof Majumdar Lecture 7
**************************************