I’ve learnt Ruby in Twenty Minutes

January 17, 2010 Ruby 7 comments

Of course not. There is a lot of interesting stuff in Ruby. But at least I tried that quick list here:
http://www.ruby-lang.org/en/documentation/quickstart/

To print something you just need to write puts keyword.

irb(main):001:0> puts “Andriy said something….”
Andriy said something….
=> nil

You could calculate online:

irb(main):002:0> 750*8.05
=> 6037.5

Lets define method to calculate price of one of the Dell notebooks here in Ukraine if price is in Dollars, but you want to know how much it is in Hryvnas.

irb(main):003:0> def exchange(price)
irb(main):004:1>   puts price*8.05
irb(main):005:1>   end
=> nil

Lets use it:

irb(main):006:0> exchange(750)
6037.5

But Ruby is object-orient language. So here is my Exchanger class and I want to initialize it with exchanging rate:

irb(main):001:0> class Exchanger
irb(main):002:1>   def initialize(rate = 8.05)
irb(main):003:2>     @rate = rate
irb(main):004:2>     end
irb(main):005:1>   def exchange(price)
irb(main):006:2>     puts price*@rate
irb(main):007:2>     end
irb(main):008:1>   end
=> nil

@rate is field of that class. Don’t you see that syntax very sweet? I see.

Next, we will create instance of our class with a bit lower rate. And use that instance of class:

irb(main):009:0> ex = Exchanger.new(8.00)
=> #<Exchanger:0x7dd50fc @rate=8.0>
irb(main):010:0> ex.exchange(750)
6000.0
=> nil

“In Ruby, you can open a class up again and modify it. The changes will be present in any new objects you create and even available in existing objects of that class. “
That is amazing as per me, because you could just write code after you have declaration of your class and change intent of it.

You need to try play with Ruby, that is very sweet language!


7 comments


FlyWeight

January 17, 2010 Design Patterns, Java 10 comments

Imagine that you are developing some gaming software. Your write Web client and on each of response you are parsing entire XML to get your game Units. You have some set of types of Units, for example 50 different animals, but when you parse your XML you can get dozens of instances of the same Unit and few dozens of instances of other Unit.
If User of the game is very passionate gamer, he could send requests very frequently. In this case your application will be creating dozens of instances for each of the Unit. But, your units have some static descriptions. For example, Dragon has Attack, initial Health level, and also you need to keep image of the dragon in the object of Dragon.

This all lead to intensive and not efficient memory usage. How could you share common information for all types of Units without creating instances for each individual Unit?

FLYWEIGHT

1) Simplest way with creating objects each time.

We have base class Unit:
 

public class Unit {
    protected String name;
    protected int health;
    protected String picture;
   
    public void setName(String name) {
    this.name = name;
    }
    public String getName() {
    return name;
    }
    public void setHealth(int health) {
    this.health = health;
    }
    public int getHealth() {
    return health;
    }
    public void setPicture(String picture) {
    this.picture = picture;
    }
    public String getPicture() {
    return picture;
    }
}

 
And two derived – Dog and Dragon. To make those objects more weightfull I added to them picture. In my case that is only very long string.

public class Dog extends Unit{
    public Dog(){
        name = “dog”;
        health = 30;
       
        for(int i = 0; i < 100; ++i)
            picture += “I
don’t want to load actuall image, but if we will be creating a lot of
strings on each of the Unit this could be very resrouce taking
operation.”
;
    }
}


And our parser executes code which looks like:

public class Parser {
    public ArrayList<Unit> parse(){
   
    ArrayList<Unit> result = new ArrayList<Unit>();

    for(int i = 0; i < 150; ++i)
        result.add(new Dragon());
   
    for(int i = 0; i < 600; ++i)
        result.add(new Dog());
   
    System.out.println(“Dogs and Dragons are parsed.”);
   
    return result;
    }
}

We want to create only 150 Dragons and 600 Dogs and this takes 28 Mb of memory.

2) How does FlyWeight work?

Lets introduce UnitsFactory. Responsibility of this factory is to manage creation of the concrete flyweight objects (Dogs and Dragons). It verifies if the object has been already created and in this case it just returns created and if not it creates new one and returns it. See:

public class UnitsFactory {
   
    private static Map<Class, Unit> _units = new WeakHashMap<Class, Unit>();
       
    public static Dog createDog(){
    Class dogClass = Dog.class;
   
    if(! _units.containsKey(dogClass))
        _units.put(dogClass, new Dog());
   
    return (Dog) _units.get(dogClass);
    }
   
    public static Dragon createDragon(){
    Class dragonClass = Dragon.class;
   
    if(! _units.containsKey(dragonClass))
        _units.put(dragonClass, new Dragon());
   
    return (Dragon) _units.get(dragonClass);   
    }
}

