vendredi 23 octobre 2015

Repeatable pattern matching

Consider the following simple example.

type PaymentInstrument =
    | Check of string
    | CreditCard of string * DateTime

let printInstrumentName instrument = 
    match instrument with 
    | Check number-> printfn "check"
    | CreditCard (number, expirationDate) -> printfn "card"

let printRequisites instrument =
    match instrument with 
    | Check number -> printfn "check %s" number
    | CreditCard (number, expirationDate) -> printfn "card %s %A" number expirationDate

As you can see the same pattern matching logic is repeated in two functions. If I would use OOP I would create interface IPaymentInstrument, define two operations: PrintInstrumentName and PrintRequisites and then implement classes - one per payment instrument. To instantiate instrument depending on some external conditions I would use (for example) the factory pattern (PaymentInstrumentFactory). If I would need to add a new payment instrument, I just need to add a new class which implements IPaymentInstrument interface and update factory instantiating logic. Other code that uses these classes remains as is.

But if I use the functional approach I should update EACH function where pattern matching on this type exists. If there will be a lot of functions using PaymentInstrument type that will be a problem.

How to eliminate this problem using functional approach?

Aucun commentaire:

Enregistrer un commentaire