it-106 pseudo-coding wk 5
TRANSCRIPT
ContentsPhase 1: Design Concepts................................................................................................................1
Project Description.......................................................................................................................1
Use Cases.....................................................................................................................................2
Data Dictionary............................................................................................................................3
High Level Design Components..................................................................................................4
Detailed Design: Checkout Diagrams..........................................................................................7
Design Analysis........................................................................................................................8
Detailed Design: Product Research............................................................................................10
Diagrams................................................................................................................................10
Design – Using Pseudocode.......................................................................................................11
Product Profit.........................................................................................................................11
Phase 2: Sequential Logic Structures............................................................................................12
Design........................................................................................................................................12
Product Profit.........................................................................................................................12
Phase 3: Problem Solving with Decisions.....................................................................................13
Safe Discount.........................................................................................................................13
Return Customer Bonus.........................................................................................................14
Applying Discounts................................................................................................................15
Phase 4: Problem Solving with Loops...........................................................................................16
Total order..............................................................................................................................16
Problems to Solve...................................................................................................................17
Calculate Profits.....................................................................................................................17
Rock, Paper, Scissors.............................................................................................................19
Number Guessing Game........................................................................................................21
Phase 5: Using Abstractions in Design..........................................................................................23
Seeing Abstractions....................................................................................................................23
Refactoring.................................................................................................................................23
Phase 1: Design Concepts
Project Description
Although we may be late to the game, we will nevertheless join the world of e-commerce to sell our fantastic product on the Internet. To do so, we need a Web site that will allow for commerce and sales. To be quick about it, we require the following:
Searchable inventory and shopping pages A shopping cart A place for customers to register when they make purchases A checkout process to make the purchase
Within this main process, there are a bunch of other needs that must be met, as follows:
We want to track the date of the last purchase a customer make so we can offer incentives and discounts based on the last time they shopped.
We will offer sales based on the number of different items that a person purchases. We will also give discounts for bulk orders a discount when a person buys many of the same
item
In addition to sales feature, the solution must provide the ability to manage and research the sales of products. It must include the following:
Must be able to add, update and remove product inventory in real time on the site Needs to have research capabilities to determine how well a product is selling, such as the
following:o How often the item is viewed, added to shopping carts, and then purchasedo How a price change affects sales and profit
Use Cases
From the description above, we can relate this to the following use cases, which describe how the user will interact with our system. Each use case is a set of screens that the users would interact with to accomplish something they need on the site.
1
In addition to the customer’s activity, the solution will allow Sales Analysts to manage and research product sales.
2
Data Dictionary
Variable Name Type DescriptiontodaysDate Date Today’s date, when the program is runningcreationDate Date The date the customer created their accountpriorPurchases Integer Number of Purchases this customer has made in
the pastlastPurchaseDate Date The date of the last purchase the customer madelineItemPrice Array The price of each line item the customer has
added to the cartlineItemQuantity Array The quantity of each line item the customer has
added to the cartmembershipLevel Integer The account nature of the customer
1 – Guest 2 – Registered 3 – Preferred
totalPurchaseAmount Double The cost of all the items in their current purchasesalesTaxRate Double The sales tax to be charged on a purchaseproductCategory Integer An indicator of the category of the product
1 – Consumer Goods 2 – Electronics 3 – Clothing
productPrice Double The price of the product as sold to the customerwholesalePrice Double The price at which we purchase the productnumberInCarts Integer The total number of times this product has been
added to a shopping cartnumberOfPurchases Integer The number of times this product has been
purchasedallProductSalesNumbers Array A list for each product of the number of times a
product has soldallProductPrices Array A list for each product of the product priceallProductWholesalePrices
Array A list for each product of the product wholesale price
3
High Level Design Components
Our architects have created the following components to be realized by our development team in meeting the use cases above.
4
UserSecurity
CustomerManager
Purchasing
CardProcessing
ShoppingCart
ProductInventory
SearchEngine
Fill out the following table to describe which components are used by each use case and how each component will help realize the use case:
Use Case Component Services ProvidedDate todaysDate Today’s date, when the program is runningSearch/Browse Inventory
productInventory Provides access to the database of inventory of all products and their descriptions and prices and such.
searchEngine Allows for searching on many criteria within the product database
productCategory 1 – Consumer Goods 2 – Electronics 3 – Clothing
lineItemPrice The price of each line item the customer has added to the cart
lineItemQuantity The quantity of each line item the customer has added to the cart
Register As Customer customerManager Create and manage customer profile and personal information
creationDate The date the customer created their accountpriorPurchases Number of Purchases this customer has made in
the pastlastPurchaseDate The date of the last purchase the customer
madeuserSecurity Provide security solutions for the visitors to the
siteChoose Products numberInCarts 1-Item
2-Item3-Item
totalPurchaseAmount The cost of all the items in their current purchase
salesTaxRate The sales tax to be charged on a purchase
Apply Discounts membershipLevel 1 – Guest2 – Registered3 – Preferred
Manage Products wholesalePrice The price at which we purchase the productproductPrice The price of the product as sold to the customerallProductPrices A list for each product of the product priceallProductWholesalePrices A list for each product of the product wholesale
priceResearch Sales numberOfPurchases The number of times this product has been
5
purchasedallProductSalesNumbers A list for each product of the number of times a
product has sold
My interpretation of graph above ↑ and below ↓ is yours.
Use Case Component Services ProvidedSearch/Browse Inventory
ProductInventory Provides access to the database of inventory of all products and their descriptions and prices and such.
SearchEngine Allows for searching on many criteria within the product database
Register As Customer CustomerManager Create and manage customer profile and personal information
UserSecurity Provide security solutions for the visitors to the site
Choose Products Search Engine Allows for searching on many criteria within the product database
Purchasing Types of products being purchased and placed in cart
Checkout Shopping Cart What can be seen in the cart for purchase or return.User Security Keeps user secure while accessing site for shopping
preferences and checkout for credit cardsCard Processing Monitors types of payment and encrypts contents
for secure transfer
Apply Discounts Card Discount Amount of allowable discount based on new, returning or bulk buyer.
Manage Products Product Inventory Reviews the amount of products sold verses products in stock
Purchasing Assess wholesale verses retail and profits established through input variables
Research Sales Product Inventoy Reviews the amount of products sold verses products in stock
Purchasing Monitors number of times item purchased, overall items sold
6
Detailed Design: Checkout Diagrams
We could realize this design as either structured or Object-Oriented given the following design diagrams.
Figure 1 Structure Design for calculateOrderTotal
7
daysSinceLast Purchase
returnCustomerBonus
bulkBuyerDiscount
bigBuyerDiscount
Calculate Subtotal
calculateOrderTotal
Figure 2: Sequence Diagram for calculateOrderTotal
Design Analysis
Given the designs above, we need to analyze which approach we should take and how the code realization will differ.
Structure Design
Describe the implementation of the structure design in Figure 1 and how it relates to the Checkout use case.
ANSWER: Implementation of the structure design can be used with the decorator style method as it ensures additional responsibilities are attached to an object dynamically keeping the same interface. Decorators provide a flexible alternative to sub-classing for extending functionality.
What procedures and functions are being created in the design?
ANSWER: A procedure is a finite sequence of well-defined instructions, each of which can be mechanically carried out in a finite amount of time. A function is the computer reading the variables and constants to figure an output calculation based on calculations ran. There are six executable functions and procedures within this design.
What data would be passed between these procedures and functions?
ANSWER: The data is the “calculateOrderTotal; bigBuyerDiscount; bulkBuyerDiscount; returnCustomerBonus”; passed to “discountManager; daysSinceLastPurchase; calculateSubtotal”; customer; calculateTotal. These would send numerical calculations through the psuedocode algorithm to give a final cost assessment to the customer.
8
calculateSubtotal()
daysSinceLastPurchase()returnCustomerBonus()
bulkBuyerDiscount()
bigBuyerDiscount()
;Taxes;Customer;DiscountManager;Order
Object-Oriented Design
Describe the implementation of the object-oriented design in and how it relates to the Checkout use case. ANSWER: Unlike a procedural language, where the program is a series of tasks that must be performed, object-oriented language is made up of objects that interact with one another. Each object is made up of a series of tasks that can be performed independently of other objects. These tasks are generally hidden from other objects, which prevents them from interfering. Only the end results of the object’s operations are then seen by other objects
What methods are being created in the design?ANSWER: A method is really the same as a procedure, function or routine in procedural programming languages. The only difference is that in object-oriented programming, a method is always associated with a class. The class defines all the common properties of the different objects that belong to it. In this design there are four methods being compiled. They are order; dicountManager; customer;taxes.What data would be passed between these methods?ANSWER: The discounts, bonuses, days since last purchase, calculation subtotal and taxes.
Comparison
How do these approaches (Structured versus OO) differ?ANSWER: Structured coding runs in a sequential format, which runs each function in a step-by-step process. Structured design is also better for smaller programming code as it is more efficient and doesn’t use as many factors to function as OOP does. As the number of functions within the structure increase, it becomes intensively difficult for the program to manage data and operate efficiently. You may even be able to run a procedure within the OOP design. OOP has polymorphism where structured doesn’t. Structured may be identified as a class within OOP. The classes work together to better manage the whole flow of the program dependent on information that is inputted.
When we get to code, how much will the detailed implementation differ because of the high level design approach we have chosen?ANSWER: Unlike low-level languages, high-level languages have high abstraction. In other words, they are much more similar to the language you speak than are the low-level languages. Many high-level languages are very similar in syntax to natural language. This makes programming much easier. High-level programming languages use abstract concepts such as loops, variables, and arrays. The most recent high-level languages use objects that are reusable. The drawback to high-level languages is that they use a lot of memory and take a lot of time to process. However, modern computers are faster allowing them to handle these larger programs. High-level language programs can often be compiled for different platforms.
9
Detailed Design: Product Research
Diagrams
For the product research use case, take a stab at either a structured design diagram or a sequence diagram that would fulfill at least part of the functionality of the use case. We will compare what you create here to the detailed design we create through the rest of the course as a way of measuring your progress.Provide a diagram of your choice here to show a flow for researching products.
The exact details are flexible within the description of the functionality, so do your best to create a flow that looks like a code solution using the components above or ones you think you need. This is practice that will give you a measuring stick for your learning as we see problems later in the course related to this system.
10
Yes
No
No
Yes
No
No
Yes
NoYes
No
No
Yes
Yes
Yes
Yes
Yes
No
Yes
Yes
Product Research HP Computer
Is item in stock?
Input “n” quantity
left
Customer purchase +1Add to cart/Purchase ?
Adjust inventory = 0
Re-order item ?
Adjust inventory -1 New Customer
Gather information
High Selling item Phase out
Returning Customer Apply discount ?
Visitor
Discount applied
First Name
Last Name
Address
City
State
Zip
Proceed to Checkout?Continue Shopping?
Pay method
Shipping address / Payment method
Confirm payment?
Continue Shopping?
Payment Confirmed
Empty Cart
Design – Using Pseudocode
Product Profit
Description
It is important to know the profit each product is providing to the bottom line. Given that we know the wholesale cost, the retail cost to consumers and the number of items we have sold, calculate the profit for a given product.
Pseudocode
{function productProfit(productPrice : Double,
wholesalePrice : Double,
numberOfPurchases : Integer}
Return Double
{
Input = createVariable(productPrice)
Input2 = createVariable(wholesalePrice)
profitPrice = (productPrice – wholesalePrice)
returnProductprofit
}
End function
11
Phase 2: Sequential Logic Structures
Design
Product Profit
Description
Continuing with the same example of calculation product profit, utilize the same scenario to create a flowchart.
Description - It is important to know the profit each product is providing to the bottom line. Given that we know the wholesale cost, the retail cost to consumers and the number of items we have sold, calculate the profit for a given product.
Flowchart
12
profitPrice = (productPrice – wholesalePrice)
Return ProductProfit
endFunction
productProfit(productPrice : Double
Additional Pseudocode
Discuss how input/output, operators, and expressions are presented in pseudocode as well as how they are used to accommodate needs for sequential logic within business applications. Additionally, discuss how various data types may be used within sequential logic structures.
ANSWER: Pseudocode is delivered in a five-step method. As part of these steps, input/output, expressions and operators are addressed. The first step involves defining the elements and other variables of the function that you will need for the pseudocode. It will also include the dimensional data variables, which are part of the “INPUT” values of the code being used. The input/output operators can also be established in this process to use information from the keyboard, apply it to the function and output to the screen or printer. The final step, in step one, is to set up the control functions you will use. Be it text and images or basic controls from simpler languages. Step 2 involves adding functional pseudocode to add specific “event driven” code to initiate the project once you have completed the initial controls. Functional pseudo code normally uses the parameters of the “if”, “then”, “while” and “else”. Functional code also incorporates the expressions of “READ”, “WRITE”, and “PRINT”. Step 3 involves checking your pseudocode for compliance conventions. Ensure the above elements are in your code. These elements a diversified throughout many code languages and are an intrinsic part of the processing of the function. Under step-4 of the process, comments should be entered to ensure the role of different task and parts of the code to the reader. Comments to not have to rivet every line of the process but are good for transferring to other steps. Finally, step-5 looks at reviewing the syntax or pseudocode you have just written. Ensure proper spelling, marker point’s parenthesis are in key positions and so on.
Sequential Logic structure is considered the oldest form and most used type of structure. The nice thing about sequential logic is it is basically a designer writing a step-by-step function to be accomplished for searching, mapping or any other operation needing to be conducted on a system. Sequential logic is like writing a shopping list and can be utilized in any programming code format, whether it is one of the lower end or high end coding programs. Items below are for testing data.
> Greater than < Less than ≥ Greater than or equal to ≤ Less than or equal to or && and symbol or | | the “or” symbol ¬ “is Not” == logically equivalent
13
Phase 3: Problem Solving with DecisionsSafe Discount
DescriptionWe want to ensure that the system will not accidentally discount a product below the price that it is purchased for. Thus, we want an operation to ensure that, when a discount is applied, it always stays more than the original purchase price.Sample data could include the following:
A product at $10 with a wholesale price of $5 and a discount of 10% returning $9. A product at $10 with a wholesale price of $6 and a discount of 50% returning $6.
Pseudocode
function applyDiscount(productPrice : Double, wholesalePrice : Double,applyDiscount : Double)
Return DoublecreateVariable (finalPrice : Double){
if finalPrice = product price− productPrice X dicount100
return discount}if (finalPrice ≥ wholesalePrice)then{
returnPrice} else {return wholesalePrice
)]return productPrice
}fi End function
14
Flowchart
Flowchart
15
finalPrice : Double
returnProductPrice
returnWholsalePriceif (finalPrice ≥ wholesalePrice)
if finalPrice
=
product price− productPrice X dicount100
returnProductPrice
T
F
returnDiscount T
F
Return Customer Bonus
Description
We want to reward customers for returning to make a purchase. To incentivize,
they receive a bonus discount as by the following levels.
• Less than a week = 10%
• More than 6 months = 6%
• Otherwise, 1% for each month (consider a month to be 30 days)
Sample data for testing:
Scenario todaysDate lastPurchaseDate totalPuchaseAmount Return amount1 2/1/2014 1/25/2014 $100 $90
2 2/1/2014 3/17/2013 $100 $94
3 2/1/2014 12/11/2013 $100 $99
customerReward todaysDate LstPurchDate TotPurchAmnt dicount
1 string string double 10
2 string string double 6
3 string string double 1
16
Pseudocode
function returnCustReward (todaysDate : Date,
lastPurchaseDate : Date,
totalPurchaseAmount : Double)
returns double
function returnCustomerBonus(customerBonus:double)then{
createVariable (TodaysDate:String)
createVariable lastPurchaseDate:string
crateVariable totalDays : intger
createVariable totalPurchaseAmount:Double)return{
If totalDays = (todaysDate – lastPurchaseDate)
return totalDays
if (totalDays ≤ 7){
return customerBonus
customerBonus = TotalPurchaseAmount X 0.10)
} else {
if (totaldays ≥ 30){
customerBonus = TotalPurchaseAmount X 0.01)
} else {
If (totalDays > 180)
customerBonus = TotalPurchaseAmount X 0.06)
return customerBonus
]
}fi
endFunction
17
Flowchart
.
18
T
Return Customer Bonus
If totalDays = (todaysDate –
lastPurchaseDate) Return totalDays
if (totalDays ≤ 7 = customerPurchase x 0.10)
if (totalDays ≥ 30 = customerPurchase x 0.01)
If (totalDays > 180 = customerPurchase x 0.06)
F
newCustomer=NoBonus Return customerBonus
End Function
Applying Discounts
Description
A customer receives his or her discount based on his or her membership status. Preferred members receive a return member bonus, and all registered members receive a bulk discount, but guests do not receive any discounts.
This should reuse the discounts from the prior work, so test cases from there would apply. Just make sure that guests receive no discount, registered members just get a discount for any items for the bulk discount, and preferred members get both the bulk discount and the return customer bonus.
Status bonusDiscount bulkDiscount noDiscount returnDiscount
Preferred 10% 6%
Registerd 6%
Guests 0%`
Pseudocode
function applyDiscounts (todaysDate : Date, lastPurchaseDate : Date,totalPurchaseAmount : Double,membershipLevel : Integer)
returns doubleif membershipLevelDiscount=(todaysDate – lastPurchasedate) x365
return daysif (guest = membershipLevel < 7){
membershipLevelDiscount = guestDiscount (todaysDate,lastPurchaseDate,purchaseAmount,)
} else if {if (membershipLevel = registered > 30)
membershipLevelBonus = bulkDiscount (todaysDate,lastPurchaseDate,purchaseAmount)
} else if{If (membershipLevel = preferred > 180)
membershipLevelDiscount = preferredDiscount + bulkDiscount (todaysDate,lastPurchaseDate,purchaseAmount)
}Return membershipLevelDiscount
}fi
end function
19
(Flowchart)
.bulk
20
Start Apply Discount
(membershipLevelDiscount = (todaysDate – lastPurcahsedate, purchaseAmount X membershipLevelDiscount)
if (guest =
membershipLevel < 7)membershipLevelDiscount = guestDiscount)
T
F
T
T
F
F
if (registered =
membershipLevel > 30)
if (preferred =
membershipLevel > 180)
membershipLevelDiscount = (bulkDiscount)
membershipLevelDiscount = preferredDisount)
Return membershipLevelDiscount
endFunction
Phase 4: Problem Solving with Loops
Total order
Once the final prices are calculated for each product, we need to total up the order and then add in sales tax. We need to go through the line items in an order and figure out the final price.
Flowchart
v
Pseudocode
function totalOrder (lineItemPrice: Array, lineItemQuantity : Array,saleTaxRate : Double)
returns doubleCreate variable Double : subtotalfor (index = each item in lineItemPrice){
lineItemTotal = lineItemPrice[array] * lineItemQuantity[array]subtotal =subtotal + lineItemTotal
end loop}
return calculateSubtotal (subtotal x salesTaxRate)end function
21
lineItemTotal=lineItemPrice[index] xlineItemQuantity[index]
index = each item in lineItemPrice
Subtotal = subtotal +lineItemTotal
ReturncalculateSubtotal (subtotal, salesTaxRate)
orderTotal
End
T
Start
Problems to Solve
Fill in the following table by walking through the logic above. The idea is to analyze how the chart and pseudocode was created, because you will be doing this in a few minutes, so do not just jump to the easy answer. Follow the steps as if you are the computer executing the software designed.
Problem lineItemPrice lineItemQuantity saleTaxRate Return amount1 [5.50, 3.00, 2.25] [12, 3, 10] 5% (5.5 x 12)x 0.05 =
$69.30
(3.0 x 3) x 0.05 = $9.27
($2.25 x 10) x 0.05 = $23.63
2 [5.50] [5] 5% ($5.50 x 5) x 0.05 = $28.88
3 [0] [0] 5% ($0.00 x 0) x 0.05 = $0.00
Calculate Profits
Description
Given the list of all the product prices and wholesale prices as well as a list of all the items sold for each product calculate the net profit for all the products.
Problem allProductPrices allWholesalePrices allSalesNumbers returnNetProfits(50,30,20,10,5) (35, 15,10,5,2) (60,80,20,45,70) $2735.00
allProductPrices:array -
allWholsalePrices:array x
allSalesNumbers:array =
netReturns
22
Flowchart
Pseudocode
function netProfits (allProductSalesNumbers: Array, allProductPrices : Array,allProductWholesalePrices : Array)
returns doublecreatVariable Double : netProfits{
for (array = each item in allProductPrices, allWholesalePrices, allSalesNumbers )netProfits=(allSalesNumbers) x allProductPrices – allPriductWholesalePrices netProfits = netprofits x allSalesNumbers}
end LoopreturnCalculateNetProfits (allSalesNumbers x allProductPrices - allWholesalePrices )
}fiend function
23
createVariable Double : netProfits
array = each item in allProductPrices, allWholesalePrices, allSalesNumbers
netProfits = allSalesNumbers(array)x
allProductPrices[array] – allPriductWholesalePrices[array)
netProfits = netprofits x allSalesNumbers(array)
returnCalculateNetProfits (allSalesNumbers x allProductPrices - allWholesalePrices )
End
Rock, Paper, Scissors
Description
To expand further, we want to try out logic in interacting with users. Here is a sample of a game, using loops and decisions to allow a person to play rock-paper-scissors with a computer.
Pseudocode
We have a helper function that we will use here that tells us who won. It will result in +1 if the player wins, a -1 if the computer wins, and a 0 if it is a tie.
function compareOutcome(computerChoice: Integer, playerChoice : Integer)
returns Integer
And the main flow of my logic is as such.
createVariable computerChoice : integercreateVariable playerChoice : interger
while (true)Integer : computerChoice = randomChooser()Integer : playerChoice = prompt “Enter a value”print “Enter a value”read valueIf (playerChoice is not a valid input)
returnPrint “You picked bad number. Try again”Else
Integer : outcome = compareOutcome(computerChoice, playerChoice)If (outcome = 0)
Prompt user “It is a tie, try again”Else if (outcome = -1)
Prompt user “You lost”Break out of loop
ElsePrompt user “You win”Break out of loop
End ifEnd if
end loop
24
Flowchart
25
Break
End of game
Prompt “You won” Break
Prompt user “You lost”
Prompt user ”It is a tie, try again”
Integer : outcome = compareOutcome(computerChoice, playerChoice)
Prompt user “You picked bad number, try again”
Integer : playerChoice = prompt “Enter a value”
Integer : computerChoice = ramdonChooser()
outcome =-1
outcome =0
playerEntry is not a valid input
whileTrue
Note: In this case, note the advantages and disadvantages of flowcharts and psuedocode. The flowchart is easy to follow the logic for one scenario, but does it make it easier or harder to understand the code as a whole? There is no strict answer, but one that tells you a bit about your way of thinking and personal preference.
Interaction Scenario
For either of the solutions above, follow the logic and map out your interaction step-by-step, trying to exercise all paths of the logic. You will have to take at least 2 times through the game to map all scenarios.
Scenario 1 = 1 rock2 paper3 scissors
Step User Input System Response1 User chooses 50 System says lower2 User chooses (1) System says (1) “Tie” Select “Go” to play again"3 User chooses (3) System says (1) “ I Win” Select “Go” to play again"4 User chooses (2) System says (1) “You Win” Select “Go” to play
again"
Scenario 2
Step User Input System Response1 User chooses (4) System says lower2 User chooses (2) System says (1) “You Win” Select “Go” to play again"3 User chooses (3) System says (1) “ I Win” Select “Go” to play again"4 User chooses (1) System says (1) “Tie” Select “Go” to play again"
Step User Input System Response1 User chooses (10) System says lower2 User chooses (3) System says (1) “ I Win” Select “Go” to play again"3 User chooses (1) System says (1) “Tie” Select “Go” to play again"4 User chooses (2) System says (1) “You Win” Select “Go” to play
again"
26
Number Guessing Game
Description
Now it is your turn to try out user interaction with a simple game. This goes back to the number guessing game. The user will input a number each time, say between 1 and 100. The computer will randomly select 1 number each game (note this is different than the example above where it selects a new answer each round), and the game continues until the user guesses the right number.
Like above, your solution should accommodate for invalid input, but do not worry about how to make that logic work for now. Your solution should give some hints though if the guess the user made was too high or too low, to help them on their way.
Flowchart
27
Pseudocode
function guessNumber(randomNumber: Integer, create Variable RandomNumber(1,100) : Integercreate Variable enterNumber(1,100) : Integercreate variable guessesTaken = (Φ) : Integer) returns Integer
while enteredNumber = randomNumber(Φ){ Interger(1,100) returnprintString “Thinking number 1 thru 100”}while guessesTaken > (?){returnPrintString “Make a Guess”
guess = input()guess = integer{
if enteredNumber > random_number printreturn “too high” }if else{ enteredNumber < random_number printReturn “too low” enteredNumber = input;
when donereturn “You have a match”}
}fiendFunction
28
Phase 5: Using Abstractions in Design
Seeing Abstractions
Throughout this course, we have been realizing the detailed design for the pieces of the whole picture we started with at the beginning of the course. We have built many abstractions, so let’s go back and document what we have found and see the abstractions we have created.
Abstraction Name Parameter List Scope/PurposecalculateSubtotal (totalPurchaseAmount :double,
salesTaxRate : double)Applies sales tax and computes the final amount due.
calculateProductProfit (productProfit Double,wholesalePrice : Double numberOfPurchases : Integer)
Takes the product retail price minus the wholesale price to get net profits.
applySafeDiscount (productPrice : Double, wholesalePrice : Double,applyDiscount : Double)
Ensures that the system will not accidentally discount a product below the wholesale price.
Return Customer Bonus
createVariable todaysDate:String createVariable lastPurchaseDate: stringcrateVariable totalDays : intgercreateVariable totalPurchaseAmount :Double)
We want to reward customers for returning to make a purchase.
Apply Discounts For Members
(todaysDate : Date, lastPurchaseDate : Date,totalPurchaseAmount : Double,membershipLevel : Integer)
Member discounts based on his or her membership status.
Order Total with Sales Tax
(lineItemPrice: Array,lineItemQuantity : Array,saleTaxRate : Double)
Applies to totaling up the order and then adding in sales tax.
Calculate Profits (allProductSalesNumbers: Array,allProductPrices : Array,allProductWholesalePrices : Array)
Applies to calculating profits from all business operations of sales.
Rock, Paper, Scissors (computerChoice: Integer,playerChoice : Integer)
Applies logic loops that interact with others.
The Number Guessing Game
create Variable (RandomNumber(1,100):Integercreate Variable enterNumber(1,100) :Integercreate variable guessesTaken = 0 : Integer)
A guessing game created to interact with user using loops.
Refactoring
Sometimes it is easy to see how the whole solution can be broken into pieces, and other times it is done as you see abstractions and opportunities for reuse in the resulting design. This is called refactoring. For
29
the pseudocode you see below, look for abstractions you could create and create a flowchart using your simplifications.
Psuedocode in Need of Refactoring
NOTE: Comparison table. WORK AREA –NOT FINAL. FIANL ON NEXT PAGE (P-31)
OLD: Color coded for inspection SWAG-1/ (Scientific Wild Ass Guess) Array : namesInSystem
Array : phoneNumbersInSystem
String : nameInput
While (nameInput is not valid){
nameInput = prompt user for input
if (nameInput is provided and not blank){
break out of loop
}end loop
Prompt user the input is required and not blank
]End loop
Integer : indexForName = -1
For (index = all items in namesInSystem
If (nameInput = namesInSystem[index]){
indexForName = index
}endFi
}End loop
If (indexForName = -1){
Prompt user “We cannot find your account, please
call us”
}Else{
String : phoneNumberInput
While (phoneNumber is not valid){
phoneNumber = prompt user for input
if (phoneNumber is provided and not blank){
break out of loop
}end loop
Prompt user the input is required and not
blank
}End loop
If (phoneNumber =
phoneNumbersInSystem[indexForName])
Prompt “we found your account welcome”
Else
Prompt “we cannot validate your account,
try again later”
End if
End if
Array : namesInSystem
Array : phoneNumbersInSystem
String : nameInput
nameInput = Validate (“User Name”);
Integer : indexForName = -1
userExist = (CheckNameInSytem/nameInput,nameInSytem)
If
indexForName = index
}Else{
Prompt user “We cannot find your account,
please call us”
}End Loop
String : phoneNumberInput
phoneNumberInput = validate (“Phone Number”);
If (phoneNumber = phoneNumbersInSystem
[indexForName]){
Prompt “we found your account welcome”
}Else{
Prompt “we cannot validate your account, try
again later”
}End Loop
functionValidate (identifier:string) returnString{
createVariable valueString
Repeat{
Print “Enter” identifier
readValue
Until (value < > empty)
return Value
}
]endFi
30
SWAG-3/ Pseudocode FINAL
Array : namesInSystem
Array : phoneNumbersInSystem
String : nameInput
Intger : userExist
nameInput = validate (“User Name”);
Integer : indexForName = -1
userExist=checkUserNameInSytem(nameInput,nameInSytem)
if (userExist==-1){
Prompt user “We cannot find your account, please call us”
}
String : phoneNumberInput
phoneNumberInput = validate(“Phone Number”)
if phoneNumberInput == phoneNumbersInSystem(userExist){
Prompt “we found your account welcome”
}Else{
Prompt “we cannot validate your account, try again later”
}End Loop
functionValidate (identifier:string) returnString{
createVariable value:String
Repeat{
Print “Enter” identifier
readValue
Until (value < > empty)
return Value
}
]endFi
31
Refactored Flowchart
The above pseudocode is long, but you can omit much of the details. You can accomplish the same logic removing more than 30 lines. You do not have to show all of the details removed if moved into an abstraction, simply name the abstraction and define the parameters to be passed to the call replacing the lines of code.
Enter flowchart:
32
T
Start
Array : namesInSystem
Array : phoneNumbersInSystem
String : nameInput
functionValidate (identifier:string)
Print “Enter” identifier
nameInput = validate (“User Name”)
readValue
Until (value < > empty)
If (nameInput = namesInSystem[index]
F
if phoneNumberInput == phoneNumbersInSystem){
Prompt user “We cannot find your account, please call us”
phoneNumberInput = validate (“Phone Number
F Prompt “we cannot validate your account, try again later”
T
33
T
Prompt “we found your account welcome””
EndFi