Skip to content

SOLID principles

Object oriented has some principles that when you follow them the non-functional attributes of your codes will be enhanced. SOLID is an acronym for 5 principles what introduced by Robert C Martin and acronym was create by Michael Feathers.

  • Single Responsibility Principle : Every class should have just One responsibility and encapsulate its responsibility entirely. The Most important reason of this principle is that there must be just one reason for changing a class. For example when you want to read a config file for database connection information and connect to database you must have two separate class, First for config file reading and the other for connection to database.
  • Open Close Principle: Every class should be open for extending and closed modification. When you write a class and you are sure then new features and enhancements must be added with extending class not with modification source code. So your code must be extendable. In the other word just modify your code for errors, new features and enhancements need new class that extends current class.
  • Liskov Substitution Principle: If S is a subtype of  T, then objects of type T may be replaced with objects of type S without altering any part of your code.
  • Interface Segregation Principle: No client should be force to depend on methods it does not use. ISP means your interfaces must be small and specific for a goal.
  • Dependency Inversion Principle: High level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend upon details. Details should depend upon abstractions. When you are designing an application it is a bad idea that you create dependency between high level and low modules, instead of this model of design, try to design dependencies with specifications then your high level modules just depends on your specification and you can substitute your modules implementations very easy. There are many solutions for Dependency Inversion, Plugin, Service Locator and Dependency Injection are some these patterns.

 

I want to start to explain some of important design patterns in my next posts and it is one the reasons that i explained SOLID principles. There are some other principles you may like to know as (YAGNI , GRASP , KISS , … ) 

Advertisements

Introduction to JUnit – Part 2

In the previous part of Introduction to JUnit i explained how we can add JUnit to our java project and what are the primary annotations of JUnit.
In this part i explain how we can test our application with a simple example, if you remember i introduced an Object Factory. this Object Factory can build some objects and return them to clients.

Our Object Factory can be used in Connection Pools, Load Balancers and many other solutions.

Step 1:

We need to prepare out environment. In this tutorial i use maven. So create a new maven project. and add following dependency to your pom.xml


<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
</dependency>

Then create a test class with name ObjectFactoryTest in your src/test/java directory of maven project.
Maybe it’s strange at first but in Test Driven Development at first we create test and then code just for passing our test. If you are not familiar with this kind of development read Test Before, Rest After!!

Step 2:

We need to write a test for our API and then write some code to pass it. So in this step we write our first test method.


private int NUM = 10;
 @Test
 public void when_ObjectFactory_is_created_its_capacity_must_be_set(){
 final ObjectFactory objectFactory = new ObjectFactory(NUM);
 Assert.assertEquals(NUM,objectFactory.getPoolSize());
 }

Congratulation you have write your first unit test. There are some points in our test method.

first naming convention: there are two approach for naming test method, as you see in my test even i did not observe java method naming conventions. In this approach you completely explain what you are testing, so you have a good document for yourself and anyone who will read your codes.

The other approach that i don’t like it so 🙂 is the java classical convention, in this approach test method name must not be declarative and is just a name for your method, for our previous test method a good name in this model is : “testObjectFactoryCreation”.

It’s your choice that which one is better and you like to use, but at all i use first approach.

Second Assertion: I did not explain about test method assertion before, When you write a test it is obvious that you need to test! in JUnit the assertion will test your assumptions. so  Assert.assertEquals(NUM,objectFactory.getPoolSize()) means that i expect that return value of  getPoolSize must be equals to the NUM constant.

OK now that we write our first test we need to run it. in this level we have some compile errors, because we have not created ObjectFactory and its getPoolSize method yet. So try to resolve just compile errors and the execute: mvn clean test

The result is : Tests run: 1, Failures: 1, Errors: 0, Skipped: 0

No you need to complete your ObjectFactory class to pass this test. Your ObjectFactory class will be something like this code:



public class ObjectFactory {
 private int poolSize;

public ObjectFactory(int poolSize) {
 this.poolSize = poolSize;
 }

public int getPoolSize() {
 return poolSize;
 }
}

You must continue with Test Code Refactor steps to complete your ObjectFactory code. ( in this post we don’t pay attention to Refactoing )

