DTO simplified. Dynamic tuples. How? Let's see a possible solution [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I've been thinking about a possible usage of dynamic keyword.
Being a big defender (say it paladin) of strongly-typed programming languages, I needed to open my mind a lot and try to think
an alternative way of doing things.
Some thing I found hard to mantain is how layers and tiers are communicated with data transfer objects (DTO).
How many dozens of DTOs have you needed to cover transferring data through your application or service? I'm sure we can count a lot
of them in any well-done project.
But, what about the domain object-to-DTO translation? You end up creating dozens of DTO which transfer info from a number of domain
objects evolved in some transaction, flow or process.
In the end, what are the most important things to keep in mind when you develop software?
- Money and/or time first. Sizing the project to cover it with the right solution with available resources.
- Create a maintainable, scalable, performant, well-designed application. Everything with our limited resources.
Talking about the second point, what is maintanable and scalable? A incredibly well-done design which has thousands of classes,
interfaces, ... to maintain and improve? Yes. Think in a well-done DDD, MVC, solution. Easy to follow, improve, fix... But not in terms
of time. You can do it right, but you'll need a lot of time.
Perhaps there's a solution for that with the flagship Dynamic Language Runtime and associated "dynamic" keyword in C# 4.0 on top of
.NET Framework 4.0.
Yes, dynamic seems evil if it's not for interop or working with dynamic languages... Right! But, remembering what I said in the
second sentence, I wanted to go forward and think about this topic.
We've tuples. Good! We can have typed multiple results as a return value in a method or property. We don't need custom DTO! Wrong because
we don't have named tuples. How can we mantain a code that's giving results with properties like "Item1, Item2, ItemN".
Tuples seem to be a good solution for example for replacing the usage of "out" keyword in methods like bool TryParse(value, out result)
into Tuple TryParse(T value), but I don't think this is a good replacement for DTO, because we're loosing the meaning of
the code... Code is readable no more.
Later, I was thinking in how to create attribute-based named tuples, but it has a drawback: you need reflection to get something like
'tuple.Return("Name")' work fine. Discarded.
It was at this point when I thought, what about dynamic and DLR? I was figuring out how to do dynamic tuples and work with them.
Something like this is possible, but I want to discuss with you if you find that fine or not:
public static class DynamicTupleExtensions
{
public static dynamic Return(this IEnumerable source, Func returnPredicate)
{
return source.Select(result => returnPredicate(result)).Single();
}
public static IEnumerable> ToTuple(this IEnumerable source)
{
return source.Select(dynamicTuple => Tuple.Create((T1)dynamicTuple.GetType().GetProperties()[0].GetValue(dynamicTuple, null)));
}
public static IEnumerable Cast(this IEnumerable source)
{
return source.Select(dynamicTuple => JsonConvert.DeserializeObject(JsonConvert.SerializeObject(dynamicTuple)));
}
public static T Cast(this object source)
where T : class
{
return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(source));
}
}
public class StronglyTypedResult
{
public int Value
{
get;
set;
}
}
public class Program
{
private static void Main(string[] args)
{
int result = AddOne(10).Return(value => value.Value);
Tuple resultAsTuple = AddOne(10).ToTuple().Single();
StronglyTypedResult typedResult = AddOne(10).Cast().Single();
Console.WriteLine(result);
Console.Read();
}
private static IEnumerable AddOne(int value)
{
return new List
{
new { Value = value + 1 }
};
}
}
Looking at the code, you'll see that I'm "abussing" of anonymous types and dynamic keyword in order to create an enumerable of
dynamic tuples.
Later, you can retrieve dynamic tuple value by using three approaches:
- Full dynamic-based tuple retrieval.
- Convert to a typed tuple.
- Cast as DTO (it's a conversion).
First one is the most controversial one: it's a full dynamic tuple consumed "as is". You lose compile-time type checking, but you
gain a lot of flexibility. I would use it in a project with high discipline and a strong naming and convention guidelines (this is heaven, I know it).
Second one it's a mix of compile-time and run-time type checking: the tuple is dinamically handled, but you get a strongly-typed
tuple. That's loosing the named tuple-like solution in the first approach. This approach would be for use in a method body, where
maybe there's no access to the classes representing DTO or you don't have them, or there's no implementation for them (same as first
option).
Finally, the third one is the safest solution: you use dynamic tuples in some layer or tier, and wherever you've classes representing
DTOs, you cast the dynamic tuple to DTO and this is working as actual and most of C# DTOs. This isn't a good option because I'm using
a JSON serializer in order to lie C# compiler and make an on-the-fly converstion from the anonymous type to the strongly-typed DTO.
At the end of the day, which is the question? The question is, what's your opinion about this solution?
It's maintainable?
What would be the performance impact of such approach?
Do you think that discipline is the only requirement to follow this approach or it's just a big fail?
Do you think that this solution is a big fail and it's a big crash in terms of creating well-designed solutions?
It's just software philosophy. And I'm pretty sure that this approaching is going to have defenders and haters.
Keep in mind that this isn't "the asker thinks that this is the best solution", but I'm just throwing here a conclusion I want
to share with everyone.
Thanks for reading and I hope you all are going to have good points (even if you hate my conclusions, it's about that!).

At the end (after one or 2 years) your early discussion have became true and more popular (check here) with the "Dynamic model binding with ASP.NET WEB API". The basic idea it's to avoid the amount of DTOs using dynamics and this way increasing the flexibility.
public Class Controller : APIController()
{
public dynamic Post(dynamic contract)
{
return contract;
}
}

It seems like you are looking for a combination of AutoMapper Dynamic Mapping and the ExpandoObject. With some creative reflection, you could probably accomplish your goal in this way.

Related

Benefit of wrapping List<T> into class TList [duplicate]

When planning out my programs, I often start with a chain of thought like so:
A football team is just a list of football players. Therefore, I should represent it with:
var football_team = new List<FootballPlayer>();
The ordering of this list represent the order in which the players are listed in the roster.
But I realize later that teams also have other properties, besides the mere list of players, that must be recorded. For example, the running total of scores this season, the current budget, the uniform colors, a string representing the name of the team, etc..
So then I think:
Okay, a football team is just like a list of players, but additionally, it has a name (a string) and a running total of scores (an int). .NET does not provide a class for storing football teams, so I will make my own class. The most similar and relevant existing structure is List<FootballPlayer>, so I will inherit from it:
class FootballTeam : List<FootballPlayer>
{
public string TeamName;
public int RunningTotal
}
But it turns out that a guideline says you shouldn't inherit from List<T>. I'm thoroughly confused by this guideline in two respects.
Why not?
Apparently List is somehow optimized for performance. How so? What performance problems will I cause if I extend List? What exactly will break?
Another reason I've seen is that List is provided by Microsoft, and I have no control over it, so I cannot change it later, after exposing a "public API". But I struggle to understand this. What is a public API and why should I care? If my current project does not and is not likely to ever have this public API, can I safely ignore this guideline? If I do inherit from List and it turns out I need a public API, what difficulties will I have?
Why does it even matter? A list is a list. What could possibly change? What could I possibly want to change?
And lastly, if Microsoft did not want me to inherit from List, why didn't they make the class sealed?
What else am I supposed to use?
Apparently, for custom collections, Microsoft has provided a Collection class which should be extended instead of List. But this class is very bare, and does not have many useful things, such as AddRange, for instance. jvitor83's answer provides a performance rationale for that particular method, but how is a slow AddRange not better than no AddRange?
Inheriting from Collection is way more work than inheriting from List, and I see no benefit. Surely Microsoft wouldn't tell me to do extra work for no reason, so I can't help feeling like I am somehow misunderstanding something, and inheriting Collection is actually not the right solution for my problem.
I've seen suggestions such as implementing IList. Just no. This is dozens of lines of boilerplate code which gains me nothing.
Lastly, some suggest wrapping the List in something:
class FootballTeam
{
public List<FootballPlayer> Players;
}
There are two problems with this:
It makes my code needlessly verbose. I must now call my_team.Players.Count instead of just my_team.Count. Thankfully, with C# I can define indexers to make indexing transparent, and forward all the methods of the internal List... But that's a lot of code! What do I get for all that work?
It just plain doesn't make any sense. A football team doesn't "have" a list of players. It is the list of players. You don't say "John McFootballer has joined SomeTeam's players". You say "John has joined SomeTeam". You don't add a letter to "a string's characters", you add a letter to a string. You don't add a book to a library's books, you add a book to a library.
I realize that what happens "under the hood" can be said to be "adding X to Y's internal list", but this seems like a very counter-intuitive way of thinking about the world.
My question (summarized)
What is the correct C# way of representing a data structure, which, "logically" (that is to say, "to the human mind") is just a list of things with a few bells and whistles?
Is inheriting from List<T> always unacceptable? When is it acceptable? Why/why not? What must a programmer consider, when deciding whether to inherit from List<T> or not?
There are some good answers here. I would add to them the following points.
What is the correct C# way of representing a data structure, which, "logically" (that is to say, "to the human mind") is just a list of things with a few bells and whistles?
Ask any ten non-computer-programmer people who are familiar with the existence of football to fill in the blank:
A football team is a particular kind of _____
Did anyone say "list of football players with a few bells and whistles", or did they all say "sports team" or "club" or "organization"? Your notion that a football team is a particular kind of list of players is in your human mind and your human mind alone.
List<T> is a mechanism. Football team is a business object -- that is, an object that represents some concept that is in the business domain of the program. Don't mix those! A football team is a kind of team; it has a roster, a roster is a list of players. A roster is not a particular kind of list of players. A roster is a list of players. So make a property called Roster that is a List<Player>. And make it ReadOnlyList<Player> while you're at it, unless you believe that everyone who knows about a football team gets to delete players from the roster.
Is inheriting from List<T> always unacceptable?
Unacceptable to whom? Me? No.
When is it acceptable?
When you're building a mechanism that extends the List<T> mechanism.
What must a programmer consider, when deciding whether to inherit from List<T> or not?
Am I building a mechanism or a business object?
But that's a lot of code! What do I get for all that work?
You spent more time typing up your question that it would have taken you to write forwarding methods for the relevant members of List<T> fifty times over. You're clearly not afraid of verbosity, and we are talking about a very small amount of code here; this is a few minutes work.
UPDATE
I gave it some more thought and there is another reason to not model a football team as a list of players. In fact it might be a bad idea to model a football team as having a list of players too. The problem with a team as/having a list of players is that what you've got is a snapshot of the team at a moment in time. I don't know what your business case is for this class, but if I had a class that represented a football team I would want to ask it questions like "how many Seahawks players missed games due to injury between 2003 and 2013?" or "What Denver player who previously played for another team had the largest year-over-year increase in yards ran?" or "Did the Piggers go all the way this year?"
That is, a football team seems to me to be well modeled as a collection of historical facts such as when a player was recruited, injured, retired, etc. Obviously the current player roster is an important fact that should probably be front-and-center, but there may be other interesting things you want to do with this object that require a more historical perspective.
Wow, your post has an entire slew of questions and points. Most of the reasoning you get from Microsoft is exactly on point. Let's start with everything about List<T>
List<T> is highly optimized. Its main usage is to be used as a private member of an object.
Microsoft did not seal it because sometimes you might want to create a class that has a friendlier name: class MyList<T, TX> : List<CustomObject<T, Something<TX>> { ... }. Now it's as easy as doing var list = new MyList<int, string>();.
CA1002: Do not expose generic lists: Basically, even if you plan to use this app as the sole developer, it's worthwhile to develop with good coding practices, so they become instilled into you and second nature. You are still allowed to expose the list as an IList<T> if you need any consumer to have an indexed list. This lets you change the implementation within a class later on.
Microsoft made Collection<T> very generic because it is a generic concept... the name says it all; it is just a collection. There are more precise versions such as SortedCollection<T>, ObservableCollection<T>, ReadOnlyCollection<T>, etc. each of which implement IList<T> but not List<T>.
Collection<T> allows for members (i.e. Add, Remove, etc.) to be overridden because they are virtual. List<T> does not.
The last part of your question is spot on. A Football team is more than just a list of players, so it should be a class that contains that list of players. Think Composition vs Inheritance. A Football team has a list of players (a roster), it isn't a list of players.
If I were writing this code, the class would probably look something like so:
public class FootballTeam<T>//generic class
{
// Football team rosters are generally 53 total players.
private readonly List<T> _roster = new List<T>(53);
public IList<T> Roster
{
get { return _roster; }
}
// Yes. I used LINQ here. This is so I don't have to worry about
// _roster.Length vs _roster.Count vs anything else.
public int PlayerCount
{
get { return _roster.Count(); }
}
// Any additional members you want to expose/wrap.
}
class FootballTeam : List<FootballPlayer>
{
public string TeamName;
public int RunningTotal;
}
Previous code means: a bunch of guys from the street playing football, and they happen to have a name. Something like:
Anyway, this code (from m-y's answer)
public class FootballTeam
{
// A team's name
public string TeamName;
// Football team rosters are generally 53 total players.
private readonly List<T> _roster = new List<T>(53);
public IList<T> Roster
{
get { return _roster; }
}
public int PlayerCount
{
get { return _roster.Count(); }
}
// Any additional members you want to expose/wrap.
}
Means: this is a football team which has management, players, admins, etc. Something like:
This is how is your logic presented in pictures…
This is a classic example of composition vs inheritance.
In this specific case:
Is the team a list of players with added behavior
or
Is the team an object of its own that happens to contain a list of players.
By extending List you are limiting yourself in a number of ways:
You cannot restrict access (for example, stopping people changing the roster). You get all the List methods whether you need/want them all or not.
What happens if you want to have lists of other things as well. For example, teams have coaches, managers, fans, equipment, etc. Some of those might well be lists in their own right.
You limit your options for inheritance. For example you might want to create a generic Team object, and then have BaseballTeam, FootballTeam, etc. that inherit from that. To inherit from List you need to do the inheritance from Team, but that then means that all the various types of team are forced to have the same implementation of that roster.
Composition - including an object giving the behavior you want inside your object.
Inheritance - your object becomes an instance of the object that has the behavior you want.
Both have their uses, but this is a clear case where composition is preferable.
As everyone has pointed out, a team of players is not a list of players. This mistake is made by many people everywhere, perhaps at various levels of expertise. Often the problem is subtle and occasionally very gross, as in this case. Such designs are bad because these violate the Liskov Substitution Principle. The internet has many good articles explaining this concept e.g., http://en.wikipedia.org/wiki/Liskov_substitution_principle
In summary, there are two rules to be preserved in a Parent/Child relationship among classes:
a Child should require no characteristic less than what completely defines the Parent.
a Parent should require no characteristic in addition to what completely defines the Child.
In other words, a Parent is a necessary definition of a child, and a child is a sufficient definition of a Parent.
Here is a way to think through ones solution and apply the above principle that should help one avoid such a mistake. One should test ones hypothesis by verifying if all the operations of a parent class are valid for the derived class both structurally and semantically.
Is a football team a list of football players? ( Do all properties of a list apply to a team in the same meaning)
Is a team a collection of homogenous entities? Yes, team is a collection of Players
Is the order of inclusion of players descriptive of the state of the team and does the team ensure that the sequence is preserved unless explicitly changed? No, and No
Are players expected to be included/dropped based on their sequencial position in the team? No
As you see, only the first characteristic of a list is applicable to a team. Hence a team is not a list. A list would be a implementation detail of how you manage your team, so it should only be used to store the player objects and be manipulated with methods of Team class.
At this point I'd like to remark that a Team class should, in my opinion, not even be implemented using a List; it should be implemented using a Set data structure (HashSet, for example) in most cases.
What if the FootballTeam has a reserves team along with the main team?
class FootballTeam
{
List<FootballPlayer> Players { get; set; }
List<FootballPlayer> ReservePlayers { get; set; }
}
How would you model that with?
class FootballTeam : List<FootballPlayer>
{
public string TeamName;
public int RunningTotal
}
The relationship is clearly has a and not is a.
or RetiredPlayers?
class FootballTeam
{
List<FootballPlayer> Players { get; set; }
List<FootballPlayer> ReservePlayers { get; set; }
List<FootballPlayer> RetiredPlayers { get; set; }
}
As a rule of thumb, if you ever want to inherit from a collection, name the class SomethingCollection.
Does your SomethingCollection semantically make sense? Only do this if your type is a collection of Something.
In the case of FootballTeam it doesn't sound right. A Team is more than a Collection. A Team can have coaches, trainers, etc as the other answers have pointed out.
FootballCollection sounds like a collection of footballs or maybe a collection of football paraphernalia. TeamCollection, a collection of teams.
FootballPlayerCollection sounds like a collection of players which would be a valid name for a class that inherits from List<FootballPlayer> if you really wanted to do that.
Really List<FootballPlayer> is a perfectly good type to deal with. Maybe IList<FootballPlayer> if you are returning it from a method.
In summary
Ask yourself
Is X a Y? or Has X a Y?
Do my class names mean what they are?
Design > Implementation
What methods and properties you expose is a design decision. What base class you inherit from is an implementation detail. I feel it's worth taking a step back to the former.
An object is a collection of data and behaviour.
So your first questions should be:
What data does this object comprise in the model I'm creating?
What behaviour does this object exhibit in that model?
How might this change in future?
Bear in mind that inheritance implies an "isa" (is a) relationship, whereas composition implies a "has a" (hasa) relationship. Choose the right one for your situation in your view, bearing in mind where things might go as your application evolves.
Consider thinking in interfaces before you think in concrete types, as some people find it easier to put their brain in "design mode" that way.
This isn't something everyone does consciously at this level in day to day coding. But if you're mulling this sort of topic, you're treading in design waters. Being aware of it can be liberating.
Consider Design Specifics
Take a look at List<T> and IList<T> on MSDN or Visual Studio. See what methods and properties they expose. Do these methods all look like something someone would want to do to a FootballTeam in your view?
Does footballTeam.Reverse() make sense to you? Does footballTeam.ConvertAll<TOutput>() look like something you want?
This isn't a trick question; the answer might genuinely be "yes". If you implement/inherit List<Player> or IList<Player>, you're stuck with them; if that's ideal for your model, do it.
If you decide yes, that makes sense, and you want your object to be treatable as a collection/list of players (behaviour), and you therefore want to implement ICollection<Player> or IList<Player>, by all means do so. Notionally:
class FootballTeam : ... ICollection<Player>
{
...
}
If you want your object to contain a collection/list of players (data), and you therefore want the collection or list to be a property or member, by all means do so. Notionally:
class FootballTeam ...
{
public ICollection<Player> Players { get { ... } }
}
You might feel that you want people to be able to only enumerate the set of players, rather than count them, add to them or remove them. IEnumerable<Player> is a perfectly valid option to consider.
You might feel that none of these interfaces are useful in your model at all. This is less likely (IEnumerable<T> is useful in many situations) but it's still possible.
Anyone who attempts to tell you that one of these it is categorically and definitively wrong in every case is misguided. Anyone who attempts to tell you it is categorically and definitively right in every case is misguided.
Move on to Implementation
Once you've decided on data and behaviour, you can make a decision about implementation. This includes which concrete classes you depend on via inheritance or composition.
This may not be a big step, and people often conflate design and implementation since it's quite possible to run through it all in your head in a second or two and start typing away.
A Thought Experiment
An artificial example: as others have mentioned, a team is not always "just" a collection of players. Do you maintain a collection of match scores for the team? Is the team interchangeable with the club, in your model? If so, and if your team isa collection of players, perhaps it also isa collection of staff and/or a collection of scores. Then you end up with:
class FootballTeam : ... ICollection<Player>,
ICollection<StaffMember>,
ICollection<Score>
{
....
}
Design notwithstanding, at this point in C# you won't be able to implement all of these by inheriting from List<T> anyway, since C# "only" supports single inheritance. (If you've tried this malarkey in C++, you may consider this a Good Thing.) Implementing one collection via inheritance and one via composition is likely to feel dirty. And properties such as Count become confusing to users unless you implement ILIst<Player>.Count and IList<StaffMember>.Count etc. explicitly, and then they're just painful rather than confusing. You can see where this is going; gut feeling whilst thinking down this avenue may well tell you it feels wrong to head in this direction (and rightly or wrongly, your colleagues might also if you implemented it this way!)
The Short Answer (Too Late)
The guideline about not inheriting from collection classes isn't C# specific, you'll find it in many programming languages. It is received wisdom not a law. One reason is that in practice composition is considered to often win out over inheritance in terms of comprehensibility, implementability and maintainability. It's more common with real world / domain objects to find useful and consistent "hasa" relationships than useful and consistent "isa" relationships unless you're deep in the abstract, most especially as time passes and the precise data and behaviour of objects in code changes. This shouldn't cause you to always rule out inheriting from collection classes; but it may be suggestive.
First of all, it has to do with usability. If you use inheritance, the Team class will expose behavior (methods) that are designed purely for object manipulation. For example, AsReadOnly() or CopyTo(obj) methods make no sense for the team object. Instead of the AddRange(items) method you would probably want a more descriptive AddPlayers(players) method.
If you want to use LINQ, implementing a generic interface such as ICollection<T> or IEnumerable<T> would make more sense.
As mentioned, composition is the right way to go about it. Just implement a list of players as a private variable.
Let me rewrite your question. so you might see the subject from a different perspective.
When I need to represent a football team, I understand that it is basically a name. Like: "The Eagles"
string team = new string();
Then later I realized teams also have players.
Why can't I just extend the string type so that it also holds a list of players?
Your point of entry into the problem is arbitrary. Try to think what does a team have (properties), not what it is.
After you do that, you could see if it shares properties with other classes. And think about inheritance.
It depends on the context
When you consider your team as a list of players, you are projecting the "idea" of a foot ball team down to one aspect: You reduce the "team" to the people you see on the field. This projection is only correct in a certain context. In a different context, this might be completely wrong. Imagine you want to become a sponsor of the team. So you have to talk to the managers of the team. In this context the team is projected to the list of its managers. And these two lists usually don't overlap very much. Other contexts are the current versus the former players, etc.
Unclear semantics
So the problem with considering a team as a list of its players is that its semantic depends on the context and that it cannot be extended when the context changes. Additionally it is hard to express, which context you are using.
Classes are extensible
When you using a class with only one member (e.g. IList activePlayers), you can use the name of the member (and additionally its comment) to make the context clear. When there are additional contexts, you just add an additional member.
Classes are more complex
In some cases it might be overkill to create an extra class. Each class definition must be loaded through the classloader and will be cached by the virtual machine. This costs you runtime performance and memory. When you have a very specific context it might be OK to consider a football team as a list of players. But in this case, you should really just use a IList , not a class derived from it.
Conclusion / Considerations
When you have a very specific context, it is OK to consider a team as a list of players. For example inside a method it is completely OK to write:
IList<Player> footballTeam = ...
When using F#, it can even be OK to create a type abbreviation:
type FootballTeam = IList<Player>
But when the context is broader or even unclear, you should not do this. This is especially the case when you create a new class whose context in which it may be used in the future is not clear. A warning sign is when you start to add additional attributes to your class (name of the team, coach, etc.). This is a clear sign that the context where the class will be used is not fixed and will change in the future. In this case you cannot consider the team as a list of players, but you should model the list of the (currently active, not injured, etc.) players as an attribute of the team.
A football team is not a list of football players. A football team is composed of a list of football players!
This is logically wrong:
class FootballTeam : List<FootballPlayer>
{
public string TeamName;
public int RunningTotal
}
and this is correct:
class FootballTeam
{
public List<FootballPlayer> players
public string TeamName;
public int RunningTotal
}
Just because I think the other answers pretty much go off on a tangent of whether a football team "is-a" List<FootballPlayer> or "has-a" List<FootballPlayer>, which really doesn't answer this question as written.
The OP chiefly asks for clarification on guidelines for inheriting from List<T>:
A guideline says that you shouldn't inherit from List<T>. Why not?
Because List<T> has no virtual methods. This is less of a problem in your own code, since you can usually switch out the implementation with relatively little pain - but can be a much bigger deal in a public API.
What is a public API and why should I care?
A public API is an interface you expose to 3rd party programmers. Think framework code. And recall that the guidelines being referenced are the ".NET Framework Design Guidelines" and not the ".NET Application Design Guidelines". There is a difference, and - generally speaking - public API design is a lot more strict.
If my current project does not and is not likely to ever have this public API, can I safely ignore this guideline? If I do inherit from List and it turns out I need a public API, what difficulties will I have?
Pretty much, yeah. You may want to consider the rationale behind it to see if it applies to your situation anyway, but if you're not building a public API then you don't particularly need to worry about API concerns like versioning (of which, this is a subset).
If you add a public API in the future, you will either need to abstract out your API from your implementation (by not exposing your List<T> directly) or violate the guidelines with the possible future pain that entails.
Why does it even matter? A list is a list. What could possibly change? What could I possibly want to change?
Depends on the context, but since we're using FootballTeam as an example - imagine that you can't add a FootballPlayer if it would cause the team to go over the salary cap. A possible way of adding that would be something like:
class FootballTeam : List<FootballPlayer> {
override void Add(FootballPlayer player) {
if (this.Sum(p => p.Salary) + player.Salary > SALARY_CAP)) {
throw new InvalidOperationException("Would exceed salary cap!");
}
}
}
Ah...but you can't override Add because it's not virtual (for performance reasons).
If you're in an application (which, basically, means that you and all of your callers are compiled together) then you can now change to using IList<T> and fix up any compile errors:
class FootballTeam : IList<FootballPlayer> {
private List<FootballPlayer> Players { get; set; }
override void Add(FootballPlayer player) {
if (this.Players.Sum(p => p.Salary) + player.Salary > SALARY_CAP)) {
throw new InvalidOperationException("Would exceed salary cap!");
}
}
/* boiler plate for rest of IList */
}
but, if you've publically exposed to a 3rd party you just made a breaking change that will cause compile and/or runtime errors.
TL;DR - the guidelines are for public APIs. For private APIs, do what you want.
There are a lot excellent answers here, but I want to touch on something I didn't see mentioned: Object oriented design is about empowering objects.
You want to encapsulate all your rules, additional work and internal details inside an appropriate object. In this way other objects interacting with this one don't have to worry about it all. In fact, you want to go a step further and actively prevent other objects from bypassing these internals.
When you inherit from List, all other objects can see you as a List. They have direct access to the methods for adding and removing players. And you'll have lost your control; for example:
Suppose you want to differentiate when a player leaves by knowing whether they retired, resigned or were fired. You could implement a RemovePlayer method that takes an appropriate input enum. However, by inheriting from List, you would be unable to prevent direct access to Remove, RemoveAll and even Clear. As a result, you've actually disempowered your FootballTeam class.
Additional thoughts on encapsulation... You raised the following concern:
It makes my code needlessly verbose. I must now call my_team.Players.Count instead of just my_team.Count.
You're correct, that would be needlessly verbose for all clients to use you team. However, that problem is very small in comparison to the fact that you've exposed List Players to all and sundry so they can fiddle with your team without your consent.
You go on to say:
It just plain doesn't make any sense. A football team doesn't "have" a list of players. It is the list of players. You don't say "John McFootballer has joined SomeTeam's players". You say "John has joined SomeTeam".
You're wrong about the first bit: Drop the word 'list', and it's actually obvious that a team does have players.
However, you hit the nail on the head with the second. You don't want clients calling ateam.Players.Add(...). You do want them calling ateam.AddPlayer(...). And your implemention would (possibly amongst other things) call Players.Add(...) internally.
Hopefully you can see how important encapsulation is to the objective of empowering your objects. You want to allow each class to do its job well without fear of interference from other objects.
Does allowing people to say
myTeam.subList(3, 5);
make any sense at all? If not then it shouldn't be a List.
It depends on the behaviour of your "team" object. If it behaves just like a collection, it might be OK to represent it first with a plain List. Then you might start to notice that you keep duplicating code that iterates on the list; at this point you have the option of creating a FootballTeam object that wraps the list of players. The FootballTeam class becomes the home for all the code that iterates on the list of players.
It makes my code needlessly verbose. I must now call my_team.Players.Count instead of just my_team.Count. Thankfully, with C# I can define indexers to make indexing transparent, and forward all the methods of the internal List... But that's a lot of code! What do I get for all that work?
Encapsulation. Your clients need not know what goes on inside of FootballTeam. For all your clients know, it might be implemented by looking the list of players up in a database. They don't need to know, and this improves your design.
It just plain doesn't make any sense. A football team doesn't "have" a list of players. It is the list of players. You don't say "John McFootballer has joined SomeTeam's players". You say "John has joined SomeTeam". You don't add a letter to "a string's characters", you add a letter to a string. You don't add a book to a library's books, you add a book to a library.
Exactly :) you will say footballTeam.Add(john), not footballTeam.List.Add(john). The internal list will not be visible.
What is the correct C# way of representing a data structure...
Remeber, "All models are wrong, but some are useful." -George E. P. Box
There is no a "correct way", only a useful one.
Choose one that is useful to you and/your users. That's it. Develop economically, don't over-engineer. The less code you write, the less code you will need to debug. (read the following editions).
-- Edited
My best answer would be... it depends. Inheriting from a List would expose the clients of this class to methods that may be should not be exposed, primarily because FootballTeam looks like a business entity.
-- Edition 2
I sincerely don't remember to what I was referring on the “don't over-engineer” comment. While I believe the KISS mindset is a good guide, I want to emphasize that inheriting a business class from List would create more problems than it resolves, due abstraction leakage.
On the other hand, I believe there are a limited number of cases where simply to inherit from List is useful. As I wrote in the previous edition, it depends. The answer to each case is heavily influenced by both knowledge, experience and personal preferences.
Thanks to #kai for helping me to think more precisely about the answer.
This reminds me of the "Is a" versus "has a" tradeoff. Sometimes it is easier and makesmore sense to inherit directly from a super class. Other times it makes more sense to create a standalone class and include the class you would have inherited from as a member variable. You can still access the functionality of the class but are not bound to the interface or any other constraints that might come from inheriting from the class.
Which do you do? As with a lot of things...it depends on the context. The guide I would use is that in order to inherit from another class there truly should be an "is a" relationship. So if you a writing a class called BMW, it could inherit from Car because a BMW truly is a car. A Horse class can inherit from the Mammal class because a horse actually is a mammal in real life and any Mammal functionality should be relevant to Horse. But can you say that a team is a list? From what I can tell, it does not seem like a Team really "is a" List. So in this case, I would have a List as a member variable.
Problems with serializing
One aspect is missing. Classes that inherit from List can't be serialized correctly using XmlSerializer. In that case DataContractSerializer must be used instead, or an own serializing implementation is needed.
public class DemoList : List<Demo>
{
// using XmlSerializer this properties won't be seralized
// There is no error, the data is simply not there.
string AnyPropertyInDerivedFromList { get; set; }
}
public class Demo
{
// this properties will be seralized
string AnyPropetyInDemo { get; set; }
}
Further reading: When a class is inherited from List<>, XmlSerializer doesn't serialize other attributes
Use IList instead
Personaly I wouldn't inherit from List but implement IList. Visual Studio will do the job for you and create a full working iplementation. Look here: How to get a full working implementation of IList
What the guidelines say is that the public API should not reveal the internal design decision of whether you are using a list, a set, a dictionary, a tree or whatever. A "team" is not necessarily a list. You may implement it as a list but users of your public API should use you class on a need to know basis. This allows you to change your decision and use a different data structure without affecting the public interface.
When they say List<T> is "optimized" I think they want to mean that it doesn't have features like virtual methods which are bit more expensive. So the problem is that once you expose List<T> in your public API, you loose ability to enforce business rules or customize its functionality later. But if you are using this inherited class as internal within your project (as opposed to potentially exposed to thousands of your customers/partners/other teams as API) then it may be OK if it saves your time and it is the functionality you want to duplicate. The advantage of inheriting from List<T> is that you eliminate lot of dumb wrapper code that is just never going to be customized in foreseeable future. Also if you want your class to explicitly have exact same semantics as List<T> for the life of your APIs then also it may be OK.
I often see lot of people doing tons of extra work just because of FxCop rule says so or someone's blog says it's a "bad" practice. Many times, this turns code in to design pattern palooza weirdness. As with lot of guideline, treat it as guideline that can have exceptions.
My dirty secret: I don't care what people say, and I do it. .NET Framework is spread with "XxxxCollection" (UIElementCollection for top of my head example).
So what stops me saying:
team.Players.ByName("Nicolas")
When I find it better than
team.ByName("Nicolas")
Moreover, my PlayerCollection might be used by other class, like "Club" without any code duplication.
club.Players.ByName("Nicolas")
Best practices of yesterday, might not be the one of tomorrow. There is no reason behind most best practices, most are only wide agreement among the community. Instead of asking the community if it will blame you when you do that ask yourself, what is more readable and maintainable?
team.Players.ByName("Nicolas")
or
team.ByName("Nicolas")
Really. Do you have any doubt? Now maybe you need to play with other technical constraints that prevent you to use List<T> in your real use case. But don't add a constraint that should not exist. If Microsoft did not document the why, then it is surely a "best practice" coming from nowhere.
While I don't have a complex comparison as most of these answers do, I would like to share my method for handling this situation. By extending IEnumerable<T>, you can allow your Team class to support Linq query extensions, without publicly exposing all the methods and properties of List<T>.
class Team : IEnumerable<Player>
{
private readonly List<Player> playerList;
public Team()
{
playerList = new List<Player>();
}
public Enumerator GetEnumerator()
{
return playerList.GetEnumerator();
}
...
}
class Player
{
...
}
I just wanted to add that Bertrand Meyer, the inventor of Eiffel and design by contract, would have Team inherit from List<Player> without so much as batting an eyelid.
In his book, Object-Oriented Software Construction, he discusses the implementation of a GUI system where rectangular windows can have child windows. He simply has Window inherit from both Rectangle and Tree<Window> to reuse the implementation.
However, C# is not Eiffel. The latter supports multiple inheritance and renaming of features. In C#, when you subclass, you inherit both the interface and the implemenation. You can override the implementation, but the calling conventions are copied directly from the superclass. In Eiffel, however, you can modify the names of the public methods, so you can rename Add and Remove to Hire and Fire in your Team. If an instance of Team is upcast back to List<Player>, the caller will use Add and Remove to modify it, but your virtual methods Hire and Fire will be called.
If your class users need all the methods and properties** List has, you should derive your class from it. If they don't need them, enclose the List and make wrappers for methods your class users actually need.
This is a strict rule, if you write a public API, or any other code that will be used by many people. You may ignore this rule if you have a tiny app and no more than 2 developers. This will save you some time.
For tiny apps, you may also consider choosing another, less strict language. Ruby, JavaScript - anything that allows you to write less code.
I think I don't agree with your generalization. A team isn't just a collection of players. A team has so much more information about it - name, emblem, collection of management/admin staff, collection of coaching crew, then collection of players. So properly, your FootballTeam class should have 3 collections and not itself be a collection; if it is to properly model the real world.
You could consider a PlayerCollection class which like the Specialized StringCollection offers some other facilities - like validation and checks before objects are added to or removed from the internal store.
Perhaps, the notion of a PlayerCollection betters suits your preferred approach?
public class PlayerCollection : Collection<Player>
{
}
And then the FootballTeam can look like this:
public class FootballTeam
{
public string Name { get; set; }
public string Location { get; set; }
public ManagementCollection Management { get; protected set; } = new ManagementCollection();
public CoachingCollection CoachingCrew { get; protected set; } = new CoachingCollection();
public PlayerCollection Players { get; protected set; } = new PlayerCollection();
}
Prefer Interfaces over Classes
Classes should avoid deriving from classes and instead implement the minimal interfaces necessary.
Inheritance breaks Encapsulation
Deriving from classes breaks encapsulation:
exposes internal details about how your collection is implemented
declares an interface (set of public functions and properties) that may not be appropriate
Among other things this makes it harder to refactor your code.
Classes are an Implementation Detail
Classes are an implementation detail that should be hidden from other parts of your code.
In short a System.List is a specific implementation of an abstract data type, that may or may not be appropriate now and in the future.
Conceptually the fact that the System.List data type is called "list" is a bit of a red-herring. A System.List<T> is a mutable ordered collection that supports amortized O(1) operations for adding, inserting, and removing elements, and O(1) operations for retrieving the number of elements or getting and setting element by index.
The Smaller the Interface the more Flexible the Code
When designing a data structure, the simpler the interface is, the more flexible the code is. Just look at how powerful LINQ is for a demonstration of this.
How to Choose Interfaces
When you think "list" you should start by saying to yourself, "I need to represent a collection of baseball players". So let's say you decide to model this with a class. What you should do first is decide what the minimal amount of interfaces that this class will need to expose.
Some questions that can help guide this process:
Do I need to have the count? If not consider implementing IEnumerable<T>
Is this collection going to change after it has been initialized? If not consider IReadonlyList<T>.
Is it important that I can access items by index? Consider ICollection<T>
Is the order in which I add items to the collection important? Maybe it is an ISet<T>?
If you indeed want these thing then go ahead and implement IList<T>.
This way you will not be coupling other parts of the code to implementation details of your baseball players collection and will be free to change how it is implemented as long as you respect the interface.
By taking this approach you will find that code becomes easier to read, refactor, and reuse.
Notes about Avoiding Boilerplate
Implementing interfaces in a modern IDE should be easy. Right click and choose "Implement Interface". Then forward all of the implementations to a member class if you need to.
That said, if you find you are writing lots of boilerplate, it is potentially because you are exposing more functions than you should be. It is the same reason you shouldn't inherit from a class.
You can also design smaller interfaces that make sense for your application, and maybe just a couple of helper extension functions to map those interfaces to any others that you need. This is the approach I took in my own IArray interface for the LinqArray library.
When is it acceptable?
To quote Eric Lippert:
When you're building a mechanism that extends the List<T> mechanism.
For example, you are tired of the absence of the AddRange method in IList<T>:
public interface IMoreConvenientListInterface<T> : IList<T>
{
void AddRange(IEnumerable<T> collection);
}
public class MoreConvenientList<T> : List<T>, IMoreConvenientListInterface<T> { }

