Monthly Archives: December 2013

Alan Turing Receives Royal Pardon

Alan Turing receives royal pardon.

Is this good? No. It just happens not to be bad.

On one hand he did not receive the glory and admiration in his life he deserved, just as many others didn’t he was working with in the Bletchley park. But this is not a disaster.

On the other hand royal pardon is not the proper way to express what happened was wrong. The justice and the treatment of Turing was against humanity. The reasoning that this was according to the actual law leaves a bit of bitter taste since Nürnberg.

Giving pardon to Turing now or the time would not have been correct because he is a war hero of a form. Even heroes should not have such privileges. They should not break in, kill or rob anyone without legal consequences. At the same time homosexuality, as we see it now is not a felony, it is not a sin: there is no place for conviction.

Therefore it is not proper that Turing was given pardon. It would be good to state that chemical castration of homosexuals is and was inhuman. Even in the light of the fact that homosexuality by the time was felony. All such convictions should be repealed retroactively.

This would not only be good, but also important. Not for Turing or for those not publicly known who were convicted. It is important for all of us wanting to live in a free society. For us, who want to have the right to make own decisions in aspects of our life that no government nor any other power has business with. Not even in England.

It is important for us, who want to live in a world where the surrounding power can face the reality. As a first step it has to face the reality that 60 years ago the government, ourself, the people made errors. Where not only the defeated are forced to accept and acknowledge that some of their acts, even being lawful, were wrong and have consequences. The ruling power should be strong enough, we ourselves should be strong enough to state it without external force.

After that statement, when we can face the fact of the errors, it is not Turing to give pardon, but ourselves, our government, the jury, who convicted him. We made errors in our history, but we have pardon and we improve.

I know that giving pardon to Turing is the first step to this direction. And this is not bad.

Design Pattern: Immutable Embedded Builder

Last week I wrote about what makes a pattern anti-pattern. This week I present a design pattern… or wait… perhaps this is an anti-pattern. Or is it? Let’ see!

The builder pattern is a programming style when there is a class that build an instance of another. The original aim of the builder pattern is to separate the building process of an object, that can be fairly complex in some cases, from the class of the object itself thus the builder can deliver different types of objects based on how the building process progresses. This is a clear example of the separation of concerns.

Immutable objects are objects that are created and can not be altered after the creation process.

Builders and immutable objects just come together very natural.

The builder and the built objects are very closely related and therefore they are usually put into the same package. But why are they implemented in separate classes? On one hand: they have to be separate classes of course. That is the whole thing is about. But on the other hand: why can not the builder be an inner class of the built class? Builder usually collect the building information in their own state and when the caller requests the object to be built this information is used to build the built object. This “use” is a copy operation most of the time. If the builder is inner class all this information can be stored in the built object. Note that the inner class can access all private parts of the class embedding it. The builder can create a built object just not ready yet and store the build information in it. When requested to build all it does are the final paintings.

This pattern is followed by Guava for the immutable collections. The builders are static inner classes. If you look at the code of ImmutableList you can see that there is an internal Builder class inside the abstract class.

But this is not the only way to embed the builder and the implementation. What if we embed the implementation inside the builder? The builder is the only code that needs mutable access to the class. An interface defining the query methods the class implements should be enough for anybody else. And if we get to this point why not to create a matrjoschka?

Lets have an interface. Lets have a builder inside the interface as an inner class (static and public by default and can not be any other way). Lets have the implementation inside the builder as a private static class implementing the outer interface.

public interface Knight {
    boolean saysNi();

    public class Builder {
        private Implementation implementation = new Implementation();

        public Builder setState(String say) {
            implementation.say = say;
            return this;
        }

        public Implementation build() {
            Implementation knight = implementation;
            implementation = null;
            return knight;
        }

        private static class Implementation implements Knight {
            private String say;

            public boolean saysNi() {
                return say.indexOf("ni") != -1;
            }
        }
    }
}

