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.
-
Are you asking because you don't want to keep your classes containing that/too many properties? Or are you focusing on how to minimize the data used in your API to avoid sending unused data?MJumper– MJumper08/02/2016 14:48:43Commented Aug 2, 2016 at 14:48
2 Answers 2
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; }
}
-
Cheers, we did consider something similar too. Might be the best idea, but will nevertheless put a bounty on it to hopefully start a little discussion.Remy– Remy07/29/2016 11:28:48Commented Jul 29, 2016 at 11:28
-
Composition will end up with lots of duplicate properties in the composite classes. If you need part of the data from
Iso
andName
, you'll just end up with a composite classIsoWithName
. Having multiple serializers that take your large object and only serialize the necessary attributes is a lot cleaner, IMO.Chris Cirefice– Chris Cirefice08/08/2016 16:52:52Commented Aug 8, 2016 at 16:52
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; }
}