Friday, February 22, 2013

Test fixtures - using XML Spring bean definition vs Java Configuration

Spring's Java based container configuration is a neat way of specifying Spring bean configurations and in my own projects I have systematically replaced XML configuration with Java Bean configuration where feasible.

However, there are still a few places where an XML bean configuration is a better fit than the Java Configuration, here I am focusing on one such use case.

Consider a test case which requires a fixture with a lot of test instances of domain classes, assume a simple domain of a Member(a person) with an address. This would be expressed the following way using a Spring XML configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:c="http://www.springframework.org/schema/c"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean name="member1" class="el.Member" c:first="First1" c:last="Last1" c:address-ref="address1"/>
 <bean name="member2" class="el.Member" p:first="First1" p:last="Last1" p:address-ref="address2"/>
 <bean name="member3" class="el.Member" p:first="First1" p:last="Last1" p:address-ref="address3"/>
 <bean name="member4" class="el.Member" p:first="First1" p:last="Last1" p:address-ref="address4"/>
 <bean name="member5" class="el.Member" p:first="First1" p:last="Last1" p:address-ref="address5"/>
 
 <bean name="address1" class="el.Address" c:city="City1" c:state="State1"/>
 <bean name="address2" class="el.Address" p:city="City2" p:state="State2"/>
 <bean name="address3" class="el.Address" p:city="City3" p:state="State3"/>
 <bean name="address4" class="el.Address" p:city="City4" p:state="State4"/>
 <bean name="address5" class="el.Address" p:city="City5" p:state="State5"/>
</beans>




The good thing about this configuration is that it is very easy to see the list of entities with Spring's c (constructor) and p(property) custom xml namespaces allowing a very concise expression.

On the other hand if the same fixture had been created through Java Configuration it would be a little more verbose, especially for cases where setters are used(like in member5 below):

@Configuration
public class FixturesJavaConfig {

 @Bean public Member member1(){return new Member("first1", "last1", address1());}
 @Bean public Member member2(){return new Member("first2", "last2", address1());}
 @Bean public Member member3(){return new Member("first3", "last3", address1());}
 @Bean public Member member4(){return new Member("first4", "last4", address1());}
 
 @Bean public Member member5(){
  Member member = new Member();
  member.setFirst("first5");
  member.setLast("last5");
  member.setAddress(address5());
  return member;
 }
 
 @Bean public Address address1(){return new Address("city1", "state1");}
 @Bean public Address address2(){return new Address("city2", "state2");}
 @Bean public Address address3(){return new Address("city3", "state3");}
 @Bean public Address address4(){return new Address("city4", "state4");}
 @Bean public Address address5(){return new Address("city5", "state5");}
}

A matter of choice at the end of the day I suppose, but this has become a pattern that I have been using now - use Java Configuration where feasible, but use XML configuration for cases where a bunch of test fixtures need to be created.

Thursday, February 7, 2013

Spring Bean names

Spring bean names are straightforward, except for cases where names are not explicitly specified.

To start with, Spring bean names for an xml based bean definition is specified this way:

<bean name="sampleService1" class="mvcsample.beanname.SampleService">
 <constructor-arg>
  <bean class="mvcsample.beanname.SampleDao"></bean>
 </constructor-arg>
</bean>

For a Java @Configuration based bean definition, the method name of the @Bean annotated method becomes the bean name:

@Configuration
@ComponentScan(basePackages="mvcsample.beanname")
public static class SpringConfig{
 
 @Bean
 public SampleService sampleService(){
  return new SampleService(sampleDao());
 }
 
 @Bean
 public SampleDao sampleDao(){
  return new SampleDao();
 }
 
}


and for Stereotype annotation(@Component, @Service, @Repository etc) based beans, the value field indicates the bean name:
@Repository("aSampleDao")
public class SampleDao {
    ...
}

@Service("aSampleService")
public class SampleService {
    ...
}

Now, what happens for cases where the bean name is not specified.

XML Based Bean Configuration Case:
For an xml based configuration, a case where the bean name is typically not specified are for beans which can act on the entire bean factory - say for eg, to define a BeanPostProcessor or a BeanFactoryPostProcessor
For eg. consider the following dummy BeanPostProcessor that just grabs all the bean names from bean factory:
public class BeanNameScanningBeanPostProcessor implements BeanPostProcessor{
 private List<String> beanNames = new ArrayList<>();
 @Override
 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  return bean;
 }

 @Override
 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  beanNames.add(beanName);
  return bean;
 }
 
 public List<String> getBeanNames(){
  return this.beanNames;
 }
}

