Coding Style

Wow, you could fill a book on this subject. And some people do.

The guidelines for coding in Java, my language of choice, are fairly fluid but there is usually a general consensus of opinion on most topics. Here are a few:

Always declare variables as final.
I only explained this one last night so it’s still fresh, and yes, in a sense it’s not a variable if it’s final.

The idea is that if a variable can have its value changed it can be confusing and lead to bugs. If every variable is final you have only to know what value it was initialized with. There is a peculiarity when this style is adopted (and eclipse will do this for you if you configure it) – anything non-final appears like a warning, particularly useful for parameters which should remain constant through a method invocation. Imagine a function working on width and height that changes the height halfway through.

Making all variables final used to be tough as some people believed in having only one return point in a method. This argument has been answered in the Java world by Kent Beck, one of the founders of XP / Agile and creator of the JUnit framework. Single Entry Single Exit, he says,

was to prevent the confusion possible when jumping into and out of many locations in the same routine. It made good sense when applied to FORTRAN or assembly language programs written with lots of global data where even understanding which statements were executed was hard work … with small methods and mostly local data, it is needlessly conservative.

Use static methods sparingly.
This didn’t matter a great deal in the past and in projects without unit tests will be less important. If you don’t have unit tests but do have business logic then you may have bigger problems.

Originally, static methods were ok as they indicated a stateless method or function. This sounds good because you don’t need to create an object to provide you some functionality – just call a method on a class. The problem with this approach is that you cannot override static methods. It’s not very ‘object oriented’ – there is no object doing the work, just a hard-coded reference to the implementing method. No abstraction – this is the implementation. Always. Well, you can override this using some mocking frameworks with functionality generally considered for ‘legacy code.’ This should tell you all you need to know. If you are hard-wiring this method into your production code but need different behavior (in tests) and achieve it with compiler tricks instead of polymorphism, some would consider this to be missing the point. I’ve seen people do very elaborate things and get into very long arguments about how to avoid using polymorphism. This seems to be missing the point on purpose. The same people will prefer untested private methods over tested package-private methods and good luck with that.

Software Development Analogies

Software development is full of analogies, e.g. creating software is like making such-and-such. None of the analogies I’ve come across get too close – each just serves a small purpose. Here are some analogies I’ve used or come across in software development:

Building software is like building houses in a time before they knew how to build houses.
This is my own, which is why I put it first 🙂 By this I mean that a lot of the way software is written is wrong or inefficient. In the software development community we are very capable of writing systems that look like they work but are seriously lacking in ‘non-functional requirements.’ Following the house analogy it would be like having a building that from the outside looks like a house but just isn’t quite right – and ‘not quite right’ enough to the point of needing replacing within a few years. Houses aren’t typically built like that anymore as far as I know. Well, that’s the house-building analogy gone then.

A software development team needs a foreman.
This one was made famous in 2014 when it was made by Uncle Bob Martin. An example of this idea was “He’d do the same thing he does on a construction project. He’d make sure everything was done, done right, and done on time. He’d be the only one with commit rights.” Rather than trying to find anything useful in the analogy, I think a lot of people just picked holes. Code reviews are important on most projects and the most experienced developer checking all code could be very beneficial. Once I remember seeing someone had completely misunderstood Hibernate and, unless the code reviewer understood Hibernate, this code would make its way into the codebase.

The software development team as a surgical team – F.P. Brooks.
This is an idea Brooks relates in his famous book “The Mythical Man-Month” which I’d recommend to any programmer who can read. He actually credits the idea to Harlan Mills. The thing that captures my imagination about this idea is the notion of having a ‘toolsmith’ – my earliest development role evolved into managing an API which I’d implemented in PHP, Java and Visual Basic. I kind of fancied myself as this toolsmith. Where Bob Martin has an idea of a foreman checking everyone’s work, Brooks / Mills have a chief programmer and co-pilot.

an acid test for method sanity

So, I just looked at a method call in an online tutorial and found this fairly simple code.

// Initialize the hasher without portable hashes (this is more secure)
$hasher = new PasswordHash(8, false);

What’s wrong with this? Not much maybe. Or maybe a lot. I have an acid test for method signatures: can I determine what the arguments are from the method name and parameter type(s)?

First things first, the first parameter ‘8’ may be given a name in production code, as might the ‘false’. That’s ok – I’m not interested in the quality of the calling code, just the signature of the method.

The crux of the problem – what is this method / constructor asking for? I read aloud the method with parameter types in place and try to determine the purpose of them. In this case I read out the following:

new Password Hash int boolean

What does this mean? No idea.

At first glance this seems like an ‘out there’ naive view of code, along the lines of ‘never use the String class’ but I feel this is a fundamental part of writing better code. Here I would prefer to create a ‘default hasher’ using a factory method maybe, assuming that I need an int and boolean to create a Password Hash. Now let me override the int and boolean with appropriate setters, e.g.


