My name is Juri Strumpflohner and this is my technical blog. I'm a kind of jun. software architect, .Net, Android, Web and Java dev, TDD and best practices promoter and martial arts practitioner.

Recent Posts Subscribe

Cross-Compiling Android Applications to the iPhone

Comment
Nice talk that gives insight in an approach for cross-compiling Android targeted apps to the iPhone (but not only). The idea is to overcome the problem of coding the mobile app for multiple platforms which often is just not feasible due to time and skills.
A thing which I find rather interesting is their decision to use XSL stylesheet transformations for doing the code generation stuff which is a somewhat alternative, but on the other side quite reasonable approach. They claim that it is not needed to tweak your - say - Android app in a special mode in order to be cross-compiled. It would be interesting to try that out, maybe I'll find some free time (which is improbable, but still...). On device specific features like Bluetooth operations etc. it certainly won't work I guess.

Duration
1h 9m

Tackle software dependencies with IoC and Dependency Injection

Coupling between objects creates "dependency", which per se is not bad at all. You will always have some dependencies among your objects. It becomes bad when it increases abnormally since that will make maintenance a nightmare. So what you'll do is of course to reduce dependencies in your code as much as possible. This means you first have to identify potential sources of bad dependencies which could possibly be avoided.

But how to identify them? 
Well, you could just imagine a change to an object and count how many objects you'd have to adapt to your changes such that your program still runs smoothly. Another possibility is to rely on code metrics such as "Coupling between objects" from the CK OO metrics suite. That can give you quite a good overview of potential problems in your application.

What are some examples/sources of coupling/dependencies?
There is a distinction between tight coupling and loose coupling.

  • Inheritance (tight coupling)
    Good OO designs will use inheritance heavily. Especially for exploiting polymorphism, nice hierarchies are created. But pay attention, inheritance is probably one of the strongest dependencies you can create, so it should just be used where it really makes sense: "For providing special behavior to an object". When you go down in the inheritance tree, objects should become more specialized, when you go up they should become more general. Inheritance shouldn't be used for instance to remove duplicate code. There is space for discussion here, however.
    You may consider using composition/aggregation instead or take a look at the decorator pattern. Another problem with inheritance is also that methods may be added and removed which may cause problems in large systems since you have to go and search where you should go and override the behavior.

  • Composition (loose coupling)
    Composition is already "better" in terms of coupling, since it creates loose coupling.

    public class MyClass{
       private ISomeInterface anInterface;
    }
    Note the usage of an interface here. I'll come back to that later. Composition creates loose coupling because when the interface changes you "just" need to adapt the dependent MyClass.

  • Instantiation (tight coupling)
    Another very common form of dependency comes through instantiation.

    public class MyClass{
       private PersistencyManager persistencyMan;
    
       public MyClass(){
          this.persistencyMan = new PersistencyMan();
       }
    }
    
    Again, a dummy example that shows the dependency created by instantiating a new object of type PersistencyManager inside the class MyClass (it doesn't matter where).

  • Instantiation through Factories/Service locators (loose coupling)

    public class MyClass{
       private PersistencyManager persistencyMan;
    
       public MyClass(){
          ConfigFactory myFactory = ConfigFactory.getDefaultFactory();
          this.persistencyMan = myFactory.getPersistencyManager(); //or through configuration
       }
    }
    
    Here the dependency is also on the Factory. This code however creates loose coupling because the process of creating objects is "outsourced" to another object. MyClass doesn't know how the object is being build.

  • Static methods, attributes or Singletons (tight coupling)

    public class MyClass{
       public void doSomeStuff(String userInput){
          ...
          MyHelper.helpMeOutWith(userInput);
          ...
       }
    }
    
    Here a dependency to a static "Helper" class is created which performs some logic.
I guess I covered most of the dependencies that may occur in your code. Well, everything nice and fine, but how should one handle/avoid these dependencies?? The main aim is to...
  • minimize the dependencies in your system by aiming for loose couplings and to
  • depend on interfaces only rather than concrete classes.
Remember, managing dependencies is the major challenge in designing good structured, large applications. If you're good in doing it, you'll have a nice time during maintenance.

The "magic" of an Inversion of Control (IoC) container and dependency injection
I'm not going to target to a specific technology now but rather I'd like to address the concept of dependency injection in general. Probably I'll focus on a specific example in a later post, let's see...

While "dependency injection" is nearly self-explanatory from an understanding point of view, "inversion of control" sounds like an obscure concept. At least that was my first impression when I took a look at it a couple of years ago. Let's start from the beginning (I'll make it short; promise). I'll often briefly make a jump to unit testing since my feeling is that that's where dependencies are really uncovered.
So, what we want is to have loose coupling in our code, but somehow we will have to instantiate our objects in order to be able to work with them. According to the the list above we'd probably choose factories or service locators.
public class MyCustomerService implements ICustomerService{
   private ICustomerDao customerDao;

