Defining objects states and behaviors

video locked
Enroll to watch

10 mins

We define the objects in our system with a 'State Based Approach'.

We then find a way to show user balances for a group: summing group expenses per user.

When finding the overall balances in a group, why didn't we use a "group by" clause to sum all the user balances from the expense table?

The number of users in a group is variable. We could try to denormalize the expenses table into two tables of balances and expense_info:

balances:

expense_id

user_id

balance

paid

owes






expense_info:

id

title

desc

imageUrl

group_id






On a 'getGroupExpenses' request for group id=123, we fire the database query:

 'select user_id, sum(balance) from balances where expense_id in (select id from expense where group_id = '123') group by user_id'

This requires a nested query, which could perform poorly.
However, this style of querying will perform very well for finding an individual user's expenses.
Depending on what you are trying to optimize, you may not may not denormalize the tables.