Building a simple voting app


#1

Hello Swirld!

I’m trying to wrap my head around sending different types of transactions over the network.

In this voting app, users have two possible actions:

  1. Cast a Vote
  2. Add a candidate

How I see it, I can possibly add an extra character to the end of the transaction:

candidateName = candidateName+"#";
byte[] transaction = candidateName.getBytes(StandardCharsets.UTF_8);

Then in the State’s handleTransaction function:

if (transaction.substring(transaction.length - 1) == '#') {
    candidates.add(new String(transaction, StandardCharsets.UTF_8));
} else {
    // increment vote for candidate
}

Is this the right way to go about this? Any suggestions are much appreciated!

mir


#2

Looks OK to me. Can you provide more information about your approach please? The information shared here is very raw and unable to get the complete picture. Stateful / stateless? codebase used? SDK version? - any additional information is beneficial


#4

The above code could be improved with the ‘design depicted’ in the below code:

class TxnConstants {
	public static final String DATA_DELIMITER = "#";
	
	public static final String TXN_VOTE = "VOTE";
	public static final String TXN_ADD_CANDIDATE = "ADDC";
}


public class VoteTxnTest {

	
	public static void main(String[] args) {

		String candidateName = null;

		// test AddCandidate
		candidateName = "Adam";
		sendTxn(TxnConstants.TXN_ADD_CANDIDATE, candidateName);

		// test Vote
		candidateName = "Eve";
		sendTxn(TxnConstants.TXN_VOTE, candidateName);
	}

	
	private static void sendTxn(String txnId, String candidateName) {

		String txnData = txnId + TxnConstants.DATA_DELIMITER + candidateName;

		// Send transaction...
		//byte[] txnBytes = txnData.getBytes(StandardCharsets.UTF_8);
		
		// For testing purpose, let's CALL DIRECTLY: handleTransaction(txnData)
		handleTransaction(txnData);
	}

	
	private static void handleTransaction(String txnData) {
		
		int delimIndex = txnData.indexOf(TxnConstants.DATA_DELIMITER);
		String txnId = txnData.substring(0, delimIndex);
		String candidateName = txnData.substring(delimIndex + 1);

		if (txnId.equals(TxnConstants.TXN_ADD_CANDIDATE)) {
			// add candidate
			System.out.println("Add candidate: " + candidateName);
		} else if (txnId.equals(TxnConstants.TXN_VOTE)) {
			// increment vote for candidate
			System.out.println("Increment vote for candidate: " + candidateName);
		} else {
			// One shouldn't be here...?!
			// So, throw Exception ?
		}
	}
}