The builder can access any fields of the Knight implementation since they are in the same top level class. (JLS1.7, section 6.6.1 Determining Accessibility)

There is no other way (except nasty reflection tricks or byte code abuse, which are out of scope for now) to get access to the implementation except using the builder.

The builder can be used to build the implementation and once it returned it it has no access to it anymore, there is no way to modify the implementation via the builder. If the implementation is immutable it is guaranteed to save the state.

Is this a pattern or an antipattern?

Design Patterns: Pattern or Anti-Pattern, that is the question

I have recently encountered the wiki page Anti-pattern that has an exhaustive list of anti patterns. Some of them were obvious for me. Some of them made me think a bit, other a bit more. Then I started to look for the anti-pattern “singleton” on the page and I could not find it. (Text search stops at singlet…)

Is singleton a pattern or an anti-pattern?

Do not worry. I will not talk about singletons. There are more than enough discussions about that on the net. For now let me just use singleton as an example. In case of singleton there is no clean line between pattern and anti-pattern.

As an example, singleton can easily be used, it is easy to understand and serves the purpose being a good example. Singletons were very popular until a few years ago until they started to be considered as anti-pattern. What has changed? Do computer scientists became cleverer and discover that something they thought as a good pattern was actually anti-pattern? Was singleton an anti-pattern from the very start, we just did not know it? Or did singleton itself change from being a good design pattern to be an anti-pattern?

In my opinion, the answer, strangely: both of the cases. It is very similar to physical theory. Newtons theorem says that the force is proportional with the acceleration and the mass of the body accelerating. Einstein said that this is not true, and the larger the speed the larger the error is. Was Newton wrong? Yes, in some sense. Can we still use Newton’s laws? Yes we can, and actually we do in case of low speed (as compared to the speed of light).

Were singletons bad from the very start? Yes, just as much as they are now. Can we still use singletons? Yes we can, and actually we do in case of low spee… ops in case of simple problems that do not need considerations that make singleton to be an anti-pattern.

It seems that anti-pattern is environment dependent. And in this case environment is much more complex than in case of physics. Quantum theory, relativity or irreversible thermodynamics (that my father is professor of) are simple, because they do not consider humans. They are only about the matter.

Programming is about people.

This is something that we tend to forget many times. When it all started it was all about bits and bytes, registers, memory and hexa code. A program was either running and executing well or not. But later it became more and more complex. Computer science became information technology. More and more people use IT and more and more people write programs. They are programmers who do this for living. Even a relatively simple project, if it is commercial needs six to eight programmers. They, we are also part of the environment that the “pattern or anti-pattern”-ness depends on.

The environment also contains simple things, like frameworks, programming languages, operating systems and other technical details, but none of them individually or together has a complexity comparable that of the humans.

anti-design-pattern

When making a decision on the pattern versus anti-pattern debate many asks the question: what can the pattern be used for? What is this good for? What good can it do? These are important questions. If there is no good: no reason to consider the pattern. But it does not make it anti-pattern. If there is no good then the approach is simply not a pattern. The important question what bad it can do? What way average Joe can f@#k up the structure. How likely is it that someone applying the pattern will shoot his own leg? This is not new thing. Game theory also states that this is more important to minimize the maximum loss than to maximize the possible gain.

Looking at a pattern, can you tell that? Probably not. In some cases, yes. Congrats, you found an anti-pattern. In other cases you can not find any wrong use. It does not mean there is none. Time will show. Average Joe will come and will use the pattern in ways you could not imagine in your wildest dream (or night mare for that matter).

Thus anti-pattern is not something inherently bad, just as guns do not kill people. The use of patterns in a wrong way is bad. When people tend to use a pattern more the wrong way, then it is an anti-pattern. This is the case with singletons.

Similar thing can be captured with code commenting. When I started to learn programming Pascal our teacher required that 50% of the code has to be meaningful comment. How does it come today? Clean code says that comment is evil. Sort of. Too many comments smell. At times I find myself in projects where comments are totally evicted. Not even Javadoc is allowed. Weird? This is just the way they apply the clean code pattern.

So the question that starts to bug me these days is whether using design patterns in programming is a good pattern or is that itself an anti-pattern?

Given, When, Then…

The words given, when, then should ring the bell for anybody, who was writing BDD tests. If not, then you should read a recent article of Martin Fowler.

The structure of a test as for BDD has three parts:

  • GIVEN the part, that describes the structure of the system before the tests starts. The test itself “describes” this state with a series of setup commands to move the system under test (SUT) into the state that is prerequisite of the test.
  • WHEN is the part that triggers the SUT. The triggers are usually method calls to the SUT and ideally contains only a few calls that are necessary to test the feature of the system that is the tested feature of the system.
  • THEN test that the state of the SUT has changed appropriately and shows the observable changes that the test is focusing on.

As Martin Fowler writes “Some people like to put Given-When-Then as comments to mark informal blocks inside unit tests.” I also followed this approach and I was busy writing //GIVEN, //WHEN, //THEN comments, but I was always bothered by comments. I am not excluding comments from my programming arsenal, but many times when I feel to write comments, especially inline comments, I can find better ways. Many times I find it to be a better approach to move even a single line, not to mention two or more lines, into a separate method with a speaking name and calling the private method from the place where the lines originally were. This proves to be much better in most cases than writing comment on the lines.

What is it then with the //GIVEN, //WHEN, //THEN comments? Is there any way to express the test better?

Certainly there are better ways. One way is to use some framework to express your tests, like Cucumber, or JBehave or if you use some non-Java language some other framework as described on the wiki page of Behavior driven development. I personally recommend to devote the time and learn those frameworks, and use one that fits your taste. Just as in the general case: time invested into testing in any form is never wasted.

Time invested into testing is never wasted.

But what to do if you just write some simple test project. Something of a few classes that does not justify the use of any such test frameworks. Of course, you still need testing, as there is only one project that does not need testing: the null project (or /dev/null for old school gentlemen). So you just start a very small project, say a half afternoon, and you start to write your code (of the unit test at first place of course). Should you write //GIVEN, //WHEN, //THEN comments?

Well, your taste. Recently I realized that I can also write the GIVEN, WHEN, THEN as labels in front of the blocks that contain the ‘given’, ‘when’ and ‘then’ code. Do not feel surprised, if you have never heard of labels in Java. Most Java programmers did not. They are stone age residues, totally useless and are kept for compatibility reason. I opt that they are in the language by mistake inherited from C, Perl and other fossils. However, if they are there, why not use them? The example code

	@Test
	@SuppressWarnings("unused")
	public void given_AnACL_when_SubjectQueryAFunction_then_GivesPermisssion() {
		final Subject subject;
		final AccessControlList acl;
		final Function function;
		GIVEN: {
			subject = mock(Subject.class);
			function = mock(Function.class);
			acl = new AccessControlList.Builder().add(
					new AccessControlElement.Builder().subject(subject)
							.function(function).build()).build();
		}
		final boolean permitted;
		WHEN: {
			permitted = can(subject).using(acl).execute(function);
		}
		THEN: {
			assertThat(permitted, is(true));
		}
	}

shows you the idea. Is it better than

	@Test
	public void given_AnACL_when_SubjectQueryAFunction_then_GivesPermisssion() {
		final Subject subject;
		final AccessControlList acl;
		final Function function;
		// GIVEN
		subject = mock(Subject.class);
		function = mock(Function.class);
		acl = new AccessControlList.Builder().add(
				new AccessControlElement.Builder().subject(subject)
						.function(function).build()).build();

		final boolean permitted;
		// WHEN
		permitted = can(subject).using(acl).execute(function);

		// THEN
		assertThat(permitted, is(true));

	}

? Matter of taste. Your opinion?