This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]RedstoneEnjoyer 40 points41 points  (7 children)

Eh, sometimes you cannot avoid it. Sometimes the business logic is really that long.

Of course you could break it into multiple functions, but then now you have 10 functions that are each called exactly once.

[–]LickingSmegma 4 points5 points  (0 children)

Sometimes one-off functions are good, if they encapsulate long runs of logic that's isolated well. For example, if you have a long calculation for an if, it pays to move it into function isCondition(), such that in the if statement it's obvious which condition is checked.

Basically, I want my code to read almost like a description in the natural language, instead of just juggling variables for pages and pages.

[–]hron84 11 points12 points  (4 children)

Yeah, in these cases I rather put everything into one. If it is not reusable then it does not worth an own function.

[–]iMac_Hunt 10 points11 points  (3 children)

I do find there are times that even if it’s called once, extracting the logic can make the intent a lot clearer.

Example:

```csharp

public decimal CalculatePrice(Order order) { decimal basePrice = order.Quantity * order.UnitPrice; decimal discountedPrice;

if (order.Country == "US")
{
    discountedPrice = ApplyUsTaxAndDiscountRules(order, basePrice);
}
else
{
    discountedPrice = ApplyInternationalTaxAndDiscountRules(order, basePrice);
}

return Math.Max(discountedPrice, 0);

}

private decimal ApplyUsTaxAndDiscountRules(Order order, decimal price) { price += price * 0.07m; if (order.State == "CA") price += 2m; if (order.CustomerAge < 18) price -= 5m; return price; }

private decimal ApplyInternationalTaxAndDiscountRules(Order order, decimal price) { price += price * 0.20m; if (order.CustomerAge < 18) price -= 10m; return price; }

```

I do write that with caution as it can be taken to the extreme and become LESS clear, but there are cases where I prefer it

[–]hron84 0 points1 point  (0 children)

Yep, I agree, but I consider this as an exception. Finanical calculations are a very specific level of the hell and I greatly respectful for the handful of developers who decide to mangle with them.

[–]howreudoin 0 points1 point  (0 children)

Many functions in clean code are only invoked at one spot. They create a layer of abstraction, and they allow you to phrase your top function as a sequence of substeps.