Do you prefer Calculus within the service class or Creating separate classes for calculations?

m4r14

mark vachi

Posted on August 28, 2023

Do you prefer Calculus within the service class or Creating separate classes for calculations?

Calculus within the service class:

// Calculus in service classes:
class ItemService {
    getAllAndSumary(){
         const items = this.itemRepo.all()
         const subItems = this.subItemsRepo.allBy({ parentId: In(items.map(d => d.id)) })
         return items.map(d=> ({
              ...d,
              count: this.countSubItemsBy(subItems.filter(sub => sub.parentId == d.id)),
              total: this.sumSubItemsBy(subItems.filter(sub => sub.parentId == d.id))
         }))
    }

    countSubItemsBy(subItems: SubItem[]) {
      // logic 
    }

    sumSubItemsBy(subItems: SubItem[]) {
      // logic 
    }
}
Enter fullscreen mode Exit fullscreen mode

Creating separate classes for calculations:

class ItemSummary {
    constructor(private _item, private _subItems) {
      Object.assign(this, _item)
    }

    get count() {
      return this._subItems.countBy({parentId: this.id })
    }

    get total() {
      return this._subItems.sumBy({ parentId:  this.id  })
    }
}

class ItemService {
    getAllAndSumary(){
         const items = this.itemRepo.all()
         const subItems = this.subItemsRepo.allBy({ parentId: In(items.map(d => d.id)) })
         return items.map(d=> new ItemSummary(d, subItems))
    }
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
m4r14
mark vachi

Posted on August 28, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related