We’re facing the issue that we often have classes with lots of properties. But we don’t need them for most API calls. So we end up having multiple versions for basically the same business object.
E.g.
public class SmallCountry
{
string Code { get; set; }
string Name { get; set; }
}
and
public class Country
{
string Code { get; set; }
string Name { get; set; }
string Iso3166_2 { get; set; }
string Iso3166Alpha2 { get; set; }
string Iso3166Alpha3 { get; set; }
long Iso3166Numeric { get; set; }
}
We discussed different options with Interfaces, Properties, special serializers, dynamic classes, etc. But nothing really convinced us.
I’m sure we are not the only ones with this issue.
The classes can be much bigger and sometimes we have lists with hundreds of them. So I think it will make a difference for REST API calls.
We are using C# with an MVC Web API.
1
Use composition.
Taking your example, you could define two small types:
public class SmallCountry
{
string Code { get; set; }
string Name { get; set; }
}
and
public class IsoCountry
{
string Iso3166_2 { get; set; }
string Iso3166Alpha2 { get; set; }
string Iso3166Alpha3 { get; set; }
long Iso3166Numeric { get; set; }
}
And then compose the more complex classes from those, eg:
public class Country
{
SmallCountry SmallCountry { get; set; }
IsoCountry IsoCountry { get; set; }
}
2
You can probably use inheritance to achieve this for example you can have a class like
public class Country
{
string Code { get; set; }
string Name { get; set; }
}
And then you can create another class lets say IsoCountry which inherits Country like below
public class IsoCountry : Country
{
string Iso3166_2 { get; set; }
string Iso3166Alpha2 { get; set; }
string Iso3166Alpha3 { get; set; }
long Iso3166Numeric { get; set; }
}