Saturday, 24. November 2007

goodbye, and thanks for hospitality

This will be my last entry at this blog.

I moved over to my new home gleichmann.wordpress.com.
Although i had a good time here (my first blogging experience), there were some factors for this switch.

First of all, my blog is a rather technical one, including a lot of source code that should be displayed in a formatted way. Unfortunately there were some problems in this area, forcing me to reformat the code manually whenever i re-edited an entry, because the formatting was gone (i will not exclude the possibility, that this was my fault...).

Because blogging here was fun and a unique experience to me, my new blog will also bear a new name - 'round about dev' belongs to this blog and should also stay unique.

Thank's to blog.com for hosting this blog - i will not delete it yet, since there may be some links that might refer to some of it's entries.

For all of you, who took or still take a look at some of my thoughts, i would be glad to welcome you at my new blog 'brain driven development'.

Have a good time!

Mario
Posted by mario.gleichmann at 22:07:32 | Permanent Link | Comments (0) |

Monday, 17. September 2007

behaviour driven development with beanSpec

first of all, this is no introduction to Behaviour Driven Development, as there are already many great articles and informations available, so the world doesn't need another entering guide yet.

this post is rather an introduction to beanSpec, a little tool for writing specifications in the sense of BDD in Java. beanSpec tries to provide a clear conceptual model that is easy to capture and apply (if you've seen RSpec so far, you will immediately feel familiar with beanSpec, because the conceptual model is almost the same).

beanSpec by example

let's dive into beanSpec by example - specifying the behaviour of java.util.Stack (ok, that's not the most fancy example, but it will serve the purpose of an introduction very well. in addition to that, you can compare it to the given @Stack example at RSpec's home and see the conceptual similarities).

we start the example with a new specification class, as all specifications within beanSpec start by extending beanSpecs class Spec:

public class StackSpec extends Spec {
}

that was easy!
now we want to specify the behaviour of a non empty Stack. therefore we simply have to define a method that will specify that context, so we should name our method according to the particular context ('a non empty Stack').

public class StackSpec extends Spec {

  @Specification
  public void a_non_empty_Stack(){
  }
}

i used a rather unusual style for the methods name (it increases the readability of the Spec in my opinion). of course you could use good old camel case style whenever you want to! further on, you may have noticed the annotation @Specification. it's for marking only those methods within your Spec, which should be evaluated, since you are free to have arbitrary helper methods within your Spec.

context

next we firstly have to describe the context within the method's body, that is a non empty Stack:

...
@Specification
public void a_non_empty_Stack(){
 
  final String lastItemAdded = "elem 3";
        
  Stack aNonEmptyStack = is(
            
    new DescriptionOf <Stack>(){
            
      public Stack isDescribedAs(){
        Stack<String> stack = new Stack<String>();
        stack.push( "elem 1" );
        stack.push( "elem 2" );
        stack.push( lastItemAdded );
        return stack; } } );
  ...

we've pushed three elements onto the Stack. Note, that we've defined the last pushed element outside the description, since we will refer to that element in the following statements.

statements

now we are ready to specifiy the behaviour of this context within the method. therefore we declare every expected behaviour in a textual style, followed by one or more operations and statements, that will specify the behaviour programmatically in a checkable way:

...
  it( "should not be empty" );
  state( aNonEmptyStack ).should( not( be( empty() ) ) );

  // or alternatively: state( aNonEmptyStack.empty() ).should( be( true ) );
...

predicates

using predicates for defining the claimed behaviour (that is the expression inside the called should() method) gives you the freedom to combine such predicates in any combinations that makes sense to your specific context. since it's very easy to write your own predicates, it's even possible to come up with your own set of domain specific predicates, giving you the chance to build a kind of domain specific vocabulary for your specifications.

for example we could be in need of a predicate that checks the given result of a statement against a regular expression, so that we could state the following:

...
it( "contains only elements that start with 'elem'" );
for( Object elem : aStackWithThreeElements.subList(0, 3) ){
  state( elem ).should( match( "elem.*" ) );
}

of course this special predicate makes no sense in the actual context (and even would fail, since our last pushed element isn't compliant in regard to the stated pattern), but for demonstrations sake here's the predicate we would have to come up with:

public class MatchPredicate extends AbstractPredicate {

  private String pattern;
    
  public MatchPredicate( String pattern ){
    this.pattern = pattern;
  }
    
  public boolean isValidFor(Object bean) {        
    return bean.toString().matches( pattern );
  }

  public static Predicate match( String pattern ){
    return new MatchPredicate( pattern );
  }
}

now that we've seen how easy it is to extend beanSpec's vocabulary with domain specific predicates, let's have a second look at some of the predefined ones, that you can use out of the box:

...
  it( "should return the top item when sent #pop" );
  state( aNonEmptyStack.pop() ).should( be( lastItemAdded ) );
        
  it( "should return the top item when sent #peek" );
  state( aNonEmptyStack.peek() ).should( be( lastItemAdded ) );
        
  it( "should NOT remove the top item when sent #peek" );
  aNonEmptyStack.peek();
  state( aNonEmptyStack.peek() ).should( be( lastItemAdded ) );
        
  it( "should remove the top item when sent #pop" );
  state( aNonEmptyStack.pop() ).should( be( lastItemAdded ) );
  while( ! aNonEmptyStack.isEmpty() ){
    state( aNonEmptyStack.pop() ).should( not( be( lastItemAdded ) ) );
  }
...

you may have asked yourself why you are able to call the method pop() in the first statement, and then stating in the next one, that the top level element is even the lastItemAdded (but pop() should have removed that element in the previous statement, right?).

this is one of the mechanics of beanSpec: every single specification statement (starting with it() ) gets a fresh new Stack object according to the definition at the start of the method. you then can operate on that object within your operations and state() expressions and change it's state if necessary. as soon as you start with a new specification statement (initiated by the next it() call) you'll again operate on a new instance.

specification templates

let's assume we want to specify the behaviour of Stack in another context (i.e. empty Stack, full Stack, Stack with one element left to full, ...).
it's very likely that you have to repeat some of your statements. according to the DRY principle, beanSpec gives you the chance to define one ore more so called specification template methods, that can be refered in your concrete context specifications:

...
// specification template
public void a_non_empty_Stack( Stack aNonEmptyStack, String lastItemAdded ){       
           
  it( "should not be empty" );
  state( aNonEmptyStack ).should( not( be( empty() ) ) );
  ...
}

// another specification template
public void a_non_full_Stack( Stack<Object> aNonFullStack ){

  it( "should add to the top when sent #push" );
  Object newlyPushedElement = aNonFullStack.push( "new Element" );
  state( aNonFullStack.peek() ).should( be( newlyPushedElement ) );
}

@Specification
public void a_stack_with_3_elements(){
        
  final String lastItemAdded = "elem 3";
        
  Stack aStackWithThreeElements = is(
            
    new DescriptionOf <Stack>(){
            
      public Stack isDescribedAs(){
        Stack<String> stack = new Stack<String>();
        stack.push( "elem 1" );
        stack.push( "elem 2" );
        stack.push( lastItemAdded );
        return stack; } } );
        
  itShouldBehaveLike( "a_non_empty_Stack", sharing( lastItemAdded ) );
        
  itShouldBehaveLike( "a_non_full_Stack" );
        
  // additional Statements
  it( "should be of size 3" );
  state( aStackWithThreeElements ).should( have( size( 3 ) ) );
  ...
}

as you can see, there are two specification templates. a specification template takes at least one argument - the object that must stand the stated specifications within the template. should there be other information that should be shared, they will follow as additional arguments.
now you can refer to those specification templates by stating itShouldBehaveLike, followed by the name of the template.
note, that the 'object to specify' is implicitly populated by beanSpec itself. all additional arguments that should be shared with the template have to be populated via an explicit sharing() statement.

specification verification summary

having specified the behaviour (and implemented Stack), we can check if Stack behaves as expected by running the StackSpec (at the moment there's only a ConsoleRunner).
beanSpec gives a summary of the evaluated specification, making it easy to read the whole specification in a textual form and recognize any misbehaviour, should one of the stated specifications should fail.

STACKSPEC
---------------

a_stack_with_3_elements
 - should not be empty : ok
 - should return the top item when sent #pop : ok
 - should return the top item when sent #peek : ok
 - should NOT remove the top item when sent #peek : ok
 - should remove the top item when sent #pop : ok
 - should remove the top item when sent #pop : ok
 - should remove the top item when sent #pop : ok
 - should add to the top when sent #push : ok
 - should be of size 3 : ok
 - contains only elements that start with 'elem' : failed

statements : 10, ok : 9, failure : 1

an_empty_Stack
 - should add to the top when sent #push : ok
 - should complain when sent #peek : ok
 - should complain when sent #pop : ok

statements : 3, ok : 3, failure : 0


Specs : 2, total statements : 13, ok : 12, failure : 1

that's it so far - a short introduction to beanSpec.
i would love to hear some feedback from you, should it be criticism or feature requests - any feedback is appreciated!
 

Posted by mario.gleichmann at 00:05:53 | Permanent Link | Comments (2) |

Friday, 07. September 2007

is it about fancy titles in software development? no! it's about your attitudes!

I've read some articles in the past that discuss the importance and hence difference between some titles or roles which are involved in software development. Whether it's the discussion of 'Programmer vs. Developer', 'Developer vs. Designer' or 'Designer vs. Architect' - all those essays contain not more than hollow words to me, since they first of all argue about nifty titles.

In fact, when it comes down to the core of software development - it's the value we create for our customers that counts, no matter if we're called an architect or designer. questions like 'are you a programmer or developer' are completely irrelevant, as it doesn't matter if we don't take responsibility for what we're 'producing'.

given a sound technological background - compare an 'architect' who doesn't take care about the projects progress (i've seen some of them which seem to be interested in the more funny things - building a technical prototype and leaving the project prematurely without taking care about the shortcomings of their consigned 'architecture') and a 'developer' who's all in all interested in the quality of her results. which of those will give more value to the overall goals of a project?

do we really add value in respect to our customers needs at everyday work? do we take responsibility in your professional environment?
independent of a particular functioning within a project, the following attitudes are considered essential when we want to take care about the long term value of our work.

passion

passion drives us to the limit. we don't settle for a half baked solution.
for example, we don't want a solution (even in the small) not only to work as required, but also in conjunction with the projects goals, that may be code that's easy to refactor or readable and easy to maintain (as Martin Fowler said: 'any fool can write code that works ...').
accepting the surrounding forces, we want to get the job done in the best way that is satisfactory for all participants.

empathy

we not only produce artifacts. we also produce means that will help others to get their job done, too (be it the end user or our very next team mate, who's efforts are based on our products).
for example, we not only want to write code that is somehow well structured, but code that is comprehensable to other developers, giving them orientation, i.e. helping to maintain or evolve the code.
we not only think about getting a job done, but getting it done in a way that will provide meaning or at least support for others, helping the project to progress.

curiosity

we not only work with our brain turned of, but strive for knowledge that will help to produce solutions that are in conjunction with the needs of our clients.
for example we not only implement relayed requirements blindly, but want to give productive feedback when recognizing contradictions, inconsistencies or incomplete specifications.
we not only will produce only as much as mandated to accomplish a single task but also use our head and/or question until we understand in order to produce solutions that are truely essential to our customers.

communicative

we share our insights, giving others the chance to evolve or at least avoiding to make mistakes (may the ones that we've encountered the hard way).
for example, we not only want to give documentation but to ensure that others understand our results in the right way.
we not want to fight a one-man-show for others, but know that the whole team is essential to progress and hence help among each other by passing relevant knowledge.

courage

we adress problems, even if they are uncomfortable for us or the team in the short term, but to avoid greater damage in the long run when concealing it.
for example, if we encounter a design flaw that we can bypass in order to get our current task done, we even adress the problem officially, giving the chance for a decision towards a more expensive solution.
we aren't keeping quiet about problems, giving the customer the chance to react, even if such problems are unpleasant for all participants.

pride

we are proud about the products we create. those pride is expressed in the achievable quality of our products under the given circumstances.
for example we we're willingly 'sign' a class or component with our name, giving others the chance for feedback or questions. We stand to the code that we've produced.
we're not proud of the title we've received within a project. we're rather proud of what we're contributed to the overall goals of the project!

what's real important

so what's the bottom line?

the importance of our role in a software development project doesn't come with an official title. It's more about how much we'll take care about the projects goals, feeling responsible about what we are contributing to the project in the long term!

it's time to get 'titled' by the real value you'll produce for the project and your customer in the end, than by some official role names.

Posted by mario.gleichmann at 00:33:15 | Permanent Link | Comments (0) |

Monday, 03. September 2007

why DAO won't die

there were some statements and blog posts about the end of the DAO pattern in the last weeks, especially in conjunction with the rising of EJB 3 and it's EntityManager. those proposals suggest to use EntityManager directly inside your business oriented services instead of encapsulating data access logic through a DAO.

i strongly disagree with this opinion. Here are some of my thoughts, why DAOs will live on:

mixing business logic with data access logic

you are tangling data access logic with business logic, especially when you have to build not only simple queries (not talking about the simple CRUD operations) but introduce i.e. more complex query building logic next to your business logik.

violation of single responsibility principle

mixing business logic and data access logic in one place gives you at least two differents reasons / causes to change.
on the one side, you may have to adapt the core business logic due to new requirements. on the other side data access logic may also change (maybe joining another table for an aggregation because of changes in the data model)

reduced readability

when you mix business logic with more complex data access logic, readability of your business services core purpose is hindered.
EntityManager provides a fixed, generic API, agnostic to your current domain context. everything within data access logic that goes beyond simple CRUD- operations has to be implemented within the service. but i only want to 'see' my core business logic in first place, not worrying about the data access logic - you should only see the WHAT, not the HOW of that data access logic. the HOW should be hidden behind a reasonable, intention revealing interface for the sake of comprehensibility.

mixing business logic and infrastructure

you are binding your business services to a special technology. i rather wouldn't mix business logic with infrastructure / technology, even if the chance is very small that technology changes, but keeping business logic free of any infrastructure (ok, this seems to be a little bit dogmatic, but binding to a special technology fixes your business logic in a very hard way, especially if you want to reuse your business logic within another technical infrastruture).

harder to test

creating mocks for EntityManager is potentially harder, since you may pass complete queries (EJB QL expressions). your mock have to inspect those query statements on a semantic level in order to behave correctly, which may be not so trivial.

lacks uniform style of representing different data sources

in a system where you have to access not only one type of data source (i.e. a relational database, an ldap database, legacy integration via message queues, ...) you'll know have different styles / levels of integration. those access logic isn't hidden behind an abstract interface any longer. but the client of those data sources shouldn't worry about the kind of data source. this should be encapsulated.
(in this case it's not the question, that it's extremely rare to replace one kind of data source with another one, but having most of times different types of data sources in parallel)

lacks uniform style of data access strategies

using EntityManager directly bounds you to the offered possibilities of its API. should you like to use JDBC in special cases or an alternative qriteria API, you'll end up with different data access technologies within your service.

violation of open closed principle

your business service is not open for extensions due to data access logic without changes, because it depends directly to the technical API. for example you can't exchange an existing data access / query building strategy (i.e. building a query string dynamically vs. using a query API) - you have to modify the business service itself, since you don't hold control of the EntityManager's implementation.

violation of dependency inversion principle

your higher level component (your business service) is directly dependend on a lower level component (EntityManager)
even if EntityManager is an interface, since you don't hold control of it's implementation (not now, not in the future), you are directly bound to it's API and it's implementation. should the interface of EntityManager change - the service has to change, too.
(if using dependency inversion principle the right way, it's not relevant if the underlying DAO interface will change, because THERE IS NO DAO interface in its own right. there is no DAO interface in its own right since the clients define there data access needs, means that there may be many DAO interfaces which belong to the different clients and not to the DAO implementation. this goes along with the interface segregation principle - see Agile Software Development by 'Uncle Bob' Robert C. Martin)

 

of course - like most design decisions - it's a matter of choosing the one or other side of a trade off. So one is right to say it depends on the context whether to use a DAO or directly include data access logic inside a business service - but you have to be clear about the consequences (which should be aligned with the projects goals which in turn should be also clear). And 'killing' the DAO comes with the mentioned ones.

Posted by mario.gleichmann at 20:37:40 | Permanent Link | Comments (17) |

Saturday, 25. August 2007

mimicry in action II - dynamically implement an interface using Dynamic Proxy

this entry is the continuation of part 1, where we saw how to leverage Dynamic Proxy in order to let an object appear as if it would implement an arbitrary interface as long as it offers the same methods.

extensions

in this second part we'll extend the solution in order to map required methods of an interface to an object's methods, even if those methods partially bear another name (or offer sybtypes of the required arguments, even if they are placed in a different order).

a fluent interface

one fundamental goal is a simple and fluent api in order to support ease of use, allowing a simple and declarative style of usage - well, we'll see ...

for clarity, we will modify our example - imagine that class Foo has no longer a matching method echo(), but a method called reverb():

public class Foo {
    public String say( String msg ){
        return "foo said " + msg;
    }
    ...
}

now we want to (have to) map the required method echo() of interface IBar to reverb(). we'll start with thinking about a possible api extension and have some thoughts about it's implementation afterwards. a possible way to express the mapping could look like this:


barClient.speakTo(
  foo.as( IBar.class, map( "echo" ).to( "reverb" ) ) );
 

mapping method names

as you can see, we only extend the signature in order to push one (or more) mappings to the proxy, using a statically imported method map(). therefore we will use varargs in the following solution, so it's completely free to the client to apply as many mappings as needed:

public class InterfaceMimic
  implements InvocationHandler{

    public static <I> I mimic(
      Object bean,
      Class<I> asInterface,
      MethodMapping...mappings ){
        return
            (I) Proxy.newProxyInstance(
                bean.getClass().getClassLoader(),
                new Class[]{asInterface},
                new InterfaceMimic( bean, mappings ) );
    }
    
    public static MethodMapping map(
      String interfaceMethod ){
        return
          new MethodMapping( interfaceMethod );
    }
    
    private MethodMapping[] mappings =
      new MethodMapping[0];
   
    private Object proxee = null;
    
    public InterfaceMimic(
      Object proxee,
      MethodMapping...mappings ){

        this.proxee = proxee;
        this.mappings = mappings;
    }
    ...
}

we're not finished yet. you surely saw the new type MethodMapping, which now extends the signature of method mimic() (formerly as() ) as a vararg.

MethodMapping

this type will hold the whole information about the mapping. you also saw the static factory method map(), which will create a new instance of MethodMapping initializing it with the name of the method required by the interface. what's left is the mapping link to the method which have to be called on the object:

public class MethodMapping {

    private String interfaceMethod = null;
    private String beanMethod = null;
    
    public MethodMapping(
      String interfaceMethod ){
       
      this.interfaceMethod = interfaceMethod;
    }

    public MethodMapping to(
      String beanMethod, Class...argTypes ){
        this.beanMethod = beanMethod;
        return this;
    }

    protected boolean matches(
      Method method ){...}

    protected Object callMappedMethodOn(
      Object bean, Method method, Object[] args ) {...}
    ...
}

now we only have to extend the proxy in order to hold the mappings and ask if there's one when intercepting a method:

public class InterfaceMimic
  implements InvocationHandler{
...
    public Object invoke(
      Object proxy,
      Method method,
      Object[] args )
        throws Throwable {

        MethodMapping mapping =
          findMappingFor( method );
        
        return
            mapping != null ?
                mapping
                  .callMappedMethodOn(
                    proxee, method, args ) :
                callProxy( method, args );
    }

    private Object callProxy(
      Method method, Object[] args) {
        try {
            return
                proxee
                    .getClass()
                    .getDeclaredMethod(
                      method.getName(),
                      method.getParameterTypes() )
                    .invoke( proxee, args );
        }
        catch (Exception e) {
            throw new RuntimeException( e );
        }
    }

    private MethodMapping findMappingFor(
      Method method ){
        for( MethodMapping mapping : mappings ){
            if( mapping.matches( method ) )
              return mapping;
        }
        return null;
    }
}

as you can see, we first try to find a matching MethodMapping. if one exists, we call the mapped method on the object. if not, we try to call a method on the object with the same name as the required one. that's all.

of course you could now extend type MethodMapping in order to additionally gathering information about the argument types of the mapped method and / or their different order, like so:

// reorderArgs will show on the first position,
// to which argument position the first interface
// argument will map, and so on ...
foo.as(
  IBar.class,
  map( "add" )
    .to( "calc", BigDecimal.class, int.class, String.class )
    .reorderArgs( 3, 2, 1 ) ) ); 

i'll leave this exercise to you. it should be no big challenge at all. if you want to see one possible solution, take a look at the open source project Bricks4J. i comitted the complete source along with a unit test in the current cvs branch, which will show you the correct usage.

conclusion

as you now have seen, Dynamic Proxy is a valuable tool when it comes to mimic interfaces. you can easily make an object appear as if it would implement an interface, even if this object methods doesn't match exactly by name or argument types.
of course you'll face a trade off - sometimes it might by easier and more comprehensible simply to implement an adaptor for an interface than using a bulk of mappings. so it's up to you - as always - to choose the right 'weapon' ...

Posted by mario.gleichmann at 21:25:14 | Permanent Link | Comments (2) |