Updates from November, 2011 Toggle Comment Threads | Keyboard Shortcuts

  • danielsaidi 11:17 pm on November 23, 2011 Permalink | Reply
    Tags: alexis ohanian, async, await, gary short, jon skeet, , reddit   

    Øredev 2011 in the rear-view mirror – Part 1 

    Øredev logo

    This is the first part of my sum-up of Øredev 2011. Read more by following the links below:

    I will label each session with day:order to satisfy all structure freaks (myself included) that read this.

    About Øredev

    Two weeks ago, I attended to the Øredev Developer Conference in Malmo, Sweden form Wednesday to Friday. It was truely inspiring, and I would like to share my experience. I will write about the sessions I attended to, the ones I missed (but watched on screen outside the conference rooms) and the ones I heard a lot of good stuff about, but either missed or had to opt-out.

    I have deliberately waited two weeks with writing this summary, since I wanted it to be objective and not influenced by the oh-so impressed mode that I was in directly afterwards. I will sum up the sessions over a couple of days, so my experience of Øredev will consist of a number of posts. I will label each session with day:order to satisfy all structure freaks (myself included) that read this.

    Finally, before beginning to write (quite a contradiction), I just want to thank my employer – Cloud Nine – for deciding to send me as one of three. It was a fantastic experience.

    1:1 – KEYNOTE: Alexis Ohanian – Only your mom wants to use your website

    After an early morning flight, we arrived at Øredev a bit too late for the morning’s keynote with Reddit co-founder Alexis Ohanian. The doors to the keynote were closed, but the keynote was displayed on screen just outside, so we managed to catch a short glimpse of it.

    Alexis talked about how to convince people that your product is worth their precious time, and that companies tend to ignore users experience…and thus their customers. He mentioned some interesting scenarios that we have gotten used to as Internet users, but that does not deliver good experience, such as online airline ticket search engines that return a huge amount of tickets in a paginable list.

    I attempted to make out the most of the real-time illustration that was being made of the keynote (and of all other keynotes), but will watch the video once it is released instead. People who attended it told me it was quite good, although Jeff Atwood threw Reddit a pinch during his Friday keynote – more on that later.

    1:2 – Jon Skeet – C#5 Async 101

    My first session was one of many at Øredev, where a distinct British, Scottish or American accent, together with an almost over-the-top engagement, seem to be two of the key-criteria to be invited as a speaker (more on this in my final conclusion). Jon was very inspiring, though, and demonstrated the new async keyword, which will be shipped together with C#5.

    Jon talked about how async operations have been around since .NET 1.0, but how they always have been jumpy and resulted in spaghetti code. I agree, although working with async operations in JavaScript over the years have made me used to handling async callbacks. The new async keyword, though, together with the new await keyword seems like a clean and promising tool for writing async operations.

    The code becomes really clean. In fact, it looks just like “ordinary” non-async code, with a few new keywords. Another really cool thing about it all is awaits are potential pause points. If .NET has all the data it needs to return a result, it will do so without going into async mode. All this, while the code looks almost exactly the same as it would do without the asyncs and awaits.

    Instead of throwing us a bunch of examples of how to use this new feature, Jon showed us a few, sure, but then also took the time to actually show us how it is implemented and how to use the Task classes in C#4. As a developer, I found this extremely entertaining, although I feel a bit disgusted at how low my opinion of “entertaining” has sunken over the years. Can’t wait to try it out, though.

    Oh, and one final thing. Jon was very clear about pointing out that async != parallell, so maybe I should forward that as well 🙂

    1:3 – Gary Short – .NET 4.0 Collection Classes Deep Dive

    This session was one that I found really interesting while listening to it, but that I afterwards doubt brought me that much to work with in my daily life as a system developer. However…

    …once more, a charismatic developer with an attitude…and a distinct Scottish accent. You have probably guessed it already…the fact that I have a hangup on the accents is that I deeply envy people with Scottish (http://www.youtube.com/watch?v=KrCMB7N5V1s) or British (http://www.youtube.com/watch?v=Ii2ZyhWvxos) accents. If I could have one wish come true (sorry, peace on earth), it would be to have one. So, now you know.

    So, yeah…Gary had one for sure…and man, could he talk. He spoke a lot about list operations and how NOT to populate a list. For instance, did you know that when you add your first item to the list, its capacity grows to 4…and that when that is no longer sufficient, it grows to 8, then 16, then 32, 64…? Well, neither did I. Gary suggested to initialize the list with an integer parameter, e.g. new List<string>(10), which will cause it to grow with a fixed intervals when needed.

    He also spoke about not using Add in a loop, that AddRange is better than sequential Add operations and how XAt is better than X (RemoveAt instead of Remove etc.) since it executes at fixed time, no matter how many items you have in your list. Combined with graphs of how much slower certain operations work when the size of the list grows, Gary really exhausted the subject. He also went through sorting and how the various sorting algorithms perform and ended the session by going through various collection types.

    So, sure, Gary knows a lot about collections, and no one can blame him for not delivering what the title of the session indicated…but I already knew about most of the stuff and feel like I maybe should have attended another session. For people not knowing about the various collections, though, I am sure it was a great run.

  • danielsaidi 12:52 pm on November 16, 2011 Permalink | Reply
    Tags: , repository, service   

    Controllers, repositories, services – where do I put the logic? 

    I could use some advice regarding a project that I am currently working on. The project is a web site, where members can join various groups (did I hear “Facebook already has that”?) and do stuff depending on what groups they belong to.

    Let’s ignore all other entities and focus on the Member and Group entities.

    I have a repository interface/protocol for each entity. The main repository’s sole responsibility is to communicate with Entity Framework (I also have other implementations of each repository interface, e.g. fake repositories that just create fake data, cache decorators etc.).

    I then have service classes (I know, I know…bad name) for more sophisticated functionality. The controller classes of my web site then use the various service classes to do stuff. Service classes can talk to each other, repositories can not.

    This architecture can be illustrated (quite simplified) as such:

    A simplified architectural view

    A simplified view of the architecture

    Now, here is my dilemma…where do I put additional logic?

    Say, for instance, that I want to be able to find all members that are in the same groups as a certain member. I could then:

    • Add a GetGroupFriends method to the Member entity. The method could then iterate over all the groups that a member is a member of (which would require stepping through Member -> GroupMember -> Group), and return a distinct list of members that are members of the same group.
    • Add a GetGroupFriendsForMember method to the MemberService and do mostly the same thing as above, but working with a repository to retrieve data instead of drilling down the member object.
    • Add a GetGroupFriendsForMember method to the GroupService and do mostly the same thing as above, but working with the repository to retrieve data instead of drilling down the member object.
    • Add a GetGroupFriends method to the Member entity and a GetGroupFriendsForMember method to one of the service classes, and make the service call the entity method.
    There are naturally some pros and cons of both methods:
    • Placing the method in the Member entity is simple, and using the method is also quite straightforward, but…
    • …it will also cause coupling. Also, the Member entity is not abstract, which means that we cannot mock it that easily (although some mocking frameworks support this)
    • Placing the method in a service is also simple and nice approach, especially since each service is abstract, but…
    • …which service should then own the logic? I would go for the group service, but I do not really know.
    I started of with placing the methods in the entities, trying to be a good OO programmer, but the responsibilities of the entities then grew and grew. I abandoned that ship.
    Now, I have all my relation- (is X a member of Y, does X know Z) and permission- (can X edit Y, can X invite Y to Z) -related logic in the various services. It’s quite nice, but in some cases, I find that the services have to evaluate data in really non-optimal ways.
    There are probably tons of  various solutions to this problem of mine…I would just really like to discuss this. If you have found a way that works for you, please share it with me 🙂
    • Henrik 2:13 pm on November 16, 2011 Permalink | Reply

      Maybe not an answer. But I try to think in real life scenarios. But i’ts very hard. Sometimes it’s hard to translate an abstraction to real life. But most often the problems are contextual. Like, who desides if you’re a member of a group? You? The group? A concensus? Someone else? Well, it depends on the context. If you are a member of a band, it’s quite obvious – either you play (or sing) in the band or you’re not. If you’re a unoin member, it’s also quite obvious (you pay the uinion fee and are listed – and the union desides if you’re a member or not). Case closed. But what about a friends group? You maybe think you are a member (or want to be), but your friends might not (if you know what I mean 🙂

      The same thing goes for validation. Who desides if you’re allowed to buy alcoholics? You or the person behind the desk? Well, actually the law says you can or not, but maybe that’s a to big abstraction?

      In your code you have some kind of GroupService. What’s that in the real life? Do you go to the big old group service station and ask: “I’m I a member of this band?” But on the other hand, you could call the union info desk and ask them for all members in your company (e.g.) That’s kind of a member service…

      And what is a Member? If you look from your own perspective (“I’m a member”) it might be one thing, for others it may mean something else (“He’s that member”).

      I’m kind of talking DDD here. And maybe that’s a to big step in your case. But it’s very interesting thoughts though 🙂

      Think Unix! Build small objects that do one thing and does it very well! That way they are easy to replace if they start to smell bad (think Dan North 🙂 A big “MemberService” may grow up to be a dragon, and then it will be hard to replace… or maybe not? Embrace uncertainty! Always know you *may* write crappy code, just don’t get emotionally attached to it and prepare for it to be replaced or removed.

      And don’t forget “Tell, don’t ask”!

      • Henrik 2:18 pm on November 16, 2011 Permalink | Reply

        Lots of types there 🙂 union, uinion, unoin,uoinuoinuoniunoinu? “I’m I a”?, “Am I a”? Don’t know…
        I should have prepared the comment to be removed or replaced.

        • danielsaidi 8:13 pm on November 16, 2011 Permalink

          I think your comment was great. It will live on forever.

      • danielsaidi 8:11 pm on November 16, 2011 Permalink | Reply

        Great stuff, Henrik. I will reply to your comments separately.

        I think your real-life example is really good, especially that “go to the big old group service station” part 🙂 However, keep i mind that my example above is really simplified. There are various kinds of members. First, there is the native Membership account (MembershipUser), which is one kind of member…or rather, an account. Then, we have a web site member, or the domain’s definition of a member. That is the entity that represents the web site user, which has connections to items, group memberships etc. We also have a group member. So, there ARE distinctions.

        I think that you would agree that my solution is populated to the brink of explosion with small classes that do “one” thing. I also think that you can go too far in trying to achieve SRP. IMO, placing related functionality in one class that grows a bit is no biggie, IF you have unit tests, abstractions etc. that makes refactoring easy when the need arises.

        However, in this particular case, when looking at the GroupService interface, I think that there is actually time for some refactoring. It is responsible for group management, group member management and group relations.

        Still, my question was more general…these two entities were just an example. Look at my question in this, new light:

        “I have entity A and entity B”.
        Each have basic methods, derived properties etc. that are directly related to the data of the entities.
        More complex entity operations are moved to an abstract service class per service.
        Where should methods that handle relations between the two entities go?

        I know where this is going…that I need more classes that do less stuff. Thank god that my code is so great (smell the irony) that these changes are cheap and easy to perform.

        I have only answered your first comment, and am already enlightened beyond what I first thought was possible. Man, you are a good listener! 🙂

    • Mattias Lind 2:22 pm on November 16, 2011 Permalink | Reply

      What you need is a GroupMemberService. Do I need to say more. 😉

    • Henrik 2:42 pm on November 16, 2011 Permalink | Reply

      If you start thinking “Where do I put additional logic?” It should be a signal, a trigger that say “hey, something isn’t right here!” You shouldn’t have to ask that question, right? Or am I wrong?

      • danielsaidi 8:24 pm on November 16, 2011 Permalink | Reply

        I do not agree at all. Let’s go for the Member and Group example once more.

        We have a Member entity and a Group entity.
        We have a MemberRepository (IMemberRepository) and a GroupRepository (IGroupRepository) that are responsible for data management.
        We have a MemberService (IMemberService) and a GroupService(IGroupService) that are responsible for basic entity handling, like get, delete, search etc.

        Now, where do we put relational logic? Forget about the “additional” word. Where do we put logic that maybe do not fit these services, that only handle a separate entity.

        In some cases, I do not think that adding them to one of these services (e.g. an AddGroupMember method in the GroupService class) is terribly wrong. If it is just one method, I would go as far as to say that adding it to one of these service classes is BETTER than to introduce another class.

        IMO, you CAN go too far with SRP.

        So no, I do not think that something is wrong. It is just a situation where we ask ourselves a question where we want a certain kind of functionality to go…

        ..but I can be wrong as well. That’s why I love having these kinds of discussions.

        • Jon 8:39 pm on November 16, 2011 Permalink

          Is your application a Member-something application or a group-something application? Or do you think it is booth? Does answering that question make you think differently about where to place the method?

    • Mattias Sundberg 2:53 pm on November 16, 2011 Permalink | Reply

      I wouldn’t put the logic in either of them without knowing the purpose of the functionality. As PHP-programmer I would put such logic in a static class with misc utilities becuase it doesn’t correspond with the data objects. Although one way to go would be to have all groups a member belongs to as properties to the member-object which you then could iterate. And groups would have all members as properties. Sure, fair bit of recursion but iteration could be done extremely fast.
      Or why not place your ACL-logic in the database?

      Either way, you .NET-guys complicate things too much haha

      • danielsaidi 8:32 pm on November 16, 2011 Permalink | Reply

        I would never place such login in a static utility class. Static classes are convenient, sure, but the convenience comes with a too high price to pay. Coupling, lack of abstractions etc…which will make such a simple thing as unit testing your code a nightmare (or even not applicable).

        At the very least, I would place each method that I find no other room for in a separate interface. The class that then implements the interface can then be replaced with any other implementation or mock…which makes such a simple thing as unit testing…simple.

        Come on, you (we…I apply the exact same method when writing PHP code) have interfaces in PHP as well. There is absolutely no need to go for those monster utility classes 😉

        • Mattias Sundberg 10:05 am on November 18, 2011 Permalink

          I started to write a comment that almost became a novel but I scrapped it 🙂
          Anyway, what I’m trying to say is that the purpose of your application should dictate which route you take. I’ve seen to many projects become monstrous just because designers view their code in a philosphical way rather than being pragmatic.
          When I design a framework or system I always start with “whichdirection might the client take in the future with this”.
          Abstraction isn’t always needed, coupling isn’t always a problem, unit testing is a waste of time in 90% of all web applications in my opinion 😉

          And in your particular project my gut feeling is that you are using methods that are a bit overkill. I don’t say it’s wrong but I don’t see the point (with regards of not knowing the purpose of the application) 🙂

        • danielsaidi 11:56 am on November 19, 2011 Permalink

          Ha ha ha, yeah some of my comments became too long as well…this one included 🙂

          I agree with you to some extent, but in my case…having three separate classes that deal with one thing instead of one huge one that deal with all…well, I prefer the small ones. Also, making them non-static and interface-based come at a(lmost) zero cost and does not IMO introduce a dramatic amount of extra complexity.

          Instead, being able to talk about that classes use other components that can do something, no matter how, is something I would not throw away for the world.

          But I really agree with “abstraction isn’t always needed, coupling isn’t always a problem”, I really do. I just think that designing the system in a way that tackles these potential(!) problems is not that much more complex than just going for a simple, unflexible approach.

          It’s like placing all your language strings into one file instead of spreading them all around your code, even though you will not need localization – when you need to change or re-use a translation, you know exactly where to look. It’s a great convenience.

          Things take time for me at this point, since I am rather new to this thinking and interesting questions pop up all the time. Just like with everything else (TDD for instance), once I have refined this way of working, I am sure that it will take less time, be more fund and result in better systems.

          And unit tests…would not throw away them either, and do not agree about your 90% rate 😉 Sure, I tend to write too many tests, like testing my MVC controllers…which often tend to make me spend time at adjusting tests in a part of the system that go through the greatest amount of changes. However, having done this several times, I can now make the choice to NOT write tests for all parts of the controllers…at least not until the first sharp version is shipped.

          So, where the tests are good, they are invaluable IMO…especially in teams with several developers, and especially when using a build server, like TFS, that can continously build and test code that is checked in.

          But, as you say, we probably build quite different systems and benefit from different things. You like your way of working, I love (or am beginning to) my way. Win-win situation? 🙂

          And there, another novel 😀

    • Jon 8:14 pm on November 16, 2011 Permalink | Reply

      This is a very interesting problem and as you point out there is of course no “right answer”. I spent a lot of time thinking about these issues the past year or so.

      Jimmy Bogard wrote a bunch of great blog posts about Strengthening your domain http://lostechies.com/jimmybogard/2010/02/04/strengthening-your-domain-a-primer/
      At the end he discusses weather to inject services into the domain objects http://lostechies.com/jimmybogard/2010/04/14/injecting-services-into-entities/
      His conclusion is that it is not worth it from a testing and simplicity point of view. I tend to agree with him.

      My logic often ended up in somewhat bloated services. But there is no one stopping you from having more services that are more specialized if they get hairy.

      I am moving towards an even more simplistic view on these problems. If we don’t have a real domain, must we really have all this infrastructure, or/mappers, services, repositories and so on for displaying some data on a web page and occasionally update it?

      Perhaps we can make it smaller, tighter and more understandable without loosing testability (scalabillity is another interesting discussion but perhaps in another post)

      What I am suggesting is looking at how the cqrs guys handle their view models: just get the freaking data with a sql query and show it. Perhaps in a nice little dto. Let the “smart” part of the application use an object model if it is needed.

      Does it sound wierd?

      • danielsaidi 8:43 pm on November 16, 2011 Permalink | Reply

        Great comment, Jon…and thank you for the links. I will check them out!

        I think the “no right answer” part is what makes the binary programmer brain go into a spin. If there is no correct answer, then we work ourselves to the bones to find the BEST solution. If you cannot be correct, you can at least choose the BEST option available. At least, that fits me.

        If I would have built the same solution in PHP, using my own framework, the solution would have been SO much simpler. Sure, not as flexible, but simple. In this project, I want to throw up when I see all these classes and interfaces, although I know (or at least, I am 99% sure) that I have done things “by the book”.

        It is like my wife said – in projects where “doing it right” or “doing it by the book” is a measure of success, failing to deliver is more likely to be the outcome.

        In the end, I am disgusted by the amount of classes and interfaces this fairly simple web site has ended up requiring…but, at the same time. I understand each class (although some services are rather big) and find it really easy to work in the solution. So, I would say that I’d choose the current architecture before anything I’ve worked with before, any given day.

        Still, I think CQRS will probably throw me off my feet when I start looking at it.

        • Jon 8:50 pm on November 16, 2011 Permalink

          The CQRS stuff made me think a lot. Not that it fits in many projects I have been working on and it is definitely not a silver bullet but it has some very appealing back to the basics to it that can be applied in many other scenarios.

        • Henrik 10:21 pm on November 16, 2011 Permalink

          I really like this!
          If it’s simple but not flexible doesn’t that make it right to? As long as you are prepared to throw things away there’s nothing wrong in building just the right thing (and ignore the flexibility). And to be honest, how often do we need the flexbility we have built? I think we mostly build it “by the book” because it is *fun*. Nothing else. And sure, there’s nothing wrong with that either!

          How I love this: if ‘doing it by the book” is a measure of success, failing to deliver is more likely to be the outcome.’ So true! 🙂 I’m gonna steel that and twitter it.

          But, is it “by the book” to have a zillion interfaces and classes? When I think of unix I think of all the little “tools” you have that does just one thing, But I don’t care *where* they are, I just have them and they do the work. I don’t really know where I’m going here… Trying to think of how to do it in .NET… have a zillion small projects instead? Probably not, maybe .NET isn’t the best tool for these things? To be honest I don’t think OOP is the best thing. We should move to Message-Oriented Programming http://c2.com/cgi/wiki?MessageOrientedProgramming. It’s not the objects that are interesting, it’s the communication between them. And that corrolates very well with the real life! A stone is very boring (it doesn’t communicate very well) but you can sit and watch a human being for hours. But both are objects!

        • danielsaidi 11:03 pm on November 16, 2011 Permalink

          I definitely agree with MOP. Although I have not applied it in any project, and it surely has a lot of drawbacks bundled with all the goodness it brings, it “feels” right.

    • Jon 8:22 pm on November 16, 2011 Permalink | Reply

      Another thing I have been thinking about:
      Why do we need repositories? I have been using them for quite some time because “every one is doing it” But when I think about *why* it boils down to abstracting your data source. Plus the testability of course.

      But when we use EF och NH we have the datacontext and the session and they are essentially a generic repository that can be mocked away. All we are doing is adding another layer of complexity on top.

      The only real reason I can think of is to swap the data source for something completely different. In my time as a developer I have done this exactly twice. The benefit I gained from the repositories was minor. And if you want to have it you would perhaps be better of just wrapping it in an ISession the way Rob Conery does in the asp.net MVC series.

      • danielsaidi 8:51 pm on November 16, 2011 Permalink | Reply

        I remember having this discussion two years ago, when I did not see the point and you tried to make my slow mind understand why they are good to have.

        Now, I think that repositories are an absolute must-have.

        First of all, if you did not have the repositories (which in my case more or less always contains bool Delete, bool Save, T Get and IQueryable GetAll) you would have to place the CRUD logic in your services, which I find a bit messy.

        Second, by using the repository pattern, I have one way of working with entities, no matter which solution I work in. Sure, I can also switch between fake data, real data, no data etc, but in the end, letting a repository handle data operations in each solution makes me work faster.

        I have a nice R# Live Template that helps me generate all required repo/service interfaces and classes, so time invested for me to have a repo is ~ 0 (maybe a little more if my repo should behave differently in some case)….do not tell anyone that I use R# live templates this way (although I accidentaly told Hadi once…big mistake).

        But once again, there is no right answer, and I may very well be (read: I am most likely) wrong. I usually am 🙂

        • Jon 8:57 pm on November 16, 2011 Permalink

          Valid points – we are back to the dreaded “it depends” =P

    • danielsaidi 9:05 pm on November 16, 2011 Permalink | Reply

      Ha ha ha, yes…the end to which all roads lead.

    • Niklas 6:13 am on November 17, 2011 Permalink | Reply

      When something feels awkward it usually means that something is missing. Is there maybe some implicit concept that needs to be made explicit? I don´t really get what a ‘Member’ is either. Could it be that instead, some User has a Membership to a Group? And that the Membership knows these things you are trying to place somewhere.

      • danielsaidi 7:36 am on November 17, 2011 Permalink | Reply

        As I wrote to Henrik, “additional” was a bad word to use. Rather, if I have two entities and one dedicated service each, where do I put stuff that, maybe, handles relational functionaltiy between the two entities. But yes, I agree…something WAS missing. For the group membership-related functionality, I have not extracted those 7 or so methods into a separate class. Privilege-related methods have been given one separate class per entity as well. It’s rather hard to describe without code examples, but now, all feels natural.

        But, as I also wrote earlier, I think that placing some piece of functionality in the “wrong” class is no biggie. To have two classes, where a MemberIsGroupMember methods ends up in the group service is not THAT bad…but, if the number of membership-related methods grow, then you should probably consider extracting them into a separate component.

        • Niklas 5:53 pm on November 17, 2011 Permalink

          In general, if a method is just some query to your datalayer, I think it should be put in the repository. But if the method contains some business logic important to your model, then it should probably go into the entity.

          If talking DDD, which your vocabulary suggests.

        • danielsaidi 6:34 pm on November 17, 2011 Permalink

          But placing it in the entity is not good if it is not just logic that can be directly derived from your entity data, e.g. CanBeProcessed for an Order, which then checks several properties to see if the Order is properly setup.

          I would not put too much or too complex login in the entity…but I may be totally wrong.

    • danielsaidi 11:18 pm on November 17, 2011 Permalink | Reply

      Guys, I just want to thank you SO much for this discussion (I am NOT putting an end to it, I would love for it to continue). After having it, I was so inspired that I sat with my code for a couple of hours, looking at it in new eyes. The changes I made are really small (moving a couple of methods to new classes), but it made the whole system so much more obvious.

      It is like Niklas wrote “when something feels awkward it usually means that something is missing”. And it did! Splitting my not that large, but too large nontheless, services into several ones made the design better, simplified testing etc. etc.

      Thanks once again!

    • Per Tronelius 11:47 pm on November 17, 2011 Permalink | Reply

      Lots of comments…
      But I must say that I agree mostly with Henrik. Let your Entitys be your “real life objects”, and let them contain Business logic… that’s why we have them, If they don’t contain logic, you should start calling them DTO:S. Your Order object a few comments up seems like an DTO with an extra get-property, nothing else.

      Use Repositories to separate your current choice of datapersistance from your Entities, making them POCO. Use repositories for persistance and effective loading of objects/graphs of objects, and use the Entities for your logic, and think of them in “real world terms” and you will find where to put the logic…

      I haven’t seen your code, but sometimes it sound like your in a “class-creating-race” and tries to separate everything into tiny individual pieces. Try for a change to create code in more of a B.B King style… with very few notes (classes) played well, rather then to code like your in a yngwie Malmsteen solo.

      • danielsaidi 12:08 am on November 18, 2011 Permalink | Reply

        Well, I now have a structure that I really think is both easy to understand and maintain, so I will go for it…until I realize that I am entirely wrong.

        So, to give you a clue about how my code works, here goes.

        My repositories work just like you described. My entities are POCOs. I can then switch out EF4 whenever I want to. For instance, I quickly made Swaplet store interested visitors in a text file instead of in the database (of which I had none live at the time).

        For the examples below, a Member is an object that is coupled with a Membership account. It contains user information, handles relations with other entities etc.

        Sorry for the terrible formatting of the code below.

        I extend my POCO entities with partial classes and metadata classes, which makes the partial Item class look something like this:

        public partial class Item
        public string ImageUrl { get; set; }

        public bool IsLentOut
        get { return LentToMemberId != null; }

        public bool MemberHasLentItem(Member member)
        return LentToMemberId == member.Id;

        public bool MemberIsOwner(Member member)
        return OwnerMemberId == member.Id;

        public class ItemMetaData
        [Required, MinLength(1)]
        public string Name { get; set; }

        A common repo can look something like this:

        public interface IMemberRepository
        void Delete(Member obj);
        Member Get(Guid id);
        IQueryable GetAll();
        Member Save(Member obj);

        I have a basic service for each entity, which lets the system manage entities of that kind in various ways. For instance:

        public interface IMemberService
        void DeleteMember(Member member);
        IQueryable GetAllMembers();
        Member GetMember(Guid memberId);
        Member GetMemberByFacebookId(int facebookId);
        Member GetMemberByUserName(string userName);
        Member SaveMember(Member member);

        After yesterdays discussions, I separated some privilege logic from these services into separate ones. For instance, these methods used to exist in the IGroupService:

        public interface IGroupPrivilegesService
        bool MemberCanEditGroup(Member member, Group group);
        bool MemberCanInviteToGroup(Member member, Group group);
        bool MemberCanLeaveGroup(Member member, Group group);
        bool MemberIsGroupAdmin(Member member, Group group);

        I do not think that this is a too complex model. In fact, I think it is really, really nice. Basic logic that directly relates to available entity data (OBS without drilling down into any relational data) ends up in the partial entity class. Basic entity handling logic ends up in a service with the same name as the entity (sure, the name sould probably change), and login that do not fit into this model ends up in separate classes.

        The only thing I am not happy about here is the naming of the classes, but hey, that’s really just semantics. If that is the convention of my code, and I stick to it all the way, I think that justifies naming the basic service classes XService. Naming conventions is really not the biggest part of this discussion.


    • Henrik 4:42 pm on November 18, 2011 Permalink | Reply

      I’m quoting a collegue. You’re facing a classic problem when using an anemic model.
      I reckon you have a lot of service classes that validates and work with your entities from the outside?
      “Entities Have an Identity and a Life”: http://msdn.microsoft.com/en-us/magazine/dd419654.aspx#id0090053

      • danielsaidi 12:07 pm on November 19, 2011 Permalink | Reply

        But now, after Niklas comment “…womething is probably missing” I really do not see a problem with my way of developing now. I really like the design of my system now, although I use IoC, DI etc…which some find being overkill. I rather find it being a great convenience, once one get use to this way of thinking.

        But looking at the link you sent me, I do not disagree that entities should have logic. The question is, should they have relational logic? Should everything I can do with an entity, like relational stuff (find all group members for a group) also go there? What is the responsibility of the entity…to handle everything one can want to do with it? I disagree…but I agree that one can probably put more logic in the entities than I tend to do.

        • Henrik 10:43 pm on November 20, 2011 Permalink

          You are absolutely right. When it comes to the relational logic that’s where the service classes comes in. But you *only* use them for those cases, then they become very thin and isolated. For the rest, let entities have logic. But if you are happy I’m happy! 🙂 If you are happy and think everything is great, then you are home! Nothing else matters 🙂

        • danielsaidi 11:08 pm on November 20, 2011 Permalink

          Another danger I see with letting EF(!) entities be responsible for a lot of their logic is that it may encourage placing entity navigational code into them, for instance:

          public partial class Member {
          public bool HasItems { get { return Items.Count() > 0; } }

          This is a very trivial example, but I think it is good to demonstrate what I think (obs, I am not sure at all) may be dangerous.

          Member is an EF entity with an association to the Item entity, which generates the navigation property Items.

          However, if I was to choose to persist items in another way, outside of the EF context, then this way of retrieving items would be at a loss, since my items would not be stored in the same database as members.

          Still, Jon sent me this Dan North lecture:

          Consider this project to be my second project 🙂 I want to do stuff right, and think I am on my way, but in this strife, I also often go too far, which makes the project take a lot longer time than if I would have just created it with, say, Wigbi.

          So, I am really not that happy 😉 I am more happy to be able to discuss these things with you guys than how my project is finally coming along. Luckily, doing stuff by the book was one of the major goals for me (which I can allow myself since it is a hobby project).

          Let’s just hope that failure to deliver will not be the outcome 😉

        • danielsaidi 11:09 pm on November 20, 2011 Permalink

          Oh, and another reflection. EF aims at making it easy for you to quickly get something up and running, so maybe trying to optimize for using is is, well…maybe it should come later. Maybe drilling down the entity relations would be just fine for now.

          We’ll see how I do things in my next project 😉

Compose new post
Next post/Next comment
Previous post/Previous comment
Show/Hide comments
Go to top
Go to login
Show/Hide help
shift + esc