RSS

Monthly Archives: January 2015

Bionics, Biological Self-Checks, and How I Just Lost my Right Nipple Ring.

Soooooooo.

Yeah, I didn’t literally lose it. It migrated to the surface over the course of more than a year. I was attempting to remove it, thinking that it needed to be re-set, and while attempting to remove the bead it just popped off.

Seriously, straight through the flesh. I didn’t feel a thing physically, so I’m presuming that there was nothing but a little cutaneous tissue holding it on. However, there was this profound moment of loss. I put up a blog post on piercing art before, and since have gotten six pieces; two in my right ear, two in my left (nonsymmetric), and two nipple rings.

I remember people fretting about male body art in the east, in my notoriously old-South family, but honestly I am much more concerned about losing it than I ever was about getting it. We think of these things as something permanent. We think of them as a lasting part of us. However, the truth is that tattoos bleach over time, scarification can (somewhat) fade over over an extended period, and believe me, the body is very good at differentiating between what does belong to it, and what does not, so every piercing you get, given enough time, will find its way out.

Some are better behaved than others.

I remember back in the day, when neuroprosthetics wasn’t a real thing, and we referred to it by the comic-book names of bionics and cybernetics, there was a lasting belief that the metal could simply be sealed to the body somehow. The thought was, incorrectly, that stopping the bleeding would convince the body that the wound was closed. Unfortunately, that isn’t the case; if you breach the skin, the immune system will know about it, and may complain vividly until the gap is closed.

This was eventually worked around by integrating the skin as part of the treatment. Modern artificial cochlea are actually two-piece components; one of them is subdermal (beneath the skin), the other superdermal. The superdermal part is the part that you can actually interact with; it requires a power source, it can be tuned and calibrated, and it can be removed. In operation, it communicates with the subdermal part via a focused magnetic field, which passes through the skin with little interference. The subdermal component is the one responsible for communicating this signal to the auditory nerves.

You know what happens when you try and merge the super- and sub- components into one? You get a nasty infection and potentially further damage.

For bionic limbs, the winning method (as of yet) is to receive signals sent to the stumps that correspond with attempted actions with the missing limb, interpret them with an on-board neural network, and feed the proper message to the twenty two or more motors in the limb. It is fantastically effective, and even allows for feedback to the brain. No breach necessary.

So how does the body know that the wound is open? Our dermis is a little more complicated than a paper bag. Describing the entire immune response requires more patience than I have as a writer, or you have as an off-brand reader who might have been expecting something more akin to modular human designs (which it is not). However, the breach of the skin releases compounds called cytokines, which act as messengers to the rest of the body and trigger a full-fledged assault. Unlike well-designed software, the body was formed on the crucible of natural selection, and often has many functional systems partially manifest in a single physical one.

So, the next obvious question. If hole-in-the-chassis bionics and cybernetics don’t work, and my right nipple ring was removed as a foreign invader, why hasn’t my left moved? There are more factors, I’m certain, than I specifically know of. However, deeper piercings, particularly those with a hole on both sides of the flesh, have slower rejection rates. (Note that I did not say “no rejection rate”; but slow enough to approximate to permanence.) Additional issues can include secondary local inflammation; which you may think of as the immune system going into five-alarm mode and accepting greater degrees of loss. This includes infections (which have their own problems, keep it clean!), irritation from over-cleaning (which also has its problems), and metal sensitivities. Using something biocompatible is generally a good idea, even if you have no known metal sensitivities. Last but not least is weight; heavier jewellery migrates on account of gravity alone.

Cytokines are one of the first-phases of what you may think of as an organic observer pattern. Think of the various immune-related tissues as observers; and compounds like cytokines, chemokins, and elastin proteins, are messages to them. “Ah,” you say, “now you’re speaking my language!” Sort of. Is it possible to prevent this by suppressing the messages? Sure, if you don’t mind developing oozing sores from a repressed immune system. As for me, I will simply be having Phil give it a thorough autoclaving and punch it back in there, perhaps further down.

Advertisements
 
Leave a comment

Posted by on January 30, 2015 in Body Art

 

Tags: , , , , , , , , ,

