Is nil coerced to null when calling Java from JRuby? - jruby

https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby indicates that the Java null object is coerced to Ruby's nil, but it doesn't mention if coercion occurs in the other direction (e.g. when an argument is passed to a Java method). Does it? If not, how can you create null from JRuby?
I did note that nil.to_java returns nil.

To clarify, the answer to your question is yes.
To see this for yourself, just try passing nil to any Java method and see what happens, it's pretty easy to do:
> java.lang.System.out.println(nil)
null
=> nil
Or
> java.lang.String.new(nil)
Java::JavaLang::NullPointerException:

Try
JavaUtil.primitive_to_java(nil)

Related

Is there any way to directly call function passed as an optional parameter while also be protected from null value error, in Flutter/Dart?

From this answer I understand that I can check for null value before calling a function passed as optional parameter:
myFunction ({ Function onFocusChange }) {
if(onFocusChange != null) {
onFocusChange(boolValue)
}
}
I also understand that there's an optionality concept like Swift and Kotlin in Flutter, using "?" operator, though they all have their own quirks.
What I'm asking is if there's any way to call the optional function and silently fail if it's null, like in Swift:
onFocusChange?(boolValue);
I tried to add the question mark on Flutter, and it immediately tries to evaluate the "onFocusChange" as boolean (ternary operator).
I wondered the same thing. I tried the suggested onFocusChange??(boolValue);, but that didn't work for me. (Maybe due to a version difference?) What I ended up doing was (onFocusChange ?? () {})(); and that worked for me to keep it all on one line. Still doesn't have the simplicity I was hoping for, but I prefer it aesthetically over the multi-line code checking for null. Don't know if dart is smart enough to not actually call the empty function when onFocusChange is null, or how much of a performance hit it might be, if any, if this sort of thing were scattered throughout one's code.

Throwing a NPE at the start of method for error checking

So im preparing for interviews and in one of Gayle Laakmans career Cup videos a guy is writing a simple method that takes in an array and does something with it. She mentions his lack of error checking so he adds in this line like so:
public int max(int[] array) {
if (array == null)
throw new NullPointerException();
//method body
}
Is it correct to manually throw a NPE exception like this, this exception will get thrown anyway in the method body as it will use the array reference at some point.
A possible advantage to this i can see is that it separates input invalidation from the method logic being invalid and somehow creating a null reference. Otherwise it is a little confusing and maybe IllegalArgumentException would work better?
There's nothing wrong with throwing NullPointerException as soon as you enter the method instead of waiting to detect it after some processing has already been done. If the method is going to fail, it might as well fail fast.
Joshua Bloch's Effective Java recommends throwing NullPointerException over IllegalArgumentException in this situation (Item 60: Favor the use of standard exceptions).
If a caller passes null in some parameter for which null values are prohibited, convention dictates that NullPointerException be thrown rather than IllegalArgumentException.
IllegalArgumentException should be thrown when an illegal non-null value is passed in.
Also have a look at java's own utility class java.util.Objects:
public static <T> T requireNonNull(T obj,
String message)
Checks that the specified object reference is not null and throws a customized NullPointerException if it is. This method is designed primarily for doing parameter validation in methods and constructors with multiple parameters, as demonstrated below:
public Foo(Bar bar, Baz baz) {
this.bar = Objects.requireNonNull(bar, "bar must not be null");
this.baz = Objects.requireNonNull(baz, "baz must not be null");
}
Type Parameters:
T - the type of the reference
Parameters:
obj - the object reference to check for nullity
message - detail message to be used in the event that a NullPointerException is thrown
Returns:
obj if not null
Throws:
NullPointerException - if obj is null
from https://docs.oracle.com/javase/7/docs/api/java/util/Objects.html
Conclusion
Whether or not you use this utility class is another question, but it definitely shows, that the team behind the Java language intended to use NullPointerException for these purposes.

When is handling a null pointer/reference exception preferred over doing a null check?

