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?

New contributor
dafie is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

1 Answer 1

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
  • 1
    Or consider adding constructors if appropriate. No need to name a new type. Static methods are a great option here. The real problem, as you noted, is avoiding code repetition. Fortunately we have lots of options to solve that problem without resorting to a design pattern. Sep 20 at 13:07

Your Answer

dafie is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.