2017-12-13 12 views
0

私のコードの中にいくつかの同様のブロックを持つコードを開発する際に問題が発生しました。私の質問は:関数間でロジックを共有するための最良の方法は何ですか?関数間でロジックを共有する方法は?

例:

以下の機能が同じ場合/ elseロジックが含まれています。より簡潔で保守可能なコードを得るために、このコードをどのようにリファクタリングすることができますか?

// pseudo code... 

const hirer = 'woman'; 

const getPositions =() => { 
if (hirer === 'woman') { 
    getPositionsFromWomen(); 
    // do other stufs here... 
} else if (hirer === 'man') { 
    getPositionFromMen(); 
    // do other stufs here... 
} 
// maybe other stufs here... 
} 


const hire = (hirer) => { 
    if (hirer === 'woman') { 
    increaseWomenHiringRate(hirer); 
    // do other stufs here... 
    } else if (hirer === 'man') { 
    increaseMenHiringRate(hirer); 
    // do other stufs here... 
    } 
setPositionClosed(); 
} 

答えて

4

一つのかなり標準的な方法は、パラメータ化ロジックにあります。この場合、おそらく機能を受け入れる機能のロジックを置くことによって、それが各論理ブランチのために呼び出します。

const hirer = 'woman'; 

const hirerDispatch = (hirer, ifWoman, ifMan) => hirer === 'woman' ? ifWoman() : ifMan(); 

const getPositions =() => { 
    hirerDispatch(hirer, getPositionsFromWomen, getPositionFromMen); 
    // maybe other stuff here... 
}; 

const hire = (hirer) => { 
    hirerDispatch(hirer,() => increaseWomenHiringRate(hirer),() => increaseMenHiringRate(hirer)); 
    setPositionClosed(); 
}; 

より複雑なパラメータ設定は、渡す引数を含めて、枝のための関数プロパティを持つオブジェクトを渡し関与する可能性がありますhireのようなラッパーは必要ありません。

0

ロジックを含むロジックにメソッドとしてJavascriptオブジェクトとしてアクションを渡すのが簡単な方法の1つです。これはあなたのコードは次のようにどのように見えるかです:

const hirer = 'woman'; 

var positionHire = { 
    women: getPositionsFromWomen, 
    men: getPositionsFromMen 
} 
const getPositions = (hirer, positionHire) => { 
if (hirer === 'woman') { 
    getPositionsFromWomen(); 
    // do other stufs here... 
} else if (hirer === 'man') { 
    getPositionFromMen(); 
    // do other stufs here... 
} 
// maybe other stufs here... 
} 

var hireRate = { 
    women: increaseWomenHiringRate, 
    men: increaseMenHiringRate 
} 

const hire = (hirer, hireRate) => { 
    if (hirer === 'woman') { 
    increaseWomenHiringRate(hirer); 
    // do other stufs here... 
    } else if (hirer === 'man') { 
    increaseMenHiringRate(hirer); 
    // do other stufs here... 
    } 
setPositionClosed(); 
} 
0

あなたの/は、他のタイプ(hirer)上のスイッチである場合。したがって、Replace conditional with polymorphismとすることができます。私はdetermineHiringRate()と推測している2番目の関数の名前が必要です(ただし、それは正しい名前ではありません)。ここで

は、ソリューションのクラス図です:

enter image description here

+0

おかげで、@Fuhrmanator、私はこれを分析します。 –

関連する問題