Lets take a look on UML diagram of our code:

UnitsFactory corresponds to FlyweightFactory, Unit – for Flyweight. Dog, Dragon corresponds to concrete Flyweights in the GoF FlyWeithgt naming.

Now we will do change to our parser to use Factory and will see how much of memory will it take.
But now we are going to create 1500 Dragons and 60000 Dogs, probably your gamer is quite more quick as you think.

    for(int i = 0; i < 1500; ++i)
        result.add(UnitsFactory.createDragon());
   
    for(int i = 0; i < 60000; ++i)
        result.add(UnitsFactory.createDog());
 

       
And this takes only about 5 Mb of memory:

What have I learned regarding to of Java?
I know that corresponding to C# Dictionary is Map in Java, and there are few concrete maps like on this good picture:

Hope this was a good story!

Go to: My Design Patterns Table 


10 comments


Presentation on DDD for my co-workers

January 17, 2010 Success No comments

Among my goals for this year is to become well-known employee in my company. To accomplish this I’m preparing different presentations and looking for some opportunities once they will appear.

On Thursday I provided presentation for my team workers on Domain-Driven Design.
As per me presentation went well, and I much improved my skills doing presentations. I know this at least because we have surveys to evaluate how the presentation went. And rates there were much higher than last time I did presentation on IoC.

I want to list few things that are flying in my mind after that presentation. They are also some tips to how provide effective presentation. (This is not full list, just associated with this presentation.)

DO

  1. Provide the same presentation to your friend. It is great if you have friend who is working in Software Industry also. Actually we have another blog, where we just fixing which stories we made with short agenda.
  2. Imagine your are providing you presentation right now, try to reproduce what you will be saying in your mind. I did this when way on the way to office.
  3. Improve your presentation with restructuring it to the way it will be easily to speak to it.
  4. Have verbose notes to each slide.
  5. Print your story and have it handy on presentation. Just have. I looked there only once.
  6. I kept attention of my audience with collaborating with it, asking questions.
  7. In the end say that presentation was good. Some people could just believe you :)

DO NOT

  1. Don’t wait for answers long. Collaboration with trainees i great, but if you ask question don’t wait long. Start answering yourself.
  2. Don’t ever make people think that you think that they don’t know something. I did one mistake. I said something like “This could be accomplished with FlyWeight design pattern. Do you know what is it?” then we had a bit of silence. But, I’m sure that many people know that pattern. Maybe I asked not clearly. And my mistake “Nothing bad, if you don’t know, the FlyWeight is…”.

REMEMBER

  1. There always be someone who disliked your presentation, maybe few. Why? Because he/she dislike you, but not your presentation. I can do nothing to such people. Just improve yourself and there will be time they will start to respect it (probably you will not have need in respect from such people).
  2. There are always some pessimists. They always find something that was not really good. Just analyze if their observations make sense, and if yes do the best to fix your issues.
  3. In opposite to those people there will be some who will rate your presentation all with max in a minute you sent survey for feedbacks.


No comments


State

January 16, 2010 Design Patterns, Java 2 comments

Imagine that you need to develop application for shipping Orders. Your Orders could be in few states: New Order, Registered, Granted, Shipped, Invoiced, Cancelled.
And there are some rules which allow your Order to migrate to another state. This means that for example you cannot ship not registered Order.
Also there are some behavioral rules. For example you cannot add new Product to your Order when it is in Cancelled state. Also behavioral rules could mean changes in state.

How could you accomplish this requirements easily?

STATE
Allowable states
To be more clear about the behavior of our Order, lets take a look on the next statechart diagram:

We could encapsulate behavior which belongs to current object’s state into separate classes derived from some parent class. Each of the concrete will be responsible for allowing changing state from one to another.

State Pattern UML

State Pattern UML in application to Order problem

Order State

How does it work?

At first our Order class has a reference to its _state, to have more real example Order also has _products.

public class Order {

private OrderState _state;
private List<Product> _products = new ArrayList<Product>();

public void setOrderState(OrderState state){
     _state = state;
}

Order delegates some state-specific requests to the current state.

public void ship(){
    _state.ship();
}

 – If the current state is Granted, it changes Order‘s state to Shipped and if needed do some surrounded work or delegates it.

This code represents concrete implementation of the OrderState. Constructor of base class has Order parameter, so this allows us have reference to holding Order: _order in derived classes.

public class Granted extends OrderState{

    public Granted(Order holdingOrder) {
        super(holdingOrder);
    }

    public void ship(){
        _order.doShipping();
        //next line changes Order’s state
        _order.setOrderState(new Shipped(_order));
    }

If you are care what method ship() is doing in Order class it could be like shipping :).

public void doShipping(){
    System.out.println(“Shipping…”);
}

