ORM and NHibernate concepts

by andrei 3. October 2008 22:11

You can read about the purpose of this list and how to use it here.
Also, the list of resources is here.

 

  1. general implementation
    B4
  2. concepts
    1. other orms
      code & implementation
      E1
      E2
    2. things to avoid
      1. n+1 selects
        Yet another classic problem is that of n+1 selects. Assume you fetch all Orders in the database and that OrderLines are Lazy Loaded. Then you touch each Order and its OrderLines. Then there will be a new SELECT issued for each Order's OrderLines. If you don't use Lazy Load, the problem will be smaller, but then you run the risk of getting into the problem just mentioned of fetching too much in some scenarios.
        resources
        B4
      2. reading way too much
        A fifth is the "reading way too much" problem when too many complex types are read even though just a tiny amount of information is really needed. This is especially common if you haven't used a somewhat careful Aggregate design and haven't used Lazy Load.
        resources
        B4
    3. mapping
      1. discriminator
        If we assume that Customer and Vendor inherits from Company, the mapping information could look like this:
        <discriminator column="Type" type="AnsiString" length="8"
        not-null="true" />
        resources
        B4
      2. inheritance
        NHibernate supports all three different inheritance solutions, namely Single Table Inheritance, Class Table Inheritance, and Concrete Table Inheritance
        resources
        B4
      3. unsaved-value
        resources
        B4
      4. N:1
        code & implementation
        B4
        resources
        B4
      5. 1:N
        code & implementation
        B4
        resources
        B4
      6. value objects
        NHibernate uses the word component for describing an Embedded Value
        code & implementation
        B4
        resources
        B4
      7. private fields
        For example, you often expose something slightly different in your property get to what is stored, or you do some interception on get/set. In these cases, you need to map, for example, the private field instead.
        code & implementation
        B4
        resources
        B4
    4. entity lifecycle
      resources
      B4
    5. lazy load
      If you do want to use (automatic) Lazy Load Fowler PoEAA with NHibernate, that's easily done
      resources
      B4
    6. scalar queries
      Scalar queries are especially useful in situations where you find it too expensive to fetch complete Customer instances but want a more lightweight result, and you don't want to define a class.
      Of course, the result won't be typesafe in this case, but you could use a variation, namely the one I talked about earlier in this chapter called report query (or a flattening query).
      resources
      B4
    7. report queries
      the result won't have Customer instances, but CustomerSnapshot instances. For it to work, you need to provide a matching constructor on the Value Object (CustomerSnapshot in the previous case) and to mention CustomerSnapshot in a mapping file via an import directive
      resources
      B4
    8. transactions
      Support for manual transaction control is pretty good in NHibernate. There are situations where you might be taken by surprise if you don't watch out (for instance, when you execute a query in the middle of a transaction, NHibernate will then Flush() changes to the database before executing the query). That's a tradeoff between querying not going "through" the cache or ordinary transaction control. The good news is that it's controllable by your code.
      What you do is grab an ITransaction instance, which you can then use to make either a Commit() or Rollback() (Commit() will by default automatically do a Flush()).
      I prefer to control the start and end of the unit of work in the consumer, outside of the repositories
      resources
      B4
    9. caching
      Advanced caching is one area where NHibernate isn't really up to par when compared to Hibernate, but I think it's rapidly becoming better. On the other hand, to me that's not usually a big deal. There are many problems with second-level caching, so that option is often ruled out.
      resources
      B4
    10. unitofwork
      NHibernate uses the Unit of Work pattern Fowler PoEAA as well, and again it's dealt with in the ISession.
    11. query
      1. Criteria objects
      2. HQL
        it's not table names but classes that are used in HQL
        resources
        B4
        1. joins
          data is fetched from two tables, and there is no mention about that in the from clause (that is, there is no join). Of course, the mapping information is used to determine what needs to be done at execution time with the HQL query.
          select o.Customer.Name, count(*) from Order o group by o.Customer.Name
          resources
          B4
    12. session
      1. clear
        to clear the Identity Map from all instances
        resources
        B4
      2. evict
        What you can do to force a database jump (instead of opening a new ISession) is to call Evict() on the instance by saying that you don't want the Identity Map to keep track of the instance any longer.
        resources
        B4
      3. flush
        It is also important pointing out that the INSERT is delayed and won't happen when you say Save(), but rather when you say Flush().
        resources
        B4
      4. saveorupdate
        I could have called SaveOrUpdate() instead, and then NHibernate would have decided on its own whether it should be an INSERT or an UPDATE. The information used in that case is the value of the Identity Field, and it's compared to what you indicated for unsaved-value in the mapping file ("00000000-0000-0000-0000-000000000000" in the case of Guids). If the Identity Field matches the unsaved-value, it's time for an INSERT; otherwise, it would be an UPDATE.
        resources
        B4
    13. identity
      1. don't set it manually
        Normally, you would give Identity Fields default values, such as Guid.NewGuid(), but that's not a good idea if it's possible to avoid it when you use NHibernate because NHibernate uses the Identity Field values to determine if it should be an UPDATE or INSERT. If you provide a default value (unless you set it to unsaved-value, of course), NHibernate will always expect UPDATE if you don't explicitly provide guidance. (You can also use the version tag for signaling INSERT/UPDATE.)
        resources
        B4
      2. guid identity
        In the case of the guid, you can generate it in all the layers, but it's recommended that you do it in the O/R Mapper
        resources
        B4
    14. repository
      the consumer injects ISession instances to the repositories
    15. interceptor
      yet another NHibernate interface
      To use a custom IInterceptor implementation, you provide it as a parameter when instantiating ISession
      resources
      B4
    16. validation
      NHibernate has an IValidatable interface that will get calls by NHibernate at Flush().
      But then I need to reference the nhibernate.dll in the Domain Model, so I prefer a solution like the one I used in Chapter 7, "Let the Rules Rule." I mean, I can use an IInterceptor
      resources
      B4
    17. concurrency
      NHibernate deals with Optimistic Offline Lock if you add a <version> tag to the entities
      resources
      B4
    18. identity map
      NHibernate uses an Identity Map on an ISession level.
      resources
      B4
    19. embedded resource
      If you want the metadata to be within the assembly, don't forget to set the property of the XML file to be an Embedded Resource.
      resources
      B4
    20. generate database from mapping
      I prefer to start with the Domain Model, then write the mapping files, and from that automatically generate the database from the mapping information
      code & implementation
      B4
      resources
      B4
    21. sessionfactory
      What you then try to do just once per application execution is to set up a SessionFactory. The reason for not creating several is that the cost is fairly high. The SessionFactory will analyze all metadata and build up memory-based structures for that. As you might guess from its name, the SessionFactory is then used for instantiating new instances that implement ISession.
      code & implementation
      B4
      resources
      B4

 

You can find the entire list of techniques in progress in the Development base concepts category. Please feel free to leave any comments or suggestions which could make these lists more useful for everyone.

Also, if you are interested in learning these skills you can try the Developer training modules.

 

 

 

Enjoy programming!

 

Process concepts

by andrei 19. September 2008 21:44

