How to prevent the arrowhead anti-pattern

后端 未结 13 1310
南旧
南旧 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 07:08

    Strange, nobody mentioned method chaining.

    If you create once a method chaining class

    Public Class Chainer(Of R)
    
        Public ReadOnly Result As R
    
        Private Sub New(Result As R)
            Me.Result = Result
        End Sub
    
        Public Shared Function Create() As Chainer(Of R)
            Return New Chainer(Of R)(Nothing)
        End Function
    
        Public Function Chain(Of S)(Method As Func(Of S)) As Chainer(Of S)
            Return New Chainer(Of S)(Method())
        End Function
    
        Public Function Chain(Of S)(Method As Func(Of R, S)) As Chainer(Of S)
            Return New Chainer(Of S)(If(Result Is Nothing, Nothing, Method(Result)))
        End Function
    End Class
    

    You can use it everywhere to compose any number of functions into an execution sequence to produce a Result or a Nothing (Null)

    Dim Cow = Chainer(Of Object).Create.
        Chain(Function() GetFoo()).
        Chain(Function(Foo) GetBar(Foo)).
        Chain(Function(Bar) GetMoo(Bar)).
        Chain(Function(Moo) GetCow(Moo)).
        Result
    
    0 讨论(0)
提交回复
热议问题