dirtydozen – Large method bodies

dirtydozen

V. Large method bodies

Count the lines, not pounds

Programmers love code, you’d think the more code the better, right? Well, far from it. In fact, in modern applications concept of small, compact or least privileged is becoming the de facto standard. However, it doesn’t mean the quality of code gets better or that the code is structured in a better way as result.

Let’s consider this enormous CompleteCheckout method below as an example.

public void CompleteCheckout(Customer customer, Basket basket)
{
    // set initial values
    var checkoutPrice = 0.0;
    var tax = 0.2;
    var shipping = 0.0;
    var invoice = new Invoice();

    // calculate checkout price = (total product price * tax) + shipping
    foreach(var product in basket.Products)
    {
        var productPrice = product.Price;
        checkoutPrice += productPrice;
    }

    // add tax to checkoutPrice
    checkoutPrice *= tax;

    // get shipping cost
    shipping = _shippingService.GetCost(customer.Address);

    // add shipping to checkoutPrice
    checkoutPrice += shipping;

    // prepare itemised invoice
    foreach (var product in basket.Products)
    {
        var invoiceItem = new InvoiceItem();
        invoiceItem.ProductName = product.Name;
        invoiceItem.ProductDescription = product.Description;
        invoiceItem.ProductImage = product.Image;
        invoiceItem.ProductQuantity = product.Quantity;
        invoiceItem.ProductPrice = product.Price;
        invoiceItem.ProductTax = tax;
        invoiceItem.ProductPriceAndTax = (product.Price + tax) * product.Quantity;
        invoice.Add(invoiceItem);
    }

    // add totals and shipping to invoice
    invoice.ShippingCost = shipping;
    invoice.CheckoutPrice = checkoutPrice;

    // save invoice to Word document
    var wordDoc = new Word();
    // Word doc create details omitted for brevity

    // take payment
    var paid = _paymentService.TakePayment(customer.Address, customer.CardDetails, checkoutPrice);

    if (!paid)
    {
        Log("Error processing your payment! Error Details: xxxxxxx");

        // redirect customer to error page
        Redirect.PaymentError();
    }
    else
    {
        // create email
        var email = new Email();
        // Email create details omitted for brevity

        // send email
        _emailService.send(email);

        // redirect customer to success page
        Redirect.PaymentSuccess();
    }
}

Read more on dirtydozen

Browse to https://qbituniverse.github.io/dirtydozen/large-method-bodies/ to carry on reading about Large method bodies

Marcin Narloch

Marcin Narloch

Creative and out-of-the-box thinker with strong interests and knowledge in technology and innovation.
dirtydozen Previous post dirtydozen – Over configuration
dirtydozen Next post dirtydozen – No unit tests

Leave a Reply

Your email address will not be published. Required fields are marked *