You can read about the purpose of this list and how to use it here.
Also, the list of resources is here.

 

  1. general implementation
  2. concepts
    1. harvested framework
      watch out so you don't fall into the trap of building frameworks up front. It's generally better to let them show themselves in your code and then you go from there.
    2. YAGNI
      So it's important to be careful and not think "You Aren't Going to Need It" (YAGNI) too often when it comes to operational mechanisms. Using YAGNI often will cost too much when it comes to adding the mechanism if (or rather when) you will need it. Remember, the idea with YAGNI is that the cost of adding something is pretty much the same now and later, in which case you can always wait until you really need it. When the cost is low now and high later, and there's a good chance you will need it, you should make a different decision.
      going for a Query Object, especially a domain-specific one, or the Specification pattern is to start by going too far, too quickly, don't you think? Let's go for the simplest possible and only consider two of all possible criteria for now
      The third solution could be to create an interface called ICustomer (or something similar, or let Customer be an interface) and then create a stub implementation of the interface. Again, that feels like overkill right now, and what would the purpose be when moving forward? To be able to swap ICustomer implementations? Is that really something I expect? No, I don't, so until proven wrong, I decide that this isn't the solution I am going to start with.
      Well, what value does the factory really add? Not anything yet. It just adds a bit of complexity. I really should have at least started without the factory, because it shouldn't be around if it doesn't add value. It feels strange to refactor away from a factory. But it's just a sign that I got carried away and started out with a too detailed design from the beginning.
      B4
    3. whiteboard or sketchpad for software design meetings
      Diagrams are a means of communication and explanation, and they facilitate brainstorming. They serve these ends best if they are minimal.
      resources
      B1
    4. Strategic Design Decision Making
      Strategic design requires minimalism and humility
      resources
      B1
    5. source control
      1. SVN
    6. Software Factories
      The idea of Software Factories is to have two lines in the software company. One line creates architectures, frameworks, and such to be used for families of applications. The other line creates the applications by using what the first line has produced, and thereby amortizing the cost of the frameworks on several projects
      A problem is that it's troublesome to just invent a framework. It's probably a better idea to harvest instead. Another thing that is somewhat problematic with Software Factories, though, is that they probably require pretty large organizations before being efficient to use
      At the heart of Software Factories is that of Domain Specific Languages
      resources
      B4
    7. risk management
      except when the team has proven skills and the domain is very familiar, the first-cut system should be based on some part of the CORE DOMAIN, however simple.
      the CORE DOMAIN is high risk because it is often unexpectedly difficult and because without it, the project cannot succeed.
      resources
      B1
    8. project documentation
      Documents Should Complement Code and Speech
      resources
      B1
    9. continuous integration
      The key to significantly reducing integration problems is to generate your builds automatically and to use an incremental integration strategy where all the code is rebuilt and tested at least daily, if not continuously. The idea is that if your recently added code breaks a build, you either fix it immediately or roll back the changes to restore the system to the last known good state.
      resources
      B4
    10. bug fixing
      It's a good idea to use TDD and refactoring for bugfixing also. First expose the bug with a red test, then solve the bug so you get green, and then refactor.
      resources
      B4
    11. Big Design Up-Front (BDUF)
      I think it's pretty well known that a Big Design Up-Front (BDUF) has some big problems. At the same time, most often we know some things from day one. It's a matter of balance.
      resources
      B4
    12. automated build & deploy
      code & implementation
      E2

 

You can find the entire list of techniques in progress in the Development base concepts category. Please feel free to leave any comments or suggestions which could make these lists more useful for everyone.

Also, if you are interested in learning these skills you can try the Developer training modules.

 

 

 

Enjoy programming!

 

TDD Concepts

by andrei 19. September 2008 21:41

You can read about the purpose of this list and how to use it here.
Also, the list of resources is here.

 

  1. general implementation
    E1
    E2
    E8
    E11
    B3
    B4
  2. concepts
    1. small steps
      Ouch, there was a lot of design done in that single test, and I now need to create two classes and new methods at old classes to just make it compile. I think I'd better comment out that test for the moment and start a little more simply, focusing on the OrderLine class.
      resources
      B4
    2. How to Set Values from the Outside
      How can we from the outside (such as in a Repository) set values in instances that are being reconstituted from persistence?
      resources
      B4
      code & implementation
      B4
    3. System Under Test (SUT)
      resources
      B4
    4. Trace.Assert
      You should think twice before using the ordinary Diagnostics assertions. One problem with that is that it won't integrate well with NUnit. Another problem is that I can't customize it for how it should act in different situations like development, continuous integration, beta testing, and during production.
      resources
      B4
    5. VSTS
      Visual Studio Team System
      resources
      B3
    6. unit test
      code & implementation
      E2
    7. UI
      It is hard to use TDD for the UI. TDD fits easier and better with the Domain Model and the core logic, although this isn't necessarily a bad thing. It helps you be strict in splitting the UI from the Domain Model, which is a basic design best practice (so it should be done anyway, but TDD stimulates it). Ensure you write very thin UI and factor out logic from the forms.
      resources
      B4
      1. Self-shunting
        a technique where you're letting the test class also act as a stub or mock
        resources
        B4
    8. The TDD Flow
      Red, Green, Refactor
      resources
      B4
    9. NMock
      resources
      B4
    10. Testdriven.Net
    11. TDD
      TDD isn't about testing. It's about programming and design.
      Domain Models are very suitable for TDD
      After having used TDD for a couple of years now, I'm still getting even fonder of the technique. I'm becoming more and more convinced that TDD is the single most important technique in becoming a better programmer.
      resources
      B4
    12. fake object
      A class with methods that return a fixed value or values that can either be hardcoded or set programmatically.
      A Fake Objectis an object that replaces the functionality of the real depended-on component in a test for reasons other than verification of indirect inputs and outputs. Typically, it will implement the same or a subset of the functionality of the real depended-on component but in a much simpler way.
      resources
      B4
    13. stub
      A testing stub is a simulation of a real object used for testing purposes. It provides a mechanism to set up expected values to supply to the code being tested.
      Using testing stubs allow us to isolate the code under test and to observe how it reacts to the external conditions simulated by the faked collaborators.
      A class with methods that do nothing. They are simply there to allow the system to compile and run.
      A Test Stub is an object that is used by a test to replace a real component on which the SUT depends so that the test can control the indirect inputs of the SUT. This allows the test to force the SUT down paths it might not otherwise exercise.
      A stub is a replacement piece of code that does just enough to not cause problems for the caller and no more
      resources
      B4
    14. state-based testing
      resources
      B4
    15. spike test
      code & implementation
      E2
    16. rhinomocks
      code & implementation
      E2
    17. refactoring
      A key principle that is used during TDD is refactoring
      resources
      B4
    18. mock
      A notable variation to stubs is the concept of mock object. A mock object is a simulation of a real object. It replaces a collaborator and provides expected values to the code under test. In addition, it supplies a mechanism to set up expectations about how it should be used and can provide some self-validation based on those expectations.
      When I first learned about mock objects, I thought that it was particularly tricky to come up with an easy mechanism to replace my collaborators. The fundamental problem was that my code was coupled with the concrete implementation of those collaborators rather than their interfaces. The "aha!" moment came when I discovered two key mechanisms called Dependency Injection and Service Locator.
      A class in which you can set expectations regarding what methods are called, with which parameters, how often, etc. You can also set return values for various calling situations. A mock will also provide a way to verify that the expectations were met.
      A Mock Object is an object that is used by a test to replace a real component on which the SUT depends so that the test can observe its indirect outputs. Typically, the Mock Object fakes the implementation by either returning hard-coded results or results that were pre-loaded by the test.
      A mock Statement would do all that and also allow the setting of expectations.
      Like a stub, the test would use the mock command instead of the real command, but when the test was complete, it would "ask" the mock command to "verify" that it was called correctly.
      In other words, you tell the mock what to expect. Then you ask it to verify that it did receive these expectations after the test is complete.
      resources
      B4
      1. Dynamic Mocks
        the technique allows you to simply pass in the class to mock to a framework and get back an object that will implement its interface
        resources
        B4
    19. interface
      it is not rare to observe that systems designed to be tested using mock objects contain a significant number of interfaces introduced for testing purposes only.
      resources
      B4
    20. interaction-based testing
      resources
      B4
    21. intellisense
      Some of you might dislike that you don't get help from intellisense (which helps you cut down on typing by "guessing" what you want to write) when writing tests first. I'm fond of intellisense too, but in this case I don't miss it. Remember, what we are talking about here is the interface, and it could be good to write it twice to get an extra check.
      resources
      B4
    22. integration test
      code & implementation
      E2
    23. persistence abstraction layer
      Thanks to that abstraction layer, I can move the Repositories back to the Domain Model, and I only need one Repository implementation per Aggregate root. The same Repository can work both against an O/R Mapper and against a Fake that won't persist to a database but only hold in memory hashtables of the instances, but with similar semantics as in the O/R Mapper-case.
      It's still a stretch to talk about PI Repositories, but with this solution I can avoid a reference to the infrastructure in the Domain Model. That said, in real-world applications I have kept the Repositories in a separate assembly anyway
      I think a nice goal is to get all the tests in good shape so that they can run both with the Fake mechanism and the infrastructure.
      resources
      B3
      B4
      code & implementation
      E12
    24. repository testing
      The solution I decided to try out was creating an abstraction layer that I call NWorkspace Nilsson NWorkspace. It's a set of adapter interfaces, which I have written implementations for in the form of a Fake. The Fake is just two levels of hashtables, one set of hashtables for the persistent Entities (simulating a database) and one set of hashtables for the Unit of Work and the Identity Map. (The Identity Map keeps track of what identities, typically primary keys, are currently loaded.)
      resources
      B3
      B4
      code & implementation
      E12
    25. database
      Databases do cause a tricky problem with TDD because once you have written to the database in one test, the database is in another state when it's time for the next test, and this causes trouble with isolation
      Test everything you can without actually hitting your database access code. The data access code should do as little as you can get away with. In most cases, this should be CRUD.
      resources
      B4
      code & implementation
      B4
      1. Separate the Testing of the Unit from the Testing of the Call to the Database
        In the spirit of TDD, it wouldn't make sense to write a test for a class and start out your implementation with a direct call to a database. Instead, the call is delegated out to a different object that abstracts the database, which is replaced with a stub or a mock as you write the test. Then you write the code that actually implements the database abstraction, and test that it calls the underlying data access objects correctly. Finally, you would write a few tests that test that your infrastructure that connects real database calls to your code works correctly.
        resources
        B4
      2. Evolving Schema
        I prefer the approach of creating and running alter scripts against your database. You could run these scripts immediately after your database reset, but because all that database state is contained in your source controlled development environment, it probably makes sense to develop the scripts and use them to modify your test environment. When your tests pass, you check it all in and then have the scripts automatically set up to run against your QA environment as needed.
        resources
        B4
      3. Reset the Data Used by a Test Before the Test
        It is possible to use this technique successfully, but after many years of test writing, I have found this approach to be the most likely to break without good reason.
        resources
        B4
      4. Maintain the State of the Database During the Run
        Essentially, what you do is to run each test in a transaction and then roll back the transaction at the end of the test.
        resources
        B4
      5. Reset the Database Before Each Test
        At first glance, this might seem the most desirable, but possibly the most time-consuming, option
        resources
        B4
    26. XtUnit
      What this tool does is allow you to put a Rollback attribute on specific test methods, allowing those methods to be run in their own COM+ transaction
      This is by far the simplest approach to keeping your database in pristine shape. It does come with a price, though. Transactions are by their nature logged, which increases the execution time.
      resources
      B4
    27. DbUnit
      it's a framework for JUnit that allows you to define "data sets" that are loaded on clean tables before each test run.
      resources
      B4

 

You can find the entire list of techniques in progress in the Development base concepts category. Please feel free to leave any comments or suggestions which could make these lists more useful for everyone.

Also, if you are interested in learning these skills you can try the Developer training modules.

 

Technorati Tags: ,,

 

 

Enjoy programming!

 

Refactoring concepts

by andrei 19. September 2008 21:39

You can read about the purpose of this list and how to use it here.
Also, the list of resources is here.

 

  1. general implementation
    E8
    E9
  2. concepts
    1. Encapsulate Collection Refactoring
      basically means that the parent will protect all changes to the collection
      resources
      B4
    2. ReSharper
      http://www.jetbrains.com/resharper/
      resources
      B4
    3. Replace Nested Conditional with Guard Clauses
      resources
      B4
    4. refactoring
      In a nutshell, what refactoring does is to take you from smelly code to nice code. It's as simple as that.
      Continuous refactoring has come to be considered a "best practice," but most project teams are still too cautious about it. If you wait until you can make a complete justification for a change, you've waited too long.
      In order to be able to use refactoring in a safe way, you must carry out extensive tests. If you don't, you will introduce bugs and/or you will prioritize, not making any changes simply for the sake of maintainability, because the risk of introducing bugs is just too large. And when you stop making changes because of maintainability, your code has slowly started to degrade.
      Don't refactor the day before a release.
      refactoring requires automatic tests
      resources
      B1
      B4
    5. Refactor!
      http://www.devexpress.com/Products/Visual_Studio_Add-in/Refactoring/
      resources
      B4
    6. Inline Singleton
      resources
      B4
    7. Extract Method
      resources
      B4
    8. Consolidate Conditional Expression
      resources
      B4
    9. code smell
      resources
      B4
      1. Duplicated Code
        resources
        B4
      2. base class methods
        the subclass is responsible for calling up to the base class at certain points in the execution of the Execute() method. I think that's too loose a contract for the subclass; the developer of the subclass has to remember to add those calls and to do it at the right places
        can be avoided through template method
        resources
        B4

 

You can find the entire list of techniques in progress in the Development base concepts category. Please feel free to leave any comments or suggestions which could make these lists more useful for everyone.

Also, if you are interested in learning these skills you can try the Developer training modules.

 

 

 

Enjoy programming!

 

Layering concepts

by andrei 19. September 2008 20:01