Clients need to get an object from our ObjectFactory, So we need to have a getObject method.


@Test
 public void getObject_should_not_return_null() {
 final ObjectFactory objectFactory = new ObjectFactory(NUM);
 final Object object = objectFactory.getObject();
 Assert.assertNotNull(object);
 }

For passing this test just you need to add follow method to your ObjectFactory class:


public Object getObject() {
 return new Object();
 }

At the first glance you will understand that our code is not suitable for ObjectFactory but don’t forget you must write code just for passing your test. So the code is not OK because your tests are not enough.
When we call getObject more that poolSize we should get an existed Object not new one.

So we can write this test method:


@Test
 public void getObject_should_return_one_of_existing_objects() {
 final ObjectFactory objectFactory = new ObjectFactory(1);
 final Object firstObject = objectFactory.getObject();
 final Object secondObject = objectFactory.getObject();

Assert.assertSame("Two objects are not the same.",firstObject,secondObject);
 }

For passing this unit test you need to change your getObject code,  Below code is one the solutions for passing test:


public Object getObject() {
 if (pool.size() < poolSize) {
 final Object object = new Object();
 pool.add(object);
 return object;
 }
 return pool.get(0);

}

pool field is a List reference to an ArrayList object ( You can see complete code in GitHub ).

But our  solution is not complete yet. When pool becomes full our code just return the first object!

So we can write this test method:


@Test
 public void getObject_should_return_different_objects_after_pool_becomes_full() {
 final ObjectFactory objectFactory = new ObjectFactory(2);
 objectFactory.getObject();
 objectFactory.getObject();
 final Object firstExistedObject = objectFactory.getObject();
 final Object secondExistedObject = objectFactory.getObject();

Assert.assertNotSame("Two objects are the same.",firstExistedObject,secondExistedObject);
 }

Our test method emerges the absence in our code.Try to resolve this problem yourself 🙂 I will upload complete code in my github, but please try to complete codes yourself, it can be a good practice.

If you have any opinions or problems please give me feedback.

Introduction to JUnit

If you have never write test, it must be a concern for you ” When can i be sure that my code works “Most of the times you have to realize many parts of your software until you could validate your code! But there is another way to validate the accuracy of you code. You can write a simple client for your code and validate the behavior of it.
For example you want to create a special Object Factory. this Object Factory must create a specified numbers of objects and in the next requests to get an instance it must get objects with a round robin algorithm,

As you see this Object Factory is not very hard to write, and you will its testing is not hard too. But if you have a web project and you don’t want to have automated tests maybe you need these augmented parts of software for testing:

  • Your API must be complete without client code ( You need to think as client when you are writing your API )
  • All the services you need to use your Object Factory
  • Web UI as a client of your code
  • Some Not required logging for watching the functionality
  • Debug your code ineffective for finding the place of bugs

If you are agree with me that these are problem continue to reading this post 😉 in the other way continue too maybe you find out a more simple solution for your accuracy.

JUnit is the most popular testing framework in the java world. The last major version of this framework is 4.x. One of the biggest changes in this version is using Annotation instead of conventions. When you want to test a code you write a class ( Test Class ) and write your tests ( Test Methods ) for the assertion of your code. You can see a simple Test Template in the following code:

public class ObjectFactoryTest {

@Test

public void ObjectFactory_should_create_with_specified_numbers_of_pool() {

//Arrange code

//Act Code

// Assert Code

}

}

So a Test Class is just a simple class with special annotations the JUnit Framework can understand them and run your tests. Some basic annotations that is desirable to know now for you are :

  • BeforeClass: A Static method that will run at the first of starting the tests of your test class, So this static method just run one time for your test class
  • AfterClass: A Static method that will run after running all test methods of your test class, So this static method just run one time for your test class too
  • Before: A method that will run before every test method of your test class.
  • After: A method that will run after every test method of your test class.
  • Test: This annotation specify your test methods

If you like to know how they run you can run following code ( Source code is from: JUnit 4 Tutorial 1 – Basic usage )

import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;

/**
 * @author mkyong
 *
 */
public class JunitTest1 {

    private Collection collection;

    @BeforeClass
    public static void oneTimeSetUp() {
        // one-time initialization code
    	System.out.println("@BeforeClass - oneTimeSetUp");
    }

    @AfterClass
    public static void oneTimeTearDown() {
        // one-time cleanup code
    	System.out.println("@AfterClass - oneTimeTearDown");
    }

    @Before
    public void setUp() {
        collection = new ArrayList();
        System.out.println("@Before - setUp");
    }

    @After
    public void tearDown() {
        collection.clear();
        System.out.println("@After - tearDown");
    }

    @Test
    public void testEmptyCollection() {
        assertTrue(collection.isEmpty());
        System.out.println("@Test - testEmptyCollection");
    }

    @Test
    public void testOneItemCollection() {
        collection.add("itemA");
        assertEquals(1, collection.size());
        System.out.println("@Test - testOneItemCollection");
    }
}

If you want to use JUnit with maven you need to add following dependency to your pom.xml

<dependency>

<groupid>junit</groupid>

<artifactid>junit</artifactid>

<version>4.8.2</version>

</dependency>

Don’t forget as a convention maven runs test classes that have Test Suffix. So your Test Class Names must be *Class.java format.

Now it’s your time to use JUnit and executed some simple tests. You can write Object Factory code with Test First Codes. In the next tutorial i will explain one of the possible implementations of Object Factory and its tests.
Please give me feedback if somewhere exists ambiguity or you need any prerequisites for these tutorials.

Test before! Rest after!!

There are many different articles, white papers and journals about testing and why we need Test Driven Development (TDD). But i wrote this post for who does not know about TDD or how to start this model of development. Here you can find out more about Kent Beck, the man who rediscovered this technique : Kent Beck
TDD is very related to the Test First concept in Extreme Programming (XP), started from 1999. In this model of development we have short iteration of development, every iteration starts by a failed test. Then developer will write code just until the test and every past tests passed. At first maybe it’s strange at first,but there are many reasons that justified this approach is effective and applicable. As an formal steps in TDD there are these step:

  • Test: In this step all your previous test has been passed, then you write a new test and run all the tests, your last test must fail, if not there is a problem in your test.
  • Code: In this step you write some code, the goal is to pass the last failed test. passing last test will make a new feature in your application. Then you run all the tests and if all of them was passed this step completed.
  • Refactor: In this step you need to refactor your code and your tests for eliminating duplicate, boilerplate, unclean codes, smell codes. There are many best practice about refactoring and its patterns that you can use them.
  • Repeat from Step 1 with your new feature.

Some augmented steps before last step can add, these optional steps will increase the quality of your code. These Steps are:

  • Document: write document for your code API. these documents will help you and other clients to find out how must use your API.
  • Log: write logs in appropriate points of your codes. then you can track the problems and events in your code more easy than before.

Maybe you have seen Red/Green development some where. it’s another name for Test First development, because at first your write a failed test ( most of test framework show them as red). Then you write some code for passing them ( most of test framework show them as green).

Writing tests before code have many advantages, you can see some of them below:

  • You don’t to write testable code. Hah? yesss. you have written test before code so your code will be testable by default.
  • Your Code Coverage will be more than 95%. If you write code just for passing your failed test you will achive this big advantage.
  • You have a history of your thinking forever. when you are writing a test you have some opinion about application. you have all of them. and you know which part of your code is for which test, So you have created a document about your code in development cycle.
  • Your API will be very handy for clients, because you have written API when you were writing the test, without any technical issues

In this post i wanted to have an overview on TDD and its advantages. In the next post we will start writing test and introducing its concepts.

Let me know about your opinions and feedback.

Spring Configurable Magic

Spring framework has several modules that provide a range of services, many of these modules Can work just for managed Objects (Spring Beans) Some examples about these services are Dependency Injection, Transaction Management, AOP Services , etc.
Everything is fine when we are using Objects as Services, so they are managed by by Spring with a specific scope. But sometimes we need our domain objects have these services. Usually domain objects are created with new keyword so they cannot be managed by default with spring.
In my Previous post (How to use Events in Spring 3.x) we had a domain object with name Order. for decoupling between object we used events.
But just Managed beans can raise event in Spring framework (Probably every Framework you know and has this feature).
Spring introduce an annotation with name Configurable. Using this annotation on our domain objects make them Managed by spring.
But how does it work:
Configurable for its purpose needs AspectJ Compiler, your class needs Byte Code Enhancement in Compile Time or Load Time until can satisfy your requirements.

I want to bring you a simple sample about how to configure and use Configurable power in your applications.

It is a good practice to have an Environment Object that all the system can access its properties to catch information about system. For example we need to know the current time of system, simple solution is to use Calendar.getInstance().getTime() or  new Date()

but there are some defects, your code will not be testable for parts that you need to test date assertion ( I will write a series of post bout Test and Testable codes as soon as possible) .

The other problem is when you want your system work with Pseudo clock. as an example your client wants to work with system in holidays as the last non holiday date.

So it is valuable to have a mechanism for these requirements. As a simple solution in this sample i will create An Environment Interface that have one method ( getCurrentTime()). Everywhere in code if i need the time of system i will use this method. Environment interface must be injected in my objects until i can happily use this method. Spring beans do not have any problem to using Environment, but in our domain objects we have to use Configurable Annotation.

If you use Maven you will need to added these dependencies to your pom:

 <groupId>org.springframework</groupId>
 <artifactId>spring-aspects</artifactId>
 <version>3.1.1.RELEASE</version>
  <dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjrt</artifactId>
 <version>1.6.8</version>
 </dependency>
 <dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjweaver</artifactId>
 <version>1.6.8</version>
 </dependency>
 <dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjtools</artifactId>
 <version>1.6.8</version>
 </dependency>

To compile your application with maven you can use following Aspectj-maven-plugin configuration :


<build>
 <plugins>
 <plugin>
 <groupId>org.codehaus.mojo</groupId>
 <artifactId>aspectj-maven-plugin</artifactId>
 <version>1.4</version>
 <configuration>
 <showWeaveInfo>true</showWeaveInfo>
 <source>1.6</source>
 <target>1.6</target>
 <Xlint>ignore</Xlint>
 <complianceLevel>1.6</complianceLevel>
 <encoding>UTF-8</encoding>
 <verbose>false</verbose>
 <aspectLibraries>
 <aspectLibrary>
 <groupId>org.springframework</groupId>
 <artifactId>spring-aspects</artifactId>
 </aspectLibrary>
 </aspectLibraries>
 </configuration>
 <executions>
 <execution>
 <goals>
 <goal>compile</goal>
 <goal>test-compile</goal>
 </goals>
 </execution>
 </executions>
 <dependencies>
 <dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjrt</artifactId>
 <version>1.6.8</version>
 </dependency>
 <dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjtools</artifactId>
 <version>1.6.11</version>
 </dependency>
 </dependencies>
 </plugin>
 </plugins>
 </build>

If you use IDE for compiling your code don’t forget to change its compiler to AspectJ. you can find it in your local maven respository in aspectjrt directory.

Assume there is a Product class and we would like to know the date of its creation, and the date if its sale.


@Configurable(preConstruction = true)
 public class Product {
 private final String name;
 private final String description;
 private final Date createDate;
 private Status status;
 private Date saleDate;
 @Autowired
 private Environment environment;

public Product(String name, String description) {
 this.name = name;
 this.description = description;
 this.status = Status.PENDING;
 this.createDate = environment.getCurrentDate();
 }

public void sell() {
 this.status = Status.SALE;
 this.saleDate = environment.getCurrentDate();
 }

public Date getCreateDate() {
 return createDate;
 }

public Date getSaleDate() {
 return saleDate;
 }

public static enum Status {
 PENDING, SALE;
 }
 }

Product is a very simple class, we used preConstruction=true because our product construction need to use environment.

Environment and its implementations are very simple too:


public interface Environment {
 Date getCurrentDate();
 }

public class DefaultEnvironment implements Environment {
 @Override
 public Date getCurrentDate() {
 return new Date();
 }
 }

