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.

jolokia queue monitoring html script (uses jquery)

Just alter the location of jquery to suit:

 

<!doctype html>
<html>
<head>
<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}
</style>
</head>
<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;
$(divName).html(mhc);
}
);
}

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

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
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:

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

Sample JSON Output:

{
   "timestamp":1399478460,
   "status":200,
   "request":{
      "mbean":"com.bea:JMSServerRuntime=jms-server-1,Name=jms-module-1!indexQueue,ServerRuntime=AdminServer,Type=JMSDestinationRuntime",
      "attribute":[
         "MessagesCurrentCount",
         "MessagesHighCount",
         "MessagesReceivedCount"
      ],
      "type":"read"
   },
   "value":{
      "MessagesHighCount":0,
      "MessagesCurrentCount":0,
      "MessagesReceivedCount":0
   }
}

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";
	@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));
	}
}

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 {
	@Test
	public void testHappyPath() {
		final Person p = new Person("Vincent", "Fleetwood");
		Assert.assertEquals("Vincent Fleetwood", p.getFullName());
	}
}