How to do method chaining for interfaces?

PHPz
Release: 2024-02-13 08:39:08
forward
885 people have browsed it

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.
Copy after login

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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!