You can read about the purpose of this list and how to use it here.
Also, the list of resources is here.

 

  1. general implementation
    E1
    E2
    B3
  2. concepts
    1. the observer pattern
      used when an object of a lower level needs to communicate upward (beyond answering a direct query)
    2. structure
      the namespace pattern that will be used is always SmartCA.<Layer Name> . There will be cases where an extra project may be required even though it still belongs in one of the four layers. Usually, this happens in the Infrastructure layer, where you may be implementing some functionality that needs to be separated from the rest of the Infrastructure project. In that particular case, the naming standard that I will follow is SmartCA. < Layer Name > . < Some other functionality name > . An example is a project with a name and namespace combination of SmartCA.Infrastructure.Caching . These types of projects can be added later if and when they are needed.
      resources
      B3
    3. smart UI Antipattern
      Put all the business logic into the user interface. Chop the application into small functions and implement them as separate user interfaces, embedding the business rules into them.
      resources
      B1
      B3
    4. service
      each layer offers its own services: for example, the application and domain layers call on the SERVICES provided by the infrastructure layer
      A Service class has no internal state and can simply act as an interface implementation that provides
      operations. This concept is very similar to web services. Services typically coordinate the work of one or
      more domain objects, and present the coordination as a well - known operation. It is also important to
      note that some services may live in the application layer, some may live in the domain layer, and others
      may live in the infrastructure layer.
      resources
      B1
      B3
    5. Separated Interface pattern
      the interface is defined in a separate assembly from its implementation
      resources
      B3
    6. Presentation layer
      Responsible for showing information to the user and interpreting the user's commands. The external actor might sometimes be another computer system rather than a human user.
      resources
      B1
      B2
      B3
      code & implementation
      E2
      1. forms classes
        code & implementation
        E2
      2. browser classes
        code & implementation
        E2
      3. Presentation Model
        In the simplest case, your Domain Model is already "presentable" and you could just data bind directly to the Domain Model objects. However, the interface of an application frequently demands that information is presented in a more "user friendly" form than it was in the Domain Model.
        The Presentation Model objects are a part of the PL and should have a structure and behavior matching the requirements of the PL (in effect, matching the needs of the UI). In our example, the PM Person class would have a FullName property rather than FirstName and LastName properties found in the Domain Model Person class.
        as soon as the PM is there as well as the supporting infrastructure for Wrapping or Mapping to the Domain Model I usually find plenty of opportunity for refining the presentational aspects of the PM, and soon enough the two models will begin to become more and more different, making it easier and easier to motivate complementing the Domain Model with a PM
        resources
        B4
        1. state
          When making the choice between Mapping and Wrapping, special attention should be paid to the difference in how state is handled in the two approaches.
          When wrapping your Domain Model objects, only one instance of the data is used by the application. If you have two views showing the same employee at the same time, and you update the employee's name in one view, the single instance of the data in the wrapped object is updated. If the second view is then refreshed, it should display the updated data, because it is also mapping directly to the same wrapped, updated object.
          When mapping your PM objects to your Domain Model objects, however, you could potentially have several different sets of PM objects representing the same Domain Model object, but with different state in them.
          resources
          B4
        2. return only PM objects
          Another issue is that you have to remember to return PM objects from PM reference properties. For example, when I read the AssignedToProject property of a PM Employee object, I want a PM Project object back, not a DM Project object. Consider a naïve implementation of a Wrapper object with a reference property as shown in the following
          resources
          B4
        3. relationships
          When we take relationships between the objects into account, the task becomes more difficult again. Object graphs (a group of objects that are all interconnected via relationships) are potentially very large, and if asking the O/O Mapper to fill a PM Employee object from a DM Employee object also results in the filling up of a few hundred related objects, we may have effectively killed performance in our application.
          resources
          B4
        4. flattened PM
          This approach is often very useful, especially because many UI controls are designed for showing tables of rows, and flattened objects adapt well to this paradigm. But whenever you are interested in representing navigable, deep structures rather than just grids of stuff, the flattened approach falls short. However, you may often find yourself complementing a fully partitioned PM with some flat objects specifically written for some grid in your application.
          "Flattened" PM objects provide a good example of how the PM often looks very different from the Domain Model and, of course, the more different they are, the more motivated we are to have two separate models instead of just adding the features needed by the PL to the Domain Model.
          resources
          B4
        5. reference values
          One way of "solving" these issues with reference properties is to simply avoid reference properties in your PM objects, using "flattened" objects instead that expose only primitive properties, quite possibly from referenced objects as well.
          resources
          B4
        6. Identity Mapping in the PM
          In the end, we might want a full-blown solution that could handle Identity Mapping in the PM as well, making sure that there are never two different PM instances representing the very same Domain Model instance around in a session.
          resources
          B4
        7. Inheritance
          This may make it tempting to just go ahead and let the Presentation Model objects inherit from the Domain Model objects instead, overriding whatever properties that need transformation, but leaving all others as they are. The problem with this is that then you are stuck with the public API of the Domain Model, because all public members of a superclass are inherited by the subclass.
          In our example, we could have let the PM Employee inherit from the Domain Model Employee, and we could have added the FullName property to the PM Employee, but the PM Employee would also have exposed the FirstName and LastName properties from the Domain Model Employee, because these public properties would be inherited.
          resources
          B4
        8. mapping vs wrapping
          In some situations, you'll find that wrapping best suits your needs, while mapping works better in other situations. Sometimes you'll use both in the same application, perhaps using wrapping as the default approach but using mapping just for wizards or other "batch jobs" that should be possible to discard without committing.
          The choice between wrapping and mapping is influenced by a number of factors, including how state is managed and the opportunities for reducing the amount of boilerplate code in your applications via code generation (wrapping) or via using an O/O Mapping framework (mapping).
          resources
          B4
        9. Mapping
          The alternative to wrapping your DM objects with your PM objects is to actually copy the data back and forth between the DM objects and the PM objects.
          As with the wrapping example, the code for copying the data could be placed in the constructor of the PM object, in which case the constructor would accept the DM object in a parameter
          resources
          B4
          1. O/O Mapper framework
            resources
            B4
        10. Wrapping
          Wrapping is often the easier solution, requiring no additional framework for state management in the PM. The idea here is that you pass the DM Employee object to the constructor method of the PM Employee object. The PM Employee then keeps an internal reference to the DM object and delegates all calls to the DM properties.
          Wrapping your Domain Model objects rather than inheriting from them gives a higher level of encapsulation that is usually well worth the extra, admittedly tedious, work of delegating between PM and Domain Model properties.
          resources
          B4
    7. onion architecture
    8. layered architecture
      factor out responsibilities into separate cohesive units (clusters of classes) and define the dependencies between those units
      each layer specializes in a particular aspect of a computer program
      resources
      B1
      B2
      B3
      code & implementation
      E1
      E2
    9. Infrastructure layer
      Provides generic technical capabilities that support the higher layers: message sending for the application, persistence for the domain, drawing widgets for the UI, and so on. The infrastructure layer may also support the pattern of interactions between the four layers through an architectural framework.
      Some technical components are designed to directly support the basic functions of other layers (such as providing an abstract base class for all domain objects) and provide the mechanisms for them to relate (such as implementations of MVC and the like).
      Any type of framework, data access code, calls to web service calls, and so forth will live in this layer. For example, the Repository Framework implementation
      instead of all calls going down, the Infrastructure layer might "know" about the Domain layer and might create instances there when reconstituting from persistence
      resources
      B1
      B2
      B3
      B4
      E14
      code & implementation
      E2
    10. factory
      factories can be useful in any layer
      code & implementation
      E1
      E2
    11. Domain layer
      Responsible for representing concepts of the business, information about the business situation, and business rules. State that reflects the business situation is controlled and used here, even though the technical details of storing it are delegated to the infrastructure.
      the Domain Model should be oblivious of the infrastructure
      resources
      B1
      B2
      B3
      B4
      code & implementation
      E1
      E2
    12. Decoupling layers, separation of concerns
      Creating programs that can handle very complex tasks calls for separation of concerns, allowing concentration on different parts of the design in isolation
      resources
      B1
      B2
    13. Decoupling from the database
    14. command pattern
      code & implementation
      E2
    15. Application layer
      Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.
      approach the application layer as an application programming interface (API), or almost
      a façade, to the domain model.
      providing some coordination, but it's very thin, only delegating to the Domain layer
      Service Layer pattern
      isn't mandatory; it is only there if it really adds value
      resources
      B1
      B2
      B3
      B4
      code & implementation
      E2

 

You can find the entire list of techniques in progress in the Development base concepts category. Please feel free to leave any comments or suggestions which could make these lists more useful for everyone.

Also, if you are interested in learning these skills you can try the Developer training modules.

 

Technorati Tags: ,,

 

 

Enjoy programming!

 

Concept lists resources

by andrei 19. September 2008 19:58

This is the list of resources from which I extracted the lists of concepts

I think these resources are very useful, but they are only a few from the many available. If you don't have a particular book for example, just Google for the concepts and you will find loads of information.

But keep in mind two important things: books are best for building the theoretical foundation when learning something new, and reading open source code is a very good method for learning how to apply what you learn in theory.

 

  1. Code & Implementation
    E1
    .NET Domain-Driven Design with C#: Problem - Design - Solution, by Tim McCarthy
    http://www.wrox.com/WileyCDA/WroxTitle/-NET-Domain-Driven-Design-with-C-Problem-Design-Solution.productCd-0470147563,descCd-DOWNLOAD.html
    E2
    Jean-Paul S. Boodhoo's NothinButDotNetStore
    http://code.google.com/p/jpboodhoo
    E3
    http://domaindrivendesign.org/examplecode/index.html
    E4
    Domain-Driven Design: Tackling Complexity in the Heart of Software, By Eric Evans
    Chapter Seven. Using the Language: An Extended Example
    E5
    Domain-Driven Design: Tackling Complexity in the Heart of Software, By Eric Evans
    Angles of Attack
    E6
    .NET Domain-Driven Design with C#: Problem - Design - Solution, by Tim McCarthy
    Chapter 3: Managing Projects
    E7
    .NET Domain-Driven Design with C#: Problem - Design - Solution, by Tim McCarthy
    Chapter 4: Companies and Contacts
    E8
    Applying Domain-Driven Design and Patterns: With Examples in C# and .NET
    Chapter 3. TDD and Refactoring
    Test-Driven Development (TDD)
    E9
    Applying Domain-Driven Design and Patterns: With Examples in C# and .NET
    Chapter 3. TDD and Refactoring
    Refactoring
    E10
    Applying Domain-Driven Design and Patterns: With Examples in C# and .NET
    Chapter 4. A New Default Architecture
    A First Sketch
    E11
    Applying Domain-Driven Design and Patterns: With Examples in C# and .NET
    Chapter 5. Moving Further with Domain-Driven Design
    Refining the Domain Model Through Simple TDD Experimentation
    E12
    Applying Domain-Driven Design and Patterns: With Examples in C# and .NET
    Chapter 6. Preparing for Infrastructure
    Let's Build the Fake Mechanism
    E13
    Applying Domain-Driven Design and Patterns: With Examples in C# and .NET
    Chapter 7. Let the Rules Rule
    E14
    Applying Domain-Driven Design and Patterns: With Examples in C# and .NET
    Chapter 8. Infrastructure for Persistence
    E15
    Applying Domain-Driven Design and Patterns: With Examples in C# and .NET
    Chapter 10. Design Techniques to Embrace
    Aspect-Oriented Programming (AOP)
    E16
    Applying Domain-Driven Design and Patterns: With Examples in C# and .NET
    Chapter 11. Focus on the UI
    The Model-View-Controller Pattern
    E17
    Applying Domain-Driven Design and Patterns: With Examples in C# and .NET
    Appendix A. Other Domain Model Styles
    E18
    Applying Domain-Driven Design and Patterns: With Examples in C# and .NET
    Appendix B. Catalog of Discussed Patterns
  2. Books
    B1
    Domain-Driven Design: Tackling Complexity in the Heart of Software, By Eric Evans
    B2
    Martin Fowler - Patterns of Enterprise Application Architecture
    B3
    .NET Domain-Driven Design with C#: Problem - Design - Solution, by Tim McCarthy
    B4
    Applying Domain-Driven Design and Patterns: With Examples in C# and .NET, By Jimmy Nilsson
  3. Articles
    A1
    http://en.wikipedia.org/wiki/Invariant_(computer_science)
    http://en.wikipedia.org/wiki/Class_invariant
    A2
    http://martinfowler.com/articles/mocksArentStubs.html
  4. Akcedo training modules
    M1
    Layering
    M2
    DDD1
    M3
    DDD2

 

