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.


(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
    votesReceived[candidate] += 1;

  function totalVotesFor(address candidate) view public returns (uint) {
    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;


Posted by:.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s