0

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

There is nothing wrong with such a pattern, but I’m not sure I would call it a ‘factory’, since that might imply some level of abstraction. In this case you are in practice just writing some named constructors, there is not really any abstraction at all, just some convenient methods to avoid repeated code.

I would personally just add such convenience methods to the class itself, so you would write CreateProgressDTO.CreateAll(...). For generic classes (assuming c#) it is sometimes useful to add a non-generic class with the same name for such methods, since that also allow for type inference.

1

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *