Home  >  Article  >  Backend Development  >  How to do method chaining for interfaces?

How to do method chaining for interfaces?

PHPz
PHPzforward
2024-02-13 08:39:08915browse

How to do method chaining for interfaces?

php editor Xiaoxin brings you an introduction on how to chain methods for interfaces. Method chaining is an elegant programming method that can continuously call multiple methods in one statement, improving the simplicity and readability of the code. In this article, we will introduce in detail the tips and precautions on how to implement method chaining for interfaces to help you better apply method chain programming and improve the efficiency and maintainability of your code. Let’s explore together!

Question content

I want to do something similar to obj.withx().withy().withz(). obj can have different types, that's why I use interfaces.

Unfortunately obj can also be nil. In this case my method chaining will panic because I'm calling a method on a nil interface and go doesn't know which method to call.

Here is a minimal reproducible example

How to still use method chaining on objects that may be nil?

  • Is there a way to provide a default implementation for withx() and other functions?
  • I also considered a pattern where each attribute function returns a function, but this seems too complex
obj.WithX().WithY()    // of type func() myInterface
obj.WithX().WithY()()  // now I got the actual object.

Workaround

These comments are mostly correct, but in fact you cannot return an untyped nil.

func new(someParam bool) inter {
    // more complicated. May return A, B or nil
    if someParam {
        return &A{}
    }
    var b *B
    return b // which is nil, but of a type that implements the interface
}

https://www.php.cn/link/845c31a2fbc3d2e14ecb17d48dcc65a4

So basically you just need a "default" type, which can be nil and which still implements the interface.

The above is the detailed content of How to do method chaining for interfaces?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete