15 recommendations to make you a better programmer

I often give the same advice over and over to programmers that I work with. Most of the time I give advice on things to do with regards to coding and that works out pretty well, but “don’ts” are just as important as the dos. Let’s look at the 15 things a programmer should watch for. Most of these are geared toward object-oriented languages, but some can apply to procedural,functional languages as well.

  1. Don’t forget the tenets of object-oriented programming, Inheritance, Encapsulation and Polymorphism.
  2. Don’t overuse inheritance. Inheritance should make sense. Ask yourself about the relationship. If “is a”, then you should inherit, if “has a” then it should be a relationship off the owner.
  3. Watch your method/function/subroutine lengths. If a method or function gets longer than 5-10 lines, you are probably missing an opportunity to abstract or extract functionality. The longer a method is, the more complex it will become exponentially.
  4. Before you start to “roll your own”, spend some time looking for open source solutions or blog articles where someone solved this problem before. There is nothing wrong with leveraging someone else’s hard work. Chances are someone else will take over your work at some point and it is easier for them if it is a solution that they can find support for by a Google search. Also, think about the testing, maintenance time with regards to rolling your own solution. Aside from that the chances that one person can produce a solution better than a community project is unlikely no matter how good you think you are.
  5. Don’t hack. There is a lot to be said for code written during a time crunch, but more often than not, programmers will use this excuse to shortcut a solution and not take time to do it the way they know it should be done. You want the next programmer to look at your code and pat you on the back for your solution, not curse you in disgust.
  6. Don’t forget about reusability. Think about every line of code you write. Ask yourself if what you are doing is going to be repetitive by you or someone else. If it is, then abstract it to a utility class and reuse it. Never just copy code from one place to another when you could extract it to a utility or utilize polymorphism to address the need.
  7. Don’t use obscure variable names. It should be very clear what data a variable contains when another person looks at your code.
  8. Don’t forget to ask for a code review or design review. No one is perfect. You should always walk through your code with a peer with both of you sitting side by side. Explain your rational, what techniques you used and ask the reviewer for recommendations. Two heads are better than one. Also, you should do this early and often. Don’t wait until you finish a project to ask for a review because by then, it may be too late to fix.
  9. Don’t use global or member variables when a local one would suffice. I’ve seen this a few times before. A junior programmer will scope their variables as wide as possible. This not only causes confusion when others look at the code, but it can cause unintended consequences in your applications.
  10. Don’t forget about threading and thread-safety. Threading is a difficult concept for unseasoned programmers. It can bite you really quick if you don’t think about it. Complex applications may have many threads accessing the same resources and if you’re not concentrating on managing this, then you can get junk data, crashes and unexpected results. And DO NOT synchronize everything as a solution to thread safety, else performance will suffer.
  11. Don’t code first and ask questions later. You should understand the problem domain and the goals you want to accomplish before you even write one line of code. Ideally, you will design the application and run through your mental sanity checks in your head well ahead of actually putting code onto a screen.
  12. Don’t forget about unit testing. Unless you just enjoy spending hours and hours testing your application or sitting with your QA resource, you should unit test your code at the lowest levels and run these tests as regression tests along with your builds. Remember that a unit test is for very small bits of code. A unit test does not take the place of actual functional testing of your application, but it sure makes it easier.
  13. Don’t forget to comment and don’t over comment. If you want to provide yourself a hint, reminder or give that hint to another programmer, use a comment to make the point. Don’t over comment your code either as too many comments are an indication of complexity and you need to revisit your code for simplification or refactoring.
  14. Don’t forget to refactor your code as you go. If you see areas of your code you need to revise, do so as early an opportunity as possible. If you wait, the problem can be compounded by other code that utilizes it. Never wait until the end of a project to refactor, you will never get the chance and by then, it is a daunting task.
  15. Don’t forget to layer and loosely couple. Do not forget to keep your code as loosely coupled as possible. A good strategy is to layer your code, e.g. DAO layer, service layer, integration layer, Controllers, UI layer, etc. For example, a UI Layer should never access classes directly from the DAO Layer, but should utilize the controllers to access data, which in turn access service layer and so on.

While this is not an all inclusive list, it does give a programmer a great advantage. Being a programmer is definitely about working smarter and not harder.

 

 

 

Let’s get fancy with @Configuration with Spring

Spring has changed a lot over the years to make things more flexible and convenient for developers. Annotations in Spring 3 really hit home, but recently, Spring has added features that almost completely eliminate the need to XML all together. In the past, you still needed an XML configuration file if you wanted to utilize third-party code as Spring beans but you could use annotations to demarcate your own code. With the latest Spring code, you can use a class for your configuration. Let’s see how it works.

...
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:/app.properties")
@ImportResource("classpath:/mongo-config.xml")
public class AppConfig {

    private @Value("#{appProperties['index.location']}") String indexLocation;

    @Bean(name="indexLocation")
    public String getIndexlocation() {

         return indexLocation;

    }

  ...

//App.class main
ApplicationContext ctx =  new AnnotationConfigApplicationContext(AppConfig.class);

There is a lot going on here, but it may not be apparent by the small amount of code we have written. This code does the following:

  • Maps a class as the configuration for Spring
  • Loads an XML Property file (There are still some things I prefer to do in the XML)
  • Creates a String bean of type String and returns the definition of a property found in the Property file

While the property example is not necessarily useful in this example, you can see the flexibility of the properties using Spring expressions to access them. The first question you might ask is why am I still loading an XML file since the @Configuration annotation eliminates the need for it. If you declare a Bean in the class, you need to inject properties into it in most cases so this is a little extra work and on top of that you are writing some code that needs to be maintained. Using the XML declaration, you can use property substitution as parameters to an existing class and no code needs to be placed your configuration class.

So how do you determine when to put class in the XML and when to declare it as a bean? Here are my general rules:

  • If you create a class, the demarcate it with a Spring stereotype (@Component, @Service, @Repository, @Controller, @Configurable, etc.)
  • If the class is a class from a third-party jar, then place the configuration in the XML
  • If the class is from a third party but you want finer grain control over the events of instantiation and circumstances, then create the Bean using the @Bean annotation in the class containing the @Configuration annotation

Pretty simple rules to follow…

There are several other annotations that can be used in the class containing the configuration as well such as @Depends-On and @Value.

Java,.NET Caching with Spring

If you want a major performance boost out of your application, then caching should be a part of your strategy. No doubt you have experienced moments in coding where you needed to store sets of data so that you don’t have to go back to the source to get them every time. The simplest form of caching is lazy loading where you actually create the objects the first time in memory and from there on out, you access them from memory. In reality, caching gets a lot more difficult and has many considerations.