public class MockEnvironment implements Environment {
 private Date date;
 @Override
 public Date getCurrentDate() {
 return this.date;
 }

public void setCurrentDate(Date date){
 this.date = date;
 }

}

MockEnvironment is created in test packages, because we need this class just in our tests. Instead of using this class you can use some mock library as Mocktio and an extension on it (Springockito). But in this sample our focus is not on them.

Our tests are very simple too:


@ContextConfiguration({"classpath*:context.xml","classpath*:test-context.xml"})
 public class ProductTest extends AbstractJUnit4SpringContextTests {
 final Date time = Calendar.getInstance().getTime();
 @Autowired
 Environment environment;

@Before
 public void before() {

((MockEnvironment) this.environment).setCurrentDate(time);
 }

@Test
 public void created_product_should_have_current_environment_date() {
 final Product product = new Product("", "");
 Assert.assertEquals(time, product.getCreateDate());

}

@Test
 public void sell_should_set_createDate_to_now(){
 final Product product = new Product("", "");
 product.sell();
 Assert.assertEquals(time, product.getSaleDate());

}
 }

I hope this post can help you to using this magic feature of Spring.
Please give me feedback and your opinions about my blog.

You can download source code from : https://github.com/psycho-ir/Spring-Configurable.git

How to use Events in Spring 3.x

There are many concepts and techniques for creating loosely coupled applications, Event is one of them. Events can eliminate many of dependencies in your code. Some times without events, SRP* is very hard to implement. Observable interface in java can help us to implement events (through Observer Pattern).

But wait, the goal of this post is a fast tutorial about Spring Event. Spring has some nice facilities for creating Event Driven Applications. You can raise a specific event in a bean and listen to it in the other bean.

Imagine a simple application with these requirements:

  • There are some orders that can have different status
  • when an order is in DELIVERED or POSTPONED state we need to send an email to the customer

The first (but not the best) solution for requirement satisfaction is sending email in our Order model, But There are some defects:

  • It’s not responsibility of Order to sending email.
  • If you follow Domain Driven principle, Order is a domain object but Email Sender maybe is a service ( different from Domain Service ) so you can’t use it in your model.

The other solution is raising some events in our Order model after changing its status. I’s not concern of Order what will happen after raising this event. In our example we need to listen to a specific kind of events, analyze them and do some business (Sending Email).

@Configurable
 public class Order implements ApplicationEventPublisherAware {
 private final String orderId;
 private final Date createDate;
 private final CustomerInfo customerInfo;
 private ApplicationEventPublisher eventPublisher;
 private Date lastUpdateDate;
 private Status status;

public Order(String orderId, CustomerInfo customerInfo) {
 this.orderId = orderId;
 this.customerInfo = customerInfo;
 status = Status.MODIFIABLE;
 this.createDate = new Date();
 this.lastUpdateDate = this.createDate;
 }

public String getOrderId() {
 return orderId;
 }

public void checkOut() {
 if (status == Status.DELIVERED) {
 throw new IllegalStateException(String.format("Order is already delivered"));
 }
 this.status = Status.CHECKED_OUT;
 this.lastUpdateDate = new Date();
 }

public void deliver() {
 if (this.status != Status.CHECKED_OUT && this.status != Status.POSTPONED) {
 throw new IllegalStateException(String.format("Order status should be CHECKED OUT for delivery to be called. but is : %s", status));
 }

this.status = Status.DELIVERED;
 this.lastUpdateDate = new Date();
 this.eventPublisher.publishEvent(new OnOrderDelivered(this));
 }

public void postponeDelivery() {
 if (status != Status.CHECKED_OUT && status != Status.POSTPONED) {
 throw new IllegalStateException(String.format("Can not postpone delivery in this state: %s", status));
 }
 this.status = Status.POSTPONED;
 this.lastUpdateDate = new Date();
 this.eventPublisher.publishEvent(new OnOrderPostponed(this));
 }

public Status getStatus() {
 return status;
 }

public CustomerInfo getCustomerInfo() {
 return customerInfo;
 }

public Date getLastUpdateDate() {
 return lastUpdateDate;
 }

public Date getCreateDate() {
 return createDate;
 }

@Override
 public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
 this.eventPublisher = applicationEventPublisher;
 }

