문제

How and why does Braintree setup their API code this way? They are somehow allowing method calls that get chained and then populated into a variable that finally gets sent in through the Search() method. I've never seen APIs work this way before (except maybe Linq). How do they set this kind of thing up behind the scenes and what makes this better (or worse)?

https://www.braintreepayments.com/docs/dotnet/transactions/search

var request = new TransactionSearchRequest().
    CreditCardCardholderName.Is("Patrick Smith").
    CreditCardExpirationDate.Is("05/2012").
    CreditCardNumber.Is("5105105105105100");

ResourceCollection<Transaction> collection = gateway.Transaction.Search(request);
도움이 되었습니까?

해결책

If each method returns a reference to the object, you could chain as many together as you like.

public class Foo {
//  stuff...

    public Foo Baz() {
        // do stuff
        return this; //return a reference to the object
    }

}

I think the idea is (like linq), to have relational looking object oriented code.

Its kind of like defining a mini language within the API that follows its own rules, rather than the larger language conventions.

I prefer to hew closer to convention, but this sort of syntax is not unusual in the context of ORM's

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top