What are the different approaches to Object-Object mapping in .NET?

I'm needing to do some mapping between objects (e.g. PersonModel to PersonViewModel) and am researching on the different approaches to do this. Specifically I'm working with Entity Framework and trying to map the generated models to a viewmodel.
However, I've yet to find an article or resource that compiles a list of how you can do this. So far, I've come across the following:
Implicit Conversion (I think this is the most basic approach? since you manually map properties from one object to another, its simple but tedious)
Extension Methods (haven't worked with this yet)
Reflection (I've tinkered a bit, but only managed very basic mapping)
Automapper (VERY popular, but I'm having trouble making it work well with EF)
Value Injecter (haven't worked with this yet)
Emit Mapper (haven't worked with this yet, but probably I would have trouble making it work with EF?)
Can you please help point out and elaborate on the approaches available there, as well as pros / cons of each? For example, I saw some that mentioned Automapper is slow compared to manual mapping? Or possibly, point out an article that tackles this?
EDIT: since some may ask what problem I have with AutoMapper, please see this: Automapper: How to map IList to EntityCollection
Well, I can give you a way where you do your own mapping, pretty simple to do and can be executed quickly over a large amount of data. I'll show you what I'd do, and then try to elaborate on why I do what I do. Here goes:
public class PersonViewModel
{
public static Expression<Func<Person, PersonViewModel>> FromPerson
{
get
{
return p => new PersonViewModel
{
Name = p.FirstName,
SurName = p.LastName
};
}
}
public string Name { get; set; }
public string SurName { get; set; }
public static PersonViewModel CreateViewModel(Person original)
{
var func = FromPerson.Compile();
var vm = func(original);
return vm;
}
}
Now you'll notice that I have 2 ways to convert from a Person EF model to a ViewModel. This is because the first one, which uses the Expression>, is used to convert a large bulk of object in a Select() statement. Simple usage:
return people.Select(PersonViewModel.FromPerson);
In this case we've probably retrieved a collection of Person objects from the DB and need to show them, say, in a list or something, but using the ViewModel. In this way the operation is performed in bulk and is much faster than simply creating all the objects via the other method. Now, the static CreateViewModel method can be used to map a single object where needed. An example is if you've gotten a single user's data from the DB and need to show it, but using your ViewModel. In that case, it would be appropriate to use the static method, instead of the Expression, which is mainly for bulk conversions.
That's what I can offer, aside from wondering what's wrong with using AutoMapper, since it's pretty straightforward and you haven't really elaborated on what the problem is with using it alongside EF. Hope this helps you at least a little bit in your problem :)
Well, if you do know the objects’ types upfront then the accepted answer works great.
If not I’d go with AutoMapper or PropMapper.
If you want to roll something of your own, the most “up to date” approach is to use compiled Expression trees. You enumerate the type’s properties and then build a block of assign expressions for each property, and “compile” this block:
var e = Expression.Assign(Expression.Property(srcObj, prop1), Expression.Property(destObj, prop2)));
Here’s a step-by-step blog post on this: https://dev.to/alexjitbit/yet-another---lightning-fast---object-mapper-for-net-2bj2

MongoDB: How to define a dynamic entity in my own domain class?

New to MongoDB. Set up a C# web project in VS 2013.
Need to insert data as document into MongoDB. The number of Key-Value pair every time could be different.
For example,
document 1: Id is "1", data is one pair key-value: "order":"shoes"
document 2: Id is "2", data is a 3-pair key-value: "order":"shoes", "package":"big", "country":"Norway"
In this "Getting Started" says because it is so much easier to work with your own domain classes this quick-start will assume that you are going to do that. suggests make our own class like:
public class Entity
{
public ObjectId Id { get; set; }
public string Name { get; set; }
}
then use it like:
var entity = new Entity { Name = "Tom" };
...
entity.Name = "Dick";
collection.Save(entity);
Well, it defeats the idea of no-fixed columns, right?
So, I guess BsonDocument is the the model to use and is there any good samples for beginners?
I'm amazed how often this topic comes up... Essentially, this is more of a 'statically typed language limitation' than a MongoDB issue:
Schemaless doesn't mean you don't have any schema per se, it basically means you don't have to tell the database up front what you're going to store. It's basically "code first" - the code just writes to the database like it would to RAM, with all the flexibility involved.
Of course, the typical application will have some sort of reoccurring data structure, some classes, some object-oriented paradigm in one way or another. That is also true for the indexes: indexes are (usually) 'static' in the sense that you do have to tell mongodb about which field to index up front.
However, there is also the use case where you don't know what to store. If your data is really that unforeseeable, it makes sense to think "code first": what would you do in C#? Would you use the BsonDocument? Probably not. Maybe an embedded Dictionary does the trick, e.g.
public class Product {
public ObjectId Id {get;set;}
public decimal Price {get;set;}
public Dictionary<string, string> Attributes {get;set;}
// ...
}
This solution can also work with multikeys to simulate a large number of indexes to make queries on the attributes reasonably fast (though the lack of static typing makes range queries tricky). See
It really depends on your needs. If you want to have nested objects and static typing, things get a lot more complicated than this. Then again, the consumer of such a data structure (i.e. the frontend or client application) often needs to make assumptions that make it easy to digest this information, so it's often not possible to make this type safe anyway.
Other options include indeed using the BsonDocument, which I find too invasive in the sense that you make your business models depend on the database driver implementation; or using a common base class like ProductAttributes that can be extended by classes such as ProductAttributesShoes, etc. This question really revolves around the whole system design - do you know the properties at compile time? Do you have dropdowns for the property values in your frontend? Where do they come from?
If you want something reusable and flexible, you could simply use a JSON library, serialize the object to string and store that to the database. In any case, the interaction with such objects will be ugly from the C# side because they're not statically typed.

Creating API that is fluent

How does one go about create an API that is fluent in nature?
Is this using extension methods primarily?
This article explains it much better than I ever could.
EDIT, can't squeeze this in a comment...
There are two sides to interfaces, the implementation and the usage. There's more work to be done on the creation side, I agree with that, however the main benefits can be found on the usage side of things. Indeed, for me the main advantage of fluent interfaces is a more natural, easier to remember and use and why not, more aesthetically pleasing API. And just maybe, the effort of having to squeeze an API in a fluent form may lead to better thought out API?
As Martin Fowler says in the original article about fluent interfaces:
Probably the most important thing to
notice about this style is that the
intent is to do something along the
lines of an internal
DomainSpecificLanguage. Indeed this is
why we chose the term 'fluent' to
describe it, in many ways the two
terms are synonyms. The API is
primarily designed to be readable and
to flow. The price of this fluency is
more effort, both in thinking and in
the API construction itself. The
simple API of constructor, setter, and
addition methods is much easier to
write. Coming up with a nice fluent
API requires a good bit of thought.
As in most cases API's are created once and used over and over again, the extra effort may be worth it.
And verbose? I'm all for verbosity if it serves the readability of a program.
MrBlah,
Though you can write extension methods to write a fluent interface, a better approach is using the builder pattern. I'm in the same boat as you and I'm trying to figure out a few advanced features of fluent interfaces.
Below you'll see some sample code that I created in another thread
public class Coffee
{
private bool _cream;
private int _ounces;
public static Coffee Make { get { return new Coffee(); } }
public Coffee WithCream()
{
_cream = true;
return this;
}
public Coffee WithOuncesToServe(int ounces)
{
_ounces = ounces;
return this;
}
}
var myMorningCoffee = Coffee.Make.WithCream().WithOuncesToServe(16);
While many people cite Martin Fowler as being a prominent exponent in the fluent API discussion, his early design claims actually evolve around a fluent builder pattern or method chaining. Fluent APIs can be further evolved into actual internal domain-specific languages. An article that explains how a BNF notation of a grammar can be manually transformed into a "fluent API" can be seen here:
http://blog.jooq.org/2012/01/05/the-java-fluent-api-designer-crash-course/
It transforms this grammar:
Into this Java API:
// Initial interface, entry point of the DSL
interface Start {
End singleWord();
End parameterisedWord(String parameter);
Intermediate1 word1();
Intermediate2 word2();
Intermediate3 word3();
}
// Terminating interface, might also contain methods like execute();
interface End {
void end();
}
// Intermediate DSL "step" extending the interface that is returned
// by optionalWord(), to make that method "optional"
interface Intermediate1 extends End {
End optionalWord();
}
// Intermediate DSL "step" providing several choices (similar to Start)
interface Intermediate2 {
End wordChoiceA();
End wordChoiceB();
}
// Intermediate interface returning itself on word3(), in order to allow
// for repetitions. Repetitions can be ended any time because this
// interface extends End
interface Intermediate3 extends End {
Intermediate3 word3();
}
Java and C# being somewhat similar, the example certainly translates to your use-case as well. The above technique has been heavily used in jOOQ, a fluent API / internal domain-specific language modelling the SQL language in Java
This is a very old question, and this answer should probably be a comment rather than an answer, but I think it's a topic worth continuing to talk about, and this response is too long to be a comment.
The original thinking concerning "fluency" seems to have been basically about adding power and flexibility (method chaining, etc) to objects while making code a bit more self-explanatory.
For example
Company a = new Company("Calamaz Holding Corp");
Person p = new Person("Clapper", 113, 24, "Frank");
Company c = new Company(a, 'Floridex', p, 1973);
is less "fluent" than
Company c = new Company().Set
.Name("Floridex");
.Manager(
new Person().Set.FirstName("Frank").LastName("Clapper").Awards(24)
)
.YearFounded(1973)
.ParentCompany(
new Company().Set.Name("Calamaz Holding Corp")
)
;
But to me, the later is not really any more powerful or flexible or self-explanatory than
Company c = new Company(){
Name = "Floridex",
Manager = new Person(){ FirstName="Frank", LastName="Clapper", Awards=24 },
YearFounded = 1973,
ParentCompany = new Company(){ Name="Calamaz Holding Corp." }
};
..in fact I would call this last version easier to create, read and maintain than the previous, and I would say that it requires significantly less baggage behind the scenes, as well. Which to me is important, for (at least) two reasons:
1 - The cost associated with creating and maintaining layers of objects (no matter who does it) is just as real, relevant and important as the cost associated with creating and maintaining the code that consumes them.
2 - Code bloat embedded in layers of objects creates just as many (if not more) problems as code bloat in the code that consumes those objects.
Using the last version means you can add a (potentially useful) property to the Company class simply by adding one, very simple line of code.
That's not to say that I feel there's no place for method chaining. I really like being able to do things like (in JavaScript)
var _this = this;
Ajax.Call({
url: '/service/getproduct',
parameters: {productId: productId},
)
.Done(
function(product){
_this.showProduct(product);
}
)
.Fail(
function(error){
_this.presentError(error);
}
);
..where (in the hypothetical case I'm imagining) Done and Fail were additions to the original Ajax object, and were able to be added without changing any of the original Ajax object code or any of the existing code that made use of the original Ajax object, and without creating one-off things that were exceptions to the general organization of the code.
So I have definitely found value in making a subset of an object's functions return the 'this' object. In fact whenever I have a function that would otherwise return void, I consider having it return this.
But I haven't yet really found significant value in adding "fluent interfaces" (.eg "Set") to an object, although theoretically it seems like there could be a sort of namespace-like code organization that could arise out of the practice of doing that, which might be worthwhile. ("Set" might not be particularly valuable, but "Command", "Query" and "Transfer" might, if it helped organize things and facilitate and minimize the impact of additions and changes.) One of the potential benefits of such a practice, depending on how it was done, might be improvement in a coder's typical level of care and attention to protection levels - the lack of which has certainly caused great volumes grief.
KISS: Keep it simple stupid.
Fluent design is about one aesthetic design principle used throughout the API. Thou your methodology you use in your API can change slightly, but it is generally better to stay consistent.
Even though you may think 'everyone can use this API, because it uses all different types of methodology's'. The truth is the user would start feeling lost because your consistently changing the structure/data structure of the API to a new design principle or naming convention.
If you wish to change halfway through to a different design principle eg.. Converting from error codes to exception handling because some higher commanding power. It would be folly and would normally in tail lots of pain. It is better to stay the course and add functionality that your customers can use and sell than to get them to re-write and re-discover all their problems again.
Following from the above, you can see that there is more at work of writing a Fluent API than meet's the eye. There are psychological, and aesthetic choices to make before beginning to write one and even then the feeling,need, and desire to conform to customers demand's and stay consistent is the hardest of all.
What is a fluent API
Wikipedia defines them here http://en.wikipedia.org/wiki/Fluent_interface
Why Not to use a fluent interface
I would suggest not implementing a traditional fluent interface, as it increases the amount of code you need to write, complicates your code and is just adding unnecessary boilerplate.
Another option, do nothing!
Don't implement anything. Don't provide "easy" constructors for setting properties and don't provide a clever interface to help your client. Allow the client to set the properties however they normally would. In .Net C# or VB this could be as simple as using object initializers.
Car myCar = new Car { Name = "Chevrolet Corvette", Color = Color.Yellow };
So you don't need to create any clever interface in your code, and this is very readable.
If you have very complex Sets of properties which must be set, or set in a certain order, then use a separate configuration object and pass it to the class via a separate property.
CarConfig conf = new CarConfig { Color = Color.Yellow, Fabric = Fabric.Leather };
Car myCar = new Car { Config = conf };
No and yes. The basics are a good interface or interfaces for the types that you want to behave fluently. Libraries with extension methods can extend this behavior and return the interface. Extension methods give others the possibility to extend your fluent API with more methods.
A good fluent design can be hard and takes a rather long trial and error period to totally finetune the basic building blocks. Just a fluent API for configuration or setup is not that hard.
Learning building a fluent API does one by looking at existing APIs. Compare the FluentNHibernate with the fluent .NET APIs or the ICriteria fluent interfaces. Many configuration APIs are also designed "fluently".
With a fluent API:
myCar.SetColor(Color.Blue).SetName("Aston Martin");
Check out this video http://www.viddler.com/explore/dcazzulino/videos/8/
Writting a fluent API it's complicated, that's why I've written Diezel that is a Fluent API generator for Java. It generates the API with interfaces (or course) to:
control the calling flow
catch generic types (like guice one)
It generates also implementations.
It's a maven plugin.
I think the answer depends on the behaviour you want to achieve for your fluent API. For a stepwise initialization the easiest way is, in my opinion, to create a builder class that implements different interfaces used for the different steps. E.g. if you have a class Student with the properties Name, DateOfBirth and Semester the implementation of the builder could look like so:
public class CreateStudent : CreateStudent.IBornOn, CreateStudent.IInSemester
{
private readonly Student student;
private CreateStudent()
{
student = new Student();
}
public static IBornOn WithName(string name)
{
CreateStudent createStudent = new CreateStudent();
createStudent.student.Name = name;
return createStudent;
}
public IInSemester BornOn(DateOnly dateOfBirth)
{
student.DateOfBirth = dateOfBirth;
return this;
}
public Student InSemester(int semester)
{
student.Semester = semester;
return student;
}
public interface IBornOn
{
IInSemester BornOn(DateOnly dateOfBirth);
}
public interface IInSemester
{
Student InSemester(int semester);
}
}
The builder can then be used as follows:
Student student = CreateStudent.WithName("Robert")
.BornOn(new DateOnly(2002, 8, 3)).InSemester(2);
Admittedly, writing an API for more than three properties becomes tedious. For this reasons I have implemented a source generator that can do this work for you: M31.FluentAPI.

DataTables vs IEnumerable<T>

I'm having a debate with another programmer I work with.
For a database return type, are there any significant memory usage or performance differences, or other cons which should make someone avoid using the DataSets and DataTables and favour types which implement IEnumerable<T>... or vice versa
I prefer returning types which implementIEnumerable<T> (List<T>, T[] etc) because it's more lightweight, strongly typed to the object when accessing properties, allows richer information about the underlying type etc. They do take more time to set up though when manually using the data reader.
Is the only reason to use DataTables these day just lazyness?
DataTables are definitely much heavier than Lists, both in memory requirements, and in processor time spent creating them / filling them up.
Using a DataReader is considerable faster (although more verbose) than using DataTables (I'm assuming you're using a DataAdapter to fill them).
That said...
Unless this is in some place where it really matters, you're probably fine either way, and both methods will be fast enough, so just go with whatever is more comfortable in each case. (Sometimes you want to fill them up with little code, sometimes you want to read them with little code)
I myself tend to only use DataTables when I'm binding to a GridView, or when I need more than one resultset active at the same time.
Another advantage to using the System.Collections classes is that you get better sorting and searching options. I don't know of any reasonable way to alter the way a DataTable sorts or searches; with the collection classes you just have your class implement IComparable or IEquatable and you can completely customize how List.Sort and List.Contains work.
Also with lists you don't have to worry about DBNull, which has tripped me up on more than one occasion because I was expecting null and got DBNull.
I also like the fact with IEnumerable<T> that you can enhance the underlying type of the collection with methods and properties which makes implementation far more elegant, and the code more maintainable. For example the FullName property. You can also add extension methods to the class if it is out of your control.
public class SomeUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return String.Format("{0} {1}", FirstName, LastName); } }
}
Using DataTables directly means tying yourself to the underlying data source and how it is laid out. This is not good from a maintainability point of view. If all your view needs is a list of some objects, that's all you should be giving it.

Categories

Resources