Avoid checking for nil when accessing subelement - hash

This is maybe a more cosmetic problem, but I find it really annoying as I always end up with some ugly code. And readability is always important, right?
I want to check if a value exists in a hash within a hash. So what I do is this.
already_exists_data[:data][:user_id]
But that can get me a nullpointer exception if :data is nil and checking :data might give me a nullpointer if already_exists_data is nil. So what I end up with is this:
if already_exists_data && already_exists_data[:data] && already_exists_data[:data][:user_id]
# Do stuff
end
Now that's some nasty looking code. Perhaps I should modify the hash to be an object instead. But I keep bumping in to this problem sometimes and was wondering how you guys confront it.
I'm currently coding in Ruby but I've had this problem with multiple other languages.

If I ask my butler to pick up the box of chocolates on the dining room table in Victoria street 34, I ask him just that. I don't want to say: Go find Victoria Street, and, if you find it, please look for number 34, and if you find it ...
I can do that because he catches his own errors: if he doesn't find the street he will just return empty-handed.
So you should use a try with an empty exception handler. In pseudo-code:
try {chocolates = streets("Victoria")(34)("dining room")("table")}
In languages (like ruby, with some homespun syntactic sugar) where blocks are expressions you might write:
if try {already_exists_data(data)(user_id)}
do_stuff
The language itself can also help: in perl, $streets{Victoria}[34]{dining_room}{table} is undefined when e.g. $streets is. Of course, your butler may come home empty-handed for years before you discover that the address is wrong. The try block solution - and your if .. && .... - have the same drawback: only use them when you really don't care if Victoria Street has a number 34 or not.

Language-agnostic solution: do not use nulls. Ever. Enforce this rule across your projects. If you absolutely have to, wrap them into Either/Optional which adds explicitness. Some languages, such as Scala, have the notion of Optional already built in.
Java-specific solution: if you have to use nulls, annotate method arguments and return values with #Nullable and #Nonnull. Decent IDEs (such as IntelliJ) are capable of analysing your code and highlighting possible null dereferences, if a value is acquired from such a method.

Another possibility is to wrap the hash access with a function call, and do the "dirty" work within the function. Then your code will be something like (pseudo-code syntax):
accessHash(already_exists_data, data, userid)
Note: you can get fancy with accessing nested hashes based on the number of parameters passed to the wrapper function, so it works in a multiple of situations.

Related

How does Js.cast() perform its type checking?

I'm using GWT 2.9 with elemental2-1.0.0-RC1.
The following code throws a ClassCastException at runtime:
DocumentRange documentRange = Js.cast(DomGlobal.document); // Fails
Range range = documentRange.createRange(); // Never reaches here
When I change to use an Js.uncheckedCast() instead, it succeeds:
DocumentRange documentRange = Js.uncheckedCast(DomGlobal.document);
Range range = documentRange.createRange(); // Works
The documentation for Js.uncheckedCast() says:
"You should always prefer regular casting over this (unless you know what you are doing!)."
I don't know why I'm having to use it, so I'm feeling nervous. Can someone explain how Js.cast() performs its type-checking and why I need to use an Js.uncheckedCast() in this instance?
Js.cast() is a way to cheat a bit, and do something that the Java language will not permit, but might actually be legal. Ignoring "how it actually works", the idea is that you can now get past issues where Java would complain, even if it turns out to be legit.
An example could be where you take a java.lang.Double or double and want to treat it as a JsNumber so you can call toPrecision(2) on it. Since java.lang.Double is final, it isn't legal to cast to an unrelated type, but Java doesn't know that in GWT, Double is really just a js Number. So, instead you can perform the cast with Js.cast(). The compiler will insert a runtime type check in there, verifying at runtime that your number is in fact a JS Number instance.
Another example could be trying to extend some native type that elemental2 provides, either to implement a workaround for a missing feature, or to do something browser-specific. Your new class may not extend the existing class - from JS's perspective this is okay, you are just describing the API that you know will exist at runtime. As such, we need to avoid the Java language check of "does this cast even make sense?", and just tell the compiler to try it.
On the other hand, you can "lie" to the compiler with Js.uncheckedCast(). This is used in cases where you are even asking the runtime to skip the check, and just pretend that it will work. This can let you do weird things, like treating Strings as if they were arrays, or solve cross-frame problems. No runtime check will be emitted, so instead you might just get a TypeError if a method/property is missing, instead of a proper ClassCastException.
In elemental2-dom 1.0.0-RC1, there is a class called DocumentRange, but it doesnt really make any sense - it is declared as a class, which means it can be type checked in JS, but the browser spec says that it should be an "interface" (which in JS-land means that it just is a description of a type, rather than something you can typecheck). https://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level2-DocumentRange-method-createRange
This bug is inherited from closure-compiler, which claims that this has a constructor: https://github.com/google/closure-compiler/blob/6a418aa/externs/browser/w3c_range.js#L241-L251
The fix is for closure-compiler to refer to this as an interface, and for a new release of elemental2 to be made so you can use this.
There are two workarounds you can make here. The first is to cheat with Js.uncheckedCast(DomGlobal.document) and say "yes, I know that the Document is not instanceof DocumentRange, but that's because there is no such class as DocumentRange, so just pretend it worked so I can call createRange() on it". This is what you are doing already - it hides the fact there is a bug, but at the end of the day it works.
The "correct" answer is to declare your own DocumentRange, and do a Js.cast() to that instead. This is still gross - you have to keep your new interface around until closure gets fixed, and then elemental2 gets released, and then you have to remember to clean it up.
In this case, I would suggest lying to GWT and using Js.uncheckedCast() - there is only a single method on here, and it is unlikely to change in a meaningful way.

