My most common code review suggestions
hackernoon.com
hackernoon.com
I think we should keep in mind this is a type added for the JDK code foremost, and use it in similar use cases, and not see it as a general replacement for nullable values.
It's still entirely possible to get a nil from Objective-C while the API is declared as nonnullable, this even happened to me with Apple's own API's if abused to a certain limit.
It is a way to introduce the benefits (as long as the library is developed properly) of non-nullable types without sacrificing retro compatibility.
Edit: I remember a bug in earlier version of Swift Cocoa binding where getting calendar events without titles would hang without possibility of recourse because of this problems.
In terms of backwards compatibility the language teams position, IIRC, was that in the cases where you are intentionally using null it's quite easy to find and flag flag the nullable variable, but in all other cases the unexpected nullability can responsibly be removed from apps, making then-unnecessary null checks superfluous.
It's a bold move, but if it works at scale Java might be able to pull the tablecloth out from under the plates too...
Think about it like this: in Java - all class references were Option<Class> by default - and what was truly lacking was the possibility of having a non-optional reference[1]. They could've treated transparently all old-code[2] references as Option<ClassName>, and just given you the possibility of having non-optional reference in the new code (that meant that you can't pass objects with non-optional references to the legacy libraries, but it's a pain that could've gone away pretty quickly as libraries got recompiled to the new java versions)
[1] Oracle's interpretation was the other way around: "Java lacks the Option type, let's add it". I argue they got it wrong - Java always had the Option type, it's just that it was implicit; and since Java was lacking the non-optional types, you couldn't do anything useful with the Option, other than check for "None" (i.e. null).
[2] By "old code" I mean "old compiled code". You keep the binary compatibility - but indeed, you would need to drop the source-level compatibility, since compiling old code with the new compiler would not have worked. But, again, that would be fixable with a "legacy syntax" compiler flag, that would produce old-style binaries from old-style source code.
assert foo != null : "foo must not be null - remember to wrap optional data in Optional<T>"
Just make sure to run your program (or at least the tests) with the JVM flag "-ea"If asserts are disabled, then the null pointer checks are still inserted by the JVM.
The problem with optionals - as Sonar will complain about - is that people will call `.get()` on an Optional without first checking `.isPresent()` for example.
Lots of things in the language that allow you to shoot yourself in the foot that other languages have solved.
Also, isn't there a static code analysis tool that checks at compile-time that reference variables annotated as @non_nullable can never be null?
Imagine I want to query a database of tagged articles. Let's say I want to get articles with an exact set of tags.
Passing this method [A, B] will give me articles with tags A and B, passing this method [] will give me articles with no tags. Not specifying the query parameter at all will result in no parameter. I could use a boolean value to keep track of that or just use an optional.
If your contract says you return a Foo, you could be returning a null. If you change that to Optional<Foo> you could still be returning a null.
It's not what Optionals are for. They are just widely misunderstood and abused.
Optional is really for functional code, not for "eliminating NPEs," because it doesn't do that - in fact it means strictly speaking you have to do additional checking.
The real purpose of optional is for allowing me to do things like `foo.first().orElseGet(other)`. `first` has to return an Optional rather than a null or it will blow up.
If you are doing `Optional.isPresent()` as a straight-up replacement for null checks then you are doing it wrong. If you want to avoid returning nulls and doing null checks, use polymorphic null objects.
The section titles are kind of generic as they convey the aspects to consider: Code Gotchas, Documentation, Code Style, Unittests.
Point 3: interesting and useful, I had never thought about it. I use varargs syntax quite often by the way, letting the caller pick what he wants to do with my code.
I tried things like TypeScript and Flow, but I didn't get it working nicely with JSDoc or ESDoc. I want type-checking & generated docs, and I don't wanna define both twice.
In general I lack the Smalltalk ideal of being able to subclass any type, like 'Int', call it something new and attach behaviour to it, while preserving API & DB compatibility.
Type aliasing in F#, ie `type Customer = int`, or discriminated unions with the same info, like `type CustomerId = CustomerId of int`, are wonderfully useful in that regard.
I agree it's the way to go, though. My typical tiny type in Python just has preconditions on string content.
Mile distance1 = 12
Kilometer distance2 = Kilometer(distance1) // Does a conversion while constructing
void someFuncThatWantsKilometers(Kilometer distance) { }
someFuncThatWantsKilometers(distance1) // Does not compile
someFuncThatWantsKilometers(distance2) // Compiles
Even better you can do this: Hour time = 1
Kilometer distance = 12
Kilometer/Hour speed = time/distance // Doesn't compile
Kilometer/Hour speed = distance/time // Compiles! Even gives you the 'new' type for free!
You could use it for everything where primitives have a deeper meaning than their pure numeric value. Database ID's, money or other financial or scientific values. Impossible to swap X and Y coordinates unless you implicitly do so.You can eliminate so many confusing bugs just by having better typed primitives.
--- disclaimer: ---
This is not exactly how it works in F# but the languages are too different to really compare
Unit of Measure in practice: [<Measure>] type cm [<Measure>] type ml = cm^3 // a millilitre is 1 cm cubed
To the point in the article about using types to convey meaning, as I commented elsewhere, you want F#s awesome type aliasing and single-case discriminated unions :)
Type aliasing:
type CustomerId = int // We can send now use IDs interchangeably with int, use CustomerId in method signatures, and expand the type with methods
Single Case Discriminated Unions: type CustomerId = CustomerId of int
let id = CustomerId (3) // Have to use a specific constructor
let myFunction (CustomerId(id)) = // DUs can be unpacked in parameters
printfn "%i" id // this function only accepts CustomerId'sA SandwichCount should not be confused with a BurgerCount!
But I will also say this is possible in other languages to some degree with some level of boiler plate.
For example, in java I can do similar. Instead of using float, wrap that in a class called kilometer and use that instead. Then define the api around it as needed (equals, compare, value, etc). Even this small thing I think is really important, and is helpful instead of using primitives or strings. Make email instead of string, dollar instead of just big decimal, etc.
Technical nitpicking: It's best to avoid using the terms "strong" and "weak" when referring to type systems, since they don't have clear, agreed upon definitions.
Some would say that Java is not a strongly typed language since its type system isn't sound.
Going with the example of a sound type system, a language could have a sound type system that does the actual checking at runtime.
It doesn't make any sense to talk about soundness for dynamic languages, because there's no static semantics to relate to the dynamic semantics.
[1] https://www.youtube.com/watch?v=igFRvriDMqk (GOTO 2015 • Secure Coding Patterns • Andreas Hallberg)
As pointed out elsewhere here, the author has Optional wrong.
This is so stereotypical of the object-oriented mindset and Java programmers are the worst offenders. If I had a programmer under me who came up with this, I would fire them on the spot and enjoy every nanosecond while doing it.
The “punt and throw an exception” mentality goes directly against the art of UNIX programming rule of repair: repair what you can, but if you must fail, do it as soon and as noisily as possible. What this means in practice is that in 99% of the cases, the programmer could have written the code to either deal with the problem or had enough information from disparate sources to reconstruct the missing data but they chose to punt and throw an exception instead. To me as a programmer, that is infuriating!
Which leads me to point 2.: the exception paradigm requires the intimate knowledge of the software to interpret, as it normally vomits a call stack trace. But in production, to the user of the application or the poor system administrator, or even to the programmer who isn’t intimately familiar with the software, that information is nothing but retching vomit, often with no clues as to what went wrong where! And did you notice how the punter is never around to decipher the gobledygook when this happens? Also infuriating.
Stop throwing exceptions, get off of your lazy asses and when you can reconstruct the missing information, or detect and correct damaged information, or diagnose the problem, do so and give back meaningful diagnostic telemetry on stderr, but don’t just punt and screw the user or the sysadmin over.
If you’re programming to put the bread on the table, it’s not someone else job to make it work; it’s yours. That’s why you get paid, to make the computer compute. No excuses.
So basically, spam on stderr and abort(). This is not exactly better than exceptions.
> the exception paradigm requires the intimate knowledge of the software to interpret, as it normally vomits a call stack trace. But in production, to the user of the application or the poor system administrator, or even to the programmer who isn’t intimately familiar with the software, that information is nothing but retching vomit, often with no clues as to what went wrong where!
Again, it's printing stuff to stderr, or having the exception system print stuff plus stack trace to stderr. The latter is strictly better than the former. It gives you more clue than printing what would otherwise be an exception message to stderr and aborting on the spot.
And using exceptions do not preclude you from being able to "repair what you can". In fact, it can help it.
I don't like exception abuse either, but it's still better than the C way.