The classic movie line goes something like “I love the smell of refactoring in the morning” right? That’s how I remember it.
I was looking into a customer’s code base recently and although my task was simply to assure the code worked as intended, I couldn’t stop but think that a little refactoring would go a long way here to make the code more concise, cheaper to run and easier to read.
Below is a sanitised version of the initial code.
–>CONTINUE READING THE ENTIRE POST<–
(Original post of Joaquim Pedro Antunes)
pragma solidity ^0.4.22;
contract Voting {
address[] public candidates;
mapping(address => uint) public votesReceived;
function Voting(address[] candidateNames) public { //330717 gas w/ 5 candidates
candidates = candidateNames;
}
function voteForCandidate(address candidate) public { //21404 gas
require(isValidCandidate(candidate));
votesReceived[candidate] += 1;
}
function totalVotesFor(address candidate) view public returns (uint) {
require(isValidCandidate(candidate));
return votesReceived[candidate];
}
function isValidCandidate(address candidate) view public returns (bool) {
for(uint i = 0; i < candidates.length; i++) {
if (candidates[i] == candidate) {
return true;
}
}
return false;
}
}