Friday, April 28, 2006

Fake Dummy Mocks Stubs

Gerard Meszaros has come up with a new name for the mocks, fakes etc. - objects that are used in the place of actual objects while testing. In his soon to come book titled XUnit Test Patterns, he proposes a new name - Test Doubles for all these objects. While Test Double covers the general set of objects used to represent a real time object during testing, there are four different types of Test Doubles vis-a-vis:
  • Stub: Programmed (by the test automater) to respond to calls made during the test (and only the calls used for the test). Test Stub returns pre-defined values (inputs, with expected outputs). Used to test indirect inputs.
  • Mock Object: Represent test doubles used to test the outputs (in an indirect way). A mock object is designed to expect certain calls from the system under test, failing which the mock object throws an exception (thus failing the test). In other words, mocks are used as indirect way to test the outputs of the system under test.
  • Dummy Parameter: A dummy (or placeholder) is used to fill parameter lists and are not used anywhere else.
  • Fake Object: Fake objects provide the same functionality as the real object, but uses "shortcuts" to obtain the results. Fake objects are only used to speed up testing and avoid probable side-effects.

Tuesday, April 25, 2006

Code quality for software architects

In the latest installment of In pursuit of code quality, Andrew Glover discusses the quality aspects that affect the long-term viability of a software architecture. Various coupling metrics that help the architect to analyze and support the software architecture in the long run are discussed. Coupling metrics represent the higher aspects of code such as code dependencies, stability and abstractness. The coupling metrics discussed in this article are:
  • Afferent Coupling: An integer metric which represents the number of components that are dependent on this object. In other words, it denotes the object's responsibility. Generally, core frameworks (struts), logging packages etc. can have high afferent coupling. It is good to know afferent coupling because changing packages such has struts etc. drastically can cause ripple effects throughout its dependent packages.
  • Abstractness: Is the ratio of abstract to concrete classes. It is always easier to change components with higher abstractness without causing too much ripple effect. If the abstractness of a component is low and the afferent coupling high, there is a chance of software entropy (too many interdependencies).
  • Efferent Coupling: The number of components that a particular component depends on (inverse of afferent coupling). High efferent coupling, combined with high afferent coupling and low abstractness will pose a huge challenge for the long term viability of a software architecture.
  • Instability: It is the ratio of the efferent coupling to the sum of afferent and efferent coupling (Ce /(Ca + Ce)). If this ratio is closer to 0 for a component, the component may be considered stable, since, the more a component is relied on, the less likely it is to change. On the other hand, if the ratio is closer to 1 (afferent coupling = 0) then, any dependency change will affect this component and hence it is more unstable.
  • Distance from the main: If you plot Abstractness along the Y-axis and Instability along the X-axis, then the main sequence is a line on the cartesian coordinates X=0 and Y=1 to X=1 and Y=0 (neither of them can be greater than 1). The distance from this main sequence represents the level of balance in the system. This can help you understand how a specific change may affect the maintainability of your architecture.
Afferent and efferent coupling, instability, abstractness, and distance from the main sequence are all reported by code analysis tools, including JDepend, JarAnalyzer, and the Metrics plug-in for Eclipse.

EHCache 1.2 released

EHCache 1.2 has been released. The 1.2 release of ehcache has many new features like support for distributed caching, new cache update policies (FIFO and LFU), having multiple cahce managers in a single machine etc. The full list of features available in ehcache 1.2 are :
  • Flexible, extensible, high performance distributed caching. The default implementation supports cache discovery via multicast or manual configuration. Updates are delivered either asynchronously or synchronously via custom RMI connections. Additional discovery or delivery schemes can be plugged in by third parties.
  • New FIFO and LFU caching policies in addition to the standard LRU.
  • Introduced CacheManagerEventListener and CacheEventListener interfaces and default implementations.
  • Multiple CacheManagers per virtual machine.
  • Programmatic flushing of application state to persistent caches
  • Significant (up to 7 fold) DiskStore performance increases.
  • API for Objects in addition to Serializable. Non-serializable Objects can use all parts of ehcache except for DiskStore and replication. Two new methods on Element: getObjectValue and getKeyValue are the only API differences between the Serializable and Object APIs.
  • Backward Compatibility with ehcache-1.1. All users of ehcache-1.1 should be able to upgrade to ehcache-1.2.
  • Tested with Hibernate2.1.8 and Hibernate3.1.3, which can utilise all of the new features except for Object API and multiple session factories each using a different ehcache CacheManager. A new net.sf.ehcache.hibernate.EhCacheProvider makes those additional features available to Hibernate-3.1.3. A version of the new provider should make it into the Hibernate3.2 release.
  • Tested with ehcache-constructs.
  • Apache 2.0 license.

Thursday, April 20, 2006

StarUML: Open source modeling tool