It would typically be defined in an xml bean configuration this way:
<bean class="mvcsample.beanname.BeanNameScanningBeanPostProcessor"/>

A second case with xml based configuration where a name is typically not specified is with inner beans, for eg. defined this way:
<bean class="mvcsample.beanname.SampleService">
 <constructor-arg>
  <bean class="mvcsample.beanname.SampleDao"></bean>
 </constructor-arg>
</bean>

The bean names for these cases is handled by a component called the BeanNameGenerator. For the case of a top level bean the name typically ends up being the package qualified class name along with a count of the instances, this way:

mvcsample.beanname.BeanNameScanningBeanPostProcessor#0

For the case of an inner bean, since it exists only in the scope of its containing bean, the name is not that relevant, however internally it does get a name based on the hex hash code of the bean definition for eg, "mvcsample.beanname.SampleDao#1881ee8b"


Java Based @Configuration Case:
For java based @Configuration on the other hand it is not possible to specify a bean without a name, the bean name is the method name.

Annotation based Configuration
For stereotype annotation based bean, if the name is not explicitly specified with the value field of stereotype annotations, then the name is again generated by AnnotationBeanNameGenerator which is an implementation of the BeanNameGenerator strategy interface, the names generated is simply the short name of the class, for eg from the javadoc for AnnotationBeanNameGenerator - bean name for com.xyz.FooServiceImpl becomes fooServiceImpl.

Conclusion:
So to finally conclude, if bean names are relevant to you in some way(for eg to disambiguate between multiple bean instances of same type), then it is best to be explicit about the names, otherwise depend on Spring to generate the bean names for you. In some cases, for eg. with Spring-data project it is possible to specify custom behavior for repositories as a separate bean and Spring-data by default uses Spring naming conventions to find the custom implementation and understanding how bean names are generated helps.


Friday, February 1, 2013

atan2 in scala

atan2 function is defined as follows:



I wanted to try a small exercise of implementing this using scala(ignoring the fact that it is already natively implemented in java.lang.Math library).

The simplest implementation that I could think of is with a if expression this way:


def atan2(x: Double, y: Double):Double = {
  if (x >0)                     atan(y/x)
  else if (y >= 0 && x < 0)     Pi + atan(y/x)
  else if (y < 0 && x < 0)      atan(y/x) - Pi
  else if (y > 0 && x==0)       Pi/2
  else if (y < 0 && x==0)       -Pi/2
  else                          Double.NaN
}

However, I wanted to see at this point if it could be reimplemented using a case-match expression, and I could only come up with a souped up version of if/else this way:

def atan2(x: Double, y: Double): Double = {
  true match {
    case _ if (x>0)             => atan(y/x)
    case _ if (y >= 0 && x < 0) => atan(y/x) + Pi
    case _ if (y < 0 && x < 0)  => atan(y/x) - Pi
    case _ if (y > 0 && x==0)   => Pi/2
    case _ if (y <0 && x==0)    => -Pi/2
    case _                      => Double.NaN
  }
}

After reading up a little more on scala extractors, I could come up with a crazier version of the same:
def atan2(x: Double, y: Double): Double = {
  (x, y) match {
    case xgt0()           => atan(y/x)
    case ygte0Andxlt0()   => atan(y/x) + Pi
    case ylt0Andxlt0()    => atan(y/x) - Pi
    case ygt0Andxeq0()    => Pi/2
    case ylt0Andxeq0()    => -Pi/2
    case _                => Double.NaN
  }
}

However, this unfortunately requires defining 5 extractors this way:
object xgt0 {
 def unapply(tup: (Double, Double)): Boolean = tup match { case (x,y) => (x>0)}
}

object ygte0Andxlt0 {
 def unapply(tup: (Double, Double)): Boolean = tup match { case (x, y) => (y >= 0 && x < 0)}
}

object ylt0Andxlt0 {
 def unapply(tup: (Double, Double)): Boolean = tup match { case (x, y) => (y < 0 && x < 0)}
}
 
object ygt0Andxeq0 {
 def unapply(tup: (Double, Double)): Boolean = tup match { case (x, y) => (y > 0 && x == 0)}
}

object ylt0Andxeq0 {
 def unapply(tup: (Double, Double)): Boolean = tup match { case (x, y) => (y < 0 && x == 0)}
}

The only conclusion I could make out of this is that if I had to re-write atan2 in scala the best approach is probably using the first one - using if expression. I am sure there is definitely a more scala way of doing this and would definitely appreciate any suggestions on these approaches