I had a debate with a work mate regarding the following code as to which one of it would be the better practice:
My code (in pseudo):
var A = <precondition either TRUE or FALSE>;
var B;
if(A)
{
// some other multi-line, complex computation based on A=TRUE
B = <value fetched from JsonElement .GetProperty("C");>
}
else
{
B = <value fetched from JsonElement .GetProperty("D");>
}
var E = B; // B is carried forward based on the condition
Their code:
var A = <precondition either TRUE or FALSE>;
var B = A ? <value fetched from JsonElement .GetProperty("C")
: <value fetched from JsonElement .GetProperty("D");
if(A)
{
// some other multi-line, complex computation based on A=TRUE
}
var E = B;
My view was their usage of the ternary operator is essentially a shorthand of the IF condition that followed and that it is pretty much a duplication where we could consolidate the logic we need to work out into a single conditional operator, but they were persistent it was not and that the usage of ternary operator is better for the sake of brevity and readability.
Could anyone shed some light here as to what the best practice would look like? Duplicating a conditional operator for cleaner code or having a simple consolidated if/else condition?
Thanks!
B
as<value fetched from JsonElement .GetProperty("D")
and remove the else?