Uncategorized

Christian Neumanns considers that null should not be hated, as elaborated in his article Why We Should Love null. Essentially he concludes that the compiler should treat nullable fields as though they are option/maybe types, and should prevent use of the values before they have been checked for nullity. Some notes follow, as far as I maintained interest.

Therefore some developers try to avoid null. For example, they use 0 instead of null in case of a number value, or their functions return an empty list or an empty string instead of null.

In some cases an empty string is a reasonable substitute for no value. I am thinking particularly of display in a user interface, where showing no characters may be the right thing to do when there is no value. 0 is far more dubious. Some developers doing the wrong thing is more a comment on those developers than it is on the validity of using null. I would not be at all surprised to hear those same developers generating plenty of null pointer errors back in their null-using days.

In real life, we are all used to the notion of ‘nothing’ appearing in thousands of different ways.

This is a total red herring. The problem with null has nothing to do with whether it is reasonable to have a representation of the concept of “nothing”. The problem is when developers fail to consider what their code will do if it gets “nothing”. I suppose this is because we write code to take particular types of inputs and manipulate them, and nothing is not a type of something. For example if I ask someone to hand me a pencil, I am not expecting them to make the motion of handing me a pencil with nothing in their hand – that would be nonsensical.

More than an astonishing 99.999% of the universe is nothing – just empty space.

Make that a very large red herring.

Instead of using a non-null value to represent ‘no data available’ it is (in most cases) much better to use null.

Yes, we increase the risk for null pointer errors. But we decrease the risk for outcomes that are worse, such as delivering wrong results without any error message and other unacceptable or catastrophic situations – for example letting users buy houses for free.

This is true, but also a moot point. Why accept either possibility?

‘unhappy’ is better than ‘very unhappy’.

And both are worse than ‘happy’. This attitude looks how the result of years of doing the best that Java will allow.

Hence, we should embrace null and make it our friend and … love it!

Odd to make such a conclusion before looking at the more relevant alternatives…

Don’t use the Null Object pattern just to avoid null pointer errors.

This, and the reasoning behind it, I agree with. Null is problematic because it can sneak in where an actual something is expected (in many languages). Introducing something else that can do the same is no solution at all. They may have their place though. Again I am thinking of a user interface that could reasonably have a blank space when there is nothing to display – if there is an object that is just giving text to display, a null object that gives empty strings might make for more readable UI code than putting all the conditional display logic in the UI code itself.

If we call get() without first checking the presence of data with isPresent() then we get a NoSuchElementException if there is no value present.

It is a shame that Java is not expressive enough to give a compiler error for this. As a best-effort approximation, a boolean field that is false, and set to true when isPresent() is called would help to catch many of these cases. It would still be a runtime error, but the error would happen any time the code runs so the developer is far more likely to see it before it can cause problems for a user. A major limitation is that as soon as the option container has been checked once it will no longer throw an error, even if it is passed around to different scopes in which its contents have not been confirmed as non-null.

If a method is declared to return an Optional, nothing prevents the programmer who implements the method from (involuntarily) returning null instead of returning a non-null Optional.

This is a weakness of Java, rather than of the Optional pattern.

If we accidentally construct an Optional by calling method of() with null as input, we get a NullPointerException.

This is an advantage over plain null, since it moves the error closer to the origin of the null value. The problem here only exists because of the use of null in the first place. In an ideal world this is something that only I/O drivers would have to deal with. Java is a long way from any kind of ideal world.

The compiler cannot force programmers to use Optional in their own methods. It is up to the programmer to decide whether he/she returns an Optional or simply sticks to returning null in case of no data.

Unless the programmer has heard of static analysis, that is…

Existing standard Java libraries cannot be retrofitted to use Optional because this would break backwards compatibility.

They cannot be retrofitted, but they can be wrapped in facades. A disciplined developer could approach some semblance of sanity in their own code that way.

In a podcast recently, probably NodeUP, there was some discussion about how much more readable console output can be when it has a bit of colour. I heartily agree – distinctive colours allow my visual firmware to very reliably distinguishing different blocks of text; more reliably than layout alone.

By “visual firmware” I am talking about the parts of the brain involved in the pre-attentive process of visual scene segmentation.

I care about effective pre-attentive processing because it means my cerebral cortex gets a far better indexed set of visual data, so I can avoid some of the conscious cognitive load of manually distinguishing the different things I am looking at. Facilitating effective pre-attentive processing is a bit like adding a GPU to a computer: graphics processing can happen separately from the CPU, leaving more clock cycles for general processing.

So, when I was reminded today that some functionality is being added to our command line client, I immediately set out to figure out how to get nice command-line colours across all the platforms the client can run on. ANSI escape codes do not work on a standard Windows console, so I was pretty sure something more would be needed. This looks like the solution: Jansi, a library that allows Java console output to use ANSI escape codes in Windows as well.

I recently read Semver in node.js and npm, which aims to shed some light on the oft misunderstood operators ~ and ^ in semver. The very short version is that:

  • ~ with just a major version will match any version with that major version.
  • ~ with a major and minor version will match any patch version of the minor version.
  • ^ will always match versions between the specified version and the next major version.

