Consider a class with a number of methods that are required to return a number of values each. In a strongly typed language such as C#, we can have the effect of returning more that one value from a method by using DTO classes.
Consider that the values that my methods are to return collectively are these (let's call it the pool):
A, B, C, D, E
But not all methods are required to return all of them. For example, consider the following:
Method Values to return:
==============================
Method1 A, B, C
Method2 A, E
Method3 B, D, E
Method4 D, E
Method5 A, C, D, E
You get the idea, the values to be returned are assortment of values from the pool.
This code should help it make the situation clearer. I am using C# here.
namespace TestBed
{
public interface MyInterface
{
MyDTO Method1(/* parameters */);
MyDTO Method2(/* parameters */);
// definitions for Method3() and so on
}
// Writing the DTO class here, as it is specific only to the class
// that implements this interface
public class MyDTO
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
public string D { get; set; }
public string E { get; set; }
// possibly a constructor
}
}
A class implementing the interface:
public class MyClass : MyInterface
{
public MyDTO Method1(/* parameters */)
{
MyDTO dto = new MyDTO();
// populate the properties of dto specific to this method
dto.A = "some values for A";
dto.B = "some values for B";
dto.C = "some values for C";
return dto;
}
public MyDTO Method2(/* parameters */)
{
MyDTO dto = new MyDTO();
// populate the properties of dto specific to this method
dto.A = "some values for A";
dto.E = "some values for E";
return dto;
}
// similar code for the other methods
}
As you can see, a method say Method1()
populates only the properties of the dto
that are relevant to it, e.g. A
, B
and C
for Method1()
. My concerns are:
- Although a method populates only the properties relevant to it, the callee of this method can access other values of the DTO too, e.g. the properties
D
andE
for theMethod1()
. - A method which populates only few number of values of the DTO (only 2 for
Method4()
), still returns an object with a lot of other values that are not useful for this method. It looks like an unnecessary overhead.
Regarding the concerns above, why (or why not, perhaps) should I use a DTO in such cases? Is there any better alternative approach in this scenario, at least until C# 7 is around.