Monthly Archives: November 2014

Some Sentences about Java

There is nothing new in this article. I just collected some trivial statements which may not be trivial for some of the junior programmers programmers. Boring old stuff.

If you happen all of these things you know more about Java than the average house wife. I do not know if there is point to know all of these. You can be a fairly good Java programmer if you do not know some of these features. However a lot of new information in this article probably indicates you have room to develop.

There are 4 different protection types

in Java (not three). These are private, package private, protected and public. If you do not specify any protection modifier when you define an element in a class it will be package private (and not public and not protected).

4 levels

There are four levels of protection in Java.

On the other hand if you do not specify protection modifier in front of a method declaration in an interface: it will be public. You may specify it to be explicitly public but it does not have effect on Java and SONAR will not like you doing so.
Protection is Transitive

Protection is Transitive

My opinion about Java allowing you to optionally write public in front of a method in an interface is that this is a technology mistake.

Similarly you can write final in front of a field in an interface, or even static. It may imply that they could be non-static or non-final: not true. Fields of an interface are final and static. Always.

Protected and package private are not the same

Package private (or default) protection will let other classes of the same package access to the method or field. Protected methods and fields can be used from
classes in the same package (so far the same as package private) and in addition to that it can be used from other classes that extend the class containing the protected field or method.

Protected is transitive

If there are three packages a, b and c, each containing a class named A, B and C so that B extends A and C extends B then the class C can access the protected fields and methods of A.

package a;

public class A {
	protected void a() {

	}
}
package b;

import a.A;

public class B extends A {
	protected void b() {
		a();
	}
}
package c;

import b.B;

public class C extends B {
	protected void c() {
		a();
	}
}

Interface can not define protected methods

Many thinks that you can also define protected methods in an interface. When programming the compiler makes it obvious fast and brutally: you can not. Btw: this is why I think that allowing the public keyword in an interface is a technology mistake: it makes people think that it could also be something else as well.

Private is the new public

Private is the new public

If you want to declare a protected method in an interface, you probably did not understand encapsulation.

Private is not that private

Private variables and methods are visible inside the compilation unit. If that sounds too cryptic: in the same Java file (almost). This is a bit more than “in the class where they are defined”. They can also be seen from classes and interfaces that are in the same compilation unit. Inner and nested classes can see private fields and methods of the class enclosing them. However enclosing classes can also see the private methods and fields of the classes they enclose down to any depth.

package a;

class Private {
	private class PrivateInPrivate {
		private Object object;
	}

	Object m() {
		return new PrivateInPrivate().object;
	}
}

This latter is not widely known. As a matter of fact it is rarely useful.

Private is class level not object

If you can access a variable or method you can access it no matter which object it belongs to. If this.a is accessible then another.a is also accessible assumed that another is an instance of the same class. Objects that are instances of the same class can fool around with each others variables or methods. Rarely makes sense to have such a code though. A real life exception is equals() (as generated by Eclipse, lines 15 and 18):

package a;

public class PrivateIsClass {
	private Object object;

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		PrivateIsClass other = (PrivateIsClass) obj;
		if (object == null) {
			if (other.object != null)
				return false;
		} else if (!object.equals(other.object))
			return false;
		return true;
	}
}

Static classes may have many instances

Protection is not object level. It is class level.

Protection is not object level. It is class level.

Classes that are not supposed to have any instances are usually called utility classes. They contain only static fields and static methods and the only constructor is private, not invoked from any of the static methods of the class. In Java 8 you can have such a beasts implemented in interfaces, since Java 8 interfaces can have static methods in it. I am not convinced that we should use that feature instead of utility classes. I am not absolutely convinced that we should use utility classes at all.

Static classes are always inside in another class (or interface). They are nested classes. They are static and just as static methods can not access instance methods and fields of the class similarly a static nested class can not access the instance methods and fields of the embedding class. That is because nested classes do not have a reference (pointer if you like) to an instance of the embedding class. Inner classes, as opposed to nested classes are non static and can not be created without an instance of the embedding class. Each instance of an inner class has a reference to exactly one instance of the embedding class and thus an inner class can access instance methods and fields of the embedding class.