The lack of a RSA at my new job led me to search for a free modeling tool. That is how I stumbled upon StarUML. StarUML is an open source modeling tool for the Windows platform. It is sponsored by Plastic Software which is a member of OMG. StarUML comes with support for UML 2.0 and MDA (Model driven architecture). Plugins for StarUML may be written any COM compatible language. Plugins for code generation and reverse engineering applications for common programming languages (Java, C++, C# etc.) are already available. The following is a list of features available in the current release of StarUML:
  • Accurate UML Standard Model: Strictly adheres to UML standard.
  • Open Software model format: All files are managed in standard XML format.
  • MDA Support
  • Applicability of methodologies and platforms: Support for application framework models like .NET and Java Enterprise Edition.
  • Excellent Extensibility: All functions are extensible through plugins which can be written in any COM compatible language.
  • Software model verification function: Automatic verification of models, facilitating eary discovery of errors.
  • Useful Add-Ins: Includes many useful add-ins. Generates code for most common programming languages, and also generates models from code.
The only problem I can see is that it is based on COM. I'd have liked it better if it was more "open", and supported other operating systems. That may come in the future, but for now, I can't complain on anything else.

Wednesday, April 19, 2006

AjaxTags for Java Server Pages

AjaxTags is a JSP tag library that provides a set of tags for Java EE developers to create Ajax-enabled web forms. AjaxTags depends on Javascript-based Prototype framework, and the scriptaculous library, it also depends on the DHTML-based OverLIBMWS library. All you have do to create an Ajax-enabled Web form is to include the library in your classpath, define the tld in web.xml and include the required Javascript core in your JSP. An additional event handler (a Java servlet) has to be written to handle the client events. The following is a list of tags provided in the current release (1.2):
  1. Autocomplete Retrieves a list of values that matches the string entered in a text form field as the user types.
  2. Callout Displays a callout or popup balloon, anchored to an HTML element with an onclick event.
  3. HTML Content Replace Builds the JavaScript required to hook a content area (e.g., DIV tag) to a link, image, or other HTML element's onclick event.
  4. Portlet Portlet-style capability from a AJAX-enabled JSP tag.
  5. Select/dropdown Based on a selection within a dropdown field, a second select field will be populated.
  6. Tab Panel Enable an AJAX-based set of property pages.
  7. Toggle Uses images to create either a single on/off toggle or a sequential rating system.
  8. Update Field Updates one or more form field values based on response to text entered in another field.
  9. Area and Anchor Shows how to AJAX-enable any area of your page.
  10. Ajax DisplayTag Shows how to AJAX-enable DisplayTag
Demos for the tags can be viewd at the live demos site, they also have the source code used for the demos. Some more resources for Ajax, as applicable to Java developers, can be found at my previous post: Ajax Resources.

Friday, April 14, 2006

Open Architecture Framework (TOGAF)

The Open Group Architecture Format (TOGAF) is an industry standard architecture framework build an information systems architecture. It is divided into three parts:
  1. Architecture Development Method (ADM): It is the core of TOGAF. Describes a step-by-step approach to developing an enterprise architecture.
  2. Enterprise Continuum: A virtual repository of architecture assets, i.e. the TOGAF foundation architecture, and the Integrated Information Infrastructure.
  3. Resources: Comprises of the TOGAF Resource Base - a set of tools and techniques available for use in applying TOGAF and the TOGAF ADM.
The TOGAF specification is available at TOGAF Version 8.1 site. Additional resources for Architecture frameworks are listed below:
  1. Introducing The Open Group Architecture Framework (TOGAF)
  2. TOGAF Certificatin page
  3. The open group architecture forum

Friday, April 07, 2006

DB2 Viper

DB2 Viper is the code name for the next release of DB2. DB2 Viper can handle both relational and XML data. In what it terms as "native XML", the XML data is stored in a parsed heirarchical format rather than requiring it to be transformed into row and column format or store it as a large object. The new storage structure will enable you to query the database using XQuery or SQL. You can download the beta version on the DB2 Viper download site. The administrators can use standard SQL data definition language statements to create database objects to store relational and XML data, and this can be done in a single statement. For example, to create a table with an XML column, you can make the query as follows:

create table case (
caseNumber varchar(10)
primary key not null,
status varchar(10),
schedule varchar(30),
county varchar(10),
arraignmentNotice xml
Since the XML data is self-describing, you don't have to give additional information with it. It will be accepted as long as it is well-formed. You can also create an XML index to speedup your searches of the XML data. This requires the index key to defined using an "xmlpattern", which is an XPath expresssion (no predicates, ofcourse) to identify the subset of the XML document. You will also have to specify the SQL datatype represented by the subset selected by the XPath expression. For example:

create index caseIndex on case(arraignmentNotice)
generate key using xmlpattern '/arraignmentNotice/date'
as sql DATE
The following is a list of the features provided with DB2 Viper
  • Efficient storage techniques for managing XML data in hierarchical format.
  • Support for indexing XML data
  • Support for XQuery as well as SQL (with XML extensions) to query XML data
  • Support for validating XML data using schemas
  • API support for popular languages like Java, C, COBOL and .NET platform
  • An Eclipse based developer's workbench which includes a graphical XQuery builder.
Additional references:

Tuesday, April 04, 2006

Singletons and EJB

This post contains the points to be noted when implementing Singleton Pattern in the EJB tier. As described in the previous post (EJB Programming Restrictions), the EJB programming model imposes some restrictions on the application programmer.
  • The restriction of not using read/write static variables within the EJB tier implies that the static variables have to be defined as final.
  • The other main implication of using Singletons in the EJB tier is when the EJBs are used in a clustered architecture. In such cases, is server in the cluster will have an instance of the singleton object.
The article "When is a singleton not singleton" describes a list of situations when a singleton may have multiple instances. This is a concise list:
  • Multiple singletons in two or more virtual machines
  • Multiple singletons simultaneously loaded by different class loaders
  • Multiple singletons arising when someone has subclassed your singleton
  • Copies of a singleton object that has undergone serialization and deserialization
  • Multiple instances created due to incorrect factory implementation.
Related posts

EJB Programming Restrictions

The EJB specification imposes some restrictions on the Bean Provider (Application programmer) to ensure portability. Although these restrictions do not affect the programmer in most cases, it has some implications in certain situations such as when using the Singleton pattern. Hence, it is advised that the EJB programmer be aware of these programming restrictions while coding EJBs. The following is a list of the restrictions (an excerpt from the EJB Specification), and the implications on the singleton pattern implementation under the EJB environment will be described in the next post. These restrictions are consistent between EJB 2.1 and EJB 3.0 specifications.
    On usage of Static fields
  1. An enterprise bean must not use read/write static fields. Using read-only static fields is allowed. Therefore, it is recommended that all static fields in the enterprise bean class be declared as final.
  2. On using Threads
  3. An enterprise bean must not use thread synchronization primitives to synchronize execution of multiple instances.
  4. The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups.
  5. Java Standard API
  6. An enterprise bean must not use the AWT functionality to attempt to output information to a display, or to input information from a keyboard.
  7. An enterprise bean must not use the package to attempt to access files and directories in the file system.
  8. An enterprise bean must not attempt to listen on a socket, accept connections on a socket, or use a socket for multicast.
  9. On Security
  10. The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language. The enterprise bean must not attempt to use the Reflection API to access information that the security rules of the Java programming language make unavailable.
  11. The enterprise bean must not attempt to create a class loader; obtain the current class loader; set the context class loader; set security manager; create a new security manager; stop the JVM; or change the input, output, and error streams.
  12. The enterprise bean must not attempt to set the socket factory used by ServerSocket, Socket, or the stream handler factory used by URL.
  13. The enterprise bean must not attempt to directly read or write a file descriptor.
  14. The enterprise bean must not attempt to obtain the security policy information for a particular code source.
  15. The enterprise bean must not attempt to load a native library.
  16. The enterprise bean must not attempt to gain access to packages and classes that the usual rules of the Java programming language make unavailable to the enterprise bean.
  17. The enterprise bean must not attempt to define a class in a package.
  18. The enterprise bean must not attempt to access or modify the security configuration objects (Policy, Security, Provider, Signer, and Identity).
  19. The enterprise bean must not attempt to use the subclass and object substitution features of the Java Serialization Protocol.
  20. The enterprise bean must not attempt to pass this as an argument or method result. The enterprise bean must pass the result of SessionContext.getEJBObject, Session- Context.getEJBLocalObject, EntityContext.getEJBObject, or Entity- Context.getEJBLocalObject instead.

Sunday, April 02, 2006

Singleton Pattern in Java 2

As discussed in the previous post "Singleton Pattern in Java", the standard way to implement singleton pattern in Java is by using a static member variable which is initialized in a static initializer block or a static method. This way the static variable will be initialized when the class is loaded. This prevents race conditions (that occur when instantiated in the getInstance() method). However, this implementation has some implications:
  • The singleton class is hard-coded into the classes that use it. It also goes against the principle of "design to interfaces".
  • Since the singleton handles its own configuration, there will be no central repository for configuring signletons. This makes managing singletons a pain, specially in complex applications with many singletons.
  • It is difficult to update the state of a singleton at runtime. It can be achieved through the use of factory classes and from within the singleton class.
The alternative approach would be to use a registry of singletons. The registry is also occasionally called "application context" or "applicatin toolbox". The registry is also a singleton itself (it can also be bound to a the JNDI context). The application can get to any other singleton instance using the registry instance. A singleton registry implementation is shown below:
public class SRegistry {
public static SRegistry REGISTRY = new SRegistry();
private static HashMap map = new HashMap();
private SRegistry() {

public static synchronized Object getInstance(String classname) {
Object singleton = map.get(classname);

if(singleton != null) {
return singleton;
try {
singleton = Class.forName(classname).newInstance();
catch(Exception e) {
map.put(classname, singleton);
return singleton;
This method of implementing singletons works well with interfaces, if the getInstance() method is modified to use a name and get the class name from the configuration values. Inspite of being extremely careful, we may end up with multiple instances of singletons with the use of serialization or because of multiple classloaders. It is possible to avoid multiple instances of singletons due to serialization by overriding the readResolve() method to return the single instance. The classloader problem can be overcome by specifying the classloader yourself as described in "Simply Singleton"

Popular Posts