I have an odd question that I have always thought about, but could never see a practical use for. I'm looking to see if there would be enough justification for this.
When is handling a null pointer/reference exception preferred over doing a null check? If at all.
This applies to any language that has to deal with null pointers/references which has exception handling features.
My usual response to this would be to perform a null check before doing anything with the pointer/reference. If non-null, continue like normal and use it. If null, handle the error or raise it.
i.e., (in C#)
string str = null;
if (str == null)
{
// error!
}
else
{
// do stuff
int length = str.Length;
// ...
}
However if we were not to do the check and just blindly use it, an exception would be raised.
string str = null;
int length = str.Length; // oops, NullReferenceException
// ...
Being an exception, we could certainly catch it so nothing is stopping us from doing this (or is there?):
string str = null;
try
{
int length = str.Length; // oops, NullReferenceException
// ...
}
catch (NullReferenceException ex)
{
// but that's ok, we can handle it now
}
Now I admit, it's not the cleanest code, but it's no less working code and I wouldn't do this normally. But is there a design pattern or something where doing this is useful? Perhaps more useful than doing the straight up, null check beforehand.
The only cases where I can imagine this might be useful is in a multi-threaded environment where an unprotected shared variable gets set to null too soon. But how often does that happen? Good code that protects the variables wouldn't have that problem. Or possibly if one was writing a debugger and wanted the exception to be thrown explicitly only to wrap it or whatnot. Maybe an unseen performance benefit or removes the need for other things in the code?
I might have answered some of my questions there but is there any other use to doing this? I'm not looking for, "do this just because we can" kinds of examples or just poorly written code, but practical uses for it. Though I'll be ok with, "there's no practical use for it, do the check."
The problem is that all null pointer exceptions look alike. Any accounting that could be added to indicate which name tripped the exception can't be any more efficient than just checking for null in the first place.
If you expect the value to not be null, then there is no point in doing any checks. But when accepting arguments, for example, it makes sense to test the arguments that you require to be non-null and throw ArgumentNullExceptions as appropriate.
This is preferred for two reasons:
Typically you would use the one-string form of the ArgumentNullException constructor, passing in the argument name. This gives very useful information during debugging, as now the person coding knows which argument was null. If your source is not available to them (or if the exception trace was submitted by an end user with no debug symbols installed) it may otherwise be impossible to tell what actually happened. With other exception types you could also specify which variable was null, and this can be very helpful information.
Catching a null dereference is one of the most expensive operations that the CLR can perform, and this could have a severe performance impact if your code is throwing a lot of NullReferenceExceptions. Testing for nullity and doing something else about it (even throwing an exception!) is a cheaper operation. (A similar principle is that if you declare a catch block with the explicit intent of catching NREs, you are doing something wrong somewhere else and you should fix it there instead of using try/catch. Catching NREs should never be an integral part of any algorithm.)
That being said, don't litter your code with null tests in places you don't ever expect null values. But if there is a chance a reference variable might be null (for example if the reference is supplied by external code) then you should always test.
I've been programming Java for more than 10 years, and I can't remember a single time I've explicitly tried to catch a null pointer exception.
Either the variable is expected to be null sometimes (for example an optional attribute of an object), in which case I need to test for null (obj.attr != null), or I expect the variable to be not null at all times (in which case a null indicates a bug elsewhere in the code). If I'm writing a method (say isUpperCase) whose argument (String s) is null, I explicitly test for null and then throw an IllegalArgumentException.
What I never ever do, is silently recover from a null. If a method should return the number of upper case characters in a string and the passed argument was null, I would never "hide" it by silently return 0 and thus masking a potential bug.
Personnally (doing C++), unless there is a STRONG contract that assures me that my pointers are not nullptr, I always test them, and return error, or silently return if this is allowed.
In Objective-C you can safely do anything with nil you can do with a non-nil and the nil ends up being a noop. This turns out to be surprisingly convenient. A lot less boilerplate null checking, and exceptions are reserved for truly exceptional circumstances. Or would that be considered sloppy coding?

How should a constructor act when given invalid parameters?

If a class has a constructor which takes some value object as parameter and relies on this to do its initialization. How should it react if this object is null?
class SomeClass
{
private SomeData _data;
public SomeClass(SomeValueObject obj)
{
_data = obj.Data;
}
}
This is one example, but in general: How should a constructor act if it is given invalid parameters and therefore cannot do the construction properly? Should it just return without doing any initialization? Set the parameters to some default values? Throw an exception? Something else?
I'm sure the answer to this is "It depends", but are there any best practices etc?
A programmer should be able to assume an object was successfully created, unless an exception is raised. The type of exception depends on the argument, but should nonetheless be unchecked. The last thing you want is the constructor fail to build a valid object and not tell the caller about it.
I think using default values in a constructor is a dangerous habit.
A lot depends on your business logic. If your business logic requires SomeValueObject to be not null, meaning SomeClass could not be instantiated without SomeValueObject then the constructor should definitely throw an Exception, probably IllegalArgumentException.
Seems like this is Java, but in C++ it should definitively throw ( a std::invalid_argument even ).
See C++ FAQ Lite 17.2.
I guess that for Java it's exactly the same.
In the rare cases where throwing exceptions presents a too big of a overhead, you should return, and set a flag in the object that it didn't construct properly. Afterwards check a isValid() member function.
Throw a null argument exception.
If field is critical it should cast an exception to indicate that object shouldnt be used. If its not critical you can assign default values.
If an object can have invalid default values, then it should initialize to the default values and wait for initialization. E.g., foo.set_values(...). In this case, there should be a query of is_ready() or is_valid() to allow checking before use.
If an object can absolutely not be in an invalid data-state, then it should throw an exception.
Both of these cases are things I've encounted.

flex3 type casting

Does anyone know the real difference between the two ways of type casting in Flex 3?
var myObject1:MyObject = variable as MyObject;
var myObject2:MyObject = MyObject(variable);
I prefer to use the second method because it will throw an Error when type cast fails, whereas the first method will just return null. But are there any other differences? Perhaps any advantages to using the first method?
The second type of casting has different behaviour for top level(http://livedocs.adobe.com/flex/2/langref/) types, e.g. Array(obj) does not cast in the straightforward way you describe; it creates a new Array if possible from obj, even if obj is an Array.
I'm sure the times this would cause unexpected behaviour would be rare but I always use "as" for this reason. It means if I do
int(str)
I know it's a cast in the "attempt to convert" sense of the word not in the "I promise it is" sense.
ref: got some confirmation on this from http://raghuonflex.wordpress.com/2007/07/27/casting-vs-the-as-operator/
The as method returns null if cast fails.
The () method throws and error if the cast fails.
If the value of variable is not compatible with MyObject, myObject1 will contain null and you will be surprised by a null pointer error (1009 : cannot access a property or method of a null object reference.) somewhere later in the program when you try to access it. Where as if you are casting using the MyObject(variable) syntax, you will get a type coercion error (1034 : Type Coercion failed: cannot convert _ to _) at the same line itself - which is more helpful than getting a 1009 somewhere later and wondering what went wrong.
I think I read somewhere on this site that as is slighty faster than (), but I can't find the question again.
Beside that this question have been asked many times, you will find an more in-depth answer here.
I recently discovered the very useful [] tag when searching on StackOverflow, it allows to only search in questions tagged with the specified tag(s). So you could do a search like [actionscript-3] as vs cast. There are more search tips here: https://stackoverflow.com/search.
And no; the irony in that I can not find the question about performance and write about how to search is not lost on me ;)
I think as returns back the base class and not null when the casting fails and () throws an error.