Software Architecture – Which Layer Should Sorting Logic Exist In

Architecturelayers

I have an api with 3 layers

1.) The endpoint layer which exposes api endpoint handler functions. These generally call the business layer, aggregate the results to form an http response.

2.) The business logic layer, which provides interfaces to get or edit data while employing business rules behind the scenes, modifying data and enforcing rules. Prevents bloating the api endpoint functions and provides re-usable logic.

3.) the data layer, does the actual modification or querying of the persistence layer (db or otherwise) without applying any logic to the data.

In some of my functions the business layer needs to work with a list of objects retrieved from the data layer which has been sorted by a specific field. There is no case (currently foreseeable) in which the business layer will ever process this list not sorted by that field, so in this case does it make sense to sort the data in the data layer, or does it make more sense to stay pure in layer intentions and even if it means re-sorting the list every time, keep the sorting in the business layer?

Best Answer

If there is only one acceptable order, business wise, decide if this ordering is an actual business rule, or is it something inherent to the data itself.

For instance:

  • A table of persons may be sorted by first or last name, or a phone number, or an e-mail address. Maybe business rules in a specific domain dictate that it may only make sense to display this data sorted by the last name of the person; but looking at the data, you can't figure it out.

  • On the other hand, a table which contains two columns: the date of a historical event, and the name of the event, will, in most cases, be sorted by date. One can expect it to be searchable by event name (including full-text search), but this doesn't mean it should be sorted by the event; the only thing it means is that the event should be indexed for full-text search.

Note that in some cases, if you decide to do the ordering in business layer, you may later be forced to move the sorting logic down the layer for performance reasons. Therefore, write your code in a way it will make this change easy later. However, don't just push the ordering to the database layer because of the hypothetical performance gains.