 – If current state is Registered, most likely that class has no implementation of method ship(), it has only addProduct(), grant(), and cancel(). So method of super class will be called. OrderState has all bulk of methods but they all throw exceptions, which says that changing state in current situation is not allowed.

public class OrderState {

    protected Order _order;

    public OrderState(Order holdingOrder){
        _order = holdingOrder;
    }
   
    public void ship(){
        raiseNotAllowableOperation(“ship”);
    }
    
    //other methods like register(), grant(), etc… here.. 
    //they look like the ship() looks

   
    private void raiseNotAllowableOperation(String operation) throws IllegalStateException {
        String stateName = this.getClass().getName();
        System.out.println(“ERROR: Operation [“+operation+“] is not allowed for current order state: “ + stateName);
        //of course in real system you will probably throw exception
        //throw new IllegalStateException(“This operation is not allowed for current order state.”);
    }

Example of Usage of Order class

Now we navigating to customer code. Our OrderingSystem creates new Order, adds some beer as product and all in correct way:

public void doHardWork(){
    Product beer = new Product();
    beer.Name = “Lvivske”;
    beer.Price = 78000;
   
    Order order = new Order();
    order.printStateName();
    order.addProduct(beer);
    order.printStateName();
   
    order.register();  
    order.printStateName();
   
    order.grant(); 
    order.printStateName();
   
    order.ship();  
    order.printStateName();
   
    order.invoice();   
    order.printStateName();
}

Output:

Order state: designpatterns.state.NewOrder
Product addeding calculation…
Order state: designpatterns.state.NewOrder
Registration…
Order state: designpatterns.state.Registered
Granting…
Order state: designpatterns.state.Granted
Shipping…
Order state: designpatterns.state.Shipped
Invoicing…
Order state: designpatterns.state.Invoiced

Ok, now we added code, which tries to add more beer when order has been already shipped.

    order.ship();  
    order.printStateName();
   
    //trying to add more beer to already shipped order
    order.addProduct(beer);
    order.printStateName();

Output:

Order state: designpatterns.state.NewOrder
Product addeding calculation…
Order state: designpatterns.state.NewOrder
Registration…
Order state: designpatterns.state.Registered
Granting…
Order state: designpatterns.state.Granted
Shipping…
Order state: designpatterns.state.Shipped
ERROR: Operation [addProduct] is not allowed for current order state: designpatterns.state.Shipped

Other ways to solve problem without State Pattern

One of the disadvantages of this you could see many of the classes needed to have:

Yes, but this is the way to greatly encapsulate your behavior. Also there are other ways to resolve problem. For example usage of the table [state|method|state] which is populated with all allowable transitions. You could also resolve issue with having switch-case method. About all of this you could read in Jimmy Nilsson’s book “Applying Domain-Driven Design and Patterns“.

What have I learned?

  • Java has no “virtual” keyword, that is because all methods are virtual. Make sense, cause in C# it is often needed to write huge amount of that word.
  • I discovered few Exceptions that Java has, for example IllegalStateException.
  • I was not able to easily figure out what to use instead of “:” in declaration of derived classed. Now I know “extends“.
  • I improved my UML skills with practicing drawing them.

I hope you enjoyed this story.

Go to: My Design Patterns Table


2 comments


Singleton

January 15, 2010 Design Patterns 3 comments

Imagine that you need some global logging system in your application.
You need to be able log your messages to some file at any point of your application, but also you need to numerate your messages.
How can you accomplish this?

SINGLETON

Class which is represented below is example of Singleton Desing Pattern.

public class LoggerSingleton {

    private LoggerSingleton(){}
   
    private int _logCount = 0;
    private static LoggerSingleton _loggerSingletonInstance = new LoggerSingleton();
   
    public static LoggerSingleton GetInstance(){
    return _loggerSingletonInstance;
    }
   
    public void Log(String message){
    System.out.println(_logCount + “: “ + message);
    _logCount++;
    }
}

You are going to start execute your doHardWork method and you want to log that you just started doing hard work and what occured doing it.

So your functional system could look like below:

public static void doHardWork() {
    LoggerSingleton logger = LoggerSingleton.GetInstance();
    HardProcessor processor = new HardProcessor(1);

    logger.Log(“Hard work started…”);

    processor.processTo(5);

    logger.Log(“Hard work finished…”);
}

As you see there is some class called HardProcessor. We should not really care how it works. All about we should care is that when it is created we want to log this and also we want to log when it is done with some calculations.

public class HardProcessor {
   
    private int _start;

    public HardProcessor(int start){
    _start = start;
    LoggerSingleton.GetInstance().Log(“Processor just created.”);
    }
   