   public MyCustomerService(){
      this.customerDao = (ICustomerDao)MyDaoFactory.getInstance(CustomerDao.class); //one example of retrieval
      ...
   } 

   //returns true if validation and persistency succeeded, false otherwise;
   //this could be more sophisticated of course, returning a number of validation problems
   public boolean saveAndValidateCustomer(Customer aCustomer){
      //a set of validation instructions for your customer object
      ...

      if(isAValidCustomer){
         customerDao.save(aCustomer);
         return true;
      }else{
         return false;
      }
   }
}
This may be a simple business logic class (in our service layer if we want so) which takes a customer, applies some validation on it and then delegates the persistency operation to the according DAO (Data Access Object). Note, we depend on interfaces here and the according dependency to the DAO object is created through a factory. This is the way you'd to it without IoC and DI (dependency injection). Now think about a unit test for the validation logic. What are the problems?? Well..we want to test the validation instructions inside the saveAndValidateCustomer(...) method but we don't want to test the persistency operation. That's out of scope of the unit test. But as you may have noticed, there is the customerDao.save(...) operation in it. We have to mock that out because we don't want to save something down or get annoying exceptions because some DB related stuff couldn't be loaded. Good we externalized the instantiation of the DAO into our factory and hopefully this factory depends on some configuration file which in the end determines which interface gets instantiated with which concrete type.
public class CustomerServiceTest{
   private ICustomerService customerService;

   public CustomerServiceTest(){
      MyDaoFactory.initializeWithConfig("mytestconfiguration.xml"); //test initialization
   }

   @Before
   public void setUp(){
      this.customerService = new CustomerService();
   }

   @After
   public void tearDown(){
      this.customerService = null;
   }

   @Test
   public void testSaveAndValidateCustomer(){
      Customer aCustomer = new Customer();
      //initialize aCustomer by setting its properties to a valid state

      boolean isValid = customerService.saveAndValidateCustomer(aCustomer);
      assertTrue("The customer object should be valid!", isValid);

      //continue and set the customer to an invalid state and check again
   }
}
Ok, we should be safe now to execute the test. Note you have to initialize your factory with some test objects which point to empty "mock" DAOs where the save operation doesn't have any side effects.
This example was without IoC and due to the usage of a factory the process of mocking out the DAO wasn't too complex. However, don't underestimate it, you have to create an appropriate configuration file and you have to somehow adapt your unit tests to use the "test" factory. But on the other side consider the case where you would have instantiated your DAO manually using new.

But still the example above needs a lot of logic just for retrieving the dependencies. IoC solves this. The concept goes down to the so-called hollywood principle: "Don't call me, I'll call you". Basically you don't retrieve you dependency but the dependency will be given, injected, to you at runtime. Thats why it's called "inversion" of control. It's not you that controls the setting of the instances directly, but the container does it. There are two different forms:
Constructor injection
public class MyCustomerService implements ICustomerService{
   private ICustomerDao customerDao;

   public MyCustomerService(ICustomerDao customerDao){
      this.customerDao = customerDao;
      ...
   } 

   public boolean saveAndValidateCustomer(Customer aCustomer){
      ...
   }
}
or
Setter injection
public class MyCustomerService implements ICustomerService{
   private ICustomerDao customerDao;

   public MyCustomerService(){
      ...
   } 

   public boolean saveAndValidateCustomer(Customer aCustomer){
      ...
   }

   public void setCustomerDao(ICustomerDao customerDao){
      this.customerDao = customerDao;
   }
}
The resulting test case is really simple!
public class CustomerServiceTest{
   private ICustomerService customerService;

   @Before
   public void setUp(){
      //in the constructor injection case:
      this.customerService = new CustomerService(new MockCustomerDao());

      //in the setter injection case:
      //this.customerService = new CustomerService();
      //this.customerService.setCustomerDao(new MockCustomerDao());
   }

   @After
   public void tearDown(){
      this.customerService = null;
   }

   @Test
   public void testSaveAndValidateCustomer(){
      //same as before
   }
}
Simple, isn't it? Unit testing becomes really simple in such cases. Normally when people claim their unit tests are too complex and therefore not done it is usually a sign they have too tightly coupled code and they therefore fail to mock out their dependencies.

Now, the way your dependencies get injected into your classes depend on the specific technology of the Inversion of Control container you're using. Generally the IoC container controls the lifecycle of your objects. You can configure your dependencies either through configuration files (usually in xml format) or through annotations inside your classes. It's just a matter of personal preferences. As mentioned I'll not go into those details now, maybe that will follow in a later post. Below there are some reference to popular dependency injection libraries.

