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.

$hasher->setFluidOunce(8);
$hasher->setFrothy(false);

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

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:

[ENGINE]

#DO NOT CHANGE THIS.
Response File Version=1.0.0.0.0

[GENERIC]

#The oracle home location. This can be an existing Oracle Home or a new Oracle Home
ORACLE_HOME=/home/oracle/Oracle/Middleware/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.
MYORACLESUPPORT_USERNAME=

#Provide the My Oracle Support Password
MYORACLESUPPORT_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
DECLINE_SECURITY_UPDATES=true

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

#Provide the Proxy Host
PROXY_HOST=

#Provide the Proxy Port
PROXY_PORT=

#Provide the Proxy Username
PROXY_USER=

#Provide the Proxy Password
PROXY_PWD=

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

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