A Case Against Using Null. (For Almost Anything.)

Java is my usual language, but this goes for everything.

I promise that this is not going to be another rant about NullPointerExceptions and their kin in other languages. This is not to say that such rants are not warranted, and even cheered; but I’m going to be a bit more academic about it. I’m also going to provide solutions, not only the ones available in Java 8, but what I used to do beforehand.

What Does “Null” Actually Mean?

Great question. Null as an adjective, according to the dictionary, means without value, effect, or significance. It also means, lacking, and nonexistent. It also means, empty. And, lastly, also probably most recently, it means zero. This is most likely a linguistic artifact, as everything is ultimately expressed in the binary on a computer. In C, null actually does equate to zero. However, this necessity has led all of us to a lot of abuse, because symbolically it isn’t what null is for. I’ll come back to that.

Null’s etymological origin comes from the latin nullus, meaning none, as in, it-has-not-been-set. While zero is reasonable, zero is an actual number. If you were enumerating the entries of a set of numbers, and you wanted to count the length of that set, you would not skip every entry that was zero, would you? However, you likely would for null, as it denotes no-entry in the set. Therein lies the critical difference.

In Java, objects are initialized to null, before they are set to any value. Object instances are the Java equivalent of C’s pointers; and while they cannot be without a value, they initialize to a language constant that reflects the absence of an intended one. Null is typically represented as zero, but not always, and I am unsure of the case with Java. However, a null pointer is a symbol, it is not reasonably a pointer to the zero position in memory. This position does, actually, exist; but on the reference of such a pointer, the virtual machine (or platform) throws up a red flag.

The nasty habit of using null as a return value when something goes wrong in an operation is almost ubiquitous, but unless this literally represents that no value has been set, it is a dangerous move. I’ve even seen it in the JDK. The response to such an ill-though-out method is usually a few lines of defensive programming, checking to see whether the object is null, and acting accordingly.

Java 8 Solutions

If you aren’t a Java programmer, you may wish to skip this section.

As it turns out, the defensive programming response to returned nulls is so similar, in every instance, that it can be encapsulated into an object itself. This would be Java 8’s Optional. Optional represents a possible value, that is, a value which cannot be guaranteed to exist. However, the Optional itself is never null.

On initialization of an Optional, it is best to set it to Optional.empty(), that is, an Optional with no contents. If a value is being wrapped in an Optional, use Optional.of(). If the presence of the value is unknown, use Optional.ofNullable(), it will do the defensive work for you. The rest of the methods of Optional apply Java 8’s influences from functional programming. What used to require complex if statements is now done primarily through ifPresent(…) and orElse(…).

This might seem like an overreaction to you. However, compared to the work that I used to have to do just to catch every wrench-in-gears value that might pass by, it is a miracle. If you disagree, you need only ask yourself how frequently you have been getting NullPointerExceptions. Adopt Optionals, and you won’t get them anymore.

Older Java Solutions

In previous versions, several further techniques have been added. The biggest problem with “!= null” is that it is an operation, and a mandatory operation, which will slow down code very slightly. This is imperceptible for the vast majority of programs, but if you need something to run searing fast, then it can be unacceptable.

If you are writing an API, I might suggest funnelling all input through a defensive checking method before passing it along to the meat methods; but if you are writing code that only you will access, there is a simpler solution: assertions. This is particularly true for unit testing with programs like JUnit.

This is exclusively functional during development, as in order to enable assertion testing, you need to pass the -ea parameter to the java compiler. Unless you can force this on users, it is exclusively meant to help you identify routes by which null, or any other unacceptable value, can make it to your methods.

The syntax is simple. Given parameter “x”:

assert x != null : "[error message]";

If the provided boolean expression evaluates to false, an AssertionError is thrown, with a message of the toString() value of whatever was passed on the right (for me, most typically an actual string).

I don’t generally like to see assertions making their way into production code today, as I am inclined toward Optionals; but this is quite effective for debugging. Additionally, such statements can be considered an essential part of JUnit tests. If you are in a rush, it is possible to ignore all assertions remaining in a slice of code by removing the “-ea” parameter from the compiler; but on the human end, this is bad practice and worth avoiding.