You can find the entire list of techniques in progress in the Development base concepts category. Please feel free to leave any comments or suggestions which could make these lists more useful for everyone.

Also, if you are interested in learning these skills you can try the Developer training modules.

 

Technorati Tags: ,,

 

 

Enjoy programming!

 

About the concept lists

by andrei 19. September 2008 19:47

For a long time now, I tried many ways of organizing the information that I learn.

 

I discovered that I almost never have to write the details, because even if I write them somewhere I almost never get back and use them. Especially if you are a developer, Google does a great job of finding anything for you. That is, if you know what to look for.

So the trick is to know the concepts or keywords that you need to learn more about. This is somehow related to the concept of mind-maps, which represent a very useful tool.

 

In these lists I am trying to extract the concepts from the programming resources that I study. I am using the lists while I work, to find solutions or help me generate ideas. And so can you.

Also, in time they can become guidelines for anyone trying to learn more about .Net programming. Starting from the list, you can search over the Web and find out about all the important things that you need to know.

 

You can find the entire list of techniques in progress in the Development base concepts category. Please feel free to leave any comments or suggestions which could make these lists more useful for everyone.

Also, if you are interested in learning these skills you can try the Developer training modules.

 

 

Enjoy programming!

 

Cheat sheets

by andrei 11. September 2008 09:54

Cheat sheets and reference cards are quite useful: they can quickly offer essential pointers in the right direction, with very little time invested. Even if you don't use something like this during development, just reading a cheat sheet (related to a technology that interests you) can be a valuable experience.

Here are a few good ones:

and some more detailed lists:

 

 

Enjoy programming!

 

Enterprise concepts

by andrei 17. August 2008 22:35