Dependency Injection libs
Spring (Java)
Guice (Google, Java)
GInjector (Google, GWT, Java)
Spring.net (.Net)
Unity (.Net)

    GWT Button with image AND text

    GWT just provides the basic widgets like check boxes, hyperlinks, buttons etc...and leave the more complex ones to the developer or to 3rd party providers. For instance they don't have lists. Another thing which quite surprised me, their implementation of a button doesn't allow to have images AND text at the same time although a lot of Google products have it (Wave, GDocs, Gmail...).
    With GWT buttons you have mainly two possibilities, using Button or PushButton. The first is just the standard one while the latter allows to assign an image which is passed in its constructor. But also the PushButton doesn't allow to have both, image AND text visualized...which somehow seems to be a use case which is quite requested. A search on the web brought me to the GWT's JavaDoc describing a CustomButton widget which can be used like this:

    <g:PushButton ui:field='pushButton' enabled='true'>
     <g:upFace>
      <b>click me</b>
     </g:upFace>
     <g:upHoveringFace>
      <b>Click ME!</b>
     </g:upHoveringFace>
     <g:downFace image='{res.save}' />
    </g:PushButton>

    But also this kind of implementation doesn't allow you to have an image and text declaration...* uff *.

    So after that, similar as for the Hyperlink, I decided to implement one by myself. The implementation wasn't that difficult after all. Here's the source code:
    import com.google.gwt.resources.client.ImageResource;
    import com.google.gwt.user.client.DOM;
    import com.google.gwt.user.client.Element;
    import com.google.gwt.user.client.ui.Button;
    import com.google.gwt.user.client.ui.Image;
    
    public class CustomButton extends Button {
     private String text;
     
     public CustomButton(){
      super();
     }
     
     public void setResource(ImageResource imageResource){
      Image img = new Image(imageResource);
      String definedStyles = img.getElement().getAttribute("style");
      img.getElement().setAttribute("style", definedStyles + "; vertical-align:middle;");
      DOM.insertBefore(getElement(), img.getElement(), DOM.getFirstChild(getElement()));
     }
     
     @Override
     public void setText(String text) {
      this.text = text;
      Element span = DOM.createElement("span");
      span.setInnerText(text);
      span.setAttribute("style", "padding-left:3px; vertical-align:middle;");
      
      DOM.insertChild(getElement(), span, 0);
     }
     
     @Override
     public String getText() {
      return this.text;
     }
    }
    
    The according usage with the GWT UiBinder is the following:
    ...
    <!-- Declaration of your ImageBundle -->
    <ui:with field="res" type="com.sample.client.IDevbookImageBundle" />
    ...
    <d:CustomButton ui:field="buttonSave" text="Save" resource="{res.save}"></d:CustomButton>
    
    Pretty simple, isn't it? And it doesn't alter the button's behavior rather than adding the image. Some explanations might be needed as for instance you may wonder why I've overridden the setText(String), getText() of the standard Button widget. This was needed in order to wrap the text inside a span element which I can then identify when adding the image in order to position the image before the text. This has the drawback that a definition like
    ...
    <d:CustomButton ui:field="buttonSave"resource="{res.save}">Save</d:CustomButton>
    
    ...won't work.

    Moreover this widget may be enhanced by making it more configurable like adding the image after the text etc. I've also hard-coded some styles as you see in order to make the widget easier to use. The final outcome:

    Client-server communication peculiarities with GWT and App Engine DataNucleus

    I just had to fight with a strange exception which got raised after a GWT-RPC call to the App Engine back-end server which had the purpose to persistently store an entity into the data store.
    The exception:

    com.google.gwt.user.client.rpc.SerializationException: Type 'org.datanucleus.sco.backed.List' was not assignable to 'com.google.gwt.user.client.rpc.IsSerializable' and did not have a custom field serializer.For security purposes, this type will not be serialized.: instance = []
     at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:610)
     at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:129)
     at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter$ValueWriter$8.write(ServerSerializationStreamWriter.java:152)
     at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeValue(ServerSerializationStreamWriter.java:534)
     at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeClass(ServerSerializationStreamWriter.java:700)
     at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeImpl(ServerSerializationStreamWriter.java:730)
     at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:612)
     at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:129)
     at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter$ValueWriter$8.write(ServerSerializationStreamWriter.java:152)
     at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeValue(ServerSerializationStreamWriter.java:534)
     at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeClass(ServerSerializationStreamWriter.java:700)
     at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeImpl(ServerSerializationStreamWriter.java:730)
     at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:612)
     at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:129)
     at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter$ValueWriter$8.write(ServerSerializationStreamWriter.java:152)
     at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeValue(ServerSerializationStreamWriter.java:534)
     at com.google.gwt.user.server.rpc.RPC.encodeResponse(RPC.java:609)
     at com.google.gwt.user.server.rpc.RPC.encodeResponseForSuccess(RPC.java:467)
     at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:564)
     at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:544)
     at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:504)

    The exception happened during the (de)serialization of the RPC call. But I didn't use any org.datanucleus.sco.backed.List type in my entities which I transfer over the network. The reason however is the persist operation on App Engine. The code is like
    @Override
    public void saveOrUpdate(SourceCodeItem item) {
     PersistenceManager pm = getPersistenceManager();
     try {
      pm.currentTransaction().begin();
      pm.makePersistent(item);
      pm.currentTransaction().commit();
     } catch (Exception ex) {
      if (pm.currentTransaction().isActive())
       pm.currentTransaction().rollback();
     } finally {
      pm.close();
     }
    }
    It takes an object of type SourceCodeItem and makes it persistent by calling makePersistent(...). This call to makePersistent changes the state of the passed object. The SourceCodeItem object has the following structure (cut out details):
    @PersistenceCapable(identityType = IdentityType.APPLICATION)
    public class SourceCodeItem implements IsSerializable {
     @PrimaryKey
     @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
     @Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
     private String id;
    
     @Persistent
     private String title;
    
     ...
     
     private List<Label> labels;
    
     public SourceCodeItem() {
      ...
      labels = new ArrayList<Label>();
     }
     ...
    }
    The highlighted member variable declaration is a list which is not persistent and it gets initialized in the constructor. However after a call to the JDO's makePersistent(..) this list will be instantiated with the above mentioned org.datanucleus.sco.backed.List type. If you don't "detach" the object from JDOs manager it will be transferred with that instance type of the list which cannot be serialized and you'll get the exception I described in the beginning.

    Now you have two choices. Change your implementation of saveOrUpdate(SourceCodeItem) and explicitly detach your object. This would result in the following code:
    @Override
    public SourceCodeItem saveOrUpdate(SourceCodeItem item) {
            SourceCodeItem result = null;
     PersistenceManager pm = getPersistenceManager();
     try {
      pm.currentTransaction().begin();
      pm.makePersistent(item);
      pm.currentTransaction().commit();
                    result = pm.detachCopy(item);
     } catch (Exception ex) {
      if (pm.currentTransaction().isActive())
       pm.currentTransaction().rollback();
     } finally {
      pm.close();
     }
    
            return result;
    }
    Alternatively, which is my favorite option is to add the following to your jdoconfig.xml:
    <property name="datanucleus.DetachAllOnCommit" value="true"/>
    In this way the detaching will be done automatically after a commit and you can leave the code as it was initially. In such a way you'd get the following lifecycle:

    Tune your emulator with a pretty Nexus One skin!

    I know it doesn't really increase your value during development. It's just for fun but those of you that like it, here are some links that point to Nexus One skins that can be used on your local dev emulator.


    Update: The Nexus S skin is available at here.

    Installation is easy. Just extract it to <android-sdk-install-root>/platforms/<your-platform>/skins and then use it.

    The result is pretty nice :)

    Update
    What I forgot to mention. If you have problems with the size of the emulator that is going to be started, you may want to add a -scale to your emulator run arguments. In Eclipse you add it under your Run Configurations:

    That's what I'm missing in Visual Studio! Give me better code editor support!!

    Visual Studio is great in doing many things as for instance in integrating with other MS products (obviously) or with debugging. The VS debugger is one of the best I've seen till now (using different IDEs).

    One thing however I always again miss is having better code editor support. I'm also using Eclipse heavily and the code support which is given there is just amazing and by far better than in Visual Studio. Examples are not only the refactorings, but also shortcuts for jumping to classes / methods which in VS is only available through 3rd-party plugins. Ok...you can use the dropdown box on top...but it is far from usable (have to switch to mouse, etc...).

    Another example I came across today in Eclipse is the following. I was just writing an argument matcher to be provided to Mockito in one of my test cases. I started with the following

    Note, argument is of type object, so I did a check using the instanceof ("is" in C#) keyword wrapped within an if clause. I then continued to write argument.getLabels(),...


    ...not recognizing that getLabels() is actually a method of SourceCodeItem, wherefore I have to cast argument to SourceCodeItem first. But...wait; strangely Eclipse provided getLabels() in its suggestions as if it would be a valid method of argument?? Confirming it...
    ...Eclipse does the cast automatically for me!! That's what I call great support....I love it!