    public int processTo(int end){
    int sum = 0;
    for(int i = _start; i <= end; ++i){
       sum += i;
    }
    LoggerSingleton.GetInstance().Log(“Processor just calculated some value: “ + sum);
    return sum;
    }  
}

Here is output of your programm:

0: Processor just created.
1: Hard work started…
2: Processor just calculated some value: 15
3: Hard work finished…

I wrote this example when was in train with my friend. And I showed him my story and he said that I wrote Monostate. -“Me? Where?”. We took a look at my code and the only one variable I was using _logCount was static initially.

What is the difference between Singleton and Monostate?

Singleton is way to ensure that class has only one instance. Monostage if see globally on it do the same as GOF Singleton. All variables of it are static and this allows you to have many instances of monostate, but of course they will share the same data.
This also resolves many issues with multiconcurrecy usage of Singleton.

Lets take a look at my example once again. Could be that your logger is no so trivial, maybe on start of application you want to open some log file and get latest message number, so logger will continue to write to file with correct numbers.
Also your application is not so trivial. Maybe you are accessing your Singleton not only from just different places in your code but from different threads.
But since your constructor interacts with IO it takes time to construct your instance. So GetInstance() in reality in such situation could create TWO instances. Not really good for your application.
For our luck there are many ways to resolve this issue. Commonly we use Double-Checked Locking.

public class ThreadSafeLoggerSingleton {

    private ThreadSafeLoggerSingleton() {
       //reads data from some file and gets latest number of message
       //_logCount = got value here…
    }

    private int _logCount = 0;

    private static ThreadSafeLoggerSingleton _loggerInstance;

    public static ThreadSafeLoggerSingleton GetInstance(){
    if (_loggerInstance == null) {
          synchronized (ThreadSafeLoggerSingleton.class) {
            if (_loggerInstance == null)
                _loggerInstance = new ThreadSafeLoggerSingleton();
          }
        }
        return _loggerInstance;
    }