You can read about the purpose of this list and how to use it here.
Also, the list of resources is here.

 

  1. general implementation
    E1
    E2
    B1
    B2
    B3
  2. concepts
    1. SOA
      an introduction to Service Oriented Architecture (SOA) that Udi Dahan has written
      resources
      B4
    2. partition
      Two possible partitions might be the subsystem for registering orders and the subsystem for administering user complaints. Both partitions might have a UI and a Domain Model.
      I think that first it's a matter of partitions, and then inside those partitions it's a question of layers, not the opposite
      resources
      B4
    3. indirection
      most problems in coding can be solved with another layer of indirection
      resources
      B4
    4. CRUD
      basic object life cycle states
      create, read, update, and delete
    5. persistence abstraction layer
      Thanks to that abstraction layer, I can move the Repositories back to the Domain Model, and I only need one Repository implementation per Aggregate root. The same Repository can work both against an O/R Mapper and against a Fake that won't persist to a database but only hold in memory hashtables of the instances, but with similar semantics as in the O/R Mapper-case.
      It's still a stretch to talk about PI Repositories, but with this solution I can avoid a reference to the infrastructure in the Domain Model. That said, in real-world applications I have kept the Repositories in a separate assembly anyway
      resources
      B3
      B4
      code & implementation
      E12
      1. delete
        the Delete() is quite interesting because it requires an Identity Map of its own for the Fake in the Unit of Work. Instances that have been registered for deletion will be held there until PersistAll(), when the deletion is done permanently.
        resources
        E12
      2. identity map
        The fake implementation uses two layers of Identity Maps
        The MakePersistent() is pretty simple; the instance is just associated with the first layer of Identity Maps. And when it's time for PersistAll(), all instances in the first layer are copied to the second layer. Simple and clean.
        resources
        B3
        B4
        code & implementation
        E12
    6. Snapshot pattern
      resources
      B4
    7. Identity Map pattern
      The idea with Identity Map is that you will not have two separate instances for a single customer. The Identity Map will take care of that for you.
      The language itself, C# for example, won't take care of this for you.
      resources
      B4
    8. Identity Field
      Saves a database ID field in an object to maintain identity between an in-memory object and a database row.
      Identity Field means a field that binds the row in the database to the instance in the Domain Model
      The simplistic solution I've adopted is to assume a property (or field) called Id. If the developer of the Domain Model has used another convention, it could be described to the Fake at instantiation of the FakeWorkspace.
      resources
      B4
    9. Web
      1. url creation, routing handling & validation
        code & implementation
        E2
      2. requestcontext from httpcontext
        code & implementation
        E2
      3. query string handling
        code & implementation
        E2
      4. namevaluecollection handling
        code & implementation
        E2
    10. UnitOfWork
      maintains a list of objects affected by a business transaction and coordinates the writing out of changes
      and the resolution of concurrency problems.
      I want to be able to do a lot of stuff to several different instances, and then persist all the work with a single call such as PersistAll().
      see the Unit of Work as something belonging to the consumer of the Domain Model (that is the Application layer or the presentation layer) rather than the Domain Model itself
      resources
      B3
      B4
      code & implementation
      B3
      B4
      E12
      1. Identity Map
        Unit of Work and Identity Map together over and over again. It's such a common combination, not only in my text, but in products as well. For example, there is Persistence Manager in JDO Jordan/Russell JDO and Session in Hibernate
        resources
        B4
      2. aggregate
        I expect it to be enough to associate the Aggregate root with the Unit of Work, the instances that are part of the Aggregate and that the Aggregate root reaches will get persisted to the database as well when we say PersistAll().
        Aggregates "should" be designed so that they are in a consistent state at PersistAll() time.
        resources
        B3
        B4
        code & implementation
        B3
      3. repository
        the Repository was fed with the _ws at instantiation time. In this way, I can control the Repositories that should participate in the same Unit of Work and those that should be isolated in another Unit of Work
        resources
        B3
        B4
        code & implementation
        B3
      4. keeping track
        I mentioned saving data previously. AddOrder() isn't really saving; it just adds the Order to the Repository. Or should it mean saving also? No, I don't think I want that behavior. What I want from AddOrder() is that the Repository (and the underlying infrastructure) from that point should know about the instance and deal with it when I ask for a PersistAll().
        the Add() call in notifying the Unit of Work that there is a new instance for persisting at next PersistAll() call
        resources
        B3
        B4
        code & implementation
        B3
      5. transactions
        Another thing that might be a problem is that when the Repository hid the Unit of Work it probably meant that there were two database transactions
        PersistAll() internally does all its work in an explicit transaction, even though you explicitly didn't ask for it
        I prefer to control the start and end of the unit of work in the consumer, outside of the repositories
        resources
        B3
        B4
        code & implementation
        B3
      6. synchronization
        a scenario should just have one Unit of Work and one Identity Map
        The reasoning for not letting the repositories completely hide the Unit of Work was that he
        wanted to synchronize changes across several Aggregates (and their respective repositories) in a single logical
        unit. In order for this to work, the repositories need to have a Unit of Work injected into them at creation time.
        I also chose to control save or not save (PersistAll()) outside of the Repositories. In this particular example, I could just as well have had PersistAll() directly on the CustomerRepository, but I chose not to. I often find that I want to synchronize changes to several Aggregates (and therefore also to several different Repositories) in a single logical unit, and that's the reason
        resources
        B3
        B4
        code & implementation
        B3
    11. UI strings handling
      code & implementation
      E2
    12. tracing
      As we just discussed, it's nice to be able to listen to what is going on at the same time as users run scenarios in the system. This is not only a very efficient solution for tracking down bugs, but it can be used for investigating where the bottlenecks are located, for example.
      If you have the possibility of using Aspect-Oriented Programming (AOP), it might not take more than a few minutes to add tracing afterward.
      resources
      B4
    13. System Metaphor
      When a concrete analogy to the system emerges that captures the imagination of team members and seems to lead thinking in a useful direction, adopt it as a large-scale structure. Organize the design around this metaphor and absorb it into the UBIQUITOUS LANGUAGE.
      resources
      B1
    14. string db queries handling
      code & implementation
      E1
      E2
    15. service locator
      means that a class internally locates its concrete collaborators through the dependency on another object (the locator). A simple example of a locator could be a factory object that uses a configuration file to load the required collaborators dynamically.
      resources
      B4
    16. Service Layer pattern
      scenario classes, delegating all the work to the Domain Model
      resources
      B4
    17. serialization
      As you might expect, the Serializer class contains two methods, Serialize and Deserialize .
      resources
      B3
      code & implementation
      B3
    18. Query Object
      The idea of the Query Object pattern is to encapsulate the criteria in a Query instance and then send that Query instance to another layer where it is translated into the required SQL.
      encapsulate queries as objects, providing object-oriented syntax for working with the queries
      we might use a Query Object, for example, inside the Repository
      resources
      B4
      1. complexity
        when the queries get complex, it's often more powerful to be able to write the queries in, for example, a string-based language similar to SQL
        resources
        B4
      2. In the Domain Model
        The consumer still gets the power of queries to be used for sending to Repositories, for example, but with a highly intuitive and typesafe API.
        //Consumer code
        CustomerQuery q = new CustomerQuery();
        q.Name.Eq("Volvo");
        resources
        B4
        1. specification
          similar to creating type safe Domain Model-specific queries, but it goes a step further because it's not generic querying that we are after, but very specific querying, based on domain-specific concepts
          resources
          B4
        2. aggregate
          Each of your Aggregates is a typical candidate for having Query Object in the Domain Model. Of course, you could also go the XP route of creating them when needed for the first time
          resources
          B4
      3. In Consumers of Repositories
        In the second case, the queries are set up in the consumers of the Repositories and sent to the Repositories as parameters. This is typically used in cases of highly flexible queries, such as when the user can choose to fill in any fields in a large filtering form. One such typical method on a Repository could be named GetCustomersByFilter(), and it takes an IQuery as parameter.
        resources
        B4
      4. In Repositories
        Probably the most common place to set up queries is in the Repositories. Then the queries become the tool for fulfilling method requests, such as GetCustomersByName() and GetUndeliveredOrders(). That is, the consumer might send parameters to the methods, but those are just ordinary types and not Query Objects.
        resources
        B4
      5. Querying and the Cache
        the GetByQuery() won't investigate the Identity Map before hitting persistence
        The reason is partly that we want to use the power of the backend, but above all that we don't know if we have all the necessary information in the Identity Map (or cache if you will) for fulfilling the query. To find out if we have that, we need to hit the database. This brings us to another problem. GetById() starts with the Identity Map; GetByQuery() does not. This is totally different behavior, and it actually means that GetByQuery() bypasses the cache, which is problematic. If you ask for the new Customer Volvo that has been added to the Identity Map/Unit of Work, but has not been persisted, it will be found if you ask by ID but not when you ask by name with a query.
        To tell you the truth, it was a painful decision, but I decided to let GetByQuery() do an implicit PersistAll() by default before going to the database.
        resources
        B4
    19. Pluggable Component Framework
      Distill an ABSTRACT CORE of interfaces and interactions and create a framework that allows diverse implementations of those interfaces to be freely substituted. Likewise, allow any application to use those components, so long as it operates strictly through the interfaces of the ABSTRACT CORE.
      resources
      B1
    20. performance monitoring
      Getting performance monitoring based on Domain Model information and other parts of your application is extremely helpful for tracking down problems, but also for keeping a proactive eye on the system. By doing that, you can easily track that it now takes perhaps 30% longer to execute a certain scenario compared to a time two months ago.
      B4
    21. MVP
      Even though the MVC pattern formally states that the Controller should receive the events and act upon the View, it is often more practical to have the View subscribe to the events and then delegate the handling onto the Controller.
      resources
      B4
      E16
    22. MVC
      The grandfather of patterns for connecting the UI to the application and domain layers is MODEL-VIEW-CONTROLLER
      The intent of the Model-View-Controller pattern (MVC) is to break UI behavior up into separate pieces in order to increase reuse possibilities and testability. The three pieces are the View, the Model, and the Controller.
      The key benefit of applying the MVC pattern is that it makes your UI code testable. Secondarily, it forces a very structured approach onto the coding/design process of the UI, which may in itself cause cleaner code in the end. You're forced to think a little more, so to speak.
      resources
      B4
      E16
      1. Combining Views/Controllers
        More complex Views are often made up of multiple smaller Views. Examples are wizards where the user navigates through a bunch of Views through next and previous buttons or maybe even jump back and forth several steps at a time. Information might be saved along the way, but it does not really get committed until the user clicks Save on the final screen.
        Another example is Master/Details Views where changes made to the details View might cause changes in the Master View as well.
        we could have a FlowController that controls the basic flow back and forth through the wizard, and each step could have its own View and Controller.
        In the Master/Detail, we might have the Controller for the Detail View raise an event on changes. Any other Controller could then subscribe to this event, including the Controller for the Master View.
        resources
        B4
        E16
      2. Decouple the Controller from the View
        the advantage of decoupling the Controller from the View is that we can vary the Controller behind the View. This can be very useful when a View can show up in a lot of different contexts, and it might not make sense to always have to enforce a particular Controller to go along with it.
        A simple solution is to create an interface for the Controller and have the View know about that only and not the actual implementation. A more complex way is to have Views raise events to anonymous subscribers (Observer pattern GoF Design Patterns). I'm not a big fan of this approach as I cannot imagine why one View would need to communicate user interactions to multiple subscriberslet alone subscribers of unknown types
        resources
        B4
        E16
      3. Adapters
        you might end up with very large interfaces if you have 10 input boxes and you need to be able to control the visibility, enabled, font, back color, fore color, border style, and so on of each of them.
        you can create an Adapter/Wrapper for each type of UI control you use. The Adapter for a TextBox could expose the mentioned properties, and the View interface would then only have to expose one property of the TextBoxAdapter data type for each textbox. Behind the scenes, the View would then provide references to the real UI controls to each Adapter during instantiation and the Adapter would simply delegate the call it receives to the actual implementation.
        resources
        B4
        E16
      4. controller
        Finally, the Controller, which is really the heart of the MVC, is the glue that ties the Model and the View together. The Controller receives messages when the user interacts with the View, translates those messages into actions that are performed on the underlying Model, and then updates the View accordingly.
        resources
        B4
        E16
      5. view
        The View should consist only of logic directly related to "painting the pixels on the screen." Keeping the View as "dumb as possible" is often the major design objective when applying MVC. The rationale is that Views/Screens in practice require a human eye to be tested. This is an error prone and costly process compared to automated unit tests.
        resources
        B4
        E16
    23. Model - View - ViewModel
      take a pure Model, create an abstract view that contained state, and data bind a View created with a visual designer to that abstract view.
      resources
      B3
      code & implementation
      B3
    24. messages (in layer and between layers)
      resources
      B3
      code & implementation
      B3
    25. logging
      Errors, warnings, and information messages must be logged. This is extremely important for investigating problems after they have occurred. We can't expect the users to write down the exact messages for us. It might also be that we want to collect information that we don't want to show to the users.
      resources
      B4
      code & implementation
      E2
      1. logging fwk
        code & implementation
        E2
      2. log4net
        http://logging.apache.org/log4net/index.html
        code & implementation
        E2
    26. Lazy Load
      The first solution that springs to mind is probably to add a TotalCredit property on the Customer. But this is problematic because it's then a bit too transparent, so that the consumer sees no cost at calling the property.
      Lazy Loading is an optimization technique and not something you have to use all the time
      resources
      B4
    27. large-scale structure
      Devise a pattern of rules or roles and relationships that will span the entire system and that allows some understanding of each part's place in the whole—even without detailed knowledge of the part's responsibility.
      Large-scale structure should be applied when a structure can be found that greatly clarifies the system without forcing unnatural constraints on model development.
      resources
      B1
    28. IoC & DI
      Dependency Injection, suggests that a class explicitly declares the interfaces of its collaborators (for example, in the constructor or as parameters in a method) but leaves the responsibility for the creation of their concrete implementation to the container. Because the class is not in control of the creation of its collaborators anymore, this principle is also known as Inversion of Control.
      makes the object that has the dependencies passive. The object declares its dependencies but is otherwise completely oblivious as to where the dependencies come from. The process for resolving the dependencies and finding the dependent objects is left to an external mechanism, which may be implemented in a variety of ways.
      IoC is not a pattern but a general principle that simply states that objects should rely on their environment to provide other objects rather than actively obtaining them
      we recognize the setter- and constructor-based approaches implemented by these containers as a concrete pattern and use the more specific name Dependency Injection for it
      distinguish between the Dependency Injection pattern and other types of IoC
      resources
      B4
      code & implementation
      E2
      1. Nested Containers
        When a container cannot satisfy all dependencies required to create a component, it tries to obtain the missing components from its parent container, which in turn can request components from its own parent container. This set-up broadly resembles the Chain of Responsibility design pattern
        In our application, a container is associated with the application. Additionally, each session has a child container, and for each request in a session, a child container of the corresponding session container is created.
        resources
        B4
      2. Castle Windsor
        resources
        B4
      3. Pico Container
        resources
        B4
      4. Spring .Net
        resources
        B4
      5. Contextualized Dependency Lookup
        A widely used pattern that adheres to the IoC principle but is not a Dependency Injection variant is Contextualized Dependency Lookup
        resources
        B4
      6. Setter Dependency Injection
        resources
        B4
      7. optional dependencies
        With constructor dependency injection, we express this by providing two constructors, one for each valid set of dependencies.
        It would also be possible to use a constructor with all arguments and pass in null for the optional ones, but this makes the contract less explicit, especially when the number of dependencies increases. It is therefore advisable to always provide one constructor for each valid set of dependencies and, if possible, to chain the constructors. If this seems impossible, it is probable that the class in question has too many dependencies and should be broken up.
        resources
        B4
      8. Constructor Dependency
      9. IoC & DI framework
        code & implementation
        E2
      10. Service Locator pattern
        The curve objects we are using in this example are data sources, but it is easy to see that we can use the same patterns to locate services providing objects (for example, an audit service that writes the calculated price to a log). Used in this way, the pattern is often referred to as Service Locator
        Using a Service Locator, we register a concrete curve implementation with the locator under a name, most likely the name of the interface. With this setup, our bond pricer can now get hold of the discount curve by asking the locator for one.
        resources
        B4
      11. Registry pattern
        In a further step toward complete decoupling, we can replace the factory with an implementation of the Registry pattern
        a registry provides objects of a given type but rather than hard-coding the type of object, it externalizes this decision and instantiates the objects using reflection
        The implementation of such a registry is simple but effective and finally achieves our goal of decoupling BondPricer from a concrete implementation of IDiscountCurve.
        resources
        B4
    29. instantiation based on configuration
      resources
      B3
      code & implementation
      B3
    30. Front Controller
      code & implementation
      E2
    31. evolving order
      Many developers have experienced the cost of an unstructured design. To avoid anarchy, projects impose architectures that constrain development in various ways. Some technical architectures do solve technical problems, such as networking or data persistence, but when architectures start venturing into the arena of the application and domain model, they can create problems of their own.
      resources
      B1
    32. efficiency
      The greatest value I've seen delivered has been when a narrowly scoped framework automates a particularly tedious and error-prone aspect of the design, such as persistence and object-relational mapping. The best of these unburden developers of drudge work while leaving them complete freedom to design.
      So you have to fight the temptation to build frameworks and regiment the implementation of the large-scale structure. The most important contribution of the large-scale structure is conceptual coherence, and giving insight into the domain. Each structural rule should make development easier.
      resources
      B1
    33. dto
      resources
      B3
      code & implementation
      E1
      E2
      1. data contract
        It is basically a Data Transfer Object (DTO) used to get data back and forth from the client to the server. All of the Data
        Contract classes are nothing but data, that is, they contain just a bunch of property setters and getters.
        Their main purpose in life is to be serialized and sent across the wire and then deserialized on the
        receiving end of the wire.
        resources
        B3
        code & implementation
        B3
      2. converter & mapper
        For every class in the domain model, there is an equivalent Data Contract class, and,
        for each set of classes, there is a ToEntity Name method and a ToEntity NameContract method.
        The ToEntity method assumes that the naming is consistent in the Converter class, and uses reflection
        to call the right method to convert a ContractBase instance to an IEntity instance.
        resources
        B3
        code & implementation
        E1
        E2
        1. mapper fwk
          code & implementation
          E2
    34. distribution
      First Law of Distributed Object Design, which is "Don't distribute" Fowler PoEAA. If you absolutely don't have to, don't do it
      resources
      B4
    35. db field names handling & mapping db tables
      code & implementation
      E1
      E2
    36. dates & times
      The next interesting bit of logic is the conversion of all of
      the DateTime argument values to Universal Time. Doing this allows the Client Membership system to
      standardize on one time zone for users who may be working around the country or the world.
      resources
      B3
      code & implementation
      B3
    37. database access
      resources
      B4
    38. configuration
      Have you had to recompile old applications just because the database server was switched to a new machine with a new name? I have. Of course, that kind of information should be configurable and depending on the application, this might be the case for loads of information.
      B4
      1. application configuration files handling
        code & implementation
        E2
    39. caching
      We should try to cache read-only data as much as possible.
      Caching is just as cool and useful as it is dangerous. Watch out, it can backfire.
      resources
      B4
    40. auditing
      As one part of the security aspects, it's important to have auditing so that it's possible to check afterwards who did what when.
      B4
    41. async messaging
      resources
      B3
      code & implementation
      B3
      1. client - server sync
        how to synchronize the client's offline data with the server
        make the synchronization a business - level process rather than a data - level
        process
        resources
        B3
        code & implementation
        B3
      2. batch jobs
        A more efficient solution to the problem would be to think asynchronous messages from the start as often as possible. The batch solution would be kind of built in from the beginning
        resources
        B4

 

