How to prevent the arrowhead anti-pattern

后端 未结 13 1347
南旧
南旧 2020-12-05 06:37

I\'m a bit confused about how to best refactor my code into something more readable.

Consider this piece of code:

var foo = getfoo();
if(foo!=null)
{         


        
13条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 06:51

    Rex Kerr's answer is indeed very nice.
    If you can change the code though,Jens Schauder's answer is probably better (Null Object pattern)

    If you can make the example more specific you can probably get even more answers
    For example ,depending on the "location" of the methods you can have something like:

    namespace ConsoleApplication8
    {
        using MyLibrary;
        using static MyLibrary.MyHelpers;
    
        class Foo { }
        class Bar { }
        class Moo { }
        class Cow { }
    
    
        internal class Program
        {
            private static void Main(string[] args)
            {
                var cow = getfoo()?.getbar()?.getmoo()?.getcow();
            }
        }
    }
    
    namespace MyLibrary
    {
        using ConsoleApplication8;
        static class MyExtensions
        {
            public static Cow getcow(this Moo moo) => null;
            public static Moo getmoo(this Bar bar) => null;
            public static Bar getbar(this Foo foo) => null;
        }
    
        static class MyHelpers
        {
            public static Foo getfoo() => null;
        }
    }
    

提交回复
热议问题