We all did that in one of our first projects: returning the entire object. It was practical, easy, and straightforward.
Until you reach a listing page.
Suddenly, you have to send a huge box of data where 90% of it is useless. Sending the entire object is fine in some cases, but even then, you can trim it down a little if you think about what you actually need.
In some cases, you don't even need to send a Model or a DTO. You can send just an integer to tell the frontend how many jobs are still pending or how many tasks have been completed.
This makes communication between the server and client lighter.
The main issue is usually lists. Sending an entire object for one or ten items might not cause any noticeable problems, but when you start dealing with hundreds or thousands of records, those unnecessary properties can become a problem.
Everything boils down to one question: What do I want to show in this specific scenario?
Here are a few examples.
Example 1: Returning a smaller DTO
Let's say we have this Task model:
class Task
{
int Id;
string Title;
string Description;
string[] Objectives;
TaskStage Stage;
DateTime ToComplete;
bool IsDeleted;
}
As you can see, it packs a lot of information. When displaying a list of tasks, the Objectives array might be one of the biggest sources of unnecessary data.
So, let's trim it down:
class ReturnTaskForListDto
{
int Id;
string Title;
TaskStage Stage;
DateTime ToComplete;
}
Here, you don't need the Objectives array because you are only showing a list of tasks. You also don't need the Description or IsDeleted properties. After all, deleted tasks shouldn't even be part of this list.
But what if you still want to give the user some information about the objectives?
You can simply send an integer:
class ReturnTaskForListDto
{
int Id;
string Title;
int HowManyObjectives;
TaskStage Stage;
DateTime ToComplete;
}
Instead of sending the entire array, you only send the number of objectives.
Example 2: Sometimes, you only need a number
Another example: what if you want to show the end user how many active tasks they have?
Instead of sending the entire Model or even the DTO we created above, you can send just an integer:
int howManyTasksActive = 0;
foreach (var task in tasks)
{
if (!task.IsDeleted)
{
howManyTasksActive++;
}
}
There you go! Now you only need to send a single variable to the frontend.
No need to send a whole collection of objects just to display a number.
Final Thoughts
The idea is simple: don't send information just because it exists in your Model.
Think about what the frontend actually needs in each scenario. Sometimes you need the entire object, sometimes a smaller DTO is enough, and sometimes a single integer does the job.
This reduces unnecessary data transfer and keeps communication between your server and client more efficient.
It's a small decision, but paying attention to these details is part of becoming a better developer.
Top comments (0)