Even if the cognitive complexity of the whole program did not change, it is easier for a reader to understand the code of the `calculateFinalPrice` function, which now only has a cognitive cost of 1.
[source,csharp,diff-id=1,diff-type=compliant]
----
decimal CalculateFinalPrice(User user, Cart cart)
{
decimal total = CalculateTotal(cart);
if (IsEligibleForDiscount(user)) // +1 (if)
{
total = applyDiscount(user, total);
}
return total;
}
bool IsEligibleForDiscount(User user)
{
return user.HasMembership()
&& user.OrdersCount > 10 // +1 (more than one condition)
&& user.AccountActive
&& !user.HasDiscount
|| user.OrdersCount == 1; // +1 (change of operator in condition)
}
----
**Break down large functions.**
==== Noncompliant code example
For example, consider a function that calculates the total price of a shopping cart, including sales tax and shipping. +
__Note:__ The code is simplified here, to illustrate the purpose. Please imagine there is more happening in the `foreach` loops.
[source,csharp,diff-id=3,diff-type=noncompliant]
----
decimal CalculateTotal(Cart cart)
{
decimal total = 0;
foreach (Item item in cart.Items) // +1 (foreach)
{
total += item.Price;
}
// calculateSalesTax
foreach (Item item in cart.Items) // +1 (foreach)
{
total += 0.2m * item.Price;
}
//calculateShipping
total += 5m * cart.Items.Count;
return total;
}
----
This function could be refactored into smaller functions:
The complexity is spread over multiple functions and the complex `CalculateTotal` has now a complexity score of zero.
**Use the null-conditional operator to access data.**
In the below code, the cognitive complexity is increased due to the multiple checks required to access the manufacturer's name. This can be simplified using the optional chaining operator.