  • How do I cache in a distributed environment
  • How do I expire items in the cache
  • How do I prevent my cache from overrunning memory
  • How do I make my cache thread-safe and segment it

All of these are concerns that you will have if you “roll your own” solution to caching. Let’s just leave the heavy lifting to the Spring Framework and we can go back to concerning ourselves with solving the complex problems of our domain.

Spring has a caching mechanism/abstraction for both Java and .NET, although the Java version is far more robust. Caching in Spring is accomplished through AOP or Aspect Oriented Programming. A caching annotation (Java) or attribute (.NET) can be placed on a method or a class to indicate that it should be cached, which cache should be used and how long to keep the resources before eviction.

Java Spring Cache with EHCache

In Java, caching with Spring couldn’t be easier. Spring supports several different caching implementations but EHCache is the default and by far my favorite. EHCache is robust, configurable and handles a distributed environment with ease. Let’s look at how we can add the ability to cache to a Spring project.
Application-context.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:cache="http://www.springframework.org/schema/cache"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
  <cache:annotation-driven />

<!-- Ehcache library setup -->
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="ehcache.xml"/>

Now that we have our cache setup, we can start to utilize it.

@Cacheable(name="records", key="recordList") //Cache the output of records, return it if already cached
public Collection findRecords(RecordId recordId) {...}

@Cacheable(name="records", key="recordsList", condition="recordType == 2") //Only cache if record type is 2
public Collection findRecords(int recordType) {...}

@CacheEvict(value = "records", allEntries=true) //Reload the cache, evict all entries
public void loadAllRecords() {...}

In the above example, we specify through the annotation that the records collection will be stored in a cache named “records” and the key to access the collection will be called “recordList”. The key parameter is optional. We also displayed an example of using Spring Expression language to process the cache conditionally. Remember that caches are defined either dynamically like above or in the ehcache.xml. For most complex caching scenarios, you will want to define the cache in the ehcache.xml with eviction and distribution rules and Spring will find it by the name parameter in the annotation.

What about .NET?

In .NET, you have a very similar mechanism to managing a cache.

<!-- Apply aspects to DAOs -->

[CacheResult("MyCache", "'Record.RecordId=' + #id", TimeToLive = "0:1:0")]
public Collection GetRecord(long RecordId)
{
   // implementation not shown...
}

Remember that with the .NET cache, you provide the caching implementation in the XML just as you do in the Java version. In this example, we have used the provided AspNetCache.

What about controlling the cache yourself, querying the cache and more complex operations? Well even that is simple by merely autowiring the cache class or retrieving it from the context.

@Autowired
EhcacheCacheManager cacheManager;

...
EHCache cache = cacheManager.getCache("records");
Collection records = cache.get("recordList");

Built-in .NET Caching

Fortunately for .NET users, there is also a built in caching framework already in .NET. This technique is used mostly in the MVC and ASP world and I am not particularly fond of it since it is specifically geared for the web side of an application. I would prefer it to be more generic like the Spring solution, but it also has some advantages such as you can configure the caches in the web.config, you can also create custom caching implementations that utilize different mechanisms for cache management. Here is a great example utilizing MongoDB. The .NET version of the cache works much the same way as the Spring one does. Here are some examples with configuration.

[OutputCache(CacheProfile="RecordList", Duration=20, VaryByParam="recordType")]
Public ActionResult GetRecordList(string recordType) {

}

Now the configuration in the web.config…

 
//web.config

  <caching>
      <outputCacheSetting>
        <outputCacheProfile>
          <add name="RecordList"  duration="3600" />
         </outputCacheProfile>
      </outputCacheSetting>
      </caching>

If we are deploying our application to the cloud in Azure, we can use the AppFabric cache as demonstrated here.

Hibernate, Data Nucleus, JPA Result Caching

Another thing to keep in mind is that when you are using tools such as Hibernate, caching is built in with these solutions. There is a built-in second level cache implementation that is provided when you configure Hibernate and I tend to use EHCache for this as well. You must remember to add the Hibernate Cache annotation onto your objects at the class level that you want to cache as well. A properly setup ORM solution with Spring and Hibernate with a properly configured second-level cache is very hard to beat in performance and maintainability.

Conclusion

We have really done a lot with very little thanks to Spring and caching. While caching is powerful and will help improve the performance of your application, if it is overdone, it can cause problems that are difficult to diagnose. If you are caching, make sure you always understand the implications of the data and what will happen throughout the caches lifecycle.

The many types of technology clouds

If you remember from school, there are many different types of clouds. You have stratus, cumulus and nimbus just to name a few. In technology, the cloud is no different. The cloud has a different meaning depending on who you talk to and they are all mostly right but they can be referring to totally different things.

Cloud Architecture

Let’s look at the Wiki definition of a cloud

Cloud computing is the use of computing resources (hardware and software) that are delivered as a service over anetwork (typically the Internet). The name comes from the use of a cloud-shaped symbol as an abstraction for the complex infrastructure it contains in system diagrams. Cloud computing entrusts remote services with a user’s data, software and computation.

There are many types of public cloud computing:[1]

In the strictest sense, cloud computing is not merely just moving your software or services onto a server outside your firewall, but it’s enlisting a service with “cloud” properties like flexible horizontal scalability through elasticity. Cloud architecture is not at all uniform as well. It also means different things to the vendors that provide the services and it they implement it how they choose. Amazon, VMWare Cloud Foundry, Stackato and Azure are some of the hottest cloud architecture services out there today.

Consumer Cloud

From a consumers perspective, the cloud means that your data is stored on the internet somewhere. For example, the iCloud product from Apple keeps all your data in sync between computers and iOS devices. The iTunes Match service stores your music on servers and the same goes for the Google Music service.

Outsourced Cloud

To many IT professionals, the cloud is just a way to offload services they currently have in house to a server outside of their infrastructure managed by someone else to varying levels. Take for example that many organizations have shifted having internal mail servers to migrating to Google for Business, where every aspect of the infrastructure is managed by Google. Another example, might be moving your internal Microsoft Exchange mail server to a hosting provider. The end result, again to varying degrees, is greater reliability and less burden and reliance on internal IT resources. JFrog Artifactory for dependency management has a cloud service or a server you can download. If I purchase this service, can I say that my dependency management is in the cloud regardless of how JFrof implements their cloud service? The answer to this question is yes.

The True Cloud

While the cloud may mean different things to different people, preparing an application for a cloud architecture is not as simple as one might think. There are all kinds of decisions that need to be made and coding practices that should be adhered to. Typically, if you follow Java conventions, then you won’t have much of an issue with cloud deployments. Let’s look at an example Java web application and some of the concerns that need to be addressed prior to cloud deployment to a service such as Cloud Foundry.

