Greg
Greg

Reputation: 141

Best pattern to control the return of a method

Is there a pattern or a best option to improve this method and reduce duplicate ifs?

I've already use the Adapter pattern to transform an interface to another.

public string GetInvoice(int id)
{
    // Search in Mongodb and get the object
    var invoice = MongoRepository.Get<IInvoiceEntity>(x => x.Invoice.Id == id)
        .First();

    if (invoice == null) 
    {
        // Search in SQL
        invoice = EFRepository.Get<IInvoiceEntity>(x => x.Invoice.Id == id)
            .First();
    }

    if (invoice == null)
    {
        // This invoice is an old system item
        var oldInvoice = WCFClient.InvoiceService.Get(id);

        var adapter = new OldInvoiceAdapter(oldInvoice);
        invoice = adapter.AdaptEntity();
    }

    return invoce.ToJson();
}

Thanks!

Upvotes: 1

Views: 99

Answers (2)

Servy
Servy

Reputation: 203820

The pattern of returning a given value if it's not null and using a different value if it is null is exactly what the null convalescing operator (??) does. This can help you write:

var invoice = GetFromMongo(id) ?? GetFromSQL(id) ?? GetFromOldArchive(id);
return invoice.ToJson();

Upvotes: 4

StriplingWarrior
StriplingWarrior

Reputation: 156524

I'd extract out the various strategies for getting the invoice into methods (which obviates the need for much of your commenting) and then simplify this method, like so:

var invoice = GetInvoiceFromMongoDb(id) 
       ?? GetInvoiceFromSql(id)
       ?? GetOldSystemInvoice(id);

return invoce.ToJson();

This makes your method really easy to understand, and breaks your code into modules, which will probably help you follow the Single-Responsibility Principle better.

Upvotes: 5

Related Questions