DEV Community

mark vachi
mark vachi

Posted on • Updated on

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

Top comments (0)