    public void Log(String message) {
        System.out.println(_logCount + “: “ + message);
        _logCount++;
    }
}

The way is not single and not all implementations of the DCL work! Read this good article on this: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

Also as you see in method Log I’m using variable of my class and do operation on it, which is almost atomary. But if operations will be more complex you will need synchronization there also.

Go to: My Design Patterns Table


3 comments


Design Patterns

January 15, 2010 Design Patterns No comments

[Update for the 5/31/2011]* 
Here below is what I call “My design patterns table”. It has links to my explanation of 23 GoF design patterns that were initially published in 1994 in book Design Patterns: Elements of Reusable Object-Oriented Software, that has changed the way people think about programming and applying standard solutions to common problems.
I tried to keep my examples of patterns very simple and in the way, that person reading example can build associations with real or close to real world situations. I also translated all of the examples into Ukrainian and at the moment in process of assembling small e-book. Hope you enjoy my examples.

Creational Patterns
Structural Patterns
Behavioral Patterns
Abstract Factory Adapter Chain of Responsibility
Builder Bridge Command
Factory Method Composite Interpreter
Prototype Decorator Iterator
Singleton Facade Mediator
Flyweight Memento
Proxy Observer
State
Strategy
Template Method
Visitor




*As of Jan 2010 this blog post has this at the beginning:
[One of the goals for this year is to familiarize with Java. To accomplish this I have two possilities. First
one is my Master Diploma work in which I’m going to significantly
improve calculations in Self-Organizing Maps with efficient usage of
concurrency in Java Second one is my decision to write my own all of the GoF Design Patterns. And as you guess I want do this with Java. Next
table represents collection of Design Patterns and will have links to
my posts on each of the Pattern. I will fill it soon, no doubts.]


No comments


Don’t lose you mind with references

January 14, 2010 .NET No comments

There could be a lot of stupid troubles with references once you work with set of solutions which of them contains lot of projects.

Here is one of them.

I worked with one simple testing tool (TT) which lives in solutionT.

Testing Tool uses projects B and C in the solution1, i.e. has references to B and C.
(Please note that we are using references by assemblies locations.)

Project B also has reference to some commont project named A.

We moved our common projects both with project A to some other solution2.
Of course we changed references of projects B.
Very nice.

I did a bit of change to the A and wrote test for the B.Tests project and it works well in solution1.
But when I started my TT I got exception I fixed back again. I was thinking how could it be…
I rebuilt all solutions carefully but the same occurred.

Do you know what the problem is?
The problem is that the latest project in the graph i.e. my Testing Tool of course has a reference to a project A and that reference is obsolete, since it has old location…

Bottom line:
When you have troubles with references ensure that latest assembly in your references graph (executable one) has all references which are up-to-date and they are rebuilt. (file timestamp should be enough).


No comments


Domain-Driven Design Quickly

January 10, 2010 Book Reviews No comments

Book Domain-Driven Design Quickly is good resource to get consistent and short explanation to DDD.

I was doing my presentation on DDD and was looking for some source to build presentation quickly. And this book is such source.

I already read Applying Domain-Driven Design and Patterns by by Jimmy Nilsson and almost read Domain-Driven Design: Tackling Complexity in the Heart of Software by Eric Evans after that reading of this book was so much enjoyable and quick (I read it for 3 hours and English is not my native language.)

This book is quick readable summary of Eric Evan’s Domain-Driven Design. And it helps to refresh your memory if you already read that book. But if not:

You could read this book to get a good vision of what is Domain-Driven Design in very short term. If wiki or quick google search doesn’t satisfy you and you have not time for big books, this book is exactly what you need. Enjoy it.



No comments


Things you need to remember to become successful developer

January 8, 2010 Success 5 comments

1. Keep on learning

I assume that you would not even read this blog without having some elementary education and you would not want to know how to become successful developer without higher education. So while you are right now developer why to stop learning?
There is no way to do that. One important thing here: Staying in one place doesn’t mean you are staying there – it means you are moving backward. Walking forward doesn’t mean you are moving forward – it means at least that you are not lost with the losers in the end. To keep going forward you need to learn continuously – not walk, but rather RUN!

Here is my short list:
• Read books
• Subscribe to RSS Feeds and read magazines
• Try out different features you hear about
• Go to seminars and do your own presentations
• Learn everything that can help you move
• Teach others since this teaches you
 

2. Establish what your goal is and keep the right way

Ok, it could be hard to run without knowing where to run. The key point here is that you need clearly imagine your goal. This goal should be long term target, and after you have a vision of your goal, go ahead and breakdown it into smaller tasks – build your roadmap. You may create list of tasks you MUST accomplish per month or per year. Then just follow it.

3. Every challenge is an opportunity

In everyday work you always encounter different troubles. You get issues and bug reports from your QA. You get new tasks from your Project Manager. Your co-worker is asking for help. You need help. These all are challenges. And the real question is: how do you meet them? I have an answer: you need to take them all with passion, because every challenge is an opportunity. You would say “Hey, but this way I will never get off stupid nasty work.” You are 100% not right here. Remember, your bosses will be glad to give you more complicated work once they see you do the best to get your current job done.

4. Be positively charged

You should look at everything in very positive manner. If it is found that you did mistake, just take it easy – everyone does them. Do you like people who start to whine once they have troubles? How do you think you will be looking in others eyes if you say “Ok, guys, I did it – I will solve this, give me a minute.” and turn around and start fixing your mistake with smile on face. After you solve the problem you will be so happy and proud of yourself.
Now your way is good and you are moving fast forward. Don’t ever, ever think that you will not be able to reach your goal.

5. Find a mentor

This does not mean that you need a person who will help you in doing your job – it is a coach or more senior stuff than you are. This means that you need a person who is where you want to be and you need to take a leaf from his/her book. And if suddenly you discover that he is not high enough – you will need to find another. But most of the time you need to have such person. Also have people, friends if you will, who will help you keeping on track. It could be your wife or girlfriend (in my case :) [2011: now wife]), or best friend who always supports you (in my case he is developer, but this doesn’t matter).

6. Be more public

If you will not show others that you are cool and you deserve more, how will they know? There is simple way to do that – start blogging, ask and answer questions, ensure google knows something about you. Share your knowledge in your team and project. If you learned something new, why do not share it. You will forget things if they are not tried and shared.

7. Track your activities; be sure that you are on track

Time to time you need to check if you are doing everything in proper way and in align with your main goal. Verify if you are accomplishing stated goals. If no, quickly find reasons and address them. Find your weak areas and work on them. This sounds funny, but I know a very good developer with strong knowledge, but his coding/typing speed is ridiculously slow. Why? Because he has a bad keyboard and doesn’t want to spend 10-20 hours with keyboard trainer. Isn’t it stupid? Man, if you read this, please promise yourself that you will overcome yourself.

8. Do your gym :)

I did a bit of “brainstorming” when writing this article. And “Do your gym” has fallen there. I’m quite young man and spend too much time with my laptop and with another computer at work and I cannot coerce myself doing gym. But this is just like sharping the blade. There is story about two woodcutters who made a bet based on count of cut trees. One was Strong man and another was Thin. The Strong one was sure that he will win since he was cutting trees like hell 8 hours without single break and since Thin has rest each hour for 15 minutes. But Thin won the battle – he cut 150 per contra 100 of the Strong man. His secret was that he was sharping the blade in breaks. Your health is your axe and if you will keep it blunt you will not be able to cut down your way in your career.

So, let any of your axes be #.


5 comments


Domain-Driven Design