So ~1 would match 1.6.2, but ~1.4 would not; ^1 would match 1.6.2, and ^1.4 would too.

A concise overview of semver can be found at semver ftw. Plenty more detail on semver in node can be found on node-semver on github. If you look closely, you’ll notice that for the ^ and ~ operators, versions below 1.0.0 are treated differently: the first non-zero component is considered to potentially introduce breaking changes. This means that ^0.2.3 would not match version 0.3.0. Some consider this a bad idea, and I would have to agree since it complicates the system and reduces the chance that developers will use it properly. The problems with major version 0 as a special case are discussed in Kill the special pre-1.0.0 meaning for ^ & ~ and 1.0.0 is not just a number

If semver seems overly complicated, there is always slimver, which describes a simplified subset of semver. Slimver excludes prerelease and build metadata and limits version numbers to 65535, which allows easy encoding as a single numeric value for easy comparison. It also simplifies the range expressions for ~ and ^ so that their meaning is identical and versions in the 0.x.x and 0.0.x range are treated the same way as others, making it far more likely that developers will get what they are expecting when using either operator.

Codeacademy

  • Getting Started with Programming: 79%

Additional references:

  • Window.confirmWindow.confirm(message) shows a modal dialog with the message and OK and Cancel buttons. Returns a boolean depending what the user clicks.
  • Window.promptWindow.prompt(message, [default]) shows a prompt with the message that takes text input, with default text in the text box.
  • String

Console.log

Console.log | MDN

The simplest form of console.log takes a single object or string, but it can do a lot more:

  • If given more than 1 object, it will convert them all to strings, concatenate the strings, and print the result.
  • If given a string with substitution strings, it will replace the substitutions with the subsequent arguments.

Details about substitution strings are at Console: Outputting text to the console. It notes the following substitutions:

  • %o – hyperlink to JS object, clicking opens inspector
  • %d or %i – display an integer
  • %s – display a string
  • %f – display floating point value
  • %c – apply CSS styles. The string argument is treated as a set of CSS properties to apply. I found that specifying an empty string for a subsequent %c argument can reset the style to the default.

String.prototype.substring/slice

substring() has some undesirable behaviour, so it is far more common to see slice() used in practice. Basically, substring() does odd things when you give it negative numbers and in a few other cases. There is a nice overview in an answer to “What is the difference between String.slice and String.substring?” on StackOverflow.

I was browsing through Node.js® Reactions and came across Setting highWaterMark way too low: (trigger warning: someone does something silly and looks like they got a bit bruised in the head/knees/shins areas).

I found it immediately hilarious, then realized there was something called highWaterMark of which I was utterly ignorant! Seeking enlightenment, I set out into the open Internet. I did not have far to search, and soon found myself alighting gently on A New Streaming API for Node v0.10, and was instantly swept up in reading. I had not read long when my eyes fell upon a most wonderful sentiment:

“Being better than the next guy isn’t enough; we have to be the best imaginable.”

I had to stop, smile, and let that sink in for a while; highWaterMark all but forgotten*. This is a world I am happy to be a part of.


* I did later find highWaterMark; it is an option for streams that sets the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.

In git, it is possible in the default configuration for anyone with commit permission to really mess things up. Someone can do a force push and wipe out everyone else’s commits.

Stop all force pushes

The bare authoritative repository can be configured to deny non-fast-forward commits such as this even when forced. An overview of this is in Git Configuration in the git book. The main settings are:

git config --system receive.denyNonFastForwards true

git config --system receive.denyDeletes true

Note that --system here will write to the /etc/gitconfig file.

Stop some force pushes

For individual branches, there is a pre-receive hook available here on Github.

I have also heard that it is possible to prevent specific users from force pushing using a pre-receive hook on the server.

Note that it is not possible to add the above on Github – the workaround is to let only a limited number of people commit, and have everyone else use pull requests.

Maybe stop some force pushes

Another option is to add a pre-push hook to run on the client, which can be used for projects on Github. This is not strictly enforceable, since a user could remove it and still do a forced push, but it can prevent accidental pushing to master, and would be a decent safety net for people new to git to make sure they can’t accidentally break something too much. Some good-looking instructions for setting it up are in the blog post Do not allow force push to master.

Fast-Forward Only Pull Requests on GitHub

Just email GitHub and ask for them, according to @domenic:

Today I made a little quine in JavaScript – someone mentioned quines and I realized I had never written one, so I wrote one. A quine is a program that can output its own source code (without taking any input).

My first attempt was a bit bloated, but got the job done:

var program = "var f=function f(){return 'var f='+f+';f(f)'; };f(f)"

I can verify that it works by evaluating the program and comparing the evaluated output to the original program:

program === eval(program)

I stripped it down a bit to end up with something I’m happier with, by making the function non-anonymous so that I could refer to it without having to bind it to a variable. Once that was done, I could make it an IIFE rather than adding a separate statement to run the function:

var program = (function f(){return '('+f+')()'; })()