April 2009


Java29 Apr 2009 07:35 am

If I were to try to apply my approach to IofC in C++ to Java, the logical starting point is the JNDI Context object.  In JNDI, to get an instance of an object, you call InitialContex.doLookup(String name); Which allows you to set a Generic type parameter to make sure that Casting is handled for you.    This is really close to what I want.  Also, When you request an object by name, what you have registered is either an instance of that object (via the InitialCOntext.bind method) or it calls a factory to create the instance, and the Factory gets registered earlier.  So far, we are in the right vicinity.

I’ve been doing some Tomcat work recently, so I’ll use that as a starting point. The JNDI implementation embedded in Tomcat is an apache project with the top level package name of org.apache.naming.  The InitialContext object is actually a participant in a Bridge design pattern.  Specifically, the user creates an InitialContext, and that will call a factory to create an Context object to use internally. Apache Naming creates an instance of org.apache.naming.NamingContext.  The interesting code is here

protected Object lookup(Name name, boolean resolveLinks)
throws NamingException {

// Removing empty parts
while ((!name.isEmpty()) && (name.get(0).length() == 0))
name = name.getSuffix(1);
if (name.isEmpty()) {
// If name is empty, a newly allocated naming context is returned
return new NamingContext(env, this.name, bindings);
}

NamingEntry entry = (NamingEntry) bindings.get(name.get(0));

if (entry == null) {
throw new NameNotFoundException
(sm.getString(“namingContext.nameNotBound”, name.get(0)));
}

We don’t really care what comes after this.  The point is that if the NamingEntry is not in the locally defined set of names, it does not know how to create the instance, and throws and exception.

What would happen if we turn this assumption on its head.  What if the failure to resolve a name just meant that the context factory should delegate it to the next context factory in the chain.  We could restrict this approach to a certain naming scheme.  If the name give falls inside a new scheme, say java:comp/chain/<classname>, use a chain of responsibility to walk the Contexts back up toward to the root to resolve the object.

The concept of lookupLink as  the default way to fetch something is intriguing.  It means that there is some method of chaining available.  Right now the only things that get resolved are the links that are explicitly put into the namespace.  Immediately following the code quoted above is:

if (name.size() > 1) {
// If the size of the name is greater that 1, then we go through a
// number of subcontexts.
if (entry.type != NamingEntry.CONTEXT) {
throw new NamingException
(sm.getString(“namingContext.contextExpected”));
}
return ((Context) entry.value).lookup(name.getSuffix(1));

Beware that there are two trees here.  the  naming tree, and  scopes of resolution.  It makes sense to think of this as a two dimensions rather than one.  The name may be a compound name, and we need to traverse down the tree to find it.  This is the top down thing I was talking about before: JNDI is designed assuming that initial context is the root of the tree, as opposed to the current leaf node.  At least, Tomcat starts there.

The nice thing about lazy resolution (back tracking) is that creating a new context is really quick.  If  most components are  resolved in the request namespace, and only rarely make it all the way up to the global namespace, than there is no performance problem.

In the current Java landscape, there are many APIs for resolving a reference.  Baseline to the language is java.naming.  The Servlet API has explicit ones for looking for objects in the request, session ,and global contexts.  Spring has the the BeanFactory interface.  OSGI has Bundle Context.  Pico container has the pico object.  The fact is that, even with inversion of control, at some point you need to kick of an object creation chain.

For instance, struts maps a segment of an URL to a class that extends the struts Action class, after binding the context to an Action form.  These objects are configured via an XML file.  The Action object is a flyweight, designed to encapsulate business behavior, where as the form object is a minimal request or session scoped object designed to do some validation prior to handover to the action.   All of this is configured by a servlet.  Once the Servlet is deployed, there is no way to change the URL scheme of the application without redeploying the app, making it ill suited to end user defined content such as a Wiki or blog.  Layout is controlled by Tiles, another related project that merged with struts, leading to a hybrid API.  Java server faces has its own object registration and creation API as well.  Since JSF and struts solve similar issues, with similar approaches, what I write about one can be applied fairly easily to the other.

As I look at the these APIs, I am struck once again by the procedural nature of them.  Time and again, we see:  create object, set properties, call execute method.  Most of these take the Class.forName approach to create the objects, and dependencies are injected via setters.  Not my style.

When I last did this full time, I ended up with a common approach where the primary interaction between the parameters and the the java objects was through builders. I was never fonds of the concept of ‘Validators’ or objects who’s sole purpose was to validate a string, and then pass it on as a string.  once I have validated a string, I want to bind it to a class that states the validation is a precondition. For instance, a Social Security number is in the format DDD-DD-DDDD.  Further business objects should not pass around String ssns, but rather instances of class SSN.   If the SSN is part of a Person object, the SSN is then passed in as a Constructor parameters, and bound to a final field, making the end object immutable.  If there is an intermediate stage, perhaps a multe page form to construct the ‘Person,’ intermediate state is held in a PersonBuilder.  The create method of the PersonBuilder enforces the preconditions are met, or returns a collection of errors.  The completed Person object probably then becomes either a Session or Application scoped variable.  Note that all fields would be final and immutable, meaning the end product is thread safe.

Struts, tiles, and so on have an API where a context object is passed around from object to object throughout the hierarchy.  Each of these should be wrapped in an Adapter so that extends java.naming.Context and bound to a well known name via InitialContext.bind().  These objects can then be stacked one after another inside a composite naming context, and called each in turn.  Here’s a first take at the adapter for tile .

public TilesApplicationContextAdapter(
TilesApplicationContex conetxt){
if (context == null) throw new IllegalArgumentException(MESSAGE);
    this.context = context;
    new InitialCOntext.bind("java:/comp/context/"+TilesApplicationContextAdapter.class.getName(),context);
}

public final TilesApplicationContext context;

public void bind(Name arg0, Object arg1) throws NamingException {
...
}
/* now the hard works starts, converting from one API to another. */

Now,  the trick is to encapsulate all of this inside a typesafe API.

import javax.naming.NamingException;

public class GenericResolver<T> {

Class<T> classOf;

GenericFactory(Class<T> c) {
classOf = c;
}

public T fetch(Context context) throws NamingException {
return (T) context.lookup( lookupStrategy(classOf));
}

public T fetch() throws NamingException {
return fetch( new InitialContext());
}

}

I’ll leave on this note:

Uncategorized24 Apr 2009 11:14 am

I needed to initialize a file as part of a unit test. The file conatined binary data. My first thought was UUEncoding, which quickly got upgraded to Base64 encoding. To get it into a format that would then work in Java or C code I used the following line of BASH.

base64 < rui.pfx | sed -e ‘s!\\!\\\\!g’ -e ‘s!\”!\\\”!g’ -e ‘s!$!\\n\”!’ -e ‘s!^!+\”!’

It was for testing a decrypter from using a key generated by SSL.

It is important to double the slashes already existing in the file before you add your own.

Note, I added this as a way to remeber how to put binary Data into code, not as a recommendation for how to mock up for unit test.  The correct solution was to use:

InputStream inputStream = this.getClass().getResourceAsStream(
file.getName());

Philosophy06 Apr 2009 10:46 am

Last week, a friend and I had a discussion regarding the question of whether Quality was subjective. While I subscribe to the position that quality was neither subjective nor objective a-la Robert Pirsig, I found myself unable to defend that position. The argument was disturbing for several reasons. First, when I attempted to show that this was an absurd position, I was accused of changing the subject, or redefining terms, etc.  I have to question whether I was. Perhaps the word “Quality” is, as my opponent in the discussion stated, the very definition of Subjective. If Quality is not Subjective, then nothing is. If a subject is defined by their values, if a person is nothing but values, as Pirsig states, then isn’t the perceived quality purely subjective?  Do to the very enjoyable adversarial nature of this discussion, I shall refer to the other participant as my opponent.

From another point of view, if two people agree that something has quality, it just means that their subjective view of quality aligns.

An example he gave was that “A long law is a bad law.” This is an objective guideline, but accepting it is subjective. One problem with this argument is that I feel fairly certain that he does not, nor does anyone agree to this hard and fast, but most people would agree that the longer a law, and , by implication, the harder it is to understand, the worse a law it is likely to be. This concept could be hammered out to the point of actually providing a guideline for judgment of law quality.

An example of Law quality that is a little more real, and certainly temporal, is that of Gay marriage. Today, Iowa’s supreme court

unanimously stated that a ban on gay marriage is unconstitutional. Laws are funny things, because they straddle the line between pure reason and emotion, the object and the subject of classical thought. The next step is for the State of Iowa to pass a constitutional amendment outlawing gay marriage the same way that California did. Is this a good decision? Obviously, people don’t agree on that topic. Does this make that question purely subjective? My opponent from today’s argument would state that it does. To him, a gay man, it is a high quality decision as it favorable affects his life. To a social conservative it is a low quality decision as it undermines the meaning of marriage. I could state that I find it a high quality decision on objective terms, as I have nothing to gain by it, but that argument falls apart under scrutiny: I have gay friends that might benefit from it, and it does reflect a pre-held value of mine that homosexuality is normal, healthy, and that people should be able to marry whom they want to regardless of gender.

If we try to view this from the perspective of the various strata posited in “Lila” there is a question of social versus intellectual quality here certainly, but also biological quality. The conservative would say that the lack of reproductive capability between two members of the same sex means that homosexuality is a low quality endeavor. The counterpoint is that sexuality is driven by biology, so that it is, by definition high quality. The transmission of AIDS through gay sex has often been used as an argument for the low quality of homosexuality at the biological level, but really the culprit there is the behavior of rampant unprotected sex. Due to the possibility of pregnancy from sex between men and women, this type of behavior is already self regulating. Birth control has changed this somewhat, but the risk of pregnancy keeps the behavior somewhat limited. There are other aspects that change the transmission rates between male/male sex and male/female sex, but in general the difference is a matter of scale, not absolute. Additionally, the risk of transmission in female/female sex is almost negligible, and yet that is never brought up as a reason that homosexual behavior might be more moral than heterosexual, although it follows from the same logic.

This digression, however interesting, does not clear up the question of whether quality is purely subjective. To address this, I think a better tact might be to start with the question of why, at the animal level, and I am defining animal as multicellular as opposed to purely reactive at the cellular level, why do we have a quality sense at all? If, as the proponents of  evolution suggest, the cells or some lower level mechanism have banded together for their mutual protection, then the quality sense of a human being is the mechanism by which that collection of cells can attempt to cooperate to modify their collective behavior to ensure the survival of the whole colony. The quality sense is how this composite subject judges the potential of survival encapsulated in some set of experiences with its environment.

Let us roll back to one of out potential ancestors, something on the level of the first mammals to take to the trees, pre-simian, but still a member of our phylogeny. I will call it a squirrel, recognizing that strictly speaking we didn’t evolve from squirrels. This squirrel is one of the first of its species with some evolutionary change that allows it to venture into the trees more than it lives on the ground. Perhaps a stronger set of fingernails/claws for gripping the bark of the trees. This squirrel has to make decisions that no other squirrel has had to make before: should it stay in the trees overnight to avoid being eaten by creatures on the ground. To rephrase it, is sleeping in trees good?

My opponent from this discussion  would say that from the squirrels point of view, yes, but from the point of view of the carnivore that feeds on squirrels, no it is not. However, the fact that the squirrel stays alive when he sleeps in the trees, more often than those that persist in sleeping on the ground, means that more squirrels have this evolutionary advantage. Thus the result of this high quality decision on the part of the squirrel is very much objective.  Quality at the animal level is therefore an attempt to determine the objective rules of the world. Quality is a hypothesis: if I do this, the result will be favorable to not doing this action. Quality has objective inputs, and objective results, but goes through the filter of the subjective process.

One branch of the same conversation covered language. I remarked that the military uses the word ‘Roger’ on the radio to indicate the successful reception of a transmission. Roger was the phonetic alphabet for the letter R. R was sent in Morse Code transmissions as shorthand for the word ‘Received’. Thus, I posited, the military should just use the word ‘Received’ to indicate a successful transmission. My friend stated that the language we speak now is not the same as the language we spoke in the 40s.

Does language exist, objectively speaking? If language really evolves that fast, is there really any language there. The books printed using the Latin characters and conforming to Strunk and White’s view point suggest that English does, in fact exist. But the sheer number of words that enter and leave everyday usage suggest that it undergoes a constant change, perhaps instantaneous change just like Newton posited for physics. Language is a protocol of communication. The acceptors of language are the people that understand it. Thus we are certainly straying into the world of the subjective as defined above.

A scholar of the English Language can state a set of rules that define English. This has been done many times, and is routinely taught in schools as Grammar. Yet words can be combined in a manner that does not agree with the rules of grammar, and yet be recognized by an individual that speaks only English. What is more, this phrase is recognized by multiple people who all agree to its meaning. Toys R Us. If this phrase is not English, then what is it? If on the the other hand, it is accepted as English, than what of those rules of grammar that were posited before. The grammarian would state that the rules of grammar signify a higher quality English than the phrase Toys R Us perpetuates.

Since studying German, I’ve often taken offense to the Grammatical rule that you should not end a sentence with a preposition. The example that most typifies how absurd this rule is Sir Winston Churchill’s statement that “This is the form of language up with which I shall not put.” I might have misquoted slightly. It is common, and often less awkward to use a modifying preposition at the end of a sentence. Come on! This is the way up. Give me a hand up. In German, such constructions are considered proper grammar. German and English share a common ancestry. As such, many of our words are cognates with their German counterparts. Is it such a stretch to state that out Grammar may be driven by the same values as German grammar?

If, as my friend and opponent would state, all of these values are purely subjective, we fall into the realm where all abstract concepts exist only in the mind. Is the law of gravity subjective? How about the number system? At some point, as we progress down the history of thought, we cross a line where things are not so clear. How about the axiom of parallel lines that Euclidean geometry is based on? Is that subjective or Objective? It really was just a value judgment. If we accept that it was purely subjective, that means that all of math is subjective. If it was objective, where does it exist outside of the mind? It starts to sound like picking and choosing those things that support the premise, and changing definitions, just as I was accused of doing during the argument. The end result is that the concept of Objective falls apart. Nothing is left as objective. As a term, it has ceased to be useful.

Perhaps this bears a little closer scrutiny. Let us start with something unmistakably Objective: A rock. Let us go further and select a specific rock, one well known in the world, the Iconic El Capitan, the rock climbers draw. Let us first try to remove all subjective from this.  The quality of it as a rock climbing location is the sickle first to go, since that is a a quality judgment made by rock climbers, who are people, and thus subjects. We remove the name of all the features like the Heart, El Cap towers, the great roof, pancake flakes, the Texas Flake, the Boot Flake, sickle ledges, the stove leg cracks, all are just now ripples on the surface of this rock face. Why do they all have to go? Because the names are in Language. Language, existing solely in the minds of the climbers is purely subjective. I choose to call the heart shaped feature to the left of the longest line of the cliff face the Heart because not only have I been told that is its name, but because it looks like a heart to me. But in fact, it looks like a stylized heart as drawn on Valentines day cards. However, if you were to compare it to a regular human heart, it would bear little resemblance. Someone who failed to see the resemblance between the stylized heart and the human hear, and thus failed to see the resemblance between the rock feature and the stylized heart, would not be able to see this feature. It would not exist for him. Thus the existence of this feature is dependent on the human being to recognize it.
Even the very presence of the cliff itself is really just the absence of the other half of the dome, long since sliced off by ice and swept down the Merced river. The cliff is the feature that makes El Cap so recognizable. How far back into the rock wall does this cliff extend? Is it just the 2 dimensional surface of the face of the cliff? What about the stove-leg cracks? Are the absence of rock which allows me to jam my hands into the wall and hold myself up against the force of gravity, part of the cliff?Even if we could go over this wall, feature by feature and accept or reject each one as being part of the wall, there are other problems of definition: how far to the left and right does El Cap extend, what about the dome that extends to the north of the cliff face. When you top out after climbing the cliff face, you are inarguably off the cliff, but you are still on top of El Cap. You can state at certain points that you have certainly passed off the dome, but where is that margin where you’ve passed from one to the other. You have to look closer and closer , defining perhaps in terms of the physics of the surface, the slope has to be horizontal, and then on the far side you are not descending at the same rate as you were before.

If the edges are questionable, there still is a point prior to that when you are inarguably “on” El Cap, correct? I would state that The definition depends on the person. OK, but what if I draw a line around the area where everyone that tops out of the Nose gathers together their gear, drinks that last bit of Gatorade and shakes hands before starting the descent. I paint an imaginary line on the ground, and make sure that I am inside that line. I call that “The Top of El Cap” and stand inside it. Surely, that is purely objective. The statement is irrefutably reduced to a “True or False” value. What could be more objective?

But lets look at that True or False statement. What are they but value judgments in their own right. Isn’t truth a statement about reality? Even if we disregard all my prior blathering about the subjectivity of language, what is “Truth” but a self supporting statement? It is Axiomatic. I suspect it is the ultimate axiom. Truth means exists. A is A, the identity relation, is the minimal amount of language we need to start a conversation. But we have Kant and Hume starting a side conversation saying that all of this is really in the mind. Does truth exist outside the human being to see that something is true? Isn’t the ultimate axiom really just the starting value of intelligence? The flip side of truth, falsehood, only exists in language. Something is only not true if you have a way of stating it.

It seems the word Quality drags everything with it. If quality is defined as objective, as Ayn Rand would have, then there is left nothing to be subjective. If quality is purely subjective, then nothing is left to be objective. The only way those terms continue to have meaning is if the term quality is left outside of them, or is used as a dividing term between them. Yes, different people can see the same objective events and differ in their quality judgements of those events. But that quality event is not an aspect of the subject so much as it is measured by them. Absent the subject, the event has no meaning. The subject is therefore essential to the quality event. But that subject is defined precisely by what objective events he finds to be high quality. Thus the definition of quality as subjective ignores the impact of the objective on the quality event. The old phrase that “[The hu]man is the measure of all things” (the sexist phrasing of the original has gotten me in trouble before) means that not only is there no quality without a subject, but that measure of the quality is variable depending on the yardstick used.