January 2, 2010 DDD 6 comments

Lets start with the following question: Where is a car on the left or on the right?
 
You would probably say that Car is on the Right, and you are correct. But hold on. What is the difference between them? Difference is that Car is not just a huge collection of parts. Car is not even a collection of parts which need to fit together, but a car is much more than that. A good Car starts with vision and carefully written specifications, and it continues with design and with testing. The design is modified based on the testing results. Only after that each part could be assembled together.

Software development is similar, we cannot just sit down and type code.

What is Domain-Driven Design?

We all want to develop our applications, but business requirements nowadays are huge, and we dive in that complexity. And we can get stuck will all of that, because the whole complexity is in the Domain. For example banking system. Do you as a software developer want to know how does it work? Probably no, but you still need to develop your system. The guy from bank stands near you and and he wants you to develop application for him. What is your starting point? Is it table in database or is it Model?

 Domain-Driven Design (DDD) is is an approach to the design of software, based on the two premises:
* that complex domain designs should be based on a model, and
* that for most software projects, the primary focus should be on the domain and domain logic (as opposed to the particular technology used to implement the system).

In other words the heart of the DDD is Model and you start developing your application with drawing your model. Model and design you create should shape each other. Model should represent knowledge to the business and it is language your team speak.
To be able effectively design you should build your Model and implementation together in the same time, cultivating a language based on the Model. You should represent knowledge in your Model and continuously distill it. You could do refactoring to it doing brainstorming and experimenting.

Ubiquitous Language

So, imagine that guy from bank, say Domain Expert, stands near you and you start talking. How does that conversion look like? It could be fractured and this creates serious problems to your project. Domain Experts have their own jargon and the development team has its own. After that daily discussions are disconnected from  the terminology embedded into code. So effect of need to translate what you are talking about into code appears, plus misunderstandings possibilities. This all could lead to not good results.
Need for some common language shows up. Eric Evans calls this language as Ubiquitous Language. Your language is your model, this means that both Domain Experts and Developers should talk the same language which is build on the model. And changes to the Ubiquitous Language means changes to the Model. If Experts start using new terms this should be represented in your model, in your code, diagrams and speech.

How could it look?
* Speech (This means daily conversations between team members.)
* Diagrams (Often these are quick diagrams on the whiteboard, which you created with your Experts.)
* Writing (This could be NOT long documents, describing the Model.)
* UML (But there is no place for cumbersome one.)

Let us move to the way you will build your application.

Layered Architecture

I hope that everybody heard about the Layered Architecture. For the DDD it is very important since we explicitly separate Domain Level, which lives between our Infrastructure and Application layers, like on picture. Note, that isolating of your Domain Level is very important.

User Interface (Presentation Layer)

Responsible for presenting information to the user and interpreting user commands.

Application Layer

This is a thin layer which coordinates the application activity. It does not contain business logic. It does not hold the state of the business objects, but it can hold the state of an application task progress.

Domain Layer

This layer contains information about the domain. This is the heart of the business software. The state of business objects is held here. Persistence of the business objects and possibly their state is delegated to the infrastructure layer.

Infrastructure Layer

This layer acts as a supporting library for all the other layers. It provides communication between layers, implements persistence for business objects, contains supporting libraries for the user interface layer, etc.

For example, a typical, the interaction of the application, domain and infrastructure could look like this. The user wants to book a flights route, and asks an application service in the application layer to do so. The application tier fetches the relevant domain objects from the infrastructure and invokes relevant methods on them, e g to check security margins to other already booked flights. Once the domain objects have made all checks and updated their status to “decided”, the application service persists the objects to the infrastructure.

The Smart UI “Anti-Pattern”

All this sounds good but simplicity of just calling infrastructure lead into temptation, and after that you see that code generated on button press actually executes hard-coded SQL, less terrible it could be when that is masked under some “helper” classes. But that all is manifestation of the the Smart UI “Anti-Pattern”. Could be surprising to you, but it has its advantages/disadvantages. Why not. It will not be a “Anti-Pattern” if it has no advantages.

Advantages:

  • Productivity is high for small applications.
  • Less capable developers could work with application easily.
  • If each screen has its logic it is possible to quickly change product to fit new requirements.
  • Maintenance guys can quickly find root of any bug – just put breakpoint on button press. :)

Looks like a lot of advantages, but let see what are disadvantages. Hope this will convince you to do not use this “Anti-Pattern”.

Disadvantages:

  • Integration of applications is difficult except through the database.
  • There is no reuse of behavior and no abstractions on business problems.
  • Lack of abstractions creates limits to possibilities of refactoring or doing work iterationaly.
  • Complexity buries you quickly. If your application grew to the enterprise level and you still have this Smart UI, then you are in a$$.
  • And finally you will not be able to migrate to any other design except of replacing each applications.