Because of this you can not create an inner class without an instance of the surrounding class. You need not specify it though if this is the current object, a.k.a this. In that case you can write new, which is, in this case, just a short form for this.new. In a static environment, for example from a static method you have to specify which instance of the enclosing class should the inner class created with. See the line 10:

package a;

class Nesting {
	static class Nested {}
	class Inner {}
	void method(){
		Inner inner = new Inner();
	}
	static void staticMethod(){
		Inner inner = new Nesting().new Inner();
	}
}

Anonymous classes can access only final variables

Variable has to be effective final

Variable has to be effective final


When an anonymous class is defined inside a method, it can access local variables if they are final. But saying that is vague. They have to be declared final and they also have to be effective final. This is what is relaxed a bit in Java 8. You need not declare such variables as final but they still have to be effective final.
Java 8 does not require final, only effective final

Java 8 does not require final, only effective final

Why do you need to declare something final, when it has to be checked being that anyway? Like method arguments: they also have to be final. You say that this is not a requirement of Java? Well, you are right. It is a requirement of programming in good style.

Do all business logic on the client using JavaScript?

History look

The first applications were running on “the” computer. There was nothing like “client” and “server”. There was the computer and the punch card input, printer output. Later the mainframe came and the clients were terminals. Looking back, we can say that this was a two tier architecture with lightweight clients. This was practically the same with the mini computers (PDP, VAX and their clones) until the PC was introduced.

The PC architecture introduced the two tier paradigm that contained a fat client and file server or database server. Three tier architecture was supposed to replace the two tier architecture to have a no-so-fat client, server supporting business logic and storage on the third tier. Then came the web and the browser and the client was replaced by web page. Thin client was invented. At least the terminology was born that time. And during the last 20 years the web technology evolved and with HTML5 we have something on the client side that is very powerful and in functionality and in capability comparable to the thick client of the early PC era. If we consider the memory and CPU power we currently have an HTML5 capable browser fairly overcomes any early PC fat client.

Time to think about what is implemented in what tier. As we see the functionality, storage and code were dangling back and forth between the client and various server components. The optimal distribution of functionality was determined by the distribution and availability of CPU power in the different tiers, storage capabilities and network latency as well as bandwidth. Technology evolving changing the ratio between these changed where we put parts of the functionality.

Today

Today clients are so powerful that we are tempted to put everything on the client. It is not only the available top-notch client, which is so powerful. We can also expect good cpu power, memory and bandwidth on the average client. Why not to put all functions on the client? Could we do all business logic on the client? Almost. There are some features, not mentioned above, that a client does not implement and is not likely to implement in the near future with the current architectures. Some of these are features like:

  • persistence
  • search
  • transactions
  • trust

Let us look at these features.

Persistence

You can not store data reliably on the client. Backup, archive, audit logging are functions that are naturally live on a server. If ever any of these are implemented on a client machine that machine is operated as a server some way. If not impossible then probably expensive to do it on a client. Individual clients can not simply backed up and they have to communicate with each other to see the same state of the data that reflects the actual state of the modeled world.

Search

Search is also something not likely to be implemented on the client. Search needs the data to search in. In some cases the data set can be copied to the client and thus the search can be implemented on the client, but in most of the cases the client will work only with a subset of the data, therefore search is implemented on the server.

Transaction

Transactions are tied to data. If you sell airplane tickets you may not want to have a system that asks all other client terminals if the seat A in row 13 is still free on a certain line. That would be a total noise like a room full of people. Perhaps something like the old stock trading rooms may resemble to that.

Trust

Clients are owned by the person having physical access to the machine. Steve Halls’ talking moose said: “Never trust a computer you can not lift.” When it comes to physical security it is crucial the other way around: Never trust a computer somebody else can lift. In an application you can not trust any communication that comes from a certain client unless you established some trust. Password, card access whatever. But the trust to maintain is up to the server, which some bad guy can not nick.

Where does it come?

