Should sorting logic be placed in the model, the view, or the controller? [closed]

Who controls the sort order?

Simple MVC diagram (From Wikipedia)

1) Natural order within the data itself:

The order is part of the Model, so it should go there. A raw pull of "all data" would return the data in the sorted order, and there is no interface to choose the sort order.

2) The user should control how they see the data:

The View would provide an interface (such as ascending/descending arrows) that interact with the Controller, and the Model understands the data well enough to do the requested sort on the data. However, a raw pull of the data doesn't necessarily have to be sorted, unlike in (1).

In either case,

The View doesn't understand that there's a sort going on, other that the ability to show which sort direction has been chosen. Don't put the logic there.

Small caveat

The sorting functionality could go purely in the View, under one circumstance (that I can think of offhand; there may be more):

A "dumb" sort where all the data is already in the view and it doesn't have to use any domain knowledge to do the sort. Very simple string or number comparison, for example. This is not possible in, for example, search results on a webpage when results are likely to be split across multiple pages.


(Note: this quote and citation is taken from @dasblinkenlight's answer, but we disagree on our interpretation of it. read his post and make up your own mind).

According to MVC description,

A controller can send commands to its associated view to change the view's presentation of the model (for example, by scrolling through a document). It can send commands to the model to update the model's state (e.g. editing a document).

Sorting logic (e.g., the sorting comparator/sorting algorithm) belongs in the model since it contains business rules and state data. Since altering the way the model data is sorted falls squarely into the "change the view's presentation of the model" category, the controller is responsible for "doing the sorting" by calling the model.changeSortedState() method.