So, don’t lose your mind, if you build your application with layers, do it correctly!

Building blocks of Domain-Driven Design 

Eric Evans introduces terminology to the Domain-Driven Design. Accordingly to him there are such building blocks of the DDD: Associations, Entities, Value Objects, Services, Modules (which are parts of the Model) and Aggregates, Repositories, Factories (which deal with Life Cycle of a Domain Object).We will talk about each of the elements.

Associations

If your Car has four tires this is association of the model of your Car. This is relation between business elements you work with.

Entities

If we were to implement the concept of a Person using a software program, we would probably create a Person class with a series of attributes: name, date of birth, place of birth, etc. For example if you create Patient entity in code it will be represented like Patient class. It is required that for medical system to identify if the patient is the same. Is the patient “Andriy Buday” physician deals with, the same as “Andriy Buday” nurse has a scheduled procedure? So basically Entity is object that has Attributes and Identity.

Value Objects

Value Object are similar to the Entities expect that they do not need Identity, which is required for Entity. For example “Ukraine, Lviv” which is Address is Value object since we do not need identity for it. We could have 300 patients in Lviv (Entities) who could share the same address. This (sharing) could even be done thought the code using Flyweight design pattern to reduce memory needs. But Address is not always Value Object. This depends on “Who is asking?”. For the post system Address could be an Entity.

Services

Consider that your Model has nouns and verbs (they are used in Ubiquitous Language). You could imagine that nouns are Entities and Value Objects. Your verbs are Services. If you have action or operation related to the Domain concept, but is not natural part of any of your Entity or Value Object you could move it into separate item, which is called Service. Interface of your Service should operate with terms of of the domain model. And the operations it does are stateless.

Modules

For a large and complex application, the model tends to grow bigger and bigger. The model reaches a point where it is hard to talk about as a whole, and understanding the relationships and interactions between different parts becomes difficult. For that reason, it is necessary to organize the model into modules. Modules are used as a method of organizing related concepts and tasks in order to reduce complexity. In code this could be packages or namespaces or even simple folders. The advantage of this is that when you place some classes together in a Module, you are telling the next developer who looks at your design to think about them together.

Aggregates

An Aggregate is a group of associated objects which are considered as one unit with regard to data changes. The Aggregate is demarcated by a boundary which separates the objects inside from those outside. Each Aggregate has one Root. The Root is an Entity, and it is the only object accessible from outside.

The picture shows that your Customer code could access Tire only though the Car instance and there is no other way to do that, since Car is Aggregate to Tire. But could be that part of Car need identity. This could be Engine of your Car, since it has its number and you need to form you taxes. In this case Engine is Entity which lives outside of your Aggregate.
We need to deal with Aggregates since they has direct relation to the Life Cycle of Domain Object.

Factories

Creation of an object can be a major operation in itself, but complex assembly operations do not fit the responsibility of the created objects. This operations could be accomplished with Factories. But not always it should be separate object. In scope of DDD Factory could even be a simple constructor. Two major requirements to the Factory are: Atomicity – this means that operation of creating an Entity should also create whole Aggregate associated with it. Abstracted to the type desired – this means that Factories should return you types rater than concrete classes. (i.e. Interfaces).

Repositories

Repository is an object which provide you CRUD operations to your Aggregates.
Repositories have many advantages, including the following:

  • They present clients with a simple model for obtaining persistent objects and managing their life cycle.
  • They decouple application and domain design from persistence technology, multiple database strategies, or even multiple data sources.
  • They communicate design decisions about object access.
  • They allow easy substitution of a dummy implementation, for use in testing (typically using an in-memory collection).

To be more clear how the Client code, Repository and Factory are interacting between each other. Lets take a look on the next sequence diagram:

I hope that diagram is self-descriptive.

Refactoring Toward Deeper Insight

Since the business and its rules are very complicated you are not able to see whole picture at once. If there are some incomes to your Ubiquitous Language you should represent this into your Model. You do this with refactoring of existing code in way that brings key concepts into light.
There are three ways to bring concepts into light:

  • Constraint. For example you could put Constraint into separate method to make it more explicit.
  • Process. This stands for introducing your Services. If process is difficult we can encapsulate algorithm into object and use a Strategy.
  • Specification. A Specification is used to test and object to see if it satisfies a certain criteria. Specification can be used when you need to to select a certain object from a collection like a condition.

Your development process should always be in continuous refactoring. Any changes to the matter you talk with your Experts should be immediately represented in code. If you see that some term starts occur too often just create an Entity or Service for it – bring it to the Light.

Preserving Model Integrity