  • Your application must be bundled as a war file
  • You application must not access the file system. (Utilize the class loader to load files from within the war, but don’t write to files)
  • Resources/Services should be looked up via JNDI
  • If you cache, utilize caching solutions like EHCache that propagate automatically across instances
  • Persist data to a database such as MongoDB, MySQL or PostgreSQL to guarantee access

For the most part, if you follow the J2EE web application conventions regarding deployments, you won’t have an issue with a deployment to a true cloud environment.

Cloud Architecture Dynamic Scaling vs. Autoscaling

One of the advantages to a cloud architecture is the ability to scale up instances of your application and only pay for what you utilize from your provider. There are two types of scaling, the first is Auto-scaling where a tool is utilized to measure load and will automatically increase instances of your application to accommodate the need and the second if dynamic scaling where you control the scale based on a load forecast. An example of dynamic scaling would be if you normally have a load of 1000 concurrent users and you have an event which will ramp up your load to 10,000. In a more traditional setting, you would have purchased servers and hardware to accommodate the worst case scenario which leaves your infrastructure largely utilized most of the time causing inefficiency and waste. In a cloud scenario,you might have 10 instances to service your normal load and for the 24 hour period of your event, you scale to 100 instances and when the smoke clears, you return to 10 instances. All this can be done with a single click of a button in a cloud infrastructure.

Automatic scaling is provided by some cloud providers in the form of a tool. Amazon provides such a tool that will monitor the load and allow you to set triggers to determine how many instances to ramp and when. Automatic scaling is very useful as it handles the unforeseen, but it should not be used in lieu of true capacity planning. It can also be dangerous and advanced intelligence needs to be built in to determine the different between junk and legitimate traffic. For example, think of what would happen if a DoS attack was performed against your application. Remember you pay based on the number of servers you ramp up.

Under the hood, scaling works by issuing commands to the server through an API. For example, with Cloud Foundry, the vmc command will let you monitor load and add instances which in turn creates a JSON request that gets sent to the server to give it instruction. You can also use a third party tool that interfaces with it in the same fashion or you can also build in the scaling intelligence into your own application by hitting the server API yourself. Using the latter technique, your application can control itself, making it very intelligent.

Conclusion

Regardless of how you see the cloud and how you utilize it, the endgame for your organization should be to offload the burden from your internal staff, decrease your expenses, provide greater uptime and flexibility and give you the ability to scale dynamically.

 

If you are using Java, you should be using Spring

I spend a fair amount of time evangelizing the Spring Framework, and with good reason. Spring is not only a great lightweight container framework that provides IoC (Inversion of Control) and Dependency Injection, but it pretty much has a tool, component for every task that you can think of when dealing with the day to day ins and outs of programming.

You probably have a need for Spring and you don’t even know it if you haven’t used it before. Most developers at one time or another have created frameworks to accomplish tasks like remoting, JMS, MVC, database interactions, batch work, etc., so I would label Spring as “The framework” for such tasks instead of succumbing to the “roll your own” urge. I started using Spring back in 2006 and I have not, in over 50 Java projects since then, neglected to utilize it to some extent. It has reduced the amount of code I have to write, allowed me to dynamically wire dependencies together at runtime and even provided tools for tasks that I thought I was going to have to write something custom to accomplish.

Spring was born as a solution to the heavy-weight EJB and J2EE container environments. It reduces the overhead of J2EE, allows the usage of containers that are not J2EE compliant like Tomcat and Jetty and provides a consistent API that most developers these days are familiar with. Here are some example of what Spring can do:

  • Dependency Injection (e.g. create a database pool object factory in XML and inject that into objects at runtime)
  • Eliminates the need to write specific code for singleton patterns
  • Allows you to turn a POJO into a service with a mere annotation
  • With Aspects, it allows you to inject values into classes that are not managed by Spring
  • Spring has an abstraction on top of over 100 different frameworks in Java
  • Spring MVC is the most concise and robust MVC framework
  • Spring provides JPA, Hibernate and DataNucleus support and will allow transaction demarkation
  • Spring provides AOP capabilities to allow method interception and point cuts
  • Exposing POJO methods as web services is as simple as adding Apache CXF to the mix
  • Annotation support is richer than any other framework
  • Spring is the most widely used Java framework
  • Property file loading and substitution in XML

Spring is not only a Java tool, in fact, Spring.NET is available for the .NET platform. It is usually a little bit behind the Java version but it is out there.

What are these new concepts AOP, IoC and Dependency Injection?

Usually a discussion of Spring always amounts to explaining the concepts that are at the core of the framework. Let’s take a look at each of them and what they give you. IoC and Dependency Injection go hand in hand. IoC is the concept and Dependency Injection is the mechanism. For example, you create a service class on your own and now you need to manage that class by ensuring it only has one instance, you also need to get that class reference to other classes to utilize so you create a mechanism for that. Now you need transaction support so you write that in, but you also need to dynamically read in properties that are for the environment you are running in and it goes on and on. As you can see, it not only gets complicated, but that is a lot of code you are writing and maintaining yourself. Spring provides it all and through XML or annotations (preferrable the latter), you can with one simple Plain Old Java Object (POJO) accomplish all of this through Spring conventions and inject the values of the objects into your service or inject your service into any other class by simply this.


//Service class Spring Bean
@Service
@Transactional
public MyService implements IService {

public void doThis();

}

//MVC Controller Class

@Controller
public MyController {

@Autowired
MyService myService

public Report doThat() {

myService.doThat();

}

}

In just a few lines of code, we created a singleton service that is transactional and we created a controller to call that service. There are way more complex things we could do here. For example, using the OpenSessionInView Pattern, we could get the Controller to control opening the transaction and closing it to allow for multiple service calls to use the same transactional context. We could also change the isolation level of the transaction. The point here is that we used Dependency Injection to demonstrate what IoC can do.

AOP or Aspect Oriented Programming is an advanced concept in the Spring world. AOP is merely the separation of cross-cutting concerns. The Transactional support of Spring is similar to AOP. The ability of Spring and AspectJ to allow you to inject objects into other objects that are not managed by Spring is another great example. Transactions, Security, Logging and anything other than the business at hand is a cross cutting concern. The goal of AOP is to separate those away from the code. If you didn’t use AOP, then you would have to actually control these elements your self. Take for example that you want to check that a user is valid before method calls. Without AOP, you would have to write some checkUserIsValid() method and call it at the beginning of each method. Using AOP, you could merely mark with an annotation or Aspects that each method of a certain class call another method on another class as an interceptor.

Spring is also for simple projects

You may be thinking Spring is too heavy weight for the task at hand… nonsense. I will guarantee that Spring, used properly, will reduce the amount of code in your project by at least 25%. That is 25% less code for your to maintain or write in the first place. Also, Spring provides even tools to accomplish the small tasks such as the following:

  • Finding resources on the classpath or file system (ResourceLocator)
  • Finding classes with a certain annotation
  • Generating JSON/XML from objects and vice versa (Jackson support)
  • load multiple property files and substitute variables inside of your spring XML files (Useful when promoting to different environments)
  • Ability to treat a JNDI resource as just another bean
  • Ability to treat a web service as just another bean
  • JDBCTemplate for issuing database queries and batch framework for batch operations
  • Spring Data for NOSQL support with Mongo
  • MVC Content negotiation to convert a POJO to JSON,XML, PDF (iText), Excel (POI) and more
  • Security integration that supports Windows, Active Directory, Kerberos, Basic, Digest, etc.
  • Robust Testing adapters for Junit and TestNG

I could spent a week delivering Spring training to a group of developers and only scratch the surface of what is there. Without a doubt though, when I have a tough problem to solve or a simple Java project, I always utilize parts of Spring. Conveniently, Spring is broken up into modules so that you can only include the ones that have the functionality you need to avoid causing any project bloat.

Conclusion

With Spring being the #1 Java framework, I highly recommend spending some time getting familiar with it and I recommend getting some training as well from someone like myself who is an expert with the framework who can show you everything it has to offer before you start utilizing it. You can also get training directly from vmWare, the company that owns SpringSource.

Fusion: Mimic NSNotification functionality from Obj-C into Java with Spring

The first time you heard of an NSNotification in Objective-C, you probably thought it was a mechanism that is used to notify a user of an event, but you quickly learn that it is designed to send event notifications from one part of your app to another. For example, you are using ASIHttp to load data asynchronously from a RESTful Web Service and you want to know when that data is loaded so that you can refresh a UI component. There are other ways to achieve this besides using NSNotification like a delegate or a reference to the object to call but that requires a tighter coupling that we would often like since layering and separation of the code is important for maintainability.

Let’s look at an example of sending and receiving an NSNotification

//Class 1
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_CONNECTION_FAILURE object:nil];
//Class 2
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectionFailure:) name:NOTIFICATION_CONNECTION_FAILURE object:nil];

