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


by: Betty Kertzmann
Betty Kertzmann
GPA 3.51


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 48 page Class Notes was uploaded by Betty Kertzmann on Tuesday September 22, 2015. The Class Notes belongs to CS 414 at Colorado State University taught by Staff in Fall. Since its upload, it has received 8 views. For similar materials see /class/210190/cs-414-colorado-state-university in ComputerScienence at Colorado State University.


Reviews for Object


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/22/15
Design by Contract I Dr Roger T Alexander University Services Building Room 240 Voice 4917026 Fax 4912466 Topics 0 The nature of Contracts 0 Preconditions and Postconditions 0 Problems Expressing Contracts Contracts Contracts in human affairs Contracts are written between two parties when one of them the supplier performs some task for the other the client Each party expects some bene ts from the contract and accepts some obligations in return One party s obligation is a bene t for the other The aim of the contract is to spell out these bene ts and obligations Contract Example Obligations Benefits Client Must ensure May bene t from precondition postcondition Be at the Santa Barbara Reach Chicago airport at least 5 minutes before scheduled departure time Bring only acceptable baggage Pay ticket price Supplier Must ensure May assume precondition posmondmon No need to carry passenger Bring customer to who is late has unacceptable Chicago baggage or has not paid ticket price ProgrammingDesigning by Contract Relationship between a supplier e g procedure method class and clients Viewed as formal agreement Expresses each party s rights and obligations Only through precise de nition of every module s claims and responsibilities can we hope to attain a signi cant degree of trust in large software systems Benefits of Design by Contract Better understanding of software construction Systematic approach to building bugfree software Effective framework for debugging testing Precise documentation of semantics Explicit welldefmed policy for dealing with abnormal cases Better understanding and control of inheritance Assertions 0 A statement of something assumed to be fact ie a constraint Eg age ofcustomer gt minimum drinking age 0 An assertion is a property of some of the values of program entities 0 Can be used in the semantic speci cation of routines Preconditions and Postconditions Precondition expresses the properties that must hold Whenever a procedure is called Postcondition describes the properties that the procedure guarantees when it returns Task performed by a procedure is by two assertions each corresponding to precondition and postcondition Preconditions and Postconditions Precondition binds clients De nes conditions under which a call procedure is legitimate Postcondition binds the server De nes the conditions that must be ensured by procedure on return 0 Bene t for client is that certain results will be obtained after the call Preconditions and Postconditions 0 Bene ts for server is guarantee that certain assumptions will be satis ed Whenever the procedure is called 0 If the client s part of the contract is not ful lled if the call does not satisfy the precondition then the class is not bound by the postcondition But what if 0 Precondition is not satis ed 0 Postcondition is not satis ed Stack Example Obligations Benefits Client Pro grammer Only call pushx on a nonfull stack Get x added as new stack top on return Supplier Imp lementor Make sure that x is pushed on top of stac No need to treat cases in which the stack is already full Who should do the checking 0 Observation A main source of complexity is constant need to check if data satisfy the requirements for correct processing Who should do the checking Nobody Not done at all not safe Everybody almost Done in several places for safety reasons Who should do the checking 0 Recommended approach is to systematically use preconditions Allow procedure author to assume that he corresponding precondition is satis ed 0 Aim is to provide simple style of programming Favors readability maintainability etc Who should do the checking Strict preconditions keep the code simple It is client s responsibility to ensure call satis es preconditions 0 Loose preconditions make the supplier more fault tolerance But supplier must deal explicitly with errors An Example Stack 1 2 3 4 5 s 7 8 9 P ubiic class Stack private Sequence fTheE1ements new sequence H Adds the specified element to the top of the stack Daram D The Hement o be added re u l nu mp0 public void nusm Omect o Centrettrenuire u I nun quotStazkpush7 Argument 0 is nunquot contractensure o h150p quotStacKpush o is not the e1ement at top of stackquot pre 1istnpty0 stack has at 1eest une element w post size of the stack has been reduced by one from the top public Object nonO Centrettrenuire Iistmptyo quotsummary The stetk is emptyquot omen resuit we need tn kezp track cf the turrent size cf the stetk at we can Express the pusttnnditiun int oidsize fTheElementssi39Ze n 34 35 35 37 Cuntractensure trhetienentssizeo e uidsize 1 as 39 4o 39 39vr Ten it the stetk is Empty or nut 41 42 pr39e true 43 post Nothing has changed 44 V 45 puhiit b00123quot istnptyo hetiementsmzeo gt 0 45 47 43 49 50 M Return the e1ement at the top of the stack 51 52 pr39e listnptyt 53 39 s4 Dost resu1t ftheEiementsta 55 post Nothing has changed 56 57 public Object top 53 it Contractrequire 1istnpty0 quotStackpup The stack is emptyquot 60 61 Dbect resuit frhet1ementstai1 62 63 return result 64 65 66 ass Stack Beware the mal formed Assertion Assertions are a great way to do passive testing 0 But they only check what you express 0 Can be too strong Yields false positives 0 Can be too weak Allows incorrect states to pass unnoticed Expressing Preconditions 0 Express only logical properties Eg empty E g full 0 Do not express constraints using underlying representatlon Client will not have access to it 0 Use methods that check logical properties In general there should not be a one one correspondence between state variables and these methods 0 Only use methods that have no sideeffects Expressing Postconditions Postconditions should also express logical properties 0 We classify postcondition expressions into two types Physical These correspond to properties of the state itself Logical These are what the client is interested in what the method does 0 Only use methods that have no sideeffects Problems Expressing Postconditions Expressing postconditions is problematic We can t always express the result that we desire Often turns out to be equivalent to the computation of the method 0 Must result to checking implied conditions Conditions that must necessarily be true if the postcondition is true But the converse is not true Postcondition Prob em 23 Postcondition Pro em 24 12 Postcondition Problem ma 3 139 M Postcondition Problem What s wr ng here 1va 1 Other Uses of Assertions Things we expectassume to be true Done at various points of interest Immediately following method calls Immediately following complex expressions At any points where we can detect faults if they have occurred At points of uncertainty We also use assertions to express facts about state Design by Contract Guidance DBC Insights Preconditions and postconditions exist even if you don t explicitly state them The assumptions that you make de ne preconditions The implementation that you write de nes postconditions The question is are you going to tell anyone about them DBC Insights Contract assertions Selectively increase observability Only report when an assertion is violated Silence otherwise 0 Reduce testing effort Often eliminate or reduce the need for a test oracle ie expected values 0 Tell you when you screw something up during maintenance General Principles 1 Separate queries from commands 2 Separate basic queries from derived queries 3 For each derived query write a postcondition that speci es What result will be returned in terms of one or more basic queries 4 For every query and command decide on a suitable precondition 1 Separate queries from commands Queries return information but have no side effects Do no change state of objects Needed for writing contract assertions Commands have side effects but return no information Can change state of objects Needed to provide behavior 2 Separate basic queries from derived queries 0 Basic queries form a conceptual model They enable us to state all the essential logical properties about an object A weaker model will prevent you from stating essential logical properties that you need 0 Derived queries are based on basic queries Values of derived queries are de ned in terms of the values of the basic queries 3 For each derived query 0 Write a postcondition that speci es what result will be returned in terms of one or more basic queries This allows us to know the values of the derived queries if we know the values of the basic queries 4 For every query and command decide on a suitable precondition 0 By Virtue of principles 2 and 3 complete effect of command is known in terms of basic queries Stack Revisited Basically the only commands on a stack are put remove and something to get the top most item What basic queries and derived queries do we need to specify the contract for Stack Put lt739gtolt739gt onto the top of the stack put I M Remove the item at the top of the stack How to apply Design by Contract General DBC Guidance 0 De ne preconditions and postconditions for each public method Really Do it You re going to disable them anyway Add contract assertions require and ensure for each public method Don t worry about getters Add contract assertions for each nonpublic method Guidance on Checking Preconditions Explicitly check the precondition prior to making a call when You cannot say with certainty that the precondition will always be satis ed assuming correctness 0 Otherwise use assertions to check your assumptions at the call site 20 Precondition Assertion Guidance 0 Each formal argument should be constrained by at least one expression 0 Global variables used by a procedure should be constrained by at least one expression Biter write helper methods that express logical properties that are dependent upon the global variable 0 Check only logical properties Do no directly reference encapsulated state Use a helper method instead Postcondition Assertion Guidance 0 Each changed variable should be constrained by at least one expression Express encapsulated state variables as logical proper tres 0 User helper methods to encapsulate complex constraints 6 g universal and existential quanti ers 0 Check result against a known value or closed form expression If not practical check against an approximation or other implied properties 21 When you get a precondition violation 0 If the procedure is brand new First check the precondition assertion against the procedure specification Correct the assertion if necessary 0 Otherwise Figure out which constraint failed identifying which variables were involved Look back to the caller tracing the statements that affect the variables Instrument client with assertions to check any assumptions you are making prior to the call When you have a postcondition violation 0 If the procedure is brand new First check the precondition assertion against the procedure specification Correct the assertion if necessary 0 Otherwise Figure out which constraint failed identifying which variables were involved Look back to the procedure body tracing the statements that affect the variables Instrument supplier with assertions to check any assumptions you are making 22 Using Contractjava For each method write speci cation as javadoc comments pre post modifies Have each prepost express only a single logical property Instrument procedure for each pre post expression appearing in speci cation comments Contractrequire for pre Contractensure for post Instrument with general assertions to check other assumptions Contract assert Questions 23 Responsibilityd riven Design Dr Roger T Alexander 240 University Services Building Voice491 7026 F X 491 2466 rtacscoloslale edu hilgvarmcscoloslaleedulrta CRC Cards Class Objectoriented class Responsibility What the class does Collaboration Relationship to other classes Bene ts Uses index cards Cheap readily available amenable to group use Forces you to be concise and clear Puts your attention on the what not how Simple easy methodology Intuitive Portable Example Collaborations are indicated by listing names of other classes Responsibilities usually listed as short English sentences Attributes are written on back of card MVC Example Basic Process Start with written requirements spec Use textual analysis to identify core classes Derive classes and place each on separate card Annotate with super and subclass information Continue textual analysis to identify responsibilities Begin to analyze existing cards for collaboration relationships Hasknowledgeof Dependson Refine until stable set is produced Continue with detailed design Textual Analysis Find Candidate Classes Nouns Model physical objects Model conceptual entities that form cohesive abstractions Eliminate aliases by choosing most meaningful class in terms of rest of system Model conceptual entitles Beware of adjectives They can be used in many ways Can suggest different objects Can suggest different uses Model physical devices Choose one word for one concept Name Contro r superclass subclass Interpret User Input Distribute Control Record Candidate Classes One card per class Include state of purpose for the class What it represents What it does Not how it does it Find Abstract Classes These help determine structure of software Spring from set of classes that share a useful attribute Implies a shared behavior for classes having that attribute Design an abstract class to capture behavior shared by several classes Goal Find as many abstract classes as possible Group Classes Identify abstract superclasses by grouping related classes Map each group to an abstract superclass rd each on an index card Include subclasses Record superclass on cards ofeach subclass Troubles naming a group Enumerate shared attributes ofgroup members and derive name Divide members into smaller more clearly de ned groups Discard it Identify Missing Classes Classes can be missing because They are unimportant Specification was imprecise likely Not easy to do Experience counts Responsibilities Represent Knowledge an object maintains Actions object can perform Convey sense of purpose of an object and its place in the system Are services provided by client Only represent publicly available services Private services deferred until later Identifying Responsibilities Look at requirements specification List verbs and verb phrases that clearly represent actions that some object in system must perform Also note information that must be maintained or manipulated Walkthrough scenarios ie use cases of how system will be used Identifying Responsibilities Look for places where something must occur as a result of some input Has the need for action been accounted for What new responsibilities are implied by the nee Use candidate list of classes already identified An identified classs suggest a responsibility Look at class statement of purpose Assigning Responsibilities Assign each identified responsibility to a class or classes it logically belongs to Guidelines Evenly distr bute intelligence State responsibilities as generally as possible Keep behavior with related information if any Keep information about one thing in one place Share responsibility among related classes Evenly Distribute Intelligence Minimize number of classes that are intelligent This leads to a centralized control model Distribute as evenly as possible Allows objects to know State Responsibilities as Generally as possible Easier to find common responsibilities Don t do this A LineEement knows how to draw a line A RectangleEement knows how to draw a rectangle Instead Each kind of DrawingEement knows how to draw itself Each subclass of DrawingEement knows how to draw itself in a unique way Keep Behavior with Related Information Objects responsible for maintaining information should also be responsible for operating on that information Objects that need certain information to carry out its actions it should also maintain that information all other things being equal Like things belong together Localizes effects of change in information fewer objects need to be noti ed Keep Information about one thing in one place Responsibility for maintaining specific information should not be shared Doing so leads to duplication and possibility of inconsistency If more than one object must know the same information Create new object that is sole repository of the information 2 Factor behavior out of objects that need information and reassign to object respons bility for maintaining information 3 Collapse different objects that require the same information into a single object Share Responsibilities Often responsibilities seem to be shared among 39ects Eg DrawingEdtor requires that correct state of drawing be displayed at all times DrawingEditor know when drawing has changed and to be redrawn Drawing knows which elements to draw Each DrawingEement know show and where its visual representation should be drawn Responsibility is shared Broken down to smaller responsibilities Assigned to most appropriate class Part II Collaborations How do classes fulfill their responsibilities Performing necessary computation themselves Collaborating with other classes Collaborations represent requests from a client to a server in fulfillment of a client responsibility Collaborations only exist to fulfill a responsibility Collaborations Pattern of collaborations reveal flow of control and information during execution Collaborations represent paths of communication between classes Finding Collaborations Begin by analyzing interactions of each class Examine responsibilities for dependencies As the following questions for each responsibility Is the class capable of ful lling this responsibility itself 2 If not what does it need 3 From what other class can it acquire what it needs Finding Collaborations Each shared responsibility also represents a collaboration For each class ask 1 What does this class know7 2 What othr classes need the result or information Discard classes that have no interactions with other classes Collaboration Relationships ls partof Hasknowledgeof Dependson lspart of Wholepart relationship Relationships between composite classes and object h m Relationships between containers and their elements Composite classes Are responsible for containing the objects that Manage its parts in some way or Are responsible for knowing about its parts Eg Drawing is responsible for knowing which 5 elements it con aIn lspart of Hasknowledgeof Composite objects often fulfill a responsibility by delegating responsibility to one or more of their Implies a responSibility to know someming parts Relationships between containers and their Implies a Conabora on bEtWeen the Class elements may or may no require a collaboration having the knowledge and the class that is Eg Stack does not collaborate with elements known Eg Hashmap does needs hash code of each elemen Dependson Recording Collaborations lmplies a hasknowledge relationship or Locate card for class playing role of client May imply existence of a thirdparty Write name of class playing role of server to the forming the connection right of the responsibility it collaboration servers Eg to help fulfill Elements in a Drawing exist in front of or 39 GUidance behind the DrawingEements in the same Make sure every collaboration has a corresponding drawing responsibility Each DrawingElemth may know who is in Include all classes that participate in a collaboration front and who is behind or Drawing may Asubclass collaboration is not recorded if superclass know already provides that collaboration How do you know it will work Perform a Walkthrough Choose a plausible set of inputs for each scenario Manually execute each scenario Start with initial input for scenario and find class that has respons bility for responding to that input Trace through the collaborations of each class that participates in satisfying that responsibility Make adjustments as necessary Repeat until scenario has stabilized ie no further adjustments necessary Questions Selecting Core Classes Form a list of candidate classes Start with written requirements spec Use textual analysis to identify key objects classes Formulate statement of purpose for each candidate class Example TM Cash dispenser Screen message Display ey Financial Transaction Selecting Core Classes Partition candidate list into three categories Core These muse be included Irrelevant These are outside system scope Use use cases Undecided Must figure this out Selecting Core Classes Classes fall into common groups Application domain Database User interaction External interface Etc Selecting Core Classes Each group has common patterns Clients gt collections Servers gt containers Things Transactions Locations Interacting systems Interacting devices Things that are not classes Some classes are really just attributes They refer to just one atomic piece of information eg balance Cannot change states Things that are not classes Phantomsghosts Classes that are really pieces of outside systems We know these indirectly Surrogatesaliases A class that is really another class already de ned Some classes are reallyjust attributes They refer tojust one atomic piece of information eg balance Cannot change states Le a signi cant change of meaning Desirable Class Characteristics Clear unambiguous name Meaningful to domain experts Consistent use of names across systems Singular noun Has responsibilities Remembers something ie has knowledge ls needed by other classes ie collaborators Actively participates in the system Creating CRC Cards Use one class per card Name of core class goes at top Use pencil Don t discard candidate list yet Assigning Responsibilities Focus on what not how Technique Brainstorm first Think logically not physically Keep it simple Determining Collaborators Role Play If this class does this what other classes will be involved What are the dependencies Write collaborations to the right ofthe responsibility Contracts Think about collaboration in terms of clients and servers and contracts Contract one class relies on another to fulfill part of its responsibility lnformally describe what the contract does and who the participants are clients These will ultimately lead to preconditions and postconditions Determining Inheritance Relationships Superclass a class this class inherits from May have objects concrete May not abstract Subclass a class that inherits from this class Key is shared behavior Kindof isa relationship Shared behavior between superclass and subclass Superclass has responsibilities shared by all subclasses Eg Customer gt RetailCustomer Partofhasa relationship Responsibilities are not shared Collaboration used instead Determining Inheritance Process Lay out CRC cards Organize by kindof relationship Super and subclass Fill in Super and subclass information on card CRC Cards and UML CRC Cards and UML Entire set of CRC cards used to create class diagram Inheritance modeled using UML generalization relationship Coaborations modeled using UML association Exception Handling er T Alexander University Services Building Room 240 Voice 4917025 Fax 491 2455 Procedural Abstraction Recall that procedures map arguments to results 7 Arguments selected from domain 7 Results members of range Procedures often only de ned for a subset of the 7 We Write partial procedures to deal with this 7 Clients must ensure that arguments are from the permitted subset of the domain 7 Implementer must ignore arguments outside this subset Partial Procedures Liskov advises avoiding partial procedures 7 In stark contrast to Meyer Partial procedures 7 Do not behave reasonably for all possible inputs 7 Should always behave in a wellde ned way for all inputs Total Procedures Behavior is defined for all possible inputs Procedure must notify caller if intended behavior cannot be performed How do we Notify A common way is to use a particular result 7 Example post X 2 0 5 result X post X lt 0 5 result 0 Notifying by Special Result Not a good idea 7 Too easy for programmer to ignore error 7 The error doesn t really look like an error but it is Special results must be explicitly checked by caller 7 Can t write 2 y factorialx nstead int r factorialx if r l 0 Notifying by Special Result Won t work if all values of type are possible results from procedure 7 Where have we seen this before What we really desire is a mechanism that 7 Conveys information in all cases 7 Makes it dif cult for programmer to ignore by mistake Exceptions are the Answer Allow us to treat retums for normal cases separately from returns due to abnormal cases Allow us to treat each exceptional condition separately Specifying Exceptions We want procedure specifications to accurately re ect all possible outcomes Must create a set of postconditions that include 7 The normal case What the procedure is supposed to o 7 Each abnormalexceptional case Liskov Exercise 35 int min int a This procedure returns the minimum value in a What should the specification be Partial Specification 1 pre a null pre alength gt 0 post result is the smallest element in a Partial Specification 2 pre a null post alenglh gt 0 2 result is the smallest element in a post alenglh 0 2 throws EmplyA rrayException Total Specification pre true post a null 2 throws NullArgumenlExeption post alenglh gt 0 2 result is the smallest element in a post alenglh 0 2 throws EmplyA rrayExceplion Writing Speci cations with Exceptions Realize that the possibility of exceptions forces the postcondition to be partitioned 7 post ltthe normal casegt 7 post ltthe abnormal casegt Each type ofexception increases the size ofthe partition by one 7 post ltthe normal casegt 7 post ltthe abnormal case 1gt 7 post ltthe abnormal case 7 Specifying Postconditions that have Exceptions Use the following syntax in your Javadoc comments post ltnormal conditionigt gt ltnormal postcondtionigt post ltabnormal conditionjgt gt throws ltexceptionjgt Important Notes 39 Do not include conditions that correspond to the condition or an exceptional case r 7 For total procedures the precondition necessarily equates to true Unless all inputs correspond to normal cases 7 Preconditions should be speci ed that describe the normal input and the abnormal input 7 All ofthese conditions collectively must equate to true You should be able to transform a total specification into a partial speci cation by simply removing all abnormal cases from speci cation Writing Contract Assertions Specify precondition just as you normally would Only include a postcondition check for each normal case Exceptions will be thrown for abnormal cases Note that there must be a conditional check to test each condition that implies the exceptional case r The throw clause for the exception is dependent upon the check Throwing Exceptions in Java Checked Exceptions 7 Are represented by instances of class that are subtypes of Exception 7 Must be declared or caught Unchecked Exceptions 7 Are represented by instances of class that are subtypes of RuntimeException 7 Do not have to be decalred or caught Which should we use Which to use Checked Exceptions 7 Used to signify abnormal conditions that occur but ose occurrence prevents establishment of the postcon ition Unchecked Exce tions 7 Signilfy abnormal conditions that occur outside the speci 1cation r Represent an error condition beyond the control of the procedure 7 Signify situation where abnormal condition has occurre an sys em cannot be returned to awell de ned stable state Dealing with Exceptions 39 Who should Catch 39 When an exceptions occurs caller has four choices 7 Ignore allowing it to propagate 7 Catch it do some processing thch 1ct it propagate c rethrow 7 Catch it do some processing thch fold to another excecotion c ow a dmchcht exception 7 Catch it do some processing and resume normal activities a c mask thc exceptions 39 Realize that regardless ofhow you deal with an exception their use alters control ow and increases complexity When to use Except1ons According to Liskov r Exceptions do not necessarily equate to errors 7 They are a means of communicating information r The can convey information about error or nonerror EXCCpthnS and Contracts conditions Note There are many that View the only acceptable use ofan exception is to signify an error Acceptable uses in this class 7 Handle arecognition difficulty 7 In place of using special data to communicate with cal er Responsibility for Precondition Violations Checkmg Precond1t1on Every method specification must define What does it mean when a precondition precisely What data is valid for the method violation occurs Every method must be designed and coded Error in Client implementation on the assumption that its data is valid 7 It means that system is in an invalid state that it If method B is used by method A then A is was net demgned to handle responsible for ensuring that the data passed to B is valid for B Precondition Violations continued What do we do ifa client fails to ensure a precondition 7 Ignore it dangerous 7 Deal with it still dangerous client is expecting operation to be carried out 7 Produce suitable diagnostic message and punt 7 Notify some other component of the violation and allow it to deal with the problem Error Handling and Preconditions Observation Every method has a set of preconditions whether they are explicitly specified or not 7 Satisfying them is an integration issue Issue Who is responsible for ensuring that preconditions are established by client 7 The Client 7 The Supplier defensive 7 Both hybrid Client is Responsible Implications 7 Client must understand speci cation of supplier completely 7 Actions of client prior to call must imply precondition Client is Responsible continued Drawbacks 7 Logic of client must accommodate semantics of Benefits 7 Supplier does not have to check results in lower complexity for supplier 7 Client can assume correct implementation of supplier Supplier is Responsible suppher ls ResponSlble contlnued Implications Drawbacks 7 Client does not have to worry about establishing precondition not really Must distinguish between valid and invalid states 7 Supplier must handle all possible inputs 7 Client complexity increases due to expanded 7 Size of the set of possible sideeffects increases interface 0f Supplier 7 Supplier complexity increases substantially 39 Must be prepared to handle all of the ways in Which call can fail 39 Client cannot assume the postcondition of supplier Supplier is Responsible Possible Actions continued for Precondition Violations Benefits Detect violation and carry out some safe 7 Client does not have to ensure the precondition aCtiOIl ultimately 1396thng t0 caller 7 Potentially more robust supplier but forces Detect violation report and terminate client to be more robust as well Detect violation restore invariant throw a special exception Carry Out a Safe Action This is the defensive approach Add logic that distinguishes between valid and invalid data 7 Handle valid data normally 7 Treat invalid data uniformly or distinguish individual cases 39 Set appropriate error codes 39 Return magic values Client must somehow be aware of problem Detect Report and Terminate This is the nondefensive approach Requires special detection code or special tool support 7 Eg AssertMate 7 Rollyourown assertion mechanism 7 Something provided by the language After termination fix the fault Detect Restore and Throw Faulttolerant variation of nondefensive approach Gives system opportunity to take corrective measures if possible 7 Correcting invalid state 7 Isolating invalid state 7 Dif cult to do Questions Java Style Guidelines File Headers The following should appear at the top of each source le ltfile namegt C8414 Assignment X ltStudent Namegt ltemail addressgt This should be a comment describing the contents of the file List all of the classes by access specifier as follows Public Classes Classl a brief description Class2 a brief description Class3 a brief description Protected Classes None Private Classes AprivateClass a brief description If you use a version control system that inserts revision comments directly into your le a good idea have them inserted at the end of the le after the source code The rationale for this is that the clarity and readability of the program are just as important as the semantics that it embodies Placing revision comments near the top of the le only makes it more dif cult to nd things Each time a revision is made a new set of comments presumably are added which pushes everything that follows lrther down breaking whatever conceptual integrity the reader has about the le What is important is that the comments be present in the le assessable if needed Placing them at the end achieves this and makes the le easier to read Block Style Use the following style of indentation and brace alignment indentation levels should be four spaces Please do not use tabs class SomeClass int fSomeStateVariable O Invariant fSomeState gt 0 ampamp fSomeState lt 10 public void foo Method description This methodm Require conditions that must be true to call method Ensure conditions that must be true after method has executed int i for i O i lt 10 i Systemoutprintln Line i i 2 0 Print a blank line Systemoutprintln public void foo class SomeClass In general both opening and closing braces should line up with the rst character of the keyword eg if while for etc that they correspond to Statements within the block should be indented four spaces Note the comments on the closing braces of the class speci cation and the lnction de nition These are particularly important as an aid to nding things in the le and for maintaining one s orientation The commentng convention includes the complete signature for the class and the lnction This crucial for distinguishing overloaded method names Variables The names of class state variables elds should begin with f and each word in the name should be upper case as in fCurrentSpeed This convention is borrowed from the old Taligent guidelines for C The rationale is that the pre x makes it easier to identify instance variables that form part of the state space of the enclosing class Static elds should begin with the pre x fg ngumberO nstances This makes it easier to distinguish class ie static variables from instance variables Local variables de ned within a block e g lnction condition etc should have the rst word of the name all lower case which each remaining word beginning with an upper case letter thisIsLocal Place all state variables at the top of the class before any of the methods Order them according to their access speci ers with public appearing rst followed by protected and nally private Place class variables those with the static modi er before instance variables Methods 0 Method names should be meaningful and descriptive of the lnction they perform Begin each method name with an lowercase letter and make the first character of each additional word in the name upper case as well public void doSomethirigO 0 Methods should appear a er all of the state variables for the class That is place state variable de nitions before methods 0 Place methods into groups according to their access specifiers with public appearing first followed by protected and finally private 0 Within a given method access group place methods alphabetically in the following sub groups Constructors Destructor nalize Accessors methods that return information Mutators also called modifiers 7 methods that change the state of an object Iterators methods that allow you to iterate over a collection of objects owned by the class Follow all coding conventions in the Code Conventions for the JavaTM Programming Language which can be found at httpiava sun J J him ndananOF inc html In cases where there are con icts between the Java coding convections from Sun and those described above the quot in this J take 39


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!"

Anthony Lee UC Santa Barbara

"I bought an awesome study guide, which helped me get an A in my Math 34B class this quarter!"

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."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

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.