I need to create a string which becomes an input to a SHA 256 function to generate its hash equivalent. The string is created by concatenating several variables as below:
String strRequest = "";
strRequest = request_passphrase.concat("access_code=").concat(access_code).concat("amount=").concat(amount).concat("command=").concat(mode).concat("currency=").concat(currency).concat("merchant_identifier=").concat(merchant_identifier).concat(request_passphrase);
if(strRequest!="" || !strRequest.isEmpty()) {
signature = sha256(strRequest);
}
What should be the best way to create an if-else to drop concatenation for a variable which is null.
For ex. if access_code is Null or empty, then the string will be request_passphrase.concat("amount=").concat(amount). and so on.
Depending on your context, the reasonable answer could be to organize your data differently:
request_passphrase.concat("access_code=").concat(access_code)
Instead of having a flat list of fields (or worse: method parameters), you could pass some sort of Map<String, String>
- where the key denotes the "field name", like ("access_code"); and the map value represents, well, the corresponding value. And if that value is null, you know to not append it.
Then you can simply iterate that map object, pull key/value pairs and append them to that string. Maybe you need an additional list that tells you the order in which the map keys should be iterated.
As said: these are options. In order to make a clear decision, one should understand more of the context; the underlying "data model"; other requirements, etc. The one thing that is definitely sure: if/else chains are never a good idea.