Imagine a big enterprise project. Could you imagine it with one model which is understandable for whole team, say 200 people? Most commonly such big projects are divided to smaller teams and which of them works on own model. So whole project consists of couple of models and some of them are intersected with other models, some of them uses other models and all of this is the Integrity of your Models.

Bounded Context

Each model has a context. When we deal with single model, the context is implicit. There is no need to define it. When we create an application which is supposed to interact with other software, for example a legacy application, it is clear that old application has its own model and context, and they are separated from the legacy model and its context. They cannot be combined, mixed or confused. When we work on enterprise project we need define the context of each model, we create. Also a model should be small enough to be assigned to one team. Only this way we could keep knowledge up to date and integrated into system.
Whole project should be assembled continuously using Continuous Integration.

Iterations between different contexts

You could probably say that you cannot have 100 models in your project without intersections between them. And you are right. Eric Evans sees few variants of such intersections.

Shared Kernel

The purpose of shared kernel is to reduce duplication, but still keep two separate contexts. Designate some subset of the domain model that the two teams agree to share. Of course this includes, along with this subset of the model, the subset of code or of the database design associated with that part of the model. This explicitly shared stuff has special status, and shouldn’t be changed without consultation with the other team.

Customer-Supplier

There are times when two subsystems have a special relationship: one depends a lot on the other. You could imagine core functionality system and reporting system. Probably reporting system depends on the core one. In such case it is very and very important that team which works on core will be supplying reporting team. That is simply needed.

Conformist

This is much like the Shared Kernel, but there is an important difference. The customer team cannot make changes to the kernel. They can only use it as part of their model, and they can build on the existing code provided.

Anticorruption Layer

We should build an Anticorruption Layer which stands between our client model and the external one. This layer works as a two way translator between two domains and languages. This layer could be needed when we deal with legacy/external model and have no ability to do changes to it.

Open Host Service

The solution is to see the external subsystem as a provider of services. If we can wrap a set of Services around it, then all the other subsystems will access these Services, and we won’t need any translation layer. The difficulty is that each subsystem may need to interact in a specific way with the external subsystem, and to create a coherent set of Services may be problematic.

Infrastructure

Persistence Ignorance

One of the key requirements to your Infrastructure to be able deal with DDD is Persistence Ignorance. This means that once you have your Infrastructure setuped you no longer need to care about how your data goes to database and how it is saved there. Also it is commonly used with Unit Of Work Pattern. This could be accomplished with some of the ORM frameworks like Hibernate.
How do we classify ORMs? We look on the ways how it solves different problems which occur when you map you object-oriented data to relational database, but yea.. there are ORMs which map to the Object databases. But the most common variant is when you have Relational database. So wee take a look how ORM resolves Inheritance issues, what is the querying language of it, does it support all common databases operations like aggregating, ordering, grouping, etc.
Basically all ORMs has Identity Map and Cache strategy they allow us work using Unit Of Work pattern and they could provide Lazy Load to do not hit database often.
NHibernate is the ORM which all the features required to quickly build an advanced persistence layer in your code.

Patterns and practices compatible with Domain-Driven Design

Nowadays Agile is a way to develop software and DDD is very comfortable with it and with technics of the Agile like TDD.

TDD

Test-Driven Design is very good thing to use with DDD. Why? Because writing test before means that your are describing your model just like it was described on the meeting with your Experts. There are even enthusiasts who wants to rename TDD to BDD (Behavioral-Driven Design).

Advantages for design

  • More client control
  • More Interfaces and Fabrics
  • More concrete
  • Low coupling

Other advantages

  • Another version of API
  • Long term support
  • Documentation
  • Like smart compiler

Disadvantages

  • UI & Database testing
  • You feel too much safe
  • Possilitity to lose whole visibility
  • More code to maintain

Designing architecture

While designing your architecture with DDD you often uses such patterns or approaches like:

SOA (Service-oriented architecture)
Generally speaking, SOA is a flexible set of design principles used during the phases of systems development and integration. It provides set of Services with which you are working.

AOP (Aspect-oriented programming)
In computing, aspect-oriented programming (AOP) is a programming paradigm in which secondary or supporting functions are isolated from the main program’s business logic. It aims to increase modularity by allowing the separation of cross-cutting concerns, forming a basis for aspect-oriented software development.

IoC (Inversion of Control and Dependency Injection)
Inversion of Control is principle with which you could easily resolve your dependencies in code delegating setup to some other part like IoC framework (StructureMap for example).

For the end I want to mention that my story is based on books by the link below.
http://domaindrivendesign.org/books
I read all of them (except of duplicated ones :) ) and recommend you to read them also. This will bring a lot of interested stuff to your mind. For example I could state that now I understand better the design of subsystem with which I work on enterprise project. Future is for Domain-Driven Design.

P.S. I hope that you enjoyed my story. Do not hesitate to leave your comments.


6 comments