Single page applications contain static HTML, CSS and JavaScript. The server communicates with the client using Ajax, REST, JSON. The users identify themselves using some authentication, probably OAuth. After that the client application displays whatever the functionality of the application needs and the server provides only data functionality. All the server should do is CRUD with access control. Whenever a client wants to access some data the server has to check if the said user has the rights to read and/or to write the data. Other than that the server need not know anything about the business functionality.

Persistence services, like MySQL or MongoDB (to name one of SQL and NoSQL) are providing REST interface and the interfaces obviously do require authentication. However the authorization scheme of these interfaces are very weak. The usual approach is: if you authenticate you are authorized. There is no document or record level access control, which I see will come in the future. First we will have applications that work as a front-end to these persistence applications that check the authorization and based on that let or deny the operation to perform. However this solution is not optimal from the performance point of view. The logical implementation of such logic is where the data is: in the database.

If and when the databases will support such a record level authorization schema we can write all our code, or almost all code in JavaScript running on the client. Applications will be developed in JavaScript. Java will only remain for enterprise integration, connection handling to legacy systems. Java will be what Cobol is today. Will it?

When null checking miserably fails

Disclaimer

Before going on I have to state that the techniques described in this article serve no practical purpose when we program Java. It is like a crossword or puzzle. It may train your brain in logical thinking, may develop your Java language knowledge or even your thinking skills. It is like a trick a magician performs. At the end you realize that nothing is what it looks like. Never do such tricks in real life programming that you may need to apply to solve this mind twister.

The Problem

I recently read an article that described the debugging case when

if(trouble != null && !trouble.isEmpty()) {
  System.out.println(“fine here: ” + trouble);
  }else{
  System.out.println(“not so fine here: ” + trouble);
}

was printing out

fine here: null

The actual bug was that the string contained “null”, a.k.a. the characters ‘n’, ‘u’, ‘l’ and ‘l’. May happen in real life especially when you concatenate strings without checking the nullity of a variable.

Then I started to think about other similar strange code and debug situation. Could I make it so that the variable is not only “null” string with these characters but really null? Seems to be crazy? Have a look at the code:

package com.javax0.blog.nullisnotnull;

public class NullIsNotNull {

	public static void troubled(){
		String trouble = new String("hallo");
		Object z = trouble != null && !trouble.toString().isEmpty() ? 
                                                          trouble.toString() : "";
		if (z == null) {
			System.out.println("z is really " + z + "?");
		}
	}
}

Will it ever print out the

z is really null?

question. The fact is that you can create a Java class containing a public static void main() so that starting that class as a Java application the sentence will be printed when main() invokes the method troubled(). In other words: I really invoke the method troubled() and the solution is not that main() prints the sentence.

In this case the variable z is not only printed as “null” but it really is null.

Hints

The solution should not involve

  • reflection
  • byte code manipulation
  • calling JNI
  • special class loaders
  • java agent
  • annotation processor

These are too heavy tools. You do not need such armory for the purpose.

Hint #1

If I change the code so that the variable z is String it does not even compile:

This is what I see in Eclipse

This is what I see in Eclipse

If it confused you even more, then sorry. Read on!

Hint #2

In the Java language String is an identifier and not a keyword. The Java Language Specification section 3.9 may give more information on the significance of this.

Hint #3

The method toString() in class Object has a return type java.lang.String. You may want to read my article about the difference between the name, simple name and canonical name of a class. It may shed some light and increase the hit count of the article.

Hint #4

To use a class declared in the same package you need not import that package.

Solution

The solution is to create a class named String in the same package. In that case the compiler will use this class instead of java.lang.String. The ternary operator in the code is simple magician trick. Something to diverge your attention from the important point. The major point is that String is not java.lang.String in the code above. If you still can not find out how to create the trick class, click on the collapsed source code block to see it in all glory:

package com.javax0.blog.nullisnotnull;

class String {
	private java.lang.String jString;
	private boolean first = true;

	public String(java.lang.String s) {
		jString = s;
	}

	public boolean isEmpty() {
		return jString.isEmpty();
	}

	@Override
	public java.lang.String toString() {
		if( first ){
			first = false;
			return jString;
		}
		return null;
	}

	public static void main(java.lang.String[] args) {
		NullIsNotNull.troubled();
	}
}