How to check if a value is literally null - c++

I have an JSON object like this:
{ "foo": null }
How do I check if the value of foo is a literal null. I found the function JsonObject::isNull() but that apparently is for
testing whether the JsonObject points to an object or not
That is not what I want my code to check, but I couldn't find a solution to this problem.

According to the doc: https://arduinojson.org/v6/issues/cannot-use-null/
If c++11 is available (which has nullptr), you can check if the json object's value is null or not like so:
if (!doc["foo"]) {}
or
if (doc["foo"] == nullptr) {}
If c++11 is not available, you can use the isNull() method:
if (doc["foo"].isNull()) {}

Related

Kotlin: How to work with List casts: Unchecked Cast: kotlin.collections.List<Kotlin.Any?> to kotlin.colletions.List<Waypoint>

I want to write a function that returns every item in a List that is not the first or the last item (a via point). The function gets a generic List<*> as input. A result should only be returned if the elements of the list are of the type Waypoint:
fun getViaPoints(list: List<*>): List<Waypoint>? {
list.forEach { if(it !is Waypoint ) return null }
val waypointList = list as? List<Waypoint> ?: return null
return waypointList.filter{ waypointList.indexOf(it) != 0 && waypointList.indexOf(it) != waypointList.lastIndex}
}
When casting the List<*> to List<Waypoint>, I get the warning:
Unchecked Cast: kotlin.collections.List
to kotlin.colletions.List
I can't figure out a way to implement it otherwise. What's the right way to implement this function without this warning?
In Kotlin, there's no way to check the generic parameters at runtime in general case (like just checking the items of a List<T>, which is only a special case), so casting a generic type to another with different generic parameters will raise a warning unless the cast lies within variance bounds.
There are different solutions, however:
You have checked the type and you are quite sure that the cast is safe. Given that, you can suppress the warning with #Suppress("UNCHECKED_CAST").
#Suppress("UNCHECKED_CAST")
val waypointList = list as? List<Waypoint> ?: return null
Use .filterIsInstance<T>() function, which checks the item types and returns a list with the items of the passed type:
val waypointList: List<Waypoint> = list.filterIsInstance<Waypoint>()
if (waypointList.size != list.size)
return null
or the same in one statement:
val waypointList = list.filterIsInstance<Waypoint>()
.apply { if (size != list.size) return null }
This will create a new list of the desired type (thus avoiding unchecked cast inside), introducing a little overhead, but in the same time it saves you from iterating through the list and checking the types (in list.foreach { ... } line), so it won't be noticeable.
Write a utility function that checks the type and returns the same list if the type is correct, thus encapsulating the cast (still unchecked from the compiler's point of view) inside it:
#Suppress("UNCHECKED_CAST")
inline fun <reified T : Any> List<*>.checkItemsAre() =
if (all { it is T })
this as List<T>
else null
With the usage:
val waypointList = list.checkItemsAre<Waypoint>() ?: return null
To improve #hotkey's answer here's my solution:
val waypointList = list.filterIsInstance<Waypoint>().takeIf { it.size == list.size }
This gives you the List<Waypoint> if all the items can be casted, null otherwise.
In case of generic classes casts cannot be checked because type information is erased in runtime. But you check that all objects in the list are Waypoints so you can just suppress the warning with #Suppress("UNCHECKED_CAST").
To avoid such warnings you have to pass a List of objects convertible to Waypoint. When you're using * but trying to access this list as a typed list you'll always need a cast and this cast will be unchecked.
I made a little variation to #hotkey answer when used to check Serializable to List objects :
#Suppress("UNCHECKED_CAST")
inline fun <reified T : Any> Serializable.checkSerializableIsListOf() =
if (this is List<*> && this.all { it is T })
this as List<T>
else null
Instead of
myGenericList.filter { it is AbstractRobotTurn } as List<AbstractRobotTurn>
I like doing
myGenericList.filter { it is AbstractRobotTurn }.map { it as AbstractRobotTurn }
Not sure how performant this is, but no warnings at least.
Kotlin ensures type safety for operations involving generics at compile time, while, at runtime, instances of generic types don't hold information about their actual type arguments. For example, List is erased to just List<*>. In general, there is no way to check whether an instance belongs to a generic type with certain type arguments at runtime.
https://kotlinlang.org/docs/typecasts.html#type-erasure-and-generic-type-checks

Compare via pointers

I would like some explanation as to what a part of this function does:
bool Compare(CBox* pBox) const
{
if (!pBox)
return 0;
return this->Volume() > pBox->Volume();
}
What does if(!pBox) check for? Is that if statement necessary?
if (!pBox) checks if the pointer pBox is null. It is necessary since you are calling a function (Volume()).
The IF is testing for null, if it is true (not zero), it ensure a zero being returned. It is necessary since you are comparing an instantiated object (you are calling its method) against another and this last can be null.

How do I check if System::Collections::ArrayList exists / is empty

I'm trying to access a handle to a ::Collections::ArrayList with a two simple accessor/mutator functions:
/** --------------------------------------------
* public accessor for RX message queue
* --------------------------------------------- */
System::Collections::ArrayList^ peak_lib::rx_queue(void)
{
return this->m_Queue_Mes_RX;
}
/** --------------------------------------------
* public mutator for RX message queue
* --------------------------------------------- */
void peak_lib::rx_queue( System::Collections::ArrayList^ inList )
{
if ( inList->Count != 0 ) // <-- error line
{
this->m_Queue_Mes_RX = inList;
}
}
My compiler throws An unhandled exception of type 'System.NullReferenceException' occurred in my.exe and adds that the reference was not called on an object ( or something along these lines, I have to translate it from polish :/ ) when I try to access the ->Count property ( see error line in code ) as somebody told me to here to check if the inList variable exists.
What's the right (or at least a better :D) way to check if an ArrayList exists when I'm using C++/CLI Visual Studio 2008?
Initially, check for null before checking for count
if (inList != nullptr)
{
if(inList->count)
{}
}
Check for the null pointer before actually accessing its member.
if (inList)
{
if(inList->count)
{}
}
Also, as stated by Konrad in the comments, System::Collections::ArrayList is obsolete so try using vector instead
A property setter should either set the property to the value passed or indicate an error. There are two ways to indicate an error: Either throw an argument exception (common) or change the object to an invalid state that is exposed in future operations with the object (rare, e.g., classes intended to be used with data binding).
It could be that setting the property to null should not be an error but your question implies you want to disallow that. So, passing null where a non-null list is expected is a Boneheaded Exception. It is something that should be corrected before release and not ignored by the called code or "handled" by the calling code.
Here's the check in that case:
if (inList == nullptr) throw gcnew ArgumentNullException(L"value");
On the other hand, passing an empty list doesn't seem exceptional at all. You should consider accepting an empty list as the property value. If that doesn't make sense, perhaps you should design your class without that read-write property and instead use a method and a read-only property or the like.
Other issues:
Consider Systems::Collections::Generic::List<T> instead of System::Collections::ArrayList
Consider exposing the list as a read-only collection.

jsoncpp how to check if tag is null .isNull() throw assertion

Im using jsoncpp , its great but when i need to check if json structure contains tag
when i do it with :
UserRoot0["error"].isNull()
its throws me assert from json_value.cpp line 1025
JSON_ASSERT( type_ == nullValue || type_ == objectValue );
i want to check if response im getting is from this type:
{
"error" : {
"message" : "Error validating application.",
"type" : "OAuthException",
"code" : 190
}
}
The [] operator is only valid for JsonValue objects that are of type Object or null. All others (Int, Bool, Array, etc.) will assert.
If your UserRoot0 object is an Array or some other non-Object type, you have some more work to do (like iterating into sub-nodes) to find your target node that may or may not contain the error. Print UserRoot0.toStyledString() to see what your JSON looks like, and make sure it looks like a JSON Object (see json.org for a nice overview of what that is).
A "ToDo" comment at the top of the json_value.cpp source file (where JSON_ASSERT is defined) implies that the developers may be planning more robust error handling instead of these asserts in future versions, but in the meantime, you can check yourself, like this:
if(UserRoot0.isObject() && UserRoot0.isMember("error"))
// Process error node
else
// This node isn't an Object node or doesn't contain the "error" key
The isMember() check will also assert for non-Object nodes, so be sure to check isObject() before checking isMember() if UserRoot0 isn't guaranteed to be an Object.
I stumbled on this too. As Ennael says you need to make sure you are dealing with an object type. FWIW my problem was caused by using JSON like this:
"error" : {
"code" : 190
}
... instead of what I intended:
{
"error" : {
"code" : 190
}
}
Excluding the outer set of parenthesis will cause the value type to become string instead of object.

Null checking the null object pattern

The main goal of the Null Object Pattern is to ensure that a usable object is provided to the client. So we want to replace the following code...
void Class::SetPrivateMemberA() {
m_A = GetObject();
}
void Class::UseA() {
if (m_A != null) {
m_A.Method();
} else {
// assert or log the error
}
}
...with this implementation:
void Class::SetPrivateMemberA() {
m_A = GetObject();
}
void Class::UseA() {
m_A.Method();
}
The problem I am thinking of is that GetObject() still returns an object, a NULL Object or otherwise. I like the idea of not checking for null repeatedly and trusting that the object sent back is usable, but why wouldn't I just do that in the first implementation?
Is the advantage of the Null Object pattern just a slight increase in trust to clean up code? With the second implementation, is it not still a good practice to check that it is not null before calling A.Method()?
You're correct that, if you're sure you're never returning nulls, just skip the null check before calling the method in your first implementation. Likewise, if you do need to do something special in the case that UseA() needs to do something differently on a null object, that you need to explicitly check for a null object anyway. However, what null object pattern really helps with is those situations where it doesn't really matter.
Take, for example, most observer patterns. If you implement your observer pattern as a member of your class for which there can only be one observer, and want to announce to the observer that your class did something, it doesn't matter to the class whether the observer is null or not.
This is also illustrated with empty container classes, which are essentially the null object pattern: Instead of returning a null container from a query, you simply return an empty container. For things like iterating through all entries of a container, it often won't matter whether it's empty or not, so getting rid of the need of a null check makes the code more maintainable/more readable. However, if you want to populate a view of your data set, you still need to explicitly show a different "No entries." that checks for an empty container.
Edit for clarity
One problem is only looking at it from the call site. Like most design patterns, this needs to encompass both sides to be fully utilized. Consider:
public PossiblyNull GetSomethingNull()
{
if (someBadSituation())
return null;
else
return SomehowProduceSomething();
}
vs
public PossiblyEmpty GetSomethingEmpty()
{
if (someBadSituation())
return StaticEmptySomething();
else
return ProdueSomethingYay();
}
Now, your call code, instead of looking like
public void DoSomethingWithChild(Foo foo)
{
if (foo != null)
{
PossiblyNull bar = foo.GetSomething();
if (bar != null)
bar.DoSomething();
}
}
it can be
public void DoSomethingWithChild(Foo foo)
{
if (foo != null)
foo.GetSomething().DoSomething();
}
With the second implementation, is it
not still a good practice to check
that it is not null before calling
A.Method()?
No. If you know that m_A is not null, then the check is superfluous; it's an example of paranoid coding. What harm does it do? It complicates your code - unnecessarily; it makes it harder to read, harder to debug.