And there you have it, my acid test for method sanity.

jolokia queue monitoring html script (uses jquery)

Just alter the location of jquery to suit:


<!doctype html>
<script type=”text/javascript” src=”jquery-1.11.1.js“></script>
<style type=”text/css”>
td { border: 1px solid #666; padding:5px; }
table { border-collapse:collapse}
<body onload=”javascript:fetch()”>
<h1>Monitoring Queues on Admin Server</h1>
<script type=”text/javascript”>
var index_url = “http://localhost:7001/jolokia-war-1.2.1/read/com.bea:JMSServerRuntime=jms-server-1,Name=jms-module-1!!indexQueue,ServerRuntime=AdminServer,Type=JMSDestinationRuntime/MessagesCurrentCount,MessagesHighCount,MessagesReceivedCount”;
var luc_index_url = “http://localhost:7001/jolokia-war-1.2.1/read/com.bea:JMSServerRuntime=jms-server-1,Name=jms-module-1!!luceneIndexQueue,ServerRuntime=AdminServer,Type=JMSDestinationRuntime/MessagesCurrentCount,MessagesHighCount,MessagesReceivedCount”;
var mine_url = “http://localhost:7001/jolokia-war-1.2.1/read/com.bea:JMSServerRuntime=jms-server-1,Name=jms-module-1!!mineQueue,ServerRuntime=AdminServer,Type=JMSDestinationRuntime/MessagesCurrentCount,MessagesHighCount,MessagesReceivedCount”;

function updateDiv(url, divName) {
$.getJSON( url,
function( data ) {
var mhc = data.value.MessagesCurrentCount;

function fetch() {
updateDiv(index_url, “#indexQueueCount”);
updateDiv(mine_url, “#mineQueueCount”);
$(“#lastDate”).html(new Date());
setTimeout(fetch, 2000)
<td>Index Queue Current Message Count</td>
<td id=”indexQueueCount”></td>
<td>Lucene Queue Current Message Count</td>
<td id=”luceneQueueCount”></td>
<td>Link Mining Queue Current Message Count</td>
<td id=”mineQueueCount”></td>
Last fetched: <span id=”lastDate”></span>

WebLogic 12c JMS queue monitoring with jolokia

Credit where it is due:
This and other helpful WebLogic administration / monitoring tips can be found in
the great WebLogic Server 12c Distinctive Recipes book by Frank Munz.

Jolokia is a great open source tool that provides, amongst other things, a RESTful interface to MBeans in JEE Containers. My specific need is WebLogic queue monitoring and jolokia is great for this. I have the following:

JMS Server: jms-server-1
JMS Module: jms-module-1
WebLogic Server: AdminServer (not recommended for production)
JMS Queue: indexQueue

By installing jolokia as a war (dropping the war file in autodeploy directory if running in development mode) I can get information about my queue by navigating to the following url:


Sample JSON Output:


WebLogic 12.1.2 Install – silent mode, console mode

Okay, well I decided to upgrade my WebLogic install knowledge tonight. I’ve got a few installs already to play with but thought I’d experience once more the joy that is the silent WebLogic install. Little did I know…

In WebLogic 12.1.2 we get some pretty big changes to the server installer:

  • Installation is now via the Oracle Unified Installer.
  • Install runs system requirement checks, warning if certain prerequisites are not met.
  • Silent mode requires a -silent flag (not -mode=silent) and a response file.
  • There is console switch or falling back to console for the installer – silent or gui only.

To get a response file you can run the GUI installer and click the ‘Save Response file’ button. Here is my response file from installing as a user oracle:


Response File Version=


#The oracle home location. This can be an existing Oracle Home or a new Oracle Home

#Set this variable value to the Installation Type selected. e.g. WebLogic Server, Coherence, Complete with Examples.
INSTALL_TYPE=WebLogic Server

#Provide the My Oracle Support Username. If you wish to ignore Oracle Configuration Manager configuration provide empty string for user name.

#Provide the My Oracle Support Password

#Set this to true if you wish to decline the security updates. Setting this to true and providing empty string for My Oracle Support username will ignore the Oracle Configuration Manager configuration

#Set this to true if My Oracle Support Password is specified

#Provide the Proxy Host

#Provide the Proxy Port

#Provide the Proxy Username

#Provide the Proxy Password

#Type String (URL format) Indicates the OCM Repeater URL which should be of the format [scheme[Http/Https]]://[repeater host]:[repeater port]

String.intern aka “I never knew that…”

Ok, so I’m trying to fill in any gaps in my java knowledge. First thing is going through my fairly comprehensive SCJP 1.5 study book. Mainly common stuff I’ve used enough of but the odd thing is of interest. Today I found the ‘intern’ method on Strings. I’ll explain.

The typical Java developer is aware of the following:

  • Strings are immutable.
  • Strings typically live in a String pool.
  • Strings should be checked for equality using the equals method, not ‘==’.

You can create a String not in the String pool using the the following:

String foo = new String("bar");

What we typically want, though, is String reuse, via the String pool. An interesting method exists around Strings to ensure getting the String instance from the String pool, this method is ‘intern’. Here is the javadoc lifted from the JSE1.7 site:

Returns a canonical representation for the string object.

A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.

Here is a class to demonstrate with tests. It uses the System.identityHashCode(Object) method to show which object reference is being looked at.

import junit.framework.Assert;
import org.junit.Test;

public class StringTest {
	final String test = "test";
	public void testStrings() {

		final String stackTest = "test";
		final String stackTest2 = new String("test");
		final String stackTest2Interned = stackTest2.intern();

		Assert.assertEquals("test", test);
		Assert.assertTrue("test" == test);
		Assert.assertTrue(stackTest == test);
		Assert.assertFalse(stackTest2 == test);
		Assert.assertTrue(stackTest2Interned == test);

		System.out.println("id of constant = " + System.identityHashCode(test));
		System.out.println("id of stackTest = " + System.identityHashCode(stackTest));
		System.out.println("id of stackTest2 = " + System.identityHashCode(stackTest2));
		System.out.println("id of stackTest2Interned = " + System.identityHashCode(stackTest2Interned));

Use the eight primitive Java types

Java has 8 primitve data types.

Here is a list of them with their size and example use:

boolean – a single bit.
A bit is a single value in memory which can have 1 of 2 values – 0 or 1. Typically in programming, 0 means false and 1 means true but this relationship does not exist in java. A boolean has to be true or false, but this rule does not hold for the Boolean object.
Example of its use would be where an object has an ‘is’ or ‘has’ attribute, e.g. person.isDeceased(), person.isEligible();

short – a 16-bit number.
Of the 16 bits used, 1 of the bits is used to determine whether the value is positive or negative. This means the minimum value represented is -32768 and the maximum is 32767.
It is rarely used as an int is typically used for counting things and a Long is typically used for the Id field of an entity.

char – 16-bit character representation.
When used directly it represents a character. It can however be used as a number – it has MIN_VALUE and MAX_VALUE as do other number types, e.g. short, int, long. This does also mean it can be used with the normal mathematical operators such as +, -, % etc.

int – 32-bit integer numbers.
Always occupies 32 bits, regardless of processor, java version etc.
A typical usage would be counting the elements in a list or some returned results. Min value is -2147483648 and Max value is 2147483647. An int is often used even when the value expected would fit into a short. This is just force of habit I think.

float – 32-bit floating point.
This is used for calculating values with numbers after the decimal point, e.g. 10/3. Min value is 1.4E-45
and max value is 3.4028235E38. It shouldn’t be used for currency as it deals with approximations. Running the following:

System.out.println(1.03 - 0.42);

will output


long – 64-bit integer
This is typically used for very large numbers – the min is -9223372036854775808 and the max is 9223372036854775807. A long is typically used for the id field of an entity persisted in the database.

double – 64-bit floating point number.
I never use doubles, I never see doubles used and doubt I will see them used. I don’t do a lot of mathematical computation though – I typically write CRUD apps and have code around the workflow of CRUD, e.g. validation, converting to and from DTOs, persistence.

Hope this helps give an idea of the different types. I think the main concerns are whether you want to use whole numbers or not and if so the concern becomes how much space do you need to represent this number – generally the smaller the better but… shorts are rarely used even when appropriate.

Using private and public as appropriate for encapsulation

Ok, well this part of the SCJP syllabus overlaps with what I’ve written on Encapsulation but I can reuse my class so this should be a cheap post 🙂

In simple terms, if a field or method is public other classes can happily depend on them being there. Private fields and methods are not available to other classes and, as long as the public methods retain their functionality, other classes will be unaffected by changes to them. This is what we want from encapsulation… and also how we achieve it.

Here is our Person class from my post on encapsulation:

public class Person {
  // in this implementation we store both fields as is.
  private final String firstName;
  private final String lastName;
  public Person(final String firstName, final String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  public String getFullName() {
     return firstName + " " + lastName;

What do other classes see? Well, they will not see the private fields. To them this class is like a black box (they cannot see /affect its inner workings) that looks like this:

public class Person {
  public Person(final String firstName, final String lastName);
  public String getFullName();

If we change how it works without changing the public-facing functionality, we do not need to worry about the other classes.

Unit test
Q: How do we ensure that our class continues to provide the same functionality?
A: Unit tests.

Here is what the test for this class might look like:

import org.junit.Assert;
import org.junit.Test;

public class PersonTest {
	public void testHappyPath() {
		final Person p = new Person("Vincent", "Fleetwood");
		Assert.assertEquals("Vincent Fleetwood", p.getFullName());