You can find the entire list of techniques in progress in the Development base concepts category. Please feel free to leave any comments or suggestions which could make these lists more useful for everyone.

Also, if you are interested in learning these skills you can try the Developer training modules.

 

 

 

Enjoy programming!

 

OOP Concepts

by andrei 16. August 2008 14:53

You can read about the purpose of this list and how to use it here.
Also, the list of resources is here.

 

  1. general implementation
    E1
    E2
  2. concepts
    1. AOP
      What AOP promises to do for you is to allow you to separate crosscutting code, such as logging or security, into aspects and to apply those aspects easily to all the classes and methods that need them.
      It also allows you to separate business rules from the core logic and to change your existing objects by adding both state and behavior to them.
      itwith only three lines of code you have applied the logging advice to all the methods of the Calculator instance and obtained a reference to it. You can now call any method on it, and you will see that the calls are properly logged.
      resources
      B4
      E15
      1. Moving Business Rules into Aspects
        The best candidates are rules that cause secondary logic to be implemented along with the core logic.
        While you could argue that the minimum balance check should remain in the Account class, it is obvious that the notification sending code is not the primary functionality of the Withdraw() method
        resources
        B4
      2. object locking
        combination of introduction and before advice to implement and enforce object locking
        resources
        B4
      3. Adding State and Behavior
        leverage AOP features and declaratively add locking support only to the classes that need it. This can be easily accomplished using a combination of introduction and before advice.
        resources
        B4
      4. logging
        we can leverage AOP to solve the problems associated with the previous logging code
        resources
        B4
      5. spring .net
        www.springframework.net
      6. aspect
        An aspect groups advices and the pointcuts they apply to, which is in a way similar to how a class groups data and associated behavior together.
        resources
        B4
      7. pointcut
        A pointcut identifies a set of joinpoints where advice should be applied. For example, if you want to apply transaction advice to all the methods that are marked with transaction attribute, you would have to declare a pointcut that identifies those methods.
        resources
        B4
      8. joinpoint
        A joinpoint is any place in the code where an advice could be applied. In theory, a joinpoint could be almost anythinginstance variable, for loop, if statement, and so on. In practice, however, most commonly used join-points are classes, methods, and properties.
        resources
        B4
      9. introduction
        An introduction is a somewhat special type of advice that only applies to classes. Introductions allow you to introduce new members into existing classes, both state and behavior, and could be used to achieve the benefits of multiple inheritance in languages that do not support it, without its tradeoffs. (Introduction is called mixin in some languages.)
        resources
        B4
      10. advice
        An advice is a piece of code that you want to encapsulate and reuse. For example, logging code would be implemented as an advice and applied wherever you need it. There are several types of advice, such as before, after, and around advice.
        resources
        B4
    2. Fluent Interface
      resources
      B4
    3. visitor
      code & implementation
      E2
      1. visitor framework
        code & implementation
        E2
    4. Template Method pattern
      you define the overall algorithm, or template method, in a base class
      the subclasses can inherit from TotalBase and provide a custom implementation of the VariationPoint() method
      resources
      B3
      B4
      code & implementation
      B3
    5. state pattern
      The idea is to encapsulate the different states as individual classes (see ConcreteStateA and ConcreteStateB). Those concrete state classes inherit from an abstract State class. Context has a state instance as a field and calls Handle() of the state instance when Context gets a Request() call. Handle() has different implementations for the different state classes.
      As we specified, orders have an acceptance status. Therefore, I just add a method called Accept(). I leave the decision about whether or not to internally use the State pattern for later. It is better to make implementation decisions like this during refactoring.
      resources
      B4
      code & implementation
      B4
    6. standalone class
      A STANDALONE CLASS is an extreme of low coupling.
      In an important subset, the number of dependencies can be reduced to zero, resulting in a class that can be fully understood all by itself, along with a few primitives and basic library concepts.
      Low coupling is fundamental to object design. When you can, go all the way. Eliminate all other concepts from the picture. Then the class will be completely self-contained and can be studied and understood alone.
      Try to factor the most intricate computations into STANDALONE CLASSES, perhaps by modeling VALUE OBJECTS held by the more connected classes.
      resources
      B1
    7. singleton
      More and more often the Singleton pattern is considered a worst practice. The reason for that is you create global instances, which are often a problem in themselves. Another problem is that singletons often make the tests harder to write (remember, testability is crucial), and the interaction with the singletons isn't very clear in the code.
      Dependency Injection will gracefully reduce the problem of too many singletons
      resources
      B4
    8. Single Responsibility Principle (SRP)
      An item such as a class should just have one responsibility and solve that responsibility well. If a class is responsible both for presentation and data access, that's a good example of a class breaking SRP.
      B4
    9. Separated Interface Pattern
      Again, just like with the Repository interfaces and the RepositoryFactory , by using the combination
      of interface and Factory, it allows me to implement the Separated Interface Pattern (Fowler). In other
      words, I can keep the interface separate from the implementation and yet still create instances of the
      interface and use those instances without even knowing what they are.
      resources
      B3
      code & implementation
      B3
    10. responsibility-driven design
    11. public field vs property
      I used to hate them myself, but I have since changed my mind. As long as the fields are both readable and writable and no interception is needed when reading or writing the values, the public fields are at least as good as properties. The good thing is that they are simpler; the bad thing is if you need to intercept when one of the values is set.
      public properties can't be used as ref arguments, but that's possible with public fields.
      resources
      B4
    12. patterns
      A design pattern should be applied only when it is needed.
      the way to most often use patterns isn't to use them in up-front design, but to refactor toward or to patterns
      resources
      B1
      B4
      1. list of patterns
        resources
        E18
    13. operations
      Operations can be broadly divided into two categories, commands and queries
      resources
      B1
      1. value object
        apart from initializers called only during creation, all their operations are functions
        value objects are safer to use and easier to test
        After completing the refactoring to separate modification from querying, consider a second refactoring to move the responsibility for the complex calculations into a VALUE OBJECT. The side effect often can be completely eliminated by deriving a VALUE OBJECT instead of changing existing state, or by moving the entire responsibility into a VALUE OBJECT.
        contain either just data or just behavior. The ones that contain only data are also known as Data Transfer Objects (DTOs)
        When we go for a Value Object pattern, it might feel obvious that we should use a struct in .NET instead of a class, but there are recommendations for size regarding when to use a struct and when not to, and you'll get more problems with infrastructure when it comes to structs. It's also the case that you will see more boxing when using structs, so the decision isn't clear-cut. I'm actually leaning to using classes, but most often I'm making them immutable. If you go that route, you need to use all the values of the class for when you are overriding the Equals().
        resources
        B1
        B3
        B4
      2. side-effect free function
        Complex logic can be done safely in SIDE-EFFECT-FREE FUNCTIONS
        resources
        B1
      3. side effect
        any effect on the state of the system. Elements of a complex design interact in other ways that are likely to produce unpredictability. The use of the term side effect underlines the inevitability of that interaction.
        resources
        B1
      4. separation
        An operation that mixes logic or calculations with state change should be refactored into two separate operations
        resources
        B1
      5. query
        Queries obtain information from the system, possibly by simply accessing data in a variable, possibly performing a calculation based on that data.
        resources
        B1
      6. predictability
        Interactions of multiple rules or compositions of calculations become extremely difficult to predict. The developer calling an operation must understand its implementation and the implementation of all its delegations in order to anticipate the result. The usefulness of any abstraction of interfaces is limited if the developers are forced to pierce the veil. Without safely predictable abstractions, the developers must limit the combinatory explosion, placing a low ceiling on the richness of behavior that is feasible to build.
        you can keep the commands and queries strictly segregated in different operations. Ensure that the methods that cause changes do not return domain data and are kept as simple as possible. Perform all queries and calculations in methods that cause no observable side effects
        Second, there are often alternative models and designs that do not call for an existing object to be modified at all. Instead, a new VALUE OBJECT, representing the result of the computation, is created and returned
        Place as much of the logic of the program as possible into functions, operations that return results with no observable side effects. Strictly segregate commands (methods that result in modifications to observable state) into very simple operations that do not return domain information. Further control side effects by moving complex logic into VALUE OBJECTS when a concept fitting the responsibility presents itself.
        resources
        B1
      7. function
        Operations that return results without producing side effects are called functions. A function can be called multiple times and return the same value each time. A function can call on other functions without worrying about the depth of nesting. Functions are much easier to test than operations that have side effects. For these reasons, functions lower risk.
        resources
        B1
      8. command
        Commands (also known as modifiers) are operations that affect some change to the systems (for a simple example, by setting a variable)
        resources
        B1
      9. automated unit tests
        If ASSERTIONS cannot be coded directly in your programming language, write automated unit tests for them. The test setup puts the preconditions in place; then, after execution, the test checks to see if the post-conditions hold.
        resources
        B1
    14. atomic operations
      resources
      B4
      1. overwriting values