Accessing values in multiple structures with similar names

I'm reasonably new to Matlab, and have been trying to teach myself. I have looked for a similar question, but can't find one that's quite right.
In my workspace I have several structures with similar names. These structures will always start with the same word ('Base'), though the rest of the name will change ('1', '2', '3'), so for example Base1, Base2, Base3... etc. These variables were generated using the data cursor tool in a figure, so contain the fields Target, Position and DataIndex. I am only interested in the value in Base*.Position(1,1). I would like to extract this value from each structure, as many times as there are structures (in one instance there may be 6 structures, another time only 4).
I am considering using the eval function, but it seems to work on exact strings rather than only the first part of a name. Additionally, a lot of documentation seems to advise against using eval.
So far I have:
clearvar except 'Base*'
list_variables=who;
for i=1:length(list_variables)
BaseTS(i) = eval('Base1.Position(1,1)');
end
It's the for loop I'm stuck on, as I don't know how to generalise so it will extract the value .Position(1,1) for each different structure name.
Thanks in advance
Instead of having many structures called Base1, Base2 etc rather put your structure in an array. Then you could rather call Base(1).Position(1,1), Base(2).Position... etc. Your code will be more flexible and manageable this way.
So I suggest when you export using the data cursor, export to a variable called Base_temp and then immediately stick this into the next element of an array:
Base(end+1) = Base_temp
or even:
Position(end+1) = Base_temp.Position(1,1);
Then it's just a case of pressing up and enter after each time you export with the data cursor.
What you have read about avioding eval is correct, it's very rare (if ever) that eval is a good idea. It makes your code hard to read and very hard to debug. But since you're learning, this is how you could fix your loop. (But don't do this way, seriously don't, use arrays rather):
for i=1:length(list_variables)
BaseTS(i) = eval(['Base', num2str(i), '.Position(1,1)']);
end
in other words use string concatenation to build up your string and use the looping variable (i) to get the different numbers. You'll need num2str to convert fromthe number to the string. But don't do it this way. This is a bad way.
Dan's suggestion about avoiding eval is very valid. But if you decide to keep on the structures you have in your workspace, here's something without loops, but again cellfun seems to use loops internally. So, I guess this could be an alternative solution, with the not-so-popular eval -
list1 = who('Base*')
list2 = cellstr(strcat('BaseTS(',num2str([1:numel(list1)]'),')='));%%//'
ev1 = strcat(list2,list1,'.Position(1,1)');%%//'
cellfun(#evalc,ev1,'uni',0)

Can I use Eclipse templates to insert methods and also call them?

I'm doing some competitions on a website called topcoder.com where the objective is to solve algorithmic problems. I'm using Eclipse for this purpose, and I code in Java, it would be help me to have some predefined templates or macros that I can use for common coding tasks. For example I would like to write methods to be able to find the max value in and int[] array, or the longest sequence in an int[] array, and so on (there should be quite many of these). Note I can't write these methods as libraries because as part of the competition I need to submit everything in one file.
Therefore ideally, I would like to have some shortcut available to generate code both as a method and as a calling statement at once. Any ideas if this is possible?
Sure you can - I think that's a nifty way to auto-insert boilerplate or helper code. To the point of commenters, you probably want to group the code as a helper class, but the general idea sounds good to me:
You can see it listed in your available templates:
Then as you code your solution, you can Control+Space, type the first few characters of the name you gave your template, and you can preview it:
And then you can insert it. Be sure if you use a class structure to position it as an inner class:
Lastly - if you want to have a template inserts a call to method from a template, I think you would just use two templates. One like shown above (to print the helper code) and another that might look like this, which calls a util method and drops the cursor after it (or between the parentheses if you'd like, etc):
MyUtils.myUtilMethod1();${cursor}

Play route syntax for ignoring a part of slug

What we want is basically this:
/foo/* controllers.FooController.foo
However this doesn't work.
We have found the following workaround:
/foo/*ignore controllers.FooController.foo(ignore)
But this makes the code of the method controllers.FooController.foo slightly ugly. Is there a better way to do this?
Looking at the code over here, the router isn't able to deal with the "slug" part without specifying an identifier... the parser combinator doesn't declare it as optional, and the map (^^) is clearly using it as is.
It could be a good feature request if it wouldn't induce other problems where a pattern will hide all other routes because it's defined higher in the file (or even worst, included).
And it looks like it has been done on purpose if we look here, we can figure out that dynamic parameter cannot be assigned a default value -- indeed, in this case we'll fall in the case I've just mentioned :-/.
My first advice would be to tell you to use ignore as an Option[String] and the action definition to set it as None (rather than an empty String because it's more expressive).
My second would be to incite you to wonder if such case is really relevant, because it's error prone and could hide further problems

lua - capturing variable assignments

Ruby has this very interesting functionality in which when you create a class with 'Class.new' and assign it to a constant (uppercase), the language "magically" sets up the name of the class so it matches the constant.
# This is ruby code
MyRubyClass = Class.new(SuperClass)
puts MyRubyClass.name # "MyRubyClass"
It seems ruby "captures" the assignment and inserts sets the name on the anonymous class.
I'd like to know if there's a way to do something similar in Lua.
I've implemented my own class system, but for it to work I've got to specify the same name twice:
-- This is Lua code
MyLuaClass = class('MyLuaClass', SuperClass)
print(MyLuaClass.name) -- MyLuaClass
I'd like to get rid of that 'MyLuaClass' string. Is there any way to do this in Lua?
When assigning to global variables you can set a __newindex metamethod for the table of globals to catch assignments of class variables and do whatever is needed.
You can eliminate one of the mentions of MyLuaClass...
> function class(name,superclass) _G[name] = {superclass=superclass} end
> class('MyLuaClass',33)
> =MyLuaClass
table: 0x10010b900
> =MyLuaClass.superclass
33
>
Not really. Lua is not an object-orientated language. It can behave like one sometimes. But far from every time. Classes are not special values in Lua. A table has the value you put in it, no more. The best you can do is manually set the key in _G from the class function and eliminate having to take the return value.
I guess that if it REALLY, REALLY bothers you, you could use debug.traceback(), get a stack trace, find the calling file, and parse it to find the variable name. Then set that. But that's more than a little overkill.
With respect at least to Lua 5.2: You can capture assignments to A) the global table of a Lua State, as mentioned in a previous reply, and also B) to any other Lua Object whose __index and __newindex metamethods have been substituted (by replacing the metatable), this I can confirm as I'm currently using both these techniques to hook and redirect assignments made by Lua scripts to external C/C++ resource management.
There is a gotcha with regards to reading them back though, the trick is to NOT let the values be set in a Lua State.
As soon as they exist there, your hooks will fail to be called, so if you want to go down this path, you need to capture ALL get/set attempts, and NEVER store the values in a Lua State.