Replace conditional with polymorphism refactoring or similar?

前端 未结 5 987
感动是毒
感动是毒 2021-02-06 00:45

I have tried to ask a variant of this question before. I got some helpful answers, but still nothing that felt quite right to me. It seems to me this shouldn\'t really be that h

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-06 01:17

    A good start would be to extract the conditional statement into a method(although only a small method) and give it a really explicit name. Then extract the logic within the if statement into their own methods - again with really explicit names. (Don't worry if the method names are long - as long as they do what they're called)

    I would write this out in code but it would be better for you to pick names.

    I would then move onto more complicated refactoring methods and patterns. Its only when your looking at a series of method calls will it seem appropriate to start applying patterns etc..

    Make your first goal to write clean, easy to read and comprehend code. It is easy to get excited about patterns (speaking from experience) but they are very hard to apply if you can't describe your existing code in abstractions.

    EDIT: So to clarify - you should aim to get your if statement looking like this

    if( isBox() )
    {
        doBoxAction();
    }
    else if( isSquirrel() )
    {
        doSquirrelAction();
    }
    

    Once you do this, in my opinion, then it is easier to apply some of the patterns mentioned here. But once you still have calculatios etc... in your if statement, then it is harder to see the wood from the trees as you are at too low of an abstraction.

提交回复
热议问题