Use factory design pattern to create the same dto

Viewed 64

I am using this DTO class to pass object between web application layers

public class CreateProgressDTO
{
    public int Total { get; set; }
    public int Created { get; set; }
    public decimal Progress { get; set; }
}

In many places I had to do the following:

var createdNone = new CreateProgressDTO()
{
    Total = totalUnitsToCreate,
    Created = 0,
    Progress = 0m
}

In many places I had the same code as above. I thought it would be nice to create a class, that would derive me proper objects:

public static class CreateProgressFactory
{
    public static CreateProgressDTO CreatedAll(int total)
    {
        return new CreateProgressDTO()
        {
            Total = total,
            Created = total,
            Progress = 100m
        };
    }

    public static CreateProgressDTO CreatedNone(int total)
    {
        return new CreateProgressDTO()
        {
            Total = total,
            Created = 0,
            Progress = 0m
        };
    }

    public static CreateProgressDTO CreatedExactly(int total, int created)
    {
        if (total == 0)
            return CreatedNone(0);

        return new CreateProgressDTO()
        {
            Total = total,
            Created = created,
            Progress = Math.Round((decimal)created / total * 100, 2)
        };
    }
}

Is it ok to use a factory pattern like this?

1 Answers

It depends a bit on the specific project. Short answer is yes, For the most part a factory is fine for a DTO.

Longer answer is: It depends a bit.

If you have a big project or solution, you need to keep in mind the complexity of the project and its file structure. If the folder structure is already set up in a way that the factory file doesn't look out of place, it's a great way to abstract some of your initialization logic and keep your code DRY. If the folder structure is not really set up to easily add one, it might be time to look at refactoring that a bit.

An alternative to factory pattern that will keep the folder structure clean (and also keep things together a bit more) is to add those methods as static methods in the DTO itself. This makes it easy to find all initialization logic for the DTO and sets up a good pattern for any other DTO's that need end up like this one.

As a last note on factories: They are very useful when you inject them from some IOC container. It makes mocking for unit tests a dream.

Related