Lesson 2
Enhancing a Voting System with C# for Robust Functionality
Introduction

Welcome back to another exciting session where we learn about enhancing existing functionality without causing regressions. Today, our scenario involves designing a voting system. We'll start with the basic implementation of the voting system and gradually introduce additional elements of complexity.

Starter Task Review

In our initial task, we created a simple voting system in C# with a set of basic functionalities:

  • bool RegisterCandidate(string candidateId): This method is used to add new candidates to our system.
  • bool Vote(long timestamp, string voterId, string candidateId): This method facilitates users casting their votes. Each vote is given a timestamp.
  • int? GetVotes(string candidateId): This method retrieves the total number of votes for a given candidate.
  • List<string> TopNCandidates(int n): We also want to add a leaderboard functionality to our system. This method returns the top n candidates sorted by the number of votes.
Initial Solution Development

Let's jump into the C# code and begin the implementation of our starter task. Here, we use C#'s built-in Dictionary and List as the core of our design. These collections allow us to have dynamic lists keyed based on candidate IDs and voter IDs, which will greatly simplify our design.

C#
1using System; 2using System.Collections.Generic; 3using System.Linq; 4 5public class VotingSystem { 6 private Dictionary<string, int> candidates; // Stores candidate_id as key and votes as value 7 private Dictionary<string, VotingHistory> voters; // Tracks each voter's voting history 8 9 public VotingSystem() { 10 this.candidates = new Dictionary<string, int>(); // Initialize candidates dictionary 11 this.voters = new Dictionary<string, VotingHistory>(); // Initialize voters dictionary 12 } 13 14 public bool RegisterCandidate(string candidateId) { 15 if (candidates.ContainsKey(candidateId)) { 16 return false; // Candidate is already registered 17 } 18 candidates[candidateId] = 0; // Initialize candidates with 0 votes 19 return true; 20 } 21 22 public bool Vote(long timestamp, string voterId, string candidateId) { 23 if (!candidates.ContainsKey(candidateId)) { 24 return false; // Return false if candidate is not registered 25 } 26 if (!voters.TryGetValue(voterId, out var voterHistory)) { 27 voterHistory = new VotingHistory(); 28 voters[voterId] = voterHistory; 29 } 30 voterHistory.Votes.Add(candidateId); // Record the vote 31 voterHistory.Timestamps.Add(timestamp); // Record the time of the vote 32 candidates[candidateId]++; // Increment vote count for the candidate 33 return true; 34 } 35 36 public int? GetVotes(string candidateId) { 37 return candidates.ContainsKey(candidateId) ? candidates[candidateId] : (int?)null; // Retrieve vote count for a candidate or null if not found 38 } 39 40 public List<string> TopNCandidates(int n) { 41 return candidates.OrderByDescending(entry => entry.Value) 42 .Take(n) 43 .Select(entry => entry.Key) 44 .ToList(); // Return top n candidates based on votes 45 } 46 47 private class VotingHistory { 48 public List<string> Votes { get; } 49 public List<long> Timestamps { get; } 50 51 public VotingHistory() { 52 this.Votes = new List<string>(); 53 this.Timestamps = new List<long>(); 54 } 55 } 56}
Introduce New Methods

Now that we have a basic voting system, our goal is to enhance this system with additional functionalities:

  • Dictionary<string, int> GetVotingHistory(string voterId):: Provides a detailed voting history for a specified voter, returning a dictionary with candidates and the number of votes they received from the voter. Returns null if the voter ID does not exist.
  • bool BlockVoterRegistration(long timestamp):: Implements a mechanism to halt any new voter registrations past a specified timestamp, effectively freezing the voter list as of that moment.
  • bool ChangeVote(long timestamp, string voterId, string oldCandidateId, string newCandidateId):: Enables voters to change their vote from one candidate to another, given the change is made within a 24-hour window from their last vote, ensuring both the old and new candidates are registered, and that the voter initially voted for the old candidate.
Implementing New Methods: 'getVotingHistory' and 'blockVoterRegistration'

We proceed to enhance our existing VotingSystem class to accommodate the new functionalities.

First, let's incorporate the methods to get the voting history and to block further voter registrations:

C#
1 private long? blockTime; 2 3 public Dictionary<string, int> GetVotingHistory(string voterId) { 4 if (!voters.ContainsKey(voterId)) { 5 return null; 6 } 7 var voterHistory = voters[voterId]; 8 var votingHistory = new Dictionary<string, int>(); 9 10 foreach (var candidateId in voterHistory.Votes) { 11 if (!votingHistory.ContainsKey(candidateId)) { 12 votingHistory[candidateId] = 0; 13 } 14 votingHistory[candidateId]++; 15 } 16 return votingHistory; // Returns a dictionary with each candidate voted for and the number of times they were voted for 17 } 18 19 public bool BlockVoterRegistration(long timestamp) { 20 blockTime = timestamp; // Records the timestamp after which no registration is allowed 21 return true; 22 }
Updating the 'vote' Method

With the introduction of the BlockVoterRegistration functionality, we must revisit our Vote method to ensure it respects the new rules set by this feature. Specifically, we need to ensure that no votes are cast after the voter registration has been blocked. This is critical in maintaining the integrity of the voting system, especially in scenarios where registration deadlines are enforced. Here's how we modify the Vote method to incorporate this change:

C#
1 public bool Vote(long timestamp, string voterId, string candidateId) { 2 // Check if blockTime is set and if the vote attempt is after the block timestamp 3 if (blockTime.HasValue && timestamp >= blockTime.Value) { 4 return false; // Vote attempt is blocked due to the registration freeze 5 } 6 7 if (!candidates.ContainsKey(candidateId)) { 8 return false; // Return false if the candidate is not registered 9 } 10 11 if (!voters.TryGetValue(voterId, out var voterHistory)) { 12 voterHistory = new VotingHistory(); 13 voters[voterId] = voterHistory; 14 } 15 16 voterHistory.Votes.Add(candidateId); // Record the vote 17 voterHistory.Timestamps.Add(timestamp); // Record the time of the vote 18 candidates[candidateId]++; // Increment vote count for the candidate 19 20 return true; 21 }

This update ensures that our voting system behaves as expected, even with the new functionality to block further voter registrations beyond a certain timestamp. It's a perfect demonstration of how new features can necessitate revisits and revisions to existing code to enhance functionality while ensuring backward compatibility.

Implementing 'changeVote' Method

The ChangeVote method allows voters to change their vote, adhering to specific rules. Here's a step-by-step explanation of implementing this functionality:

  • Verify Candidate and Voter Validity: Check if both the old and new candidate IDs exist in the system, and verify that the voter has previously voted for the old candidate.

  • Timestamp Constraints: Ensure that the voter is trying to change their vote within an allowable timeframe after their initial vote.

  • Update Votes: If all conditions are met, subtract one vote from the old candidate, add one vote to the new candidate, and update the voter's voting record.

C#
1 public bool ChangeVote(long timestamp, string voterId, string oldCandidateId, string newCandidateId) { 2 // Verify existence in the voting system 3 if (!candidates.ContainsKey(oldCandidateId) || !candidates.ContainsKey(newCandidateId)) { 4 return false; 5 } 6 7 // Check if the voter_id is valid and has previously voted 8 if (!voters.ContainsKey(voterId) || !voters[voterId].Votes.Any()) { 9 return false; // Voter is either not registered or has not voted yet 10 } 11 12 var voterHistory = voters[voterId]; 13 // Confirm voter has voted for the old candidate 14 var lastVoteIndex = voterHistory.Votes.LastIndexOf(oldCandidateId); 15 if (lastVoteIndex == -1) { 16 return false; 17 } 18 19 // Ensure the operation is within the permitted timeframe 20 if (timestamp - voterHistory.Timestamps[lastVoteIndex] > 86400) { // 24 hours in seconds 21 return false; 22 } 23 24 // Perform the vote change 25 // Remove the old vote 26 voterHistory.Votes.RemoveAt(lastVoteIndex); 27 voterHistory.Timestamps.RemoveAt(lastVoteIndex); 28 29 // Append the new vote 30 voterHistory.Votes.Add(newCandidateId); 31 voterHistory.Timestamps.Add(timestamp); 32 33 // Update candidates' vote counts 34 candidates[oldCandidateId]--; 35 candidates[newCandidateId]++; 36 37 return true; 38 }
Lesson Summary

Congratulations! You've successfully enhanced the voting system by adding functionalities to view voting history, block new candidate registrations, and, most importantly, enable vote changes under specific conditions. Each of these features was developed with careful consideration to maintain the integrity and backward compatibility of the system. Continue exploring with practice sessions and further experimentation to refine your skills in developing complex, functionality-rich applications. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.