Lab 6: Practice with Exceptions and Encapsulation
1 Lab Objectives
To give you practice throwing and catching exceptions.
To give you practice editing code to have good encapsulation.
2 Problem Setup
This starter file provides a rudimentary voting system. The system contains a list of candiates (a ballot) and a list of votes cast so far (the votes). The system provides two methods for user-interaction: the screen method lists the candidates and prompts a user for their vote, and the countVotes method takes a candidate name and produces the number of votes cast for that candidate so far.
3 Exercises
Work on these in any order, depending on which concepts you most want to practice:
3.1 Exceptions
This voting booth doesn’t check user inputs against the ballot: if a user makes a typo while entering the name of the candidate to vote for, the voting system simply casts a vote for the name that was entered. Ideally, the voting system should check for typos. However, the voting system should also allow write-in candidates who were not on the original ballot.
Use exceptions to provide verification that a user intended to vote for a write-in candidate. If a user enters a name that is not on the ballot, ask the user whether they intended to vote for the name they entered as a write-in. If yes, store the vote. If not, send the user back to the voting screen.
3.2 Encapsulation
Critique the encapsulation on this code: write out all the changes you think should be made to result in a well-encapsulated voting system.
As time permits, make the changes to result in a better-encapsulated system.
3.3 Data Protection
Revisit the public/private modifiers on all fields and methods in your classes. Figure out which modifier makes sense, and make sure your code compiles under any changes you make.
To think about: If a malicious site using your voting machine managed to replace the screen method (wherever it is in your current implementation), could they cast the vote for someone other than who a user tried to vote for? Can your code do anything to stop them?