//somewhere after the event is fired, maybe in viewWillDisappear delegate method
[[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_CONNECTION_FAILURE object:nil];

Pretty simple mechanism for wiring up a notification, but what if we are in Java and we want to use the same mechanism. Often the reason for doing this is Java is that you have a hierarchy of UI components in Swing, GWT or Vaadin and you have an event that takes place deep in one hierarchy that needs to be received deep in another. In this cases a listener won’t work because the objects are not related to each other and using a listener would require coupling them tightly together. Spring has just such an abstraction to assist for this purpose.

The following technique will decouple your code from itself but will add a coupling to Spring and JMX. This is an acceptable tradeoff. Let’s look at how we can publish a notification. To make this work, you need to follow the instructions for creating a Bean that you want to manage and mapping it in the mbean exporter per the Spring documentation. Also, make note that this technique is for beans that have been exported as managed beans in JMX. For a more rudimentary notification mechanism just use the raw JMX API Notification API itself.

package com.domain.notification;

import org.springframework.jmx.export.notification.NotificationPublisherAware;
import org.springframework.jmx.export.notification.NotificationPublisher;
import javax.management.Notification;

@ManagedResource(objectName="bean:name=MyTestNotification", description="My Managed Bean", log=true,
    logFile="jmx.log", currencyTimeLimit=15, persistPolicy="OnUpdate", persistPeriod=200,
    persistLocation="foo", persistName="bar"
public class MyTestNotification implements MyBean, NotificationPublisherAware {

    private String name;
    private int age;
    private boolean isSuperman;
    private NotificationPublisher publisher;

    // other getters and setters omitted for clarity

    @ManagedAttribute(description="The Age Attribute", currencyTimeLimit=15)
    public int add(int x, int y) {
        int answer = x + y;
        this.publisher.sendNotification(new Notification("add", this, 0));
        return answer;
    }

    public void setNotificationPublisher(NotificationPublisher notificationPublisher) {
        this.publisher = notificationPublisher;
    }

public void setAge(int age) {
    this.age = age;
  }

  @ManagedAttribute(description="The Name Attribute",
      currencyTimeLimit=20,
      defaultValue="bar",
      persistPolicy="OnUpdate")
  public void setName(String name) {
    this.name = name;
  }

  @ManagedAttribute(defaultValue="foo", persistPeriod=300)
  public String getName() {
    return name;
  }

  @ManagedOperation(description="Add two numbers")
  @ManagedOperationParameters({
    @ManagedOperationParameter(name = "x", description = "The first number"),
    @ManagedOperationParameter(name = "y", description = "The second number")})
  public int add(int x, int y) {
    return x + y;
  }

  public void dontExposeMe() {
    throw new RuntimeException();
  }
}

In the case of this class, the notification will pop when someone calls the add() method of the MyTestNotificationBean. add() is a managed method in JMX at this point. Now lets look at how to receive this notification from another class.

package com.domain.notification;

import javax.management.AttributeChangeNotification;
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;

public class EventNotificationListener
               implements NotificationListener, NotificationFilter {

    public void handleNotification(Notification notification, Object handback) {
        System.out.println(notification); //receive the add notification
        System.out.println(handback);
    }

    public boolean isNotificationEnabled(Notification notification) {
        return AttributeChangeNotification.class.isAssignableFrom(notification.getClass());
    }

There are many ways to wire this together to make it work and this is just one example. The disadvantages of this approach is that it is nowhere near as simple as the NSNotification mechanism in Objective C and it provides some overhead since the MyTestNotification class will need to be mounted as an managed bean in JMX.

As mentioned, we can also forgo Spring and use straight JMX to achieve our goal. Let’s look at an example.

import javax.management.*;

public class NyNotification
        extends NotificationBroadcasterSupport
        implements MyBean {

public void myMethod() {

Notification n =
	    new AttributeChangeNotification(this, 10,
					    "I changed",
					    "Change",
					    "int",
					    20,
					    this.test);

	/* Now send the notification using the sendNotification method
	   inherited from the parent class NotificationBroadcasterSupport. */
	sendNotification(n);

}

   @Override
    public MBeanNotificationInfo[] getNotificationInfo() {
        String[] types = new String[]{
            AttributeChangeNotification.ATTRIBUTE_CHANGE
        };

        String name = AttributeChangeNotification.class.getName();
        String description = "An attribute of this MBean has changed";
        MBeanNotificationInfo info =
                new MBeanNotificationInfo(types, name, description);
        return new MBeanNotificationInfo[]{info};
    }

@Override
 public void handleNotification(NotificationListener listener, Notification notification, Object handback) {
        System.out.println(notification); //receive the notification
        System.out.println(handback);
    }
...

Still a lot of coupling going on here and a disadvantage is that we are extending NotificationBroadcasterSupport. While we may be creating a nice way to mimic notifications, these techniques should be used as a “last resort” mechanism.

Another mechanism that can be used for this purpose is the ApplicationContext’s publishEvent(ApplicationEvent event) method or ApplicationEventPublisher if you have no access to the an ApplicationContext. This is a nice quick way to register an event and get a notification. Let’s look at the example.

...
       //We'll publish en event somewhere
        MyEvent fileUploadEvent = new MyEvent(this, user);
        getApplicationContext().publishEvent(fileUploadEvent);

//now somewhere else we can receive it.

public class EventListener implements ApplicationListener {

	@Override
	public void onApplicationEvent(ApplicationEvent evt) {
		if (evt instanceof MyEvent)
                   //do something

...

We need to register our sync executor in the ApplicationContext.xml

<bean id=”applicationEventMulticaster” class=”org.springframework.context.event.SimpleApplicationEventMulticaster”>
<property name=”taskExecutor”>
<bean class=”org.springframework.scheduling.timer.TimerTaskExecutor”/>
</property>
</bean>

or as an alternative, we can extend SimpleApplicationEventMulticaster

public class GlobalEventMulticaster extends SimpleApplicationEventMulticaster implements InitializingBean {

private ApplicationContext application;

 public void afterPropertiesSet() throws Exception {

        if (this.application == null) {

            this.application = ///get Your application context

        }

    }

References

JMX Notifications

Spring/JMX Notifications

Good developers program in a language, talented developers code

By Chris L Hardin
Sr. Software Architect

Have you ever heard of “framework fatigue”? This term is meant to describe the creep of hundreds of third-party frameworks into development projects. Ten years ago, there wasn’t a whole lot of choice out there for Java, my current language of choice, so the average number of third-party libraries included in a project were 1-5, but today, the average has grown to around 30. You’ve got Spring, Hibernate, JUnit, Struts, Commons, TestNG, Joda, Unitils, DBUnit, iBatis just to name a few in the Java space and each of these have dependencies on other libraries and those have dependencies on others. I could rattle off another list for C#. While I don’t think that choice is a bad thing, and while I tend to use 20-30 third-party libraries in a project, I do think that there have been certain side effects of this that have been detrimental to technology. I am going to address what I think is the biggest.

Getting a Job

When did getting a job become more about knowing a specific framework and not being an expert on the Java language? I have seen managers walk over qualified resumes looking for the names of frameworks only to land on someone less qualified who decided to put a particular framework on their resume.


Kevin Rose, CEO of Digg.com, said the next time he hires for a project, he is going to hire for talent rather than technology. He said that when he was hiring for a project, he looked for developers working in PHP, but after placing the individuals, he decided to branch out to other technologies and the developers he hired, weren’t able to make the transition and dare I use the term, “Think outside the box”. A talented developer may know PHP, but can easily ramp up on any other technology, whereas, a developer with merely a toolbox, may not necessarily be able to assimilate other technologies fast enough if at all.

Recruiters and managers are the worst offenders here. These folks are not necessarily technology experts so they try to cultivate a candidate that has the exact blend of frameworks that the target company is using. While this doesn’t necessarily always result in a poor hire, it does tend to exclude perfectly qualified candidates with real talent.

Let’s look at an example that I ran across recently. A manager in Denver had a requirement for a developer with Struts 2, so he excluded any candidate without Struts 2 knowledge. In reality, he could expand his search to include an older version of Struts or just MVC frameworks in general. The principles are the same, the technical details can be learned quickly. A talented candidate can take adapt and move with your enterprise. This is what Rose was trying to get across.

Ten years ago, having just the knowledge of a language or knowing one object-oriented language, could get you a job doing Java or C++, to name two of the bigger choices. Now, you have to learn and have experience with every framework imaginable just to get your resume to a hiring manager. This is why the tech sector says there are shortages in the development field of highly-qualified labor. Heaven forbid we have a shortage of Java Server Faces developers… Most of you know how I feel about JSF so you get the joke.

Java, in particular is plagued with frameworks and they change rapidly. Five years ago, it was J2EE, EJB and such APIs and Struts, then Spring, Hibernate and more lately Grails/Groovy. My point is that it is impossible to know all these frameworks and it is also impossible to know some frameworks completely. Spring, for example, is just too large for any one person to hold all the knowledge on it’s features. Even if you could learn it all, two or three new versions would be out by that time and you learned the first. The key here is familiarity and talent. A rudimentary understanding of what a framework is used for and a little research, will give you what you need to get the job done.

Here is a little secret that developers have known for years and non-technical people have yet to figure out. It doesn’t matter what language a developer knows, they are all similar. A talented developer has an interpreter and compiler in his head and thinks in pseudo-code anyway. Applying that to a language or framework is just a matter of figuring out the syntax…and that is the easy part.