When to return 'this' instead of 'void' in a method and why?

坚强是说给别人听的谎言 提交于 2021-02-08 10:12:51

问题


What are the benefits (or drawbacks) of returning a reference to 'this' object in a method that modifies itself? When should returning a 'this' be used as apposed to void?

When looking at an answer on code review stack exchange, I noticed that the answer used a 'return this' in a self operating method.

Simplified class from original:

class Item
{
    public Item(string name)
    {
        Name = name;
    }

    public string Name { get; private set; }

    public Item AddComponent(ItemComponent component)
    {
        _components.Add(component);
        return this;
    }

    private List<ItemComponent> _components = new List<ItemComponent>();
}

Consuming code simplified:

var fireSword = new Item("Lightbringer")
                   .AddComponent(new Valuable { Cost = 1000 })
                   .AddComponent(new PhysicalDamage { Slashing = 10 });

Related question seems to have conflicting answers by different users.

This question is also similar with the answer referencing fluent interfaces to use in object creation.


回答1:


Returning this is using a fluent interface design, that is a special case of method chaining when the return type is of the current object on which we are applying the method.

Method chaining is also the root of functional programming.

It is extensively used by Linq extension methods with IEnumerable<> and IQueryable<>.

It allows to call methods on the same object in a chained manner without repeating a variable name for each method call.

Therefore, this produces a shorter, cleaner and more maintainable code with fewer sources of errors.

So we use this when we want or need that.



来源:https://stackoverflow.com/questions/65173197/when-to-return-this-instead-of-void-in-a-method-and-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!