I'm using a code analysis software called SonarQube and it's giving me this error message saying that I should remove the return statement or make it conditional
I'm thinking about suppressing the message but not entirely sure yet.
protected static SubAccount GetSubAccountByProductCode(Holding acordHolding, string productCode, string optionType)
{
var OptionTypeElement = ACORDUtil.CreateACORDElement("OptionType");
const string subAccountPrefix = "SubAccount";
var OlifeExtensions = new List<XmlElement>();
if (string.IsNullOrEmpty(optionType))
{
OptionTypeElement.InnerText = "V";
}
else
{
OptionTypeElement.InnerText = optionType;
}
OlifeExtensions.Add(OptionTypeElement);
foreach (var acordSubAccount in acordHolding.Investment.SubAccount.Where(sa => sa.ProductCode.Equals(productCode)))
{
acordSubAccount.OLifEExtension.Add(ACORDUtil.CreateOLifEExtension(OlifeExtensions));
return acordSubAccount;
}
//sub account not found, create one for this product symbol.
var newSubAccount = new SubAccount();
newSubAccount.id = string.Format("{0}-{1}", subAccountPrefix, productCode);
newSubAccount.ProductCode = productCode;
acordHolding.Investment.SubAccount.Add(newSubAccount);
var oLifeExt = ACORDUtil.CreateOLifEExtension(OlifeExtensions);
newSubAccount.OLifEExtension.Add(oLifeExt);
return newSubAccount;
}
Make sonarqube not throw out an error message.
Solution 1. You are right to use a boolean variable, next is to use if else if, e.g. boolean result = true; if (condition 1) { result = false; } else if (condition 2) { result = false; } else { // none of the above // do something } return result; You can also combine conditions 1 and 2 with a || operator.
C# if (if-then) StatementThe boolean-expression will return either true or false . If the boolean-expression returns true , the statements inside the body of if ( inside {...} ) will be executed. If the boolean-expression returns false , the statements inside the body of if will be ignored.
Well, it'll only happen for one item, so you could make it simpler and more obvious:
var acordSubAccount = acordHolding.Investment.SubAccount.FirstOrDefault(
sa => sa.ProductCode.Equals(productCode)); // possibly use == instead of .Equals?
if (acordSubAccount != null)
{
acordSubAccount.OLifEExtension.Add(ACORDUtil.CreateOLifEExtension(OlifeExtensions));
return acordSubAccount;
}
It's because you have a return in your ForEach loop.
It reads like you expect exactly one item to match, therefore perhaps change it to use SingleOrDefault. This will return exactly one element matching the condition, or throw an exception if there are multiple matching.
var acordSubAccount = acordHolding.Investment.SubAccount.SingleOrDefault(
sa => sa.ProductCode.Equals(productCode));
if (acordSubAccount != null)
{
acordSubAccount.OLifEExtension.Add(ACORDUtil.CreateOLifEExtension(OlifeExtensions));
return acordSubAccount;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With