Showing posts with label Business Layer. Show all posts
Showing posts with label Business Layer. Show all posts

Thursday, January 5, 2012

jDTO Binder 0.7 Released

I'm proud to announce the release of version 0.7 of jDTO Binder, the java framework to populate DTO objects easily.

This release includes the latest bugfixes and two new features:

Default configuration file.

The jDTO framework has the "convention over configuration" philosophy and therefore a new convention was introduced: If there is a package resource called jdto-mappings.xml on the default package, then it will use that configuration file instead of the annotations config, so now, if you're using CDI, you have the option to map your DTOs using an XML configuration file.

Read / Write Maps

The framework has gained the ability to read and write maps, so now implementations of the java.util.Map interface can be used to populate DTO's and can be populated out of objects.

The following code snippets demonstrates how to use this feature.

Map from object:

SimpleEntity entity = new SimpleEntity("myString", 23, 34.45, true);

HashMap<String, Object> map = binder.extractFromDto(HashMap.class, entity);


String strVal = (String) map.get("aString");
int intVal = (Integer) map.get("anInt");
double doubleVal = (Double) map.get("aDouble");
boolean boolVal = (Boolean) map.get("aBoolean");

Object from map:

HashMap<String, String> values = new HashMap<String, String>();

values.put("myString", "simpleString");
values.put("related.aString", "relatedString");

SimpleAssociationDTO dto = binder.bindFromBusinessObject(SimpleAssociationDTO.class, values);

These new features enables the users of the framework to explore new posibilites for example populating objects from properties files in a really elegant way.

Sunday, June 26, 2011

Spring AOP Scoped Proxies

In this post I'll be discussing the Spring AOP Scoped Proxies as a way to expand the scope of the beans managed by the spring IoC container. So far we know two types of scopes common to the IoC container: Singleton, just one instance per container, and Prototype, one instance per client (of the bean). The previous two scopes can give us an idea of stateless/stateful beans but in some context there are other contexts that can be useful, for example in a web application we can think on the scope of a request or the scope of a session to make parts of the application that only makes sense on a web context.

It's true that the right thing to do when we're designing our backend is to try and do the whole functionality as independent of the context as possible but sometimes having a bean that depends on the context makes the application logic so simple, elegant and easy to code that we're tempted to make things that way, for example, if we're coding an application logic that depends a lot on the information of the currently logged user it would be really handy to have in our bean something like this:
 @Autowired
private CurrentUser currentUser
And then get the data as we please. But the thing is with the prototype scope or singleton scope it would be very difficult to achieve this, specially when a lot of users ar accessing the app simultaneously. So to this purpose we'll configure the AOP scoped proxies.

First of all, we'll speak about the dependencies we need:
  • Spring AOP, to have the AOP functionality in our application.
  • CGLIB if we're going to have proxies for classes that doesn't implement any interface.
Then, we'll have our standard configuration but apart from that, some special configuration so spring can tell which request matches to which thread and thus access the session and request scopes.

We'll add the following lines in our web.xml file:
   <listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
Finally we configure the bean to be session scoped or request scoped:

 @Service
@Scope(value="session",proxyMode= ScopedProxyMode.TARGET_CLASS)
public class CurrentUser implements Serializable {
//session data here
}

If we're configuring our beans in the XML fashion, then we add the tag:
 <bean ... scope="session"> 
<aop:scoped-proxy/>
</bean>
To our bean definition and that's it. Really easy and really clean because our bean logic doesn't get dirty with Servlet spec classes and if we need to switch this logic to be for instance a desktop application, we can always switch the bean to be singleton and take care of it by ourselves.

Friday, April 29, 2011

Drools as a replacement for the 'Composite Strategy' design pattern.

When facing the need to implement complex business rules over the classical object-oriented approach we always fall down to one of the following solutions:

Spaghetti code:
 if (bill.getAmmount() > 100) {
//apply the best calculation for the store
if (customer.getAge() > 65) {
//apply the senior citizen discount
bill.setAmmount(bill.getAmmount() - 10);
if (customer.isPremium()) {
//apply 10% discount
}
} else {
if (customer.isPremium()) {
//apply 10% discount
}
}
}
Can you guess the business rules out of that code? What about adding a new rule?

The Composite Strategy design pattern:
 DiscountStrategy ds = buildStrategy(customer, bill);
ds.applyDiscounts();
In this last case we would need to create five classes and one interface, one per business rule, one for the composite strategy (to decide in which order is best to apply the strategies) and one strategy factory (to decide which strategies apply). Thats a lot of classes!! And also it would be really hard for any person to understand what were the business rules in the first place.

The bottom line is, we have three business rules:
  • Only bills with value higher than $100 can have discounts.
  • Senior citizens have $10 discount on their purchase.
  • Premium customers have 10% discount on their purchase.
For the cases where two discount policies can be applied we have two situations: what is best for the store and what is best for the customer, and all of this highly affects the readability and maintainability of the code, and also the addition of one simple new rule can make things worse!

The drools approach:
Drools helps us defining complex business logic introducing a new way to face problems: Logical programming. We can define all of our business rules in an elegant fashion:
 package com.juancavallotti
global Bill bill;
import function com.juancavallotti.DiscountLogic.applyDiscount;
rule "Discounts are only for bill over 100 dollars"
salience 20
when
$customer : Customer( )
$bill : Bill( ammount <= 100 )
then
System.out.println("Low value bill");
retract($customer);
retract($bill);
end
rule "Senior Citizen Discount"
salience 10
no-loop
when
Customer( age > 65 )
then
System.out.println("Senior Citizen Discount");
bill.setAmmount(bill.getAmmount() - 10);
end
rule "Premium Customer Discount"
salience 0
no-loop
when
Customer( premium == true )
then
System.out.println("Premium Customer Discount");
bill.setAmmount(applyDiscount(bill.getAmmount(), 10));
end
In the file (called discount.drl) we define our business rules in a very simple format. Now if the business requirements change, we only need to add more rules to the file in a declarative way and the rules engine takes care of how those rules will be applied on our objects.

Also we gave priority to our rules with the "salience" rule property, the greater the salience the more priority the rule has.

I've added the "no-loop" rule property so the rules don't get applied more than once.

Finally the discount service would look as simple as this:
 public class DiscountLogic {
private StatefulKnowledgeSession kbSession;
public DiscountLogic(StatefulKnowledgeSession kbSession) {
this.kbSession = kbSession;
}
public Bill applyDiscountPolicy(Customer customer, Bill bill) {
kbSession.insert(customer);
kbSession.setGlobal("bill", bill);
kbSession.insert(bill);
kbSession.fireAllRules();
return bill;
}
public static double applyDiscount(double ammount, double discountPercent) {
return ammount * (1 - discountPercent / 100f);
}
}
In order to inject the StatefulKnowledgeSession instance we need to add some boilerplate code that will bootstrap our knowledge base and compile the rules and so. You may want to download the sample code and play with it.

To learn more about drools, please refer to the drools documentation. (We are currently having fun with the drools-expert module).

Have Fun!