New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Engineering Software

by: Mrs. Carolyne Abbott

Engineering Software CS 2220

Mrs. Carolyne Abbott
GPA 3.71


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 23 page Class Notes was uploaded by Mrs. Carolyne Abbott on Monday September 21, 2015. The Class Notes belongs to CS 2220 at University of Virginia taught by Staff in Fall. Since its upload, it has received 23 views. For similar materials see /class/209704/cs-2220-university-of-virginia in ComputerScienence at University of Virginia.

Similar to CS 2220 at UVA

Popular in ComputerScienence


Reviews for Engineering Software


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/21/15
David Evans wwwcsvirginiaeduc5205 Subtype Condition 1 Signature Rule We can use a subtype method where a supertype methods is expected Subtype must implement all of the supertype methods Argument types must not be more restrictive Result type must be at least as restrictive Subtype method must not throw exceptions that are not subtypes of exceptions thrown by supertype How do we know if saying B is a subtype ofA is safe Substitution Principle If B is a subtype of A everywhere the code expects an A a B can be used instead and the program still satisfies its specification c5205 engineering software 2 Signature Rule class A public RA m PA p class B extends A public RB m PB p RB must be a subtype of RA RB lt RA PB must be a supertype of PA PB gt PA covariant for results contravariant for parameters c5205 engineering software 3 c5205 engineering software 4 Subtype Condition 2 Methods Rule 0 Precondition of the subtype method must be weaker than the precondition of the supertype method mApre gt mBpre o Postcondition of the subtype method must be stronger than the postcondition of the supertype method mBpost gt mApost public int f a A x X REQUIRES a is initialized EFFECTS returns avalue xvalue return am x public class A An A may be initialized or uninitialized An initialized A has an associated int value public int m x X REQUIRES this is initialized public class B extends A A B may be initialized or uninitialized A B may be awake or asleep An initialized B has an associated int value public int m x X REQUIRES this is initialized M Can t make the precondit on stronger The callsite might not satisfy it c5205 engineering software 5 c5205 engineering software 6 public intra A x x REQUIRES aisiniuaiiz return a m x public class A An A may be initialized or uninitialized An initialized A has an associated int value public int m x REQUIRES this is initialized ed EEEEcTs returns a value gtlt vaiue public class B extends A A B may be initialized or uninitialized A B may be awake or aslee public int m x X REQUIRES nothing An initialized B has an associated int value Kay precondition is Weaker ms englneenng sn ware Properties Example public class StringSet Overview An immutable set of Strings public class MutStringSet Overview A mutable set of Strings MutStringSet cannot be a subtype of StringSet since it does not satisfy unchangable property Subtype Condition 3 Properties Subtypes must preserve all properties described in the overview speci cation of the supertype ms englneenng sn ware Properties Example public class StringSet extends MutStringSet Overview An immutable set of Strings public class MutStringSet Overview A mutable set of Strings StringSet could be a subtype of MutStringSet according to the properties rule ms englneenng sn ware Ibut couldn t satisfy methods rule ms englneenng sn ware 1n Substitution Principle Summary 0 Signatures subtype methods must be type correct in supertype callsites result is a subtype covariant para meters are supertypes contravariant 0 Methods subtype preconditions must be weaker than supertype preconditions covariant subtype postconditions must be stronger than supertype postconditions contravariant 0 Properties subtype must preserve all properties specified in supertype overview ms enqlneennq sn ware in client code MysteryTypel mtl MysteryTypeZ mt2 MysteryType3 mt3 anything could be here mtl mt2m mt3 if the Java compiier accepts this code which of these are guaranteed to e true a The apparent tvpe of mt2 is MvstervTvpe2 b At the last statement the actual tvpe of mt2 is MvstervTvpe2 c MvstervTvpe2 has a method named m d The MvstervTvpe2 m method takes a parameter of tvpe MvstervTvpe3 e The MvstervTvpe2 m method r s a subtvpe of MvstervTvpe1 t After the last statement the actual tvpe of mt1 is MvstervTvpel ms enqlneennq sn ware ll i clieth code MysteryTypel rnt1 MysteryTypeZ rnt2 MysteryType3 rnB an irig could be here rnt1 rnt2 rn rnt3 a The apparent type or rnt2 is MysteryTypeZ T UE the apparent type is obvious trorn the declarat on At the last statement the actual type ofth is MysteryTypeZ E we only know the actual type lt MysteryType2 MysteryTypeZ has a rnethod named TRUE U 1 The MysteryTypeZ rn method takes a pararneter or type MysteryType3 FA we only know it takes a pararneter gt WsteryType3 e The MysteryTypeZ rn method returns a subtype oflVlysteryTypel TRUE the assignment type checking depends on this t After the last statement the actual type 0t mt1 is MysteryTypel LSE we only know that the actual type lt WsteryTypei 52n5 enameeang sn ware Subtyping Rules dass A in client code MysteryTypel mt1 public RA m PA p MysteryTypez mm M T 3 839 class B extends A FEW we m 39 public RB m PB a mt1 mt2m mt3 If B lt A what do we know about RB and PB RB must be a subtype of RA RB lt RA PA must be a subtype of PB PB gt PA 52n5 enameeang sn ware Demystifying Subtyping Class A MysteryTypel mt public RA m PA p MysteryTypeZ mt2 MysteryType3 m8 mt1 mt2m mt3 If A is MysteryTypeZ what do we know about RA and PA RA must be a subtype of MysteryTypel RA lt MysteryTypel MysteryType3 must be a subtype of PA PA gt MysteryType3 52n5 enameeang sn ware Substitution Principle Summary Param Types Psub 2 Psuper contravariant Preconditions presub 3 presuper for inputs Result Type Rsub g Rsuper covariant Postconditions postsub 3 postsuper for outputs Properties propertiessub 2 propertiessu per These properties ensure if sub is a subtype of super code that is correct using an object of supertype is correct using an object of subtype Substitution Principle Is this the only way 52n5 enameeanq sn ware 52n5 enameeang sn ware Eiffel s Rules Described rn Bertrand Meyer paper out today 52n5 enameeanq sn ware Validation MG R AlluirliiGlNTOTHETUh x rarer FEE if ltzxg David Evans wwwcsvirginiaeducsZOS Java s License READ THE TERMS OF THIS AGREEMENT AND ANY PROVIDED SUPPLEMENTAL LICENSE TERMS COLLECTIVELY quotAGREEMENTquot CAREFULLY BEFORE OPENING THE SOFTWARE MEDIA PACKAGE BY OPENING THE SOFTWARE MEDIA PACKAGE YOU AGREE TO THE TERMS OF THIS AGREEMENT IF YOU ARE ACCESSING THE SOFTWARE ELECTRONICALLY INDICATE YOUR ACCEPTANCE OF THESE TERMS BY SELECTING THE quotACCEPTquot BUTTON AT THE END OF THIS AGREEMENT IF YOU DO NOT AGREE TO ALL THESE TERMS PROMPTLY RETURN THE UNUSED SOFTWARE TO YOUR PLACE OF PURCHASE FOR A REFUND OR IF THE SOFTWARE IS ACCESSED ELECTRONICALLY SELECT THE quotDECLINEquot BUTTON AT THE END OF THIS AGREEMENT c5205 engineering software 3 Java s License 2 RESTRICTIONS Unless enforcement is prohibited by applicable law you may not modify decompile or reverse engineer Software You acknowledge that Software is not designed licensed or intended for use in the design construction operation or maintenance of any nuclear facility Sun disclaims any express or implied warranty of fitness for such uses c5205 engineering software 5 Dictionary Definition validate 1 To declare or make legally valid 2 To mark with an indication of official sanction 3 To establish the soundness of corroborate Can we do any of these with software c5205 engineering software 2 Java s License 5 LIMITATION OF LIABILITY TO THE EXTENT NOT PROHIBITED BY LAW IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE PROFIT OR DATA OR FOR SPECIAL INDIRECT CONSEQUENTIAL INCIDENTAL OR PUNITIVE DAMAGES HOWEVER CAUSED REGARDLESS OF THE THEORY OF LIABILITY ARISING OUT OF OR RELATED TO THE USE OF OR INABILITY TO USE SOFTWARE EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES c5205 engineering software 4 Software Validation Process designed to increase our confidence that a program works as intended For complex programs cannot often make guarantees This is why typical software licenses don t make any claims about their program working c5205 engineering software 6 Increasing Confidence 0 Testing Run the program on set of inputs and check the results 0 Verification Argue formally or informally that the program always works as intended 0 Analysis Poor programmer s veri cation examine the source code to increase confidence that it works as intended Testing and Fishing Using some successful tests to conclude that a program has no bugs is like concluding there are no fish in the lake because you didn t catch one mus e gmeenllg mnware 7 mus e gmeenllg lumen s Exhaustive Testing 0 Test a possible inputs 0 P51 50x50 grid all cells can be either dead or alive before starting 2500 3753 5mmmmaaeuiaemaassowswaessi7592539770595233397322319319533770553573272575295333 my 1351 we 7mm 1 l 1 ms 93mllmlsmimsalvagagvvvslssmmvsuwmlwas moammwoglewsmwtameomlsn sova 259791 223 sci 2083773S aw 50739033203 1 l womvoevsmamemmmgmvsumgoaaaessw 5 1 23772240377 new mmmsosmsmssmolwvomvaeaglaamwaseamsmesszaeagssweasaaevsognaaemmammsom 073035029235237721wamwziuasaeasammmumammoeaaelawesoeam But that s not all all possible start stop step clicks different platforms how long to you need to run it etc Selective Testing 0 We can t test everything pick test cases with high probability of finding flaws o BlackBox Testing design tests looking only at specification 0 GlassBox Testing design tests looking at code Path complete at least one test to exercise each path through code mus e gmeenllg mnware 9 mus e gmeenllg lumen 10 Black Box Testing public CellState getNextState MODIFIES this EFFECTS Returns the next state for this cell If a cell is currently dead cell and has three live neighbors then it becomes a live cell I a cell is currently alive and has two or three live neighbors it remains alive Otherwise the cell dies Test all paths through the speci cation public CellState getNextState FIES is EFFECTS Returns the next state for this cell Ifa cell is currently dead cell and has three live neighbors en it ecomes a ive cell If a cell is currently alive and has two or three live neighbors it remains alive Otherwise the cell dies Test all paths through the speci cation currently dead three live neighbors currently alive two live neighbors currently alive three live neighbors currently dead lt 3 live neighbors currently dead gt 3 live neighbors currently alive lt 2 live neighbors currently alive gt 3 live neighbors immAwN mus e gmeenllg mnware 11 mus e gmeenllg lumen 12 Black Box Testing public Cellstate getNexSrate Glass Box Testing MODIFIES this public CellState geiNeXStateO EFFECTS Returns the next slate for this cell If a cell is currendy dead cell and has ree live neighbors then it bec mes a live cell i39 COWB WS 0r If a cell IS currently a ive n has two or three live neighbors it me a lt5 m0ble gt WW gewe ghbmol remal H e o erwised1e cell dies while neighbors hasMoreElemenBOM SlmObJect neighbor nelgh Test all 7 paths through the specification bors nexrilernento r neighbor instanceof Cell Cell cell Cellnelghbor HOW many paths are if cell lsAllveO countallve Test boundary conditions there through this co 1 all neighbors are dead if countallve 3M return CellState createAlive o 2 all neighbors are alive else if geState lsAllve 0m countallve 2 339 cell is at a corner of the return CellState createAlive 4 cell is at an edge of the grid 0 I e return CellState createDead 0 ms enameenng sn ware ms enameenng sn ware Path Complete Testing How many paths Insuf cient if oountalive 3 Often bugs are mlssmg paths emquot oestatecreateAiv Impossible r e else if getState isAlive ampamp re Most programs have an infinite number countalive 2 rn OellStatecreateAlive of paths e se retum OellStatecreateDead 0 Loops and recursion oTest with zero one and several iterations Branching 0 Can test all paths ms enameenng sn ware ms enameenng sn ware Testing Recap Quizzing Testing can nd problems not to prove your program works Since exhaustive testing is impossible select test cases with maximum probability of finding bugs A successful test case is one that reveals a bug in your program Typically at least 40 of cost of software project is testing often 80 of cost for safety critical software ms womenu sn ware ms womenu sn ware 94 44 4 39 7 D a t a E il39i g l i 3 c l Abstraction k wwwcsvirginiaeduc5205 Abstract Data Types Separate what you can do with data from how it is represented Client interacts with data through provided operations according to their specifications Implementation chooses how to represent data and implement its operations c5205 engineering software 3 Up and Down Clients manipulate an abstract data type by calling its operations methods and constructors clients 0 0 Abstract Type g 32 Concrete Representation class implementation The representation of an abstract data type is visible only in the class implementation c5205 engineering software 5 Managing Complexity Modularity Divided problem into procedures Used specifications to separate what from how A big program can have thousands of procedures How can we group them into modules c5205 engineering software Data Abstraction in Java A class defines a new data type Use private instance variables to hide the choice of representation private declarations are only visible inside the class c5205 engineering software Cell State Representation clients CellState CS ISAllve O 0 Abstract Type g 32 Concrete Representation class implementation private boolean alive public boolean isAIive return alive c5205 engineering software AdvantagesDisadvantages More code to write and maintain Run time overhead time to call method Client doesn t need to know about representation Suppose we want to add more states eg question 2 Set Example p52 Set abstract data type represent a set of objects Operations Create an empty set Mathematical set operations add contains size remove union ms nglneenng sn ware 7 ms nglneenng sn ware a Type Parameters We want to have sets of different types of objects How should we declare the Set methods public boolean add elem public boolean containsT elem public 7 choose We don t wantjust one Set dataty e We want different Sets for different element types ms nglneenng sn ware 9 Generic Datatype public class SetltTgt public boolean addT el public T choose public boolean containsT el Note Java did not support generic datatypes until version 15 this is why the book doesn39t use them ms nglneenng sn ware 1n Creating Specific Types public class SetltTgt public boolean addT el public T c oose public boolean containsT el public class SetltStnnggt public boolean addStn39ng el setltStrmggt gt public String choose public boolean oontainsString el Abstract Data Type Specifications Overview what the type represents MutabilityImmutability A Set is a mutabe unbounded set of objects of type T Abstract Notation A typical Set is XU xn Operations procedural specifications for each operation public methods and constructors use the abstract notation introduced in overview ms mumu sn ware 11 ms mumu sn ware 12 Set Specification public class SetltTgt RVIEW A Set is a mutable unbounded set ofobjects of type T A typical Set is LL xin public Set EFFECTS Initializes this to an empty set public boolean addT el ES this EFFECTS Adds eto the elements of this thispost this 6 U e Returns true iff ewas not an element of thispre contains ue I it is EFFECTS Returns true iff eis an element of this EFFECTS Returns ee this EFFECTS Returns el isIn this ms englneenng sn ware 13 ms englneenng sn ware 14 union public void unionSetltTgt t s e elemen s 39 MODIFIES this EFFECTS thispost thispre ut Specifications should be declarative what the outcome is not operational how it does it Implementing Abstract Data Types ms englneenng sn ware 15 ms englneenng sn ware 15 Choosing a Representation Need a concrete data representation to store the state Think about how it maps to abstract state Think about how methods will be implemented A good representation choice should Enable straightforward implementations of as many methods as possi Aow performancecritical methods to be implemented efficiently Set Representation Option 1 private T rep Recall Java arrays are bounded Easy to implement most methods hard to implement insert Option 2 private VectorltTgt rep Easy to implement all methods Performance may be worse than for array ms mumu sn ware 17 ms mumu sn ware 18 Implementing Set public class SetltTgt OVERVIEW SeE are unbounded mutable seE of elemenE oftype T A typical Set is x1 xn Representation private Vector rep public StringSet EFFECTS Initializes this to be empty rep new ec r 0 public void insert string s l MODIFIES this EFFECTS Adds s to the elemenE of this thisJJost thispre u l 5 rep add 5 Could this implementation of insert be correct It depends public int size EFFECTS Remms the number of elements in this etltTgt unique new etlt gt O for T el rep if luniqueisIn el uniqueaclcl current return uniquerepsize Is it correct public int size EFFECTS Returns the number of elements in this return repsize ms womenis sn ware 21 Reasoning About Data Abstractions How can we possibly implement data abstractions correctly if correctness of one method depends on how other methods are implemented How can we possibly test a data abstraction implementation if there are complex interdependencies between methods ms womenis sn ware 22 What must we know to know if size is correct public int size EFFECTS Remms the number of elements in this return repsize O This implementation is correct only if we know the rep does not contain duplicates To Reason about Operations We need to know How the concrete rep maps to abstract values Abstraction Function What values of the concrete rep are valid Representation Invariant Rep Invariant Predicate that all legitimate objects of the ADT must satisfy I C a boolean Helps us reason about correctness of methods independently Prove all objects satisfy the invariant before leaving the implementation code Assu me all objects passed in satisfy the invariant Reasoning with Rep Invariants REQUIRES Rep Invariant is true for this and any other reachable ADT objects EFFECTS Rep Invariant is true for all new and modi ed ADT objects on exit Every public datatype operation implicitly includes these preconditions and I J39Linns ms englneenng sn ware 25 ms englneenng sn ware 2s Rep Invariant for Set public class Set Representation private VectorltTgt rep RepInvariant c c contains no duplicates or RepInvariant c fora iJ39 repiequaisrepj only when i j Implementing Insert 39 void insert String s FIES this Not a correct implementation after it returns this might not satisfy the rep invariant ms englneenng sn ware 27 ms englneenng sn ware 2a Implementing Insert public void insert String s ODIFIES this EFFECTS Adds s to the elements of this thisipost thisipre U s if lcontains s repaclcl s Possibly correct implementation we need to know how to map rep to abstraction notation to know if thispost thispre U s Abstraction Function The Abstraction Function maps a concrete state to an abstract state C a Function from concrete representation to the abstract notation introduced in overview specification IWhat is the range of the Abstraction Function Range is concrete states for which rep invariant is true ms munu sn ware 2g ms munu sn ware an Semanch am Spec ymg Procedures guM IND 39YD UR HEAD David Evans wwwcsvirginiaeducsZOS The Stack and Heap Java lang smng String s new String hello smng is a tvpe W the Java API for Objects live on the heap creates an object on the heap Local variables live on the stac May point to objects on the heap ms nglnggnng sn ware String s new String hello String t s Java lang smng Java lang smng s new String goodbye ms nglnggnng sn ware Java Semantics b ms nglnggnng sn ware String s new String hello String t s Java lang smng ms nglnggnng sn ware Primitive Types Not everything in Java is an Object Some types are primitive types boolean byte char double oat int Ion Values of primitive types are stored directly on the stack ms nglnggnng sn ware String s new String o hell String t s s int i 205 t javalal lgSml lg intj i I 205 J 205 How can we see the difference between primitive types and objects ms nqlnggnng sn ware Equality X 7 Object Types same objects Primitive Types same value Xequals y Object Types method that compares values of objects Primitive Types doesn t exist ms nqlnggnng sn ware Mutability If an object is mutated all references to the object see the new value StringBuffer sb new hl StringBuffer tb sb tbappend gh Java lang SUll lgBuffer tb ImmutableMutable Types Types can be mutable or immutable Objects of an immutable type never change value after they are created String is immutable StringBuffer is mutable Stringconcat creates a new String object StringBufferappend mutates the old object ms nqlnggnng sn ware g ms nqlnggnng sn ware publlc class Sml39lgs publlc stauc vold test Smrlg args smng s new song hello ng t new song hello er so new SUll lgBuffer he r o m E t s concat goodbye Whatse me VaLes 05 5 5b and b now mm 0 these are true a r bjsj a cjs sjdjseqLas r ejsb b a teamss no i ms nqlnggnng sn ware 11 Java Semantics Question 9 spec ls not enougn to 5 Ni determlne lfs t s1 and t1 are ne some objects Java Language Specification Section 3105 String Literals Each string literal is a reference 431 to an instance 431 125 of class String 433 String objects have a constant value String literals or more generally strings that are the values of constant expressions 1528 are quotinternedquot so as to share unique instances using the method Stringintern ms mun J sn ware Java Semantics Question halo delwei halo delwei Java lang smng hello goodbvel Java Semantics Question Java Semantics Question halo delwei Java lang smng hello goodbvel After test returns halo delwei Java lang smng hello goodbvel Abstraction by Specification Managing Complexity 0 Divide problem into subproblems that Can be solved independently Can be combined to solve the original problem How do we know they can be solved independenUy How do we know they can be combined to solved the original problem cs205 engineering software 19 cs205 engineering software 20 Abstraction fl An abstract on is a manytoone map Using Abstractions When a client uses an abstraction it should work as the client expects it to no matter with implementation is provided How should client know what to expect c5205 engineering software 21 c5205 engineering software 22 Specification 0 Tells the client of an abstraction what the client can expect it to do 0 Tells the implementer of an abstraction what the implementation must do to satisfy the client Contract between client and implementer Client will only rely on behavior described by specification Implementer will provide an implementation that satisfies the specification Good Specifications 0 Clear precise and unambiguous Cients and implementers will agree on what they mean 0 Complete Describe the behavior of the abstraction in all situations 0 Declarative Describe what the abstraction should do not how it should do it c5205 engineering software 23 c5205 engineering software 24 Formality of Specifications 0 Informal written in a natural language eg English People can disagree on what it means Degrees of informality 0 Formal written in a specification language Meaning is de ned by speci cation language whose meaning is defined precisely but eventually informally May be analyzed by machines eszus engineering sn ware Example Informal Specification Excessive bail shall not be required nor excessive nes imposed nor cruel and unusual punishments inflicted 8th Amendment eszus engineering sn ware What do you call people who decide what informal specifications mean cszu5 engineering snnware Correct Implementation public static boolean violatesEigthAmendment Punishment p EFFECTS Returns true if p violates the 8 11 amendment crueand unusual punishments return pisCruel ampamp pisUnusual 0 Or did they mean pisCruel pisUnusual cszu5 engineering snnware Procedural Specifications 0 Specification for a procedure describes What its inputs are What the mapping between inputs and outputs are What it can do the state of the world eszus engineering sn ware Requires and Effects 0 Header name of procedure types of parameters and return value Java declaration o Clauses comments in Java REQUIRES precondition the client must satisfy before calling EFFECTS postcondition the implementation satisfy at return cszu5 engineering snnware Contract Client promises to satisfy the precondition in the requires clause Implementer promises if client satis es the precondition the return value and state when the function returns will satisfy the postcondition ms nqlneenng sn ware 3 Specification Contract f REQUIRES precondition EFFECTS postcondition ltthe precondition is true after we call f 0 the postcondition is true precondition f 039 postcondition ms nqlneenng sn ware 32 Specification Example public String bestStock REQUIRES false EFFECTS Returns the name of the best stock to buy on the NASDAQ tomorrow Can we implement a procedure that satisfies this specification Yes al l lmplemel ltatol l Wlll satlsf this speci cationl if the Dl eCOl ldlthl l h the requires clause lS hot satisfied the procedure Cal l do anything al ld still Satisfy ltS speclfcatonl ms nqlneenng sn ware 33 Specification Example public String bestStock REQUIRES true EFFECTS Returns the name of the best stock to buy on the NASDAQ tomorrow Can we implement a procedure that satisfies this specification ms nqlneenng sn ware 34 Requires Clauses The weaker more easy to make true the requires clause The more useful a procedure is for clients The more difficult it is to implement correctly Avoid requires clauses unless there is a good reason to have one Default requires clause is REQUIRES true Cient doesn t need to satisfy anything before calling ms em mu sn ware 35 Specification Example public static int biggest int a REQUIRES true EFFECTS Returns the value of the biggest element of a Is this a reasonable specification No what should client expect to happen if a is empty Specification Example public static int biggest int a REQUIRES a has at least one element EFFECTS Returns the value of the biggest element of a Is this a good specification Maybe depends on the client Its risky Bad Use of Requires Clause Bug discovered in Microsoft Outlook that treats messages that start with begin as empty attachments can be exploited by viruses To workaround this problem Do not start messages with the word quotbeginquot followed by two spaces Use only one soace be een the word quot eginquot and e following data Capitalize the word quotbeginquot so that it is reads 39Beginquot Use a different word Such as quotsmrtquot or quotcom fltrrl HUD USUDDUVI mlubsbft Urndefault asw stldKE NrU5er523m thls ls rib lDr E avallable was YEVEkEdV by Mltmsb zszns enameeang sn ware Modifies Modi es clause any state not listed in the modifies clause may not e changed by the procedure public static int biggst int a REQUIRES tru MODIFIES nothing EFFECTS Ifa has at least one element returns the value iggest element ofa Otherwise retums IntegerMINiVALUE smallest int value Specification Example public static int biggest int a REQUIRES true EFFECTS If a has at least one element returns the value biggest element of a Otherwise returns IntegerMINVALUE smallest int value Better but client has to deal with special case now Best would probably be to use an exception zszns en Modifies How does a client know a is the same after biggest returns public static int biggest int a REQUIRES true EFFECTS Ifa has at least one element returns the value biggst element ofa OthenNise retums IntegerMINiVALUE smallest int value Reading the effects clause is enough 7 if biggest modifies anything it should describe it But that s a lot of wor zszns enameeang sn ware Modifies Example public static int replaceBiggest int a int b REQUIRES a and b both have at least one element MODIFIES a EFFECTS Replaces the value of the biggest element in a with the value of the biggest element in b Objectrite Programming David Evans wwwcsvirginiaeducsZOS Midterm Exam 0 Out at end of class today 0 Due Monday at beginning of class c5205 engineering software from Class 2 Buzzword Description Am objectoriented distributed in erpre e robust secure architecture neutral portable high performance multithreaded and dynamic language Sun95 Later in the course we will discuss how well it satisfies these buzzwords c5205 engineering software 3 What is Object Oriented Programming c5205 engineering software What is an Object 0 Packaging state and procedures state the rep oWhat a thing is procedures methods and constructors What you can do with it c5205 engineering software 5 Bjarne Stroustrup C s Answer 39EI39 quot39I39equotEaquotee Data absl Faet39el 39l39 395 I W F exeeptiens objectoriented programming canand ought to be a superset of data abstraction hesetechn1qtresneedpropelesupporHo be FFIEIIII I supperEmtheFen o anguageFeature nd ll IF generalptn poseralanguagesupportingdata abstl39laEE39eFE 639 Objeet OFIIICI39Eleld p39elgl39a39Ill39Il39I39g39 ust c5205 engineering software I invented the term Object Oriented and I can tell you I did not have C in mind Alan Kay ms enameeang sn ware Programming Language History 0 Simula Dahl and Nygaard 19627 First language with subtyping and inheritance o CLU Liskov et al 19705 First language with good support for data abstraction but no subtyping or inheritance o Smalltalk Kay et al 19705 First successful language and programming system to support subtyping and inheritance ms enameeang sn ware Programming Language History Before 1954 twidling knobs machine code assembly code FORTRAN John Backus UVa dropout 1954 Formula Translation Algol Peter Naur Alan Perlis et al 1958 1960 Most influential programming language Many of the things Algol did first types while blocks are in Java ms enameeang sn ware ObjectOriented Programming 0 ObjectOriented Programming is a state of mind where you program by thinking about objects 0 It is difficult to reach that state of mind if your language doesn t have Mechanisms for packaging state and procedures Java has class Subtyping Java has extends subtype and subclass and implements subtype 0 Other things can help dynamic dispatch inheritance automatic memory management mixins good donuts etc Who was the first object oriented programmer ms enameeanq sn ware ms enameeang sn ware By the word operation we mean any process which alters the mutual relation of two or more things be this relation of what kind it may This is the most general definition and would include all subjects in the universe Again it might act upon other things besides number were objects found whose mutual fundamental relations cou d be expressed by t ose of the abstract science of operations and which should be also susceptible of adaptations to the action of the operating notation and mechanism of the engine Su posing for instance that the fundamental relations of pitc e sounds in the science of harmony and of musical composition were susceptible of such ex ression and adaptations the engine might compose elaborate and scientific pieces of music of any degree of complexity or extent Ada Countess of Lovelace around 1843 12 ms enameeanq sn ware Don t forget to email your registration survey if you haven t yet please do it today David Evans wwwcsvirginiaeducs205 COUFSG Announcements 0 Assistant Coaches Drew Abott and Dan Marcus Lab hours after class today Sunday 7 830pm 0 Office Hours Posted time conflicts with c5202 New time is 1030 noon on Thursdays My door is almost always open feel free to stop by outside of office hours oszos engineering software 2 Why so many programming languages Pro tamming uby Fundamental Differences o All equivalently powerful Universal languages all capable of simulating each other 0 Fundamental differences EXpressiveness how easy it is to describe a computation Truthiness likelihood that a program means what a programmer things it means Safeness impact of programmer mistakes 0 There is usually a conflict between expressiveness and truthinesssafeness oszos engineering software 3 oszos engineering software 4 Pragmatic Differences 0 Performance of available compilers interpreters 0 Tools available 0 Libraries 0 Portability o Availabilitycost of programmers What is Java JAV 39 A Island in Indonesia known for coffee and volcanoes B A Programming Language JavaTM C A Portable LowLevel Language JVML D E A Platform JavaVM A semisuccessful marketing strategy JavaScript is not related to Java or JavaTM oszos engineering software 5 oszos engineering software 6 Java History 0 1991 Stealth Project formed at Sun Computing for consumer electronics market 0 James Gosling tasked with selecting a programming language for project Started with C but found inadequate o In later classes we ll talk about why Developed extensions and subtractions that led to new language Oak 0 1993 Web arrives o 1995 Sun releases HotJava browser and Java PL Netscape incorporated into browser c5205 engineering software 7 Buzzword Description A simple object oriented distributed interpreted robust secure architecture neutral portable high performance multithreaded and dynamic language Sun95 Later in the course we will discuss how well it satisfies these buzzwords c5205 engineering software 3 Non Buzzword Description 0 Java sacrifices expressiveness for safety and truthiness A Java program is 5x larger than the corresponding Scheme or Python program 0 Java sacrifices performance for safety and truthiness A Java program is 2x slower than the corresponding C program but 5x faster than the corresponding SchemePython program Caveat these numbers are guesses and gross simplifications Real numbers depend on the program and programmer c5205 engineering software 9 Java Programming Language 0 Syntax Similar to C Designed to be easy for C and C programmers to learn 0 Semantics what programs mean Similar to Scheme Designed to make it easier to reason about properties of programs c5205 engineering software 10 Programming Systems Scheme Interpreter Object Files Machine I cszos engineering software 11 Java VM Why use a virtual machine I A o Portability If you can implement a Java VM on your machine then you can run all Java programs class Files 0 Security A VM can limit what programs can do to the real machine 0 Simplicity VM instructions can be simpler than machine instructions Java Program java Files Java Compiler Java Virtual Machine Machine c5205 engineering software 12 Programming in Java Program is composed of classes A class Defines a new datatype Defines methods and state associated with that datatype We call a value of a class datatype an object Objects package state and code 52 5 enemeeana sn ware 13 Types Every entity in a Java program has a type Primitive types int char boolean etc Object types all classes Variables are declared with a type boolean alive CellState state in Celljava Compiler checks and requires type correctness A Java Class CS205 Fall 2006 CelleamJava Comments to end of line public class Cellsmm ERVIEW A Cellsmte is an immutable object that represenE the state ofa cell either alive or dead private boolean alive iitslance variable state arm5 J 1 private CellSlam molean isalive EFFECTS Initializes this to alive if isalive is true otherwise initializes this m the dead state this alive isalive constructor 52 5 enemeeana sn ware 14 VlSlblIlty Modifiers CS205 Fall 2006 CellStatejava public class CellState OVERVIEW A Cellsmm is an immutable object that represenE the smte of a cell either alive or dead private boolean alive private Cellsmtebool39public quotany Code Bah EFFECTS Initializes v ii otherwise initiaiizesi read and modlf private onlycaccessible insidequotc7lass thisalive isalive llow do these help manage complexity 52 5 enemeeana sn ware 15 52 5 enemeeana sn ware 6 private CellStateboolean lsallve EFFECTS lrlluallzes ml to allye lf lsallye lS Due otherWise ll llhallzes this to the dead state static public nonnull CellState createAllVeO EFFECTS Returns an allye cell state return new CellStatetme l static public nonnull CellState createDeado EFFECTS Returns a dead cell state return new CellStatefalse J public Color getColorO EFFECTS Returns the dlsplay color for this state if allye return Color green else return Color Wht e l 52 5 enemeeanc sn ware 17 ExtremeLlfeCeII Class ptblic class EmemeLlfeCell extends Cell I prIic CellState gemextsmte EFFECFS Remns me next state for lls oell The next slam Wlll be allye lf H15 oell or any ole rlelclhbors ls curermy allye All this code is needed to walk through the list oe s ye Itthe cell has atleast one neighboring tell that Of Glgh bOFS relun CellState oeaEAllyeO nltSimobiectgt neigrbors gelNelgTborsO while nelghbors hasMoreElemerlBOM amooiect neighbor neigrbors nexl emerlto if nei moor instanceot Cell I l Cel neihbor l NO allye rlelgl39bor found next smm ls curerlt SEE return getstateo Hirit you probably Will Want l the same code for ConwaytiteCell 52 5 enemeeanc sn ware Ia


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Amaris Trozzo George Washington University

"I made $350 in just two days after posting my first study guide."

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.