As an alternative, Apache Spring has a class called Assert which handles more or less the same tasks as the assert keyword.

Broader Solutions for Object Oriented Languages

At last, in the most general sense, there is the Null Object Pattern. This is, still, my ultimate preference when building a set of classes, as there is no need for Optional when null never enters the equation.

A Nullary Object is an object extending the appropriate interface, with defined behavior, denoted as equivalent to null. This has its ups, and its downs. As an example, suppose we had this interface:

public interface Animal {
    public String speak();
}

with these implementations:

public class Dog implements Animal {
    public String speak() { return "bark"; }
}

public class Cat implements Animal {
    public String speak() { return "meow"; }
}

public class Bird implements Animal {
    public String speak() { return "tweet"; }
}

And we had one further class that requires one unknown animal, which will indubitably call “speak()”. Which animal is beyond our control, and we don’t want our program to crash on a NullPointerException simply because no animal was specified. The solution is one further class:

public class NullaryAnimal implements Animal {
    public String speak() { return "…"; }
}

In the case of abstract classes, it is often helpful to have the nullary class be a member of the class itself. This is also particularly helpful when there are multiple behaviors which might, otherwise, be implemented as “null”. The potential down side is for people who were actually looking for an exception to be thrown; in such a case, simply fill speak() with an Apache Commons NotImplementedException or something relatable.

One extension of this pattern is such:

public abstract class Sequence {
    //...
    
    public static final Sequence ANY = new Sequence(…);
    public static final Sequence ALL = new Sequence(…);
    public static final Sequence NONE = new Sequence(…);
}

In this instance, a new Sequence can be initialized to Sequence.NONE, ALL, or ANY, and be replaced if a new value is provided. Additionally, since these are actual objects and constant values, they respond appropriately to equals checks.

There may be a name for this pattern, I’m honestly not sure. I came up with it on my own, but I very much doubt that I’m the first.

Conclusion?

Hardly. However, you now hopefully have a new set of tools to keep unfinished declarations and, even worse, “= null” statements out of your program. I hope I’ve made your life easier!

 
Leave a comment

Posted by on January 10, 2015 in Programming

 

Tags: , , , , , , , , , , , , , , , ,

Software Language Engineering: Analysis

(Early Edition)

So, at this point we have a clearly defined Backus-Naur form for our grammar, a working scanner for terminal tokens, and a working parser for non-terminal generation and the construction of the abstract syntax tree.

The biggest hurdles are over. However, they weren’t quite the last. One thing that must be done before any compiler or interpreter can be built is the construction of a utility for analysis. In this section, I’ll be describing the basic contract for a contextual analyzer. In the next section, I’ll be showing you some example code.

Introduction

Some of the analysis was already done. The core concept to keep in mind, when building a build tool, is the fewer the passes, the quicker your tool will run. Basic syntax errors have already been detected; as they prevent the construction of the AST for our language. However, you might notice that there are a few obtuse things that you can still do.

Enter “3 + 4 = 2” into the algebra tool, and you’ll notice that it will gobble it down just fine; even though it is concretely incorrect. This is where the second phase of analysis comes in.

Can we sweep for these while we generate the abstract syntax tree? Does your processor have more than one core? Then we absolutely can. Even if you are using a single-core, the penalty would be rather mild. However, it is important to recognize that code analysis is the work of a separate module.

Types of Analysis

There are two major forms of analysis to worry about: syntactic analysis, and contextual analysis.

Syntactic Analysis

Syntactic analysis is almost always the responsibility of the parser. Contextual analysis depends on it. Syntactic analysis is the process that generates the phrase structure of the program; without it, further phases are obliquely impossible. It’s more commonly known as parsing, and if you’re following this tutorial in sequence, you’ve already done it. If not, there are four preceding chapters dedicated to explaining it in detail.

Generally, I recommend, on the establishment of a syntax error during syntactic analysis, simply skipping the node and checking for what might be next. This is not an issue for small programs, much less one-line programs; but for larger utilities and libraries it is vanishingly uncommon for the number of bugs to be limited to one. Often, knowledge of the effect on another, later, mistake is critical to the creation of a satisfactory solution,

