Can a C# method chain be “too long”?

前端 未结 4 2089
青春惊慌失措
青春惊慌失措 2021-02-05 05:57

Not in terms of readability, naturally, since you can always arrange the separate methods into separate lines. Rather, is it dangerous, for any reason, to chain an excessively l

4条回答
  •  花落未央
    2021-02-05 06:55

    This is considered a code smell by some and not by others. Anytime you see the following:

    Foo.getBar().getBlah().getItem().getName();
    

    you should really be thinking, "what do I really want?" Instead perhaps your method should contain a function call:

    String getName(Int _id, String _item)
    {
        return myBar.getName( _id, _item );
    }
    

    which then delegates downward, amongst the classes. Then, if something changes in one of your classes at a later update, you'll see exactly where it occurs and can change it in one location.

提交回复
热议问题