Updates from January, 2017 Toggle Comment Threads | Keyboard Shortcuts

  • danielsaidi 8:31 am on January 24, 2017 Permalink | Reply  

    This blog is moving 

    I have finally got around to begin moving this blog to my own web site, where I get much more control over my code-focused posts. You can find this new blog at my personal site:


    While WordPress has a bunch of great tools for blogging, being able to write posts in plain text and MarkDown will be a real boost for me.

    I will delete blog posts as I move them. All discussions will be copied over with the blog.

  • danielsaidi 2:10 pm on May 4, 2012 Permalink | Reply
    Tags: code, source code,   

    Posting source code on a WordPress hosted blog 

    As you probably have noticed, this is a blog about code…mostly. I post a lot of code here…but the code parts of the blog have been terribly formatted.

    The reason to this is that I host my blog at wordpress.com. This means that I serve under some limitations, such as only getting to select from a couple of themes (actually, there are tons of themes to choose from), not being able to add my own plugins etc. So, when it comes to code, I have not found a plugin that could be used to handle the code formatting. To make the code stand out, I have instead wrapped the code in pre tags and highlighted the code with a distinct color, but I have disliked that approach a lot.

    A couple of weeks ago, however, I found this blog post by the WordPress team themselves. Turns out that posting source code and getting it to format correctly is a walk in the park, using the sourcecode markup.

    By wrapping your code inside a:

    [code language=”css”]
    your code here

    WordPress will format the source code correctly. There are a number of language formats to choose from, such as C#, Java, JavaScript, Python, CSS, XML etc. etc. etc. See the original blog post for examples.

    Thanks, WordPress!

  • danielsaidi 9:37 pm on February 27, 2012 Permalink | Reply
    Tags: , dependency injection, , , inversion of control, sub routines   

    Dependency Injection gone too far? 

    I am currently working with a new version of a hobby console app of mine, that should execute certain actions depending on the input arguments. Now, I wonder if I am taking the concept of dependency injection too far.

    Which dependencies should you inject, and which should you keep as invisible dependencies?

    How does Cloney work?

    The Cloney console application will do different things depending on the input arguments it is provided with. For instance, if I enter

     cloney --clone --source=c:/MyProject --target=d:/MyNewProject

    Cloney will clone the solution according to certain rules.

    To keep the design clean and flexible, I introduced the concept of sub routines. A sub routine is a class that implement the ISubRoutine interface, which means that it can be executed using the input arguments of the console application. For instance, the CloneRoutine listens for the input arguments above, while the HelpRoutine triggers on cloney –help.

    When I start the application, Cloney fetches all ISubRoutine implementation and tries to execute each with the input arguments. Some may trigger, some may not. If no routine triggers, Cloney displays a help message.

    So, what is the problem?

    Well, there is really no problem…just different ways to do things.

    For instance, when it comes to parsing the input arguments and making them convenient to handle, I use a class call CommandLineArgumentParser, which implements ICommandLineArgumentParser. The class transforms the default string array to a dictionary, which makes it easy to map an arg key to an arg value.

    Using the class is a choice each sub routine must take. The interface just defines the following method:

     bool Run(IEnumerable<string> args)

    Yeah, that’s right. Each sub routine just acts like a program of its own. As far as the master program is concerned, it just delegates the raw argument array it receives to each sub routine. How the routine handles the arguments is entirely up to it.

    The old design – DI for all (too much?)

    Previously, the CloneRoutine had two constructors:

       public CloneRoutine()
       : this(Default.Console, Default.Translator, Default.CommandLineArgumentParser, Default.SolutionCloner) { ... } 
       public CloneRoutine(IConsole console, ITranslator translator, ICommandLineArgumentParser argumentParser, ISolutionCloner solutionCloner) { ... }

    Since a sub routine is created with reflection, it must provide a default constructor. Here, the default constructor use default implementations of each interface, while the custom constructor is used in the unit tests and supports full dependency injection. Each dependency is exposed and pluggable.

    So, what is the problem?

    Well, I just feel that since the command line arguments are what defines what the routine should do, letting the class behavior be entirely determined by how another component parses the input arguments, makes the class unreliable.

    If I provide the class with an implementation that returns an invalid set of arguments, even if I provide the routine with arguments that it should trigger on (and especially considering that the return value is a do-as-you-please IDictionary), the class may explode due to an invalid implementation.

    It that not bad?

    The new design – DI where I think it’s needed (enough?)

    Instead of the old design, it this not better:

       public CloneRoutine() :this(Default.Console, Default.Translator, Default.SolutionCloner) { ... }
       public CloneRoutine(IConsole console, ITranslator translator, ISolutionCloner solutionCloner) {
          this.argumentParser = Default.CommandLineArgumentParser;

    This way, I depend on the choice of ICommandLineArgumentParser implementation that I have made in the Default class, but if that implementation is incorrect, my unit tests will break. The other three injections (IMO) are the ones that should be exchangable. The argument parser should not be.

    Is this good design, or am I doing something terribly bad by embedding a hard dependency, especially since all other component dependencies can be injected. Please provide me with your comments regarding this situation.

    • Henrik 12:05 am on February 28, 2012 Permalink | Reply

      I think this looks good! What you can do is either Property Injection (i.e. make argumentParser a public property which can be set by the test code when needed) or the Extract and Override technique (i.e make argumentParser a protected virtual property and then make a testable class that inherits from your “production” class (e.g. CloneRoutineStub : CloneRoutine) and then overrides that virtual property.

      Or am I getting your question wrong?

    • danielsaidi 7:21 am on February 28, 2012 Permalink | Reply

      Thanks for commenting, Henrik! I guess my question was this: when should you allow behavior to be injected and when should you not go down that path.

      For the example above, I think injecting the IConsole, ITranslator and ISolutionCloner implementations is fine, since they define responsibility that SHOULD be delegated by the class.

      However, I think that acting on the input arguments received in the Run method should be the responsibility of the class, and should not be injectable.

      If the routine chooses a certain component to parse arguments is absolutely fine (and I kind of have an DI model since the routine uses the Default.CommandLineArgumentParser), but it should not be exposed.

      If I allow the argument parsing behavior to be injectable, I can make the class stop working in really strange ways, since the parser has to parse the arguments in a very specific way. IMO, the argument parser differs from the other three components.

      So….do you agree? 🙂

    • Henrik 8:18 am on February 28, 2012 Permalink | Reply

      I agree! I think it’s perfectly okay! Context is king!
      It’s not a self-purpose to require dependencies to be injected.

      Maybe you want me to disagree, so we get this lovely war feeling? 🙂

      • danielsaidi 8:41 am on February 28, 2012 Permalink | Reply

        I do love the war feeling, but sometimes, getting along is a wonderful thing as well. 🙂

        System design sure is tricky sometimes. I really appreciate having you and other devs to discuss these things with.

    • Daniel Lee 9:42 am on February 28, 2012 Permalink | Reply

      I can’t see why you would ever need to switch out the command line argument parser. And as you say yourself, it feels more like core logic than a dependency.

      So you made the right decision.

      (Although, in such a small codebase as Cloney, I don’t know if this really matters all that much?)

    • danielsaidi 10:01 am on February 28, 2012 Permalink | Reply

      Nice, thanks Daniel 🙂

      I think I’ll roll with this design for now, and replace it whenever I see the need to. I do not like all these hard dependencies to the Default class – it’s like making the classes dependent on the existence of StructureMap.

      However, as you say, it IS core logic. Cloney is not a general library, so these kinds of dependencies may not be as bad as if I’d have the same design in, say, a general lib like .NExtra.

    • Johan Driessen 12:39 pm on February 28, 2012 Permalink | Reply

      If your main concern is that your unit tests will be more fragile, and break if your implementation of the argument parser is incorrect (or just changes), why don’t you just make the argumentParser-field protected virtual?

      Then you can just create a “TestableCloneRoutine” in your tests, that inherits from CloneRoutine and replaces the argumentparser with a stub, so that your tests don’t become dependant on the actual implementation, while still not making the internals visible to other classes.

      AKA “extract and override”.

      • Johan Driessen 12:41 pm on February 28, 2012 Permalink | Reply

        Actually, you would have to make argumentParser a property (still protected and virtual) and have it return Default.CommandLineArgumentParser in CloneRoutine.

        • danielsaidi 2:39 pm on February 28, 2012 Permalink

          Thanks for your input, Johan. I will try to clarify my main concern regarding the design.

          If we see to the unit tests, I think that the following expression is a good test scenario:

          “If I start Cloney with the argument array [“–help”], the HelpRoutine class should trigger and write to the console”

          In my unit tests, for instance, I can then trigger the Run method with various arguments and see that my IConsole mock receives a call to WriteLine only when I provide the method with valid input.

          If, on the other hand, the argument parse behavior is exposed, the HelpRoutine will communicate that it has an IArgumentParser that parses a string[] to an IDictionary. IMO, this is not relevant.

          Furthermore, if I make the parser injectable, my test scenario would rather be expressed like this:

          “If I start Cloney with the argument array [“–help”], the HelpRoutine class should trigger and write to the console if the argument parser it uses parses the array to an IDictionary where the “help” key is set to true.”

          I am not sure which test scenario I prefer. The second one is more honest, since the routine’s behavior IS based on the parser’s behavior…but is that really what I want to test?

          I considered re-adding the IArgumentParser as a constructor parameter again, just to make it possible to inject it, but I am not really sure. I see benefit with this, as I do with keeping it completely internal.

          IMO, the fact that the routine uses an ArgumentParser to parse the arguments should not be of any concern to anyone but the class. It’s the resulting behavior that should matter.

          But I have a split feeling about it all.

  • danielsaidi 1:13 am on January 3, 2012 Permalink | Reply  

    Kick-starting 2012 

    Last year ended in a downhill slope, didn’t it? With me moving to a new apartement in the beginning of December, after planning for and celebrating the birthday of both my oldest daughter and my wife in the end of November and also preparing for the Christmas holiday, not much time was left for blogging.

    So, for those of you spending the entire New Year’s Eve refreshing the start page of my immensely popular blog (eh), sorry for not producing!

    However, I will kick-start this new year with a…rather short and pointless post about not that much. Instead, I will just sum up what I will write about shortly, to try to tempt you into returning in a couple of days:

    • Øredev 2011 – Sure, this is pathetic, summing it up after such a long time…but I will complete it! Look at it as some kind of new year’s resolution.
    • TeamCity – …or, at least, my take on it, with multiple builds, passing params into the boo script etc. etc.
    • VS Config transforms – …and how you can use them for all your config files (with and without SlowCheetah)
    • Wigbi 2.0.0 – I am doing a quick SOLIDification of the Wigbi source and will soon be done. I will blog about the progress so far.

    So, keep coming back. In the mean time, stroll down memory lane and take a look at what I have written earlier…then visualize how much better my writings and topics will be in 2012…then let me know how I can get there.

  • 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 😉

  • danielsaidi 3:06 pm on September 8, 2011 Permalink | Reply
    Tags: ,   

    TeamCity 6.5.1 does not play well with NServiceBus 

    I am currently moving projects from an old TeamCity 5.1.2 server to a new 6.5.1 server.

    Everything has been going great, until I tried moving a project that uses NServiceBus test framework. When TeamCity tries to launch these tests, it fails with the following error message (one of many):

    [xxx.Test_Name] Test(s) failed. System.InvalidOperationException : Could not load C:\TeamCity\BuildAgent3\work\c53933ba5b3b087f\xxx\bin\release\xxx.XmlSerializers.dll. Consider using ‘Configure.With(AllAssemblies.Except(“xxx.XmlSerializers.dll”))’ to tell NServiceBus not to load this file. —-> System.BadImageFormatException : Could not load file or assembly ‘file:///C:\TeamCity\BuildAgent3\work\c53933ba5b3b087f\xxx.Tests\bin\release\xxx.XmlSerializers.dll’ or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded. at NServiceBus.Configure.GetAssembliesInDirectoryWithExtension(String path, String extension, String[] assembliesToSkip) in d:\BuildAgent-02\work\672d81652eaca4e1\src\config\NServiceBus.Config\Configure.cs:line 213 at NServiceBus.Configure.<GetAssembliesInDirectory>d__3.MoveNext() in d:\BuildAgent-02\work\672d81652eaca4e1\src\config\NServiceBus.Config\Configure.cs:line 190 at System.Linq.Buffer`1..ctor(IEnumerable`1 source) at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source) at NServiceBus.Configure.With(String probeDirectory) in d:\BuildAgent-02\work\672d81652eaca4e1\src\config\NServiceBus.Config\Configure.cs:line 101 at NServiceBus.Configure.With() in d:\BuildAgent-02\work\672d81652eaca4e1\src\config\NServiceBus.Config\Configure.cs:line 75 at NServiceBus.Testing.Test.Initialize() in d:\BuildAgent-02\work\672d81652eaca4e1\src\testing\Test.cs:line 20 at xxx.Setup() in c:\TeamCity\BuildAgent3\work\c53933ba5b3b087f\xxx.Tests\xxxTests.cs:line 17 –BadImageFormatException at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) at System.Reflection.Assembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, StackCrawlMark& stackMark) at System.Reflection.Assembly.LoadFrom(String assemblyFile) at NServiceBus.Configure.GetAssembliesInDirectoryWithExtension(String path, String extension, String[] assembliesToSkip) in d:\BuildAgent-02\work\672d81652eaca4e1\src\config\NServiceBus.Config\Configure.cs:line 204

    I have replaced secret component names with xxx – do not let it confuse you.

    Now, I am really wondering where d:\BuildAgent-02 comes from, since it does not exist on the old server and not on the new one either. After reading up a bit, it seems that it is an NServiceBus issue.

    The problem resambles the issue being described here:


    However, I have installed VS2010 and SP1 and it still does not work. I am out of ideas. I have tried bending the laws of physics, but all I am left with is a NServiceBus test suite that just won’t work.

    Any ideas out there?

    • Eugene Petrenko 4:49 pm on September 8, 2011 Permalink | Reply

      Check you specified NUnit assemblies wildcard in the way **/obj/** folders are excluded. MSBuild used to put there assemblies without dependent assemblies.

  • danielsaidi 7:01 pm on July 24, 2011 Permalink | Reply  

    Floods tear Denmark apart and cause massive domain and hosting problems 

    Two weeks ago, heavy rain and extreme weather hit large parts of Denmark, causing major problems. One victim was my hosting provider, who faced immense server problems as the flood hit them with full force (exaggeration possible).

    My .NET server went up after a day or so, but the one where I host my PHP sites (like saidi.se and wigbi.com) were down for more than a week. You may have noticed that the blog lacked some images and that you could not access some of the stuff I have linked to…

    …but I bet that the Danish population had larger problems than that, so I should not complain.

    Last weekend, the server came back online, so hopefully, everything will be back to normal. If it is not, and you find something that does not work, please let me know.

  • danielsaidi 7:26 am on May 27, 2011 Permalink | Reply
    Tags: badimageformatexception, ,   

    How to handle BadImageFormatException in NUnit 

    While I have been developing the new version of my hobby project in .NET, everything has been working great all along…until now. Apparently, NUnit thinks that there is something wrong with one of my assemblies:


    So far, this assembly only contains two classes, so the easiest option would be to just delete it and create a new project and hope for the best…but, I have this thing for wanting to know what is causing this problem.

    However, my ambitions were laid to rest, since deleting the two projects and re-adding the classes solved all my problems.  I would have posted a solution here, but now we’ll never know what caused this problem in the first place.

    Or won’t we?

    After writing this blog post, Mikey posted a comment that pointed me in the right direction. I must have disabled one architecture, causing the test project to fail when using the project.

    Thanks Mikey!

    • Mikey 11:32 pm on October 19, 2013 Permalink | Reply

      I ran into this issue today — it turned out that the project I wanted to test was set to compile as X86, but my NUnit test project was set to ANY CPU — I set them both to ANY CPU and the issue went away.

  • danielsaidi 11:22 pm on May 16, 2011 Permalink | Reply
    Tags: app store, door codes, gps, mellon   

    Mellon! is out on the App Store 

    It has taken me a great while, but now I’ve finally managed to get my act together and get my first app out on App Store. The app is called Mellon! (can you guess why??) and is an app that lets you store door codes by location.

    When you are near a door, just open Mellon! to get the door code. It is an easy and a safe solution to connect door codes to their location. You can store codes temporarily and bind them to their location once you arrive. You can also share door codes with your friends.

    It’s a quite basic app, but imo quite functional. For instance, imagine having a party and just having to share your door code with all your guests ONCE by e-mail or SMS, instead of having to answer the phone the whole evening.

    I have had the idea for so long, but it required a focused Creative Hack event at C9 to make me realize it together with great colleagues.

    Grab the app at http://itunes.apple.com/se/app/mellon-door-codes/id436691390?mt=8.

  • danielsaidi 1:06 pm on March 17, 2011 Permalink | Reply
    Tags: , , linus thorvalds   

    Linus Thorvalds replies to a guy that thinks he should have built git in C++ 

    This git-related story is probably old to all you hardcore gitters, but for me (n00b as I am) it was a brand new and hilarious read. To really appreciate it, first read up on some background information about why git was created in the first place.

    After git was released and worked really, really well, a brave soul decided to stepp up and criticize the decision to build git in C instead of C++. He was pretty full of himself, which makes Linus reply amazing.

    Happy reading!







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