1Chapter 9 Chapter 9 ––Designing Designing ClassesClassesChapter GoalsChapter GoalsLearn to identify side effectsLearn to identify side effectsKnow when to use method preconditions Know when to use method preconditions and and postconditionspostconditionsGo in depth a bit more on static (Go in depth a bit more on static (akaakaclass) class) methods and fieldsmethods and fieldsDesign programs the objectDesign programs the object--oriented wayoriented way9.3 Immutable Classes9.3 Immutable ClassesRecall that Recall that accessoraccessormethods only retrieve methods only retrieve informationinformationThey do not change the state of the objectThey do not change the state of the objectCalling them multiple times in a row will yield Calling them multiple times in a row will yield same resultssame resultsImmutable Classes are classes that only Immutable Classes are classes that only have have accessoraccessormethodsmethodsExample: String ClassExample: String ClassAdvantagesAdvantagesDo not have to worry about the dangers of Do not have to worry about the dangers of handing off references in methods because handing off references in methods because there are no methods that can modify them.there are no methods that can modify them.DisadvantagesDisadvantagesYour objects are fixed once they are created.Your objects are fixed once they are created.9.4 Side Effects9.4 Side EffectsMutatorsMutatorsare designed to change the internal data are designed to change the internal data of the implicit parameterof the implicit parameterSide effect of a method: modifying externally Side effect of a method: modifying externally observable data (explicit parameters or reference observable data (explicit parameters or reference types)types)public void public void transfer(doubletransfer(doubleamount, amount, BankAccountBankAccountother)other){{balance = balance = balancebalance--amount;amount;other.balanceother.balance= = other.balanceother.balance+ amount; + amount; // Modifies explicit parameter// Modifies explicit parameter}}Best to avoid if possible (otherwise, document the Best to avoid if possible (otherwise, document the effect thoroughly)effect thoroughly)Other Side EffectsOther Side EffectsWhy donWhy don’’t we add a t we add a printBalanceprintBalance() method to () method to BankAccountBankAccount??public void public void printBalanceprintBalance()(){{System.out.println("TheSystem.out.println("Thebalance is now $" balance is now $" + balance);+ balance);} } Assumes the printing should be done to the screenAssumes the printing should be done to the screenAssumes the printing should be in EnglishAssumes the printing should be in EnglishMakes this class dependent on the System class and Makes this class dependent on the System class and PrintStreamPrintStreamclassclassYou want to localize the input and output of your You want to localize the input and output of your program to as few places as possibleprogram to as few places as possible2How to minimize Side Effects?How to minimize Side Effects?Never modify explicit parameters to a Never modify explicit parameters to a methodmethodTreat them as constantsTreat them as constantspublic void public void deposit(doubledeposit(doubleamount)amount){{amount = amount = amountamount+ balance;+ balance;}}Pass By ValuePass By ValueTwo ways to pass parametersTwo ways to pass parametersPass by reference Pass by reference ––the memory location is the memory location is sent, meaning that the data can be changedsent, meaning that the data can be changedPass by value Pass by value ––a copy of the memory a copy of the memory location is createdlocation is createdJava only uses pass by valueJava only uses pass by valueEven objects are passed by value, since the Even objects are passed by value, since the reference is copiedreference is copiedWonWon’’t work!t work!public class public class BankAccountBankAccount{{public void public void transferTotransferTo((BankAccountBankAccountother, other, double amount)double amount){{balance = balance = balancebalance––amount;amount;double double newBalancenewBalance= = other.balanceother.balance+ amount;+ amount;other = new other = new Neither will thisNeither will thisclass Qclass Q::public void public void addResponse(StringaddResponse(Stringquestion) {question) {String response = String response = ““I acceptI accept””;;question = new question = new String(questionString(question+ response);+ response);}}class Rclass R::public void invite() {public void invite() {Q friend = new Q();Q friend = new Q();String invite = String invite = ““Want to go to the dance?Want to go to the dance?””;;intintinviteLengthinviteLength= = invite.lengthinvite.length();();do {do {friend.addResponse(invitefriend.addResponse(invite););} } while(invite.lengthwhile(invite.length() == () == inviteLengthinviteLength););}}You would need to do thisYou would need to do thisclass Qclass Q::public public StringStringaddResponse(StringaddResponse(Stringquestion) {question) {String response = String response = ““I acceptI accept””;;returnreturnnew new String(questionString(question+ response);+ response);}}class Rclass R::public void invite() {public void invite() {Q friend = new Q();Q friend = new Q();String invite = String invite = ““Want to go to the dance?Want to go to the dance?””;;intintinviteLengthinviteLength= = invite.lengthinvite.length();();do {do {invite =invite =friend.addResponse(invitefriend.addResponse(invite););} } while(invite.lengthwhile(invite.length() == () == inviteLengthinviteLength););}}39.5 Preconditions9.5 PreconditionsPrecondition: Requirement that the caller of a Precondition: Requirement that the caller of a method must meet method must meet Publish preconditions so the caller won't call Publish preconditions so the caller won't call methods with bad parameters methods with bad parameters /**/**Deposits money into this account.Deposits money into this account.@@paramparamamount the amount of money to depositamount the amount of money to deposit(Precondition: amount >= 0)(Precondition: amount >= 0)*/*/PreconditionsPreconditionsTypical use: Typical use: To restrict the parameters of a method To restrict the parameters of a method To require that a method is only called when To require
View Full Document