2016-04-06 8 views
0

Coffeescriptでこれをリファクタリングする方法はありますか?異なる配列へのリファクタリング

class Article 
    constructor:() -> 
     @rims = [] 
     @tyres = [] 
     @others = [] 
     @wheels = [] 

    addRim: (id) -> 
     product = new SimpleProduct(id) 
     @rims.push(product) 
     product 

    addTyre: (id) -> 
     product = new SimpleProduct(id) 
     @tyres.push(product) 
     product 

    addOther: (id) -> 
     product = new SimpleProduct(id) 
     @others.push(product) 
     product 

    addWheel: (rimId, tyreId) -> 
     wheel = new Wheel(rimId, tyreId) 
     @wheels.push(wheel) 
     wheel 

答えて

1

これらの関数は3つの同一の機能がその構文は、変数(配列)を取り、他の一般的なaddProductメソッドを使用してビットを乾燥させている可能性が1

class Article 
    constructor:() -> 
     @rims = [] 
     @tyres = [] 
     @others = [] 
     @wheels = [] 

    add: (aryName, model, args...) => 
     m = new model(args...) 
     @[aryName].push m 

class Rim 
    constructor: (args...) -> 
    console.log args 

class Tyre 
    constructor: (args...) -> 

a = new Article() 

a.add('rims', Rim, 'a','b','c') 
0

に入れてプッシュすることができます追加しますそれに新しいシンプルな製品。あなたのaddWheelは別の方法を保証するのに十分に異なって見えます。私は実際には、addWheelがRimsを作成する場所で、おそらく最良のソリューションと思われますが、このモデルの使い方はわかりません。

class Article 
    constructor:() -> 
     @rims = [] 
     @tyres = [] 
     @others = [] 
     @wheels = [] 

    addProduct: (variable, id) -> 
     variable.push(product = new SimpleProduct(id)) 
     product 

    addRim: (id) -> 
     this.addProduct(@rims, id) 

    addTyre: (id) -> 
     this.addProduct(@tyres, id) 

    addOther: (id) -> 
     this.addProduct(@others, id) 

    addWheel: (rimId, tyreId) -> 
     wheel = new Wheel(rimId, tyreId) 
     @wheels.push(wheel) 
     wheel 

ホイールはリムとタイヤを持っているという事実は、あなたがリムとタイヤのためにあなたのモデルに別々のインスタンス変数を必要としないことがあり、それがこのような巣にそれらをより良いことがあります、ここで

class Article 
    constructor:() -> 
     @others = [] 
     @wheels = [] 

    addOther: (id) -> 
     @others.push(product = new SimpleProduct(id)) 
     product 

    addWheel: (rimId, tyreId) -> 
     wheel = new Wheel(rimId, tyreId) 
     @wheels.push(wheel) 
     wheel 

    rims: -> 
     @wheels.map((wheel) -> wheel.rim) 

    tyres: -> 
     @wheels.map((wheel) -> wheel.tyre) 

class Wheel 
    constructor: (rim, tyre) -> 
     @rim = new SimpleProduct(rim) 
     @tyre = new SimpleProduct(tyre) 

次の操作を行うことができます:

a = new Article() 
a.addWheel(2,3) 
a.tyres() // returns [SimpleProduct(2)] 

この第二の例は、あなたがaddWheel()メトを使用して追加されたタイヤにアクセスするためにthis.tyresを使用しようとしている場合にのみですd。私はあなたが明確なタイヤ、リム、ホイール(タイヤとリム)を使用していることを知っています。

関連する問題