public static enum Status {
 MODIFIABLE,
 CHECKED_OUT,
 POSTPONED,
 DELIVERED,
 CANCELED;
 }
 }

As you see Order is a configurable class, if you have not worked with this concept before, don’t be anguished. For this post just you need to know Configurable classes can create everywhere with new keyword but they are managed by spring, so you can inject other beans in them or use most of the spring facilities with them. I promise to post an article about it as soon as possible 🙂

Order class implements  org.springframework.context.ApplicationEventPublisherAware interface.

this interface has a setter method with name setApplicationEventPublisher that presents ApplicationEventPublisher for using in your class.

as you see in deliver method we used this object to publish an event (this.eventPublisher.publishEvent(new OnOrderDelivered(this))).
you can publish every event that extends org.springframework.context.ApplicationEvent
we have raised another event OnOrderPostponed when an order becomes postponed.

public abstract class OnOrderStatusChanged extends ApplicationEvent {
 private final Order order;

public OnOrderStatusChanged(Order source) {
 super(source);
 this.order = source;
 System.out.println(String.format("Order:%s status is changed to %s", source.getOrderId(), source.getStatus()));
 }

public Order getOrder() {
 return order;
 }
 }

public class OnOrderDelivered extends OnOrderStatusChanged {
 public OnOrderDelivered(Order order) {
 super(order);
 }
 }

public class OnOrderPostponed extends OnOrderStatusChanged {
 public OnOrderPostponed(Order order) {
 super(order);
 }
 }

OnOrderStatusChanged is an abstract class what OnOrderDelivered and OnOrderPostponed extends it. until now we could create our events and raise them. now if you create a spring test and call deliver method of an order you will see “Order:X status is changed to DELIVERED” The last step is doing something when these events published. we want to send an email to the customer when these method raised. additionally it’s valuable for customer to posting the product when his order is in delivered state.
Listeners are simple Beans that implements generic ApplicationListener interface. Parameter type in this interface is the type of event that you want to listen to it. it is possible to defince parameter type as the parent and listen to all of its childres. for example in our model if we use OnOrderStatusChanged our listener will catch all event from OnOrderDelivered and OnOrderPostponed

It can be suitable for sending email in our scenario. but we don’t use this model and create two different listener for them.

As you see below their code is very simple

@Service
 public class OrderDeliveredEmailSender implements ApplicationListener,Ordered {

@Override
 public void onApplicationEvent(OnOrderDelivered event) {
 System.out.println(String.format("Message sent for delivered order to:%s ORDER-ID:%s",event.getOrder().getCustomerInfo().getEmail(),event.getOrder().getOrderId()));
 }

@Override
 public int getOrder() {
 return 100;
 }
 }

@Service
 public class OrderPostponedEmailSender implements ApplicationListener {

@Override
 public void onApplicationEvent(OnOrderPostponed event) {
 System.out.println(String.format("Message sent for postponed order to:%s ORDER-ID:%s", event.getOrder().getCustomerInfo().getEmail(), event.getOrder().getOrderId()));
 }
 }

These two beans will fire onApplicationEvent when  correspond event is raised. For posting product to the customer we need to create another Listener for OnOrderDelivered event.

@Service
 public class OnOrderDeliveredPost implements ApplicationListener,Ordered {
 @Override
 public void onApplicationEvent(OnOrderDelivered onOrderDelivered) {
 System.out.println(String.format("Order:%s is posting for customer.",onOrderDelivered.getOrder().getOrderId()));
 }

@Override
 public int getOrder() {
 return 1000;
 }
 }

As you see this listener will send product to the customer when its state is DELIVERED. But wait there what is Ordered interface? if you have not use org.springframework.core.Ordered interface, it is valuable to know that with using this interface you can define the order between beans in a collection. in our scenario customer like to receive an email before we post the product to him. for this purpose these two class implement Ordered interface, don’t forget the lowest order has the highest priority.

*Single Responsibility Principle

You can download source code from : https://github.com/psycho-ir/spring-event.git