As a side effect of continuing the scan, the error reporter may have a hundred additional syntax errors to report, even though they all reference the same mistake. This can explode exponentially. Accordingly, for a final edition of a builder, it is best to limit the number of reported errors before the program calls it quits. For Javac, the limit is a hundred errors, unless the -Xmaxerrs and -Xmaxwarns flags are set to a higher value.

On the completion of syntactic analysis, without error, we have a singular tree with a single root node, most commonly called Program. If syntactic analysis does not complete properly, it is still possible to proceed to contextual analysis, but no further, as erroneous code has an arbitrary interpretation. Computers require determinism.

Contextual Analysis

So, as of contextual analysis, we have a complete abstract syntax tree. The remaining question is, does the correctly formed code also conform to the controls of the language? Is a symbol used before declaration, when the language demands that it not be? Is a variable used outside of its proper scope? Are there duplicate declarations, without any rule for how to handle those declarations? The general rule is that if you cannot establish the analysis rule in BNF, then it is contextual.

After the contextual analyzer has completed its task, given that there are no show-stopping errors, it returns an AST as well. In this case, it is what’s known as a decorated syntax tree. Every user-defined symbol will maintain a node reference to its declaration in the AST, Every expression, for a language concerned about type, is demarcated with its result type.

You may remember, from the introduction to Backus-Naur Form, that it was designed for “context-free grammars”. The term “contextual analysis” more literally means analyzing extensions to the grammar that supersede the domain of BNF.

The best way to think of a proper decorated syntax tree is as an abstract syntax tree, with which any node can be taken at random and read from beginning to end, which forms a complete, definite, and concrete statement.

Procedure of Analysis

Like every class, we must begin with a concrete description of its contract. This includes its responsibilities, and the resources made available to it. Its responsibility, in broad summary, is to find every occurrence of a contextual unknown and link it to its definition. Resources include the code itself as an abstract syntax tree, and a concrete error reporter.

Every analysis tool, the parser included, must be initialized with an error reporter. It is not recommended to make the error reporting functionality ingrained to the class, as it is often best the same error reporter used by parser (your syntax analyzer), and functionally, it has a very different contract—one class, for one responsibility.

We again apply the visitor pattern, much as we do for syntax analysis. Is it possible to use the same visitor pattern for both syntax analysis and context analysis? Technically, yes, but it is discouraged, as syntactical analysis and contextual analysis are two separate contracts. It is possible to feed the incomplete abstract syntax tree to a waiting context analyzer, but this is a tactic more sophisticated than we are ready for at this juncture. I’ll probably return to it in the final section.

To my knowledge, there is not yet a BNF-equivalent for non-context-free grammars that can easily be used for context analysis. This is not to say that there are none; if you insist on following the same pattern that you did for syntax analysis, you may consider Noam Chomsky‘s formal grammar. It uses a lot of unconventional symbols, so you may also consider getting accustomed to using a compose key.

As formal grammars, unless you are working with a set of people who are fully informed on their usage, go well outside of the bounds of this tutorial, I suggest considering the depth of complexity of your contextual grammar before resorting to them. What you will definitely need is a clear and inarguable description of what these rules are, even if it is in plain English.

The context analyzer will also, for most languages, be creating an identification table as it works. Perhaps your target language does not use variables, and has no need for one; I am assuming that it does. It is also possible that your target language does not mind late definitions, as long as there are eventually definitions. It would not be the first. For my algebra solver, I am currently assuming that it does mind; but later on, perhaps I’ll reformat it so that it doesn’t. Subsequent definitions, or even a loosely related concept called “late binding”, It isn’t as hard to do as you might initially think.

Summary Abstractions

We’ll need an abstraction of the core context analyzer. While I chose to call the syntax analyzer “Parser”, a more common term, there is no equivalent that I am aware of for the context analyzer. Thus, we’ll call it “ContextAnalyzer”. I propose a single method in ContextAnalyzer, called check(AST ast). This will initiate the visitor pattern.

Once I complete the code, I’ll highlight it to you in the next lesson.

 

Tags: , , , , , , , , , , , , , ,