Conditions on a constructors arguments [duplicate] - c++

This question already has answers here:
How to handle failure in constructor in C++?
(8 answers)
Closed 7 years ago.
Is it possible to check the arguments of a constructor for certain constraints and if they're not met the object is not created and return a value to tell it failed to be created .
for instance .
Class Device
{
string id;
Device(string ID)
{
If (ID.Length != 7)
{
//Do not create Object
}
id == ID;
}
}
Here I only want 7 char long id String , not less not more ! if its not 7 char I don't want the Object created is it possible to do this ?
I couldn't think of any solution to this other than external function check which is something I want to stay away from !

The usual way would be to check the condition, and if it's not met, throw an exception.
Another possibility would be to accept an array of 7 characters, so the code won't compile if something else is passed. This tends to be trickier to get to work well in general though (e.g., it usually won't work if somebody passes an object of the wrong type, even something like a string that actually does contain 7 characters).
A sort of intermediate point would be to create a type specifically to hold your string of 7 characters, and throw an exception in its ctor if the length is wrong. This can give a little more granularity so it's easier to know what's wrong when the exception is thrown, as well as assuring that creating the Device object will succeed if you pass it a valid DeviceName (or whatever name you prefer) object.

You can throw an exception.
https://stackoverflow.com/a/7894215/2887128
Class Device
{
string id;
Device(string ID)
{
If (ID.Length != 7)
{
throw invalidObjectParametersException;
}
id == ID;
}
}
You could also adjust your design and wrap construction in some sort of factory.

One option I can think of is to throw an error if the condition is not met and catch that error in the function that creates the object.

Yes, you can implement a valid method, which will return if the created object is valid. In order to do that, without creating your real object, you would have to create an internal struct, which would become a private member of the owner class:
Class Device
{
struct DeviceImplementation {
string id;
Device owner;
DeviceImplementation (Device *owner, const string &id):
owner(owner),
id(id)
{
}
};
std::unique_ptr<DeviceImplementation> implementation;
public:
Device(const string &ID)
{
If (ID.Length != 7)
{
//Do not create Object
} else
implementation=std::unique_ptr<DeviceImplementation>(new DeviceImplementation(this, ID));
}
bool isValid() const {return implementation!=nullptr;}
}

No, a constructor can only return an object (or raise an exception).
If you want the chance to verify parameters or context, you should make:
a) the constructor private (so it cannot be called from outside the class anymore)
b) provide a static public method that returns an object (or, for example, NULL if it failed), and inside this method do your tests, and if they are successful call the private constructor and return the created object.
Of course, the outside code needs to able to handle a NULL return (or whatever you chose to do to signal that it failed).
This is a simple and common solution, but you can make up others with similar ideas.

Related

c++, dealing with exceptions from constructors

I have a class which is loaded from an external file, so ideally I would want its constructor to load from a given path if the load fails, I will want to throw an error if the file is not found/not readable (Throwing errors from constructors is not a horrible idea, see ISO's FAQ).
There is a problem with this though, I want to handle errors myself in some controlled manner, and I want to do that immediately, so I need to put a try-catch statement around the constructor for this object ... and if I do that, the object is not declared outside the try statement, i.e.:
//in my_class.hpp
class my_class
{
...
public:
my_class(string path);//Throws file not found, or other error error
...
};
//anywhere my_class is needed
try
{
my_class my_object(string);
}
catch(/*Whatever error I am interesetd in*/)
{
//error handling
}
//Problem... now my_object doesn't exist anymore
I have tried a number of ways of getting around it, but I don't really like any of them:
Firstly, I could use a pointer to my_class instead of the class itself:
my_class* my_pointer;
try
{
my_class my_pointer = new my_class(string);
}
catch(/*Whatever error I am interesetd in*/)
{
//error handling
}
The problem is that the instance of this object doesn't always end up in the same object which created it, so deleting all pointers correctly would be easy to do wrong, and besides, I personally think it is ugly to have some objects be pointers to objects, and have most others be "regular objects".
Secondly, I could use a vector with only one element in much the same way:
std::vector<my_class> single_vector;
try
{
single_vector.push_back(my_class(string));
single_vector.shrink_to_fit();
}
catch(/*Whatever error I am interesetd in*/)
{
//error handling
}
I don't like the idea of having a lot of single-element vectors though.
Thirdly, I can create an empty faux constructor and use another loading function, i.e.
//in my_class.hpp
class my_class
{
...
public:
my_class() {}// Faux constructor which does nothing
void load(string path);//All the code in the constructor has been moved here
...
};
//anywhere my_class is needed
my_class my_object
try
{
my_object.load(path);
}
catch(/*Whatever error I am interesetd in*/)
{
//error handling
}
This works, but largely defeats the purpose of having a constructor, so I don't really like this either.
So my question is, which of these methods for constructing an object, which may throw errors in the constructor, is the best (or least bad)? and are there better ways of doing this?
Edit: Why don't you just use the object within the try-statement
Because the object may need to be created as the program is first started, and stopped much later. In the most extreme case (which I do actually need in this case also) that would essentially be:
int main()
{
try
{
//... things which might fail
//A few hundred lines of code
}
catch(/*whaveter*/)
{
}
}
I think this makes my code hard to read since the catch statement will be very far from where things actually went wrong.
One possibility is to wrap the construction and error handling in a function, returning the constructed object. Example :
#include <string>
class my_class {
public:
my_class(std::string path);
};
my_class make_my_object(std::string path)
{
try {
return {std::move(path)};
}
catch(...) {
// Handle however you want
}
}
int main()
{
auto my_object = make_my_object("this path doesn't exist");
}
But beware that the example is incomplete because it isn't clear what you intend to do when construction fails. The catch block has to either return something, throw or terminate.
If you could return a different instance, one with a "bad" or "default" state, you could have just initialized your instance to that state in my_class(std::string path) when it was determined the path is invalid. So in that case, the try/catch block is not needed.
If you rethrow the exception, then there is no point in catching it in the first place. In that case, the try/catch block is also not needed, unless you want to do a bit of extra work, like logging.
If you want to terminate, you can just let the exception go uncaught. Again, in that case, the try/catch block is not needed.
The real solution here is probably to not use a try/catch block at all, unless there is actually error handling you can do that shouldn't be implemented as part of my_class which isn't made apparent in the question (maybe a fallback path?).
and if I do that, the object is not declared outside the try statement
I have tried a number of ways of getting around it
That doesn't need to be a problem. There's not necessarily need to get around it. Simply use the object within the try statement.
If you really cannot have the try block around the entire lifetime, then this is a use case for std::optional:
std::optional<my_class> maybe_my_object;
try {
maybe_my_object.emplace(string);
} catch(...) {}
The problem is that the instance of this object doesn't always end up in the same object which created it, so deleting all pointers correctly would be easy to do wrong,
A pointer returned by new is correct to delete. In the error case, simply set the pointer to null and there would be no problem. That said, use a smart pointer instead for dynamic allocation, if you were to use this approach.
single_vector.push_back(my_class(string));
single_vector.shrink_to_fit();
Don't push and shrink when you know the number of objects that are going to be in the vector. Use reserve instead if you were to use this approach.
The object creation can fail because a resource is unavailable. It's not the creation which fails; it is a prerequisite which is not fulfilled.
Consequently, separate these two concerns: First obtain all resources and then, if that succeeded, create the object with these resources and use it. The object creation as such in this design cannot fail, the constructor is nothrow; it is trivial boilerplate code (copy data etc.). If, on the other hand, resource acquisition failed, object creation and object use are both skipped: Your problem with existing but unusable objects is gone.
Responding to your edit about try/catch comprising the entire program: Exceptions as error indicators are better suited for things which are done in many places at various times in a program because they guarantee error handling (by default through an abort) while separating it from the normal control flow. This is impossible to do with classic return value examination, which leaves us with a choice between unreadable or unreliable programs.
But if you have long-lived objects which are created only rarely (in your example: only at startup) you don't need exceptions. As you said, constructor exceptions guarantee that only properly initialized objects can be used. But if such an object is only created at startup this danger is low. You check for success one way or another and exit the program which cannot perform its purpose if the initial resource acquisition failed. This way the error is handled where it occurred. Even in less extreme cases (e.g. when an object is created at the beginning of a large function other than main) this may be the simpler solution.
In code, my suggestion looks like this:
struct T2;
struct myEx { myEx(const char *); };
void exit(int);
T1 *acquireResource1(); // e.g. read file
T2 *acquireResource2(); // e.g. connect to db
void log(const char *what);
class ObjT
{
public:
struct RsrcT
{
T1 *mT1;
T2 *mT2;
operator bool() { return mT1 && mT2; }
};
ObjT(const RsrcT& res) noexcept
{
// initialize from file data etc.
}
// more member functions using data from file and db
};
int main()
{
ObjT::RsrcT rsrc = { acquireResource1(), acquireResource2() };
if(!rsrc)
{
log("bummer");
exit(1);
}
///////////////////////////////////////////////////
// all resources are available. "Real" code starts here.
///////////////////////////////////////////////////
ObjT obj(rsrc);
// 1000 lines of code using obj
}

javax.xml.ws.WebServiceException: javax.xml.ws.WebServiceException: Failed to instantiate handler [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?
What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
There are two overarching types of variables in Java:
Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type int or char are primitives.
References: variables that contain the memory address of an Object i.e. variables that refer to an Object. If you want to manipulate the Object that a reference variable refers to you must dereference it. Dereferencing usually entails using . to access a method or field, or using [ to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type Object are references.
Consider the following code where you declare a variable of primitive type int and don't initialize it:
int x;
int y = x + x;
These two lines will crash the program because no value is specified for x and we are trying to use x's value to specify y. All primitives have to be initialized to a usable value before they are manipulated.
Now here is where things get interesting. Reference variables can be set to null which means "I am referencing nothing". You can get a null value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to null).
If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a NullPointerException.
The NullPointerException (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.
Take the following code:
Integer num;
num = new Integer(10);
The first line declares a variable named num, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to null.
In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the reference variable num is assigned to that Integer object.
If you attempt to dereference num before creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized," but sometimes you may write code that does not directly create the object.
For instance, you may have a method as follows:
public void doSomething(SomeObject obj) {
// Do something to obj, assumes obj is not null
obj.myMethod();
}
In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this:
doSomething(null);
In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException.
If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes.
In addition to NullPointerExceptions thrown as a result of the method's logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method:
// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");
Note that it's helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely.
Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething() could be written as:
/**
* #param obj An optional foo for ____. May be null, in which case
* the result will be ____.
*/
public void doSomething(SomeObject obj) {
if(obj == null) {
// Do something
} else {
// Do something else
}
}
Finally, How to pinpoint the exception & cause using Stack Trace
What methods/tools can be used to determine the cause so that you stop
the exception from causing the program to terminate prematurely?
Sonar with find bugs can detect NPE.
Can sonar catch null pointer exceptions caused by JVM Dynamically
Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.
In Java 14, the following is a sample NullPointerException Exception message:
in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null
List of situations that cause a NullPointerException to occur
Here are all the situations in which a NullPointerException occurs, that are directly* mentioned by the Java Language Specification:
Accessing (i.e. getting or setting) an instance field of a null reference. (static fields don't count!)
Calling an instance method of a null reference. (static methods don't count!)
throw null;
Accessing elements of a null array.
Synchronising on null - synchronized (someNullReference) { ... }
Any integer/floating point operator can throw a NullPointerException if one of its operands is a boxed null reference
An unboxing conversion throws a NullPointerException if the boxed value is null.
Calling super on a null reference throws a NullPointerException. If you are confused, this is talking about qualified superclass constructor invocations:
class Outer {
class Inner {}
}
class ChildOfInner extends Outer.Inner {
ChildOfInner(Outer o) {
o.super(); // if o is null, NPE gets thrown
}
}
Using a for (element : iterable) loop to loop through a null collection/array.
switch (foo) { ... } (whether its an expression or statement) can throw a NullPointerException when foo is null.
foo.new SomeInnerClass() throws a NullPointerException when foo is null.
Method references of the form name1::name2 or primaryExpression::name throws a NullPointerException when evaluated when name1 or primaryExpression evaluates to null.
a note from the JLS here says that, someInstance.someStaticMethod() doesn't throw an NPE, because someStaticMethod is static, but someInstance::someStaticMethod still throw an NPE!
* Note that the JLS probably also says a lot about NPEs indirectly.
NullPointerExceptions are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException. These are the most common, but other ways are listed on the NullPointerException javadoc page.
Probably the quickest example code I could come up with to illustrate a NullPointerException would be:
public class Example {
public static void main(String[] args) {
Object obj = null;
obj.hashCode();
}
}
On the first line inside main, I'm explicitly setting the Object reference obj equal to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException because there is no code to execute in the location that the reference is pointing.
(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)
What is a NullPointerException?
A good place to start is the JavaDocs. They have this covered:
Thrown when an application attempts to use null in a case where an
object is required. These include:
Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other
illegal uses of the null object.
It is also the case that if you attempt to use a null reference with synchronized, that will also throw this exception, per the JLS:
SynchronizedStatement:
synchronized ( Expression ) Block
Otherwise, if the value of the Expression is null, a NullPointerException is thrown.
How do I fix it?
So you have a NullPointerException. How do you fix it? Let's take a simple example which throws a NullPointerException:
public class Printer {
private String name;
public void setName(String name) {
this.name = name;
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String[] args) {
Printer printer = new Printer();
printer.print();
}
}
Identify the null values
The first step is identifying exactly which values are causing the exception. For this, we need to do some debugging. It's important to learn to read a stacktrace. This will show you where the exception was thrown:
Exception in thread "main" java.lang.NullPointerException
at Printer.printString(Printer.java:13)
at Printer.print(Printer.java:9)
at Printer.main(Printer.java:19)
Here, we see that the exception is thrown on line 13 (in the printString method). Look at the line and check which values are null by
adding logging statements or using a debugger. We find out that s is null, and calling the length method on it throws the exception. We can see that the program stops throwing the exception when s.length() is removed from the method.
Trace where these values come from
Next check where this value comes from. By following the callers of the method, we see that s is passed in with printString(name) in the print() method, and this.name is null.
Trace where these values should be set
Where is this.name set? In the setName(String) method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method.
This is enough to give us a solution: add a call to printer.setName() before calling printer.print().
Other fixes
The variable can have a default value (and setName can prevent it being set to null):
private String name = "";
Either the print or printString method can check for null, for example:
printString((name == null) ? "" : name);
Or you can design the class so that name always has a non-null value:
public class Printer {
private final String name;
public Printer(String name) {
this.name = Objects.requireNonNull(name);
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String[] args) {
Printer printer = new Printer("123");
printer.print();
}
}
See also:
Avoiding “!= null” statements in Java?
I still can't find the problem
If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. Also, try simplifying the code first (see SSCCE).
Question: What causes a NullPointerException (NPE)?
As you should know, Java types are divided into primitive types (boolean, int, etc.) and reference types. Reference types in Java allow you to use the special value null which is the Java way of saying "no object".
A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference. For example, if you write this:
public class Test {
public static void main(String[] args) {
String foo = null;
int length = foo.length(); // HERE
}
}
the statement labeled "HERE" is going to attempt to run the length() method on a null reference, and this will throw a NullPointerException.
There are many ways that you could use a null value that will result in a NullPointerException. In fact, the only things that you can do with a null without causing an NPE are:
assign it to a reference variable or read it from a reference variable,
assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
pass it as a parameter or return it as a result, or
test it using the == or != operators, or instanceof.
Question: How do I read the NPE stacktrace?
Suppose that I compile and run the program above:
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:4)
$
First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception ... but the standard javac compiler doesn't.)
Second observation: when I run the program, it outputs two lines of "gobbledy-gook". WRONG!! That's not gobbledy-gook. It is a stacktrace ... and it provides vital information that will help you track down the error in your code if you take the time to read it carefully.
So let's look at what it says:
Exception in thread "main" java.lang.NullPointerException
The first line of the stack trace tells you a number of things:
It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be "main". Let's move on ...
It tells you the full name of the exception that was thrown; i.e. java.lang.NullPointerException.
If the exception has an associated error message, that will be output after the exception name. NullPointerException is unusual in this respect, because it rarely has an error message.
The second line is the most important one in diagnosing an NPE.
at Test.main(Test.java:4)
This tells us a number of things:
"at Test.main" says that we were in the main method of the Test class.
"Test.java:4" gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.
If you count the lines in the file above, line 4 is the one that I labeled with the "HERE" comment.
Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first "at" line) will tell you where the NPE was thrown1.
In short, the stack trace will tell us unambiguously which statement of the program has thrown the NPE.
See also: What is a stack trace, and how can I use it to debug my application errors?
1 - Not quite true. There are things called nested exceptions...
Question: How do I track down the cause of the NPE exception in my code?
This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code, and the relevant API documentation.
Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:
int length = foo.length(); // HERE
How can that throw an NPE?
In fact, there is only one way: it can only happen if foo has the value null. We then try to run the length() method on null and... BANG!
But (I hear you say) what if the NPE was thrown inside the length() method call?
Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.lang.String class and line 4 of Test.java would be the second "at" line.
So where did that null come from? In this case, it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo.)
OK, so let's try a slightly more tricky example. This will require some logical deduction.
public class Test {
private static String[] foo = new String[2];
private static int test(String[] bar, int pos) {
return bar[pos].length();
}
public static void main(String[] args) {
int length = test(foo, 1);
}
}
$ javac Test.java
$ java Test
Exception in thread "main" java.lang.NullPointerException
at Test.test(Test.java:6)
at Test.main(Test.java:10)
$
So now we have two "at" lines. The first one is for this line:
return args[pos].length();
and the second one is for this line:
int length = test(foo, 1);
Looking at the first line, how could that throw an NPE? There are two ways:
If the value of bar is null then bar[pos] will throw an NPE.
If the value of bar[pos] is null then calling length() on it will throw an NPE.
Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:
Where does bar come from? It is a parameter to the test method call, and if we look at how test was called, we can see that it comes from the foo static variable. In addition, we can see clearly that we initialized foo to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo to null ... but that is not happening here.)
So what about our second scenario? Well, we can see that pos is 1, so that means that foo[1] must be null. Is this possible?
Indeed it is! And that is the problem. When we initialize like this:
private static String[] foo = new String[2];
we allocate a String[] with two elements that are initialized to null. After that, we have not changed the contents of foo ... so foo[1] will still be null.
What about on Android?
On Android, tracking down the immediate cause of an NPE is a bit simpler. The exception message will typically tell you the (compile time) type of the null reference you are using and the method you were attempting to call when the NPE was thrown. This simplifies the process of pinpointing the immediate cause.
But on the flipside, Android has some common platform-specific causes for NPEs. A very common is when getViewById unexpectedly returns a null. My advice would be to search for Q&As about the cause of the unexpected null return value.
It's like you are trying to access an object which is null. Consider below example:
TypeA objA;
At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw NullPointerException which makes sense.
See this below example as well:
String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown
A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:
Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other illegal uses of the null object.
Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html
A null pointer is one that points to nowhere. When you dereference a pointer p, you say "give me the data at the location stored in "p". When p is a null pointer, the location stored in p is nowhere, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a null pointer exception.
In general, it's because something hasn't been initialized properly.
A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow best practices to avoid NullPointerExceptions at all.
See also:
A good list of best practices
I would add, very important, make a good use of the final modifier.
Using the "final" modifier whenever applicable in Java
Summary:
Use the final modifier to enforce good initialization.
Avoid returning null in methods, for example returning empty collections when applicable.
Use annotations #NotNull and #Nullable
Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null.
Use equals with a known object first: if("knownObject".equals(unknownObject)
Prefer valueOf() over toString().
Use null safe StringUtils methods StringUtils.isEmpty(null).
Use Java 8 Optional as return value in methods, Optional class provide a solution for representing optional values instead of null references.
A null pointer exception is an indicator that you are using an object without initializing it.
For example, below is a student class which will use it in our code.
public class Student {
private int id;
public int getId() {
return this.id;
}
public setId(int newId) {
this.id = newId;
}
}
The below code gives you a null pointer exception.
public class School {
Student student;
public School() {
try {
student.getId();
}
catch(Exception e) {
System.out.println("Null pointer exception");
}
}
}
Because you are using student, but you forgot to initialize it like in the
correct code shown below:
public class School {
Student student;
public School() {
try {
student = new Student();
student.setId(12);
student.getId();
}
catch(Exception e) {
System.out.println("Null pointer exception");
}
}
}
In Java, everything (excluding primitive types) is in the form of a class.
If you want to use any object then you have two phases:
Declare
Initialization
Example:
Declaration: Object object;
Initialization: object = new Object();
Same for the array concept:
Declaration: Item item[] = new Item[5];
Initialization: item[0] = new Item();
If you are not giving the initialization section then the NullPointerException arise.
In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.
When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.
Your reference is "pointing" to null, thus "Null -> Pointer".
The object lives in the VM memory space and the only way to access it is using this references. Take this example:
public class Some {
private int id;
public int getId(){
return this.id;
}
public setId( int newId ) {
this.id = newId;
}
}
And on another place in your code:
Some reference = new Some(); // Point to a new object of type Some()
Some otherReference = null; // Initiallly this points to NULL
reference.setId( 1 ); // Execute setId method, now private var id is 1
System.out.println( reference.getId() ); // Prints 1 to the console
otherReference = reference // Now they both point to the only object.
reference = null; // "reference" now point to null.
// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );
// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...
This an important thing to know - when there are no more references to an object (in the example above when reference and otherReference both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.
Another occurrence of a NullPointerException occurs when one declares an object array, then immediately tries to dereference elements inside of it.
String[] phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}
This particular NPE can be avoided if the comparison order is reversed; namely, use .equals on a guaranteed non-null object.
All elements inside of an array are initialized to their common initial value; for any type of object array, that means that all elements are null.
You must initialize the elements in the array before accessing or dereferencing them.
String[] phrases = new String[] {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
System.out.println(phrase.equals(keyPhrase));
}

Returning object loses properties [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
This is basically my main function :
void GameObject::deserialize(QList<GameObject*> *list)
{
QFile _file(_filename);
if (!_file.open(QIODevice::ReadOnly | QFile::Text))
{
qDebug() << "Couldn't open file to read";
return;
}
QTextStream in(&_file);
while (!in.atEnd())
{
QString currentline = in.readLine();
if (currentline.startsWith("GameObject {"))
{
list->append(getGameObject(&in, currentline));
}
}
_file.close();
}
It opens a file, and parses it for GameObjects.
The getGameObject (cleaned up) function is this one :
GameObject *GameObject::getGameObject(QTextStream *in, QString current_line)
{
GameObject *go = new GameObject();
QList<GameObjectVariable*> govl;
bool ok;
while (!in->atEnd() && !current_line.startsWith("} end GameObject"))
{
current_line = in->readLine();
if (current_line.startsWith("GameObjectVariable")) {
GameObjectVariable *gov = this->getGameObjectVariable(in, current_line);
govl.append(gov);
go->setVariableList(&govl);
qDebug() << QString("AR : Type As String of the returned object : ") + gov->getTypeAsAString();
qDebug() << QString("AR : Type as number : ") + QString::number(gov->getType());
if (gov->getType() == NUMBER_LIST) {
qDebug() << "Number List";
qDebug() << QString("Value as a string of the number list : ") + ((GameObjectVariableNumberList*)gov)->getValueAsAString();
}
else if (gov->getType() == STRING_LIST) {
qDebug() << "String List";
qDebug() << QString("Value as a string of the string list : ") + ((GameObjectVariableStringList*)gov)->getValueAsAString();
}
else if (gov->getType() == GAMEOBJECT) {
qDebug() << "GameOBject";
qDebug() << QString("Value as a string of the gameobject : ") + ((GameObjectVariableGameObject*)gov)->getValueAsAString();
}
}
}
return go;
}
This one basically is a big mess of ifs, but it works, up to a point. The goal of this function is to read line by line, and return a gameobject filled with the read info. This is a weird format we use for the project though.
The last bunch of lines are Debug lines I've put in to try to understand where the problem was.
This is the other (cleaned up) function that's related :
GameObjectVariable* GameObject::getGameObjectVariable(QTextStream *in, QString current_line)
{
GameObjectVariable *gov;
bool ok;
int type;
QList<QString> ls;
QList<int> ln;
QList<GameObject*> lgo;
while (!in->atEnd() && !current_line.startsWith("} end GameObjectVariable")) {
current_line = in->readLine();
if (current_line.startsWith("type: "))
{
type = current_line.right(current_line.size() - 5).toInt(&ok, 10);
}
else if (current_line.startsWith("value: ")) {
if (current_line.startsWith("value: {"))
{
while (!in->atEnd() && !current_line.startsWith("} end value"))
{
current_line = in->readLine();
if (!current_line.startsWith("} end value"))
{
if (type == GAMEOBJECT_LIST)
{
lgo.append(getGameObject(in, current_line));
}
else if (type == STRING_LIST)
{
ls.append(current_line);
}
else if (type == NUMBER_LIST)
{
ln.append(current_line.toInt(&ok, 10));
}
}
}
if (type == GAMEOBJECT_LIST)
((GameObjectVariableGameObjectList*) gov)->setValue(&lgo);
else if (type == STRING_LIST)
((GameObjectVariableStringList*) gov)->setValue(&ls);
else if (type == NUMBER_LIST)
((GameObjectVariableNumberList*) gov)->setValue(&ln);
}
}
}
qDebug() << QString("BR : Get the type as string : ") + gov->getTypeAsAString();
qDebug() << QString("BR : Get the type as number : ") + QString::number(gov->getType());
qDebug() << QString("BR : get the value as string of the object : ") + gov->getValueAsAString();
return gov;
}
This function reads the lines in the GameObjectVariable 'tag'. The type is a defined int that is macroed to the text type we use for the other if forest.
Now this again works fine, except for when we have a list of values (the part that starts with else if (current_line.startsWith("value: {"))).
The debug lines at the end of the function (the "BR :" ones) show the object properly filled, but the ones at the end of the getGameObject calling function (starting with "AR :") crash, because apparently the value is null.
GameObjectVariable object is this one (again, cleaned up) :
class GameObjectVariable
{
public:
GameObjectVariable(QString name, QList<int> idListEdit = QList<int>(), QList<int> idListView = QList<int>());
// GETTERS
QString getName() {return this->name;}
int getType() {return this->type;}
void *getValue() {return this->value;}
// SETTERS
void setName(QString name) {this->name = name;}
void setValue(void* value) {this->value = value;}
QString getTypeAsAString();
virtual QString getValueAsAString() = 0;
private:
QString name;
protected:
void *value;
int type;
};
getValueAsAString is set as virtual because every type mentioned in the code above (like GameObjectVariableStringList overwrite this one with a return of their value with the correct type)
Finally, here is an example of file we try to deserialize :
GameObject {
name: Number 1
type: Test
GameObjectVariableStringList: {
type: 3
name: List String
value: {
String 1
String 2
} end value
} end GameObjectVariable
(type: 3 corresponds to STRING_LIST)
The main problem is bolded.
The problem
getGameObjectVariable()'s local variable GameObjectVariable *gov is an uninitialised pointer, which you suddenly cast to some other type and then start trying to call methods on.
How did you expect that to end? You are telling the compiler this: Poke at random memory as if it holds an allocated, initialised object. Also, this object might have any of 3 different types.
Seriously: What did you think was happening in that function, that it was somehow producing a usable object? I'm genuinely curious.
Anyway, for at least three reasons, this is malformed code that exhibits completely undefined behaviour:
The pointer is uninitialised, so like any uninitialised variable, reading/dereferencing it is UB.
No object is alive at the (invalid) address to which it points, but you call methods on it as if an object lives there; that is UB.
Said methods then presumably start writing stuff to whatever arbitrary address you happened to end up at, with no permission, which is lethal UB.
(Also, even if there was valid memory to access and a valid object at it, casting the pointer to another type then using it is only valid if an instance of that other type was specifically allocated at that address - or some more-derived one, but then the C-style cast is (A) bad style and (B) potentially very dangerous if e.g. multiple and/or virtual inheritance are in play.)
Due to all this UB, anything can happen, or nothing might happen, or exactly what you want just might happen - but the code is fundamentally broken.
For example, as seems to have occurred here, the compiler might coincidentally act like there is a valid object while within the same function, but then you return that garbage pointer to getGameObject(), and it suddenly reveals that you fed it rubbish.
UB gives the compiler, and particularly its optimising layers, free reign to do whatever they want, chiefly because they are allowed to assume UB does not happen. So, e.g. they can assume there must be a valid object pointed to by gov, even if there blatantly isn't. That assumption gets lost after you return, though, for whatever reason.
Who knows? The precise reasons for the observed behaviour are pretty uninteresting to speculate about. You can produce assembly output if you really want to know why what happened happened.
The (immediate) solution
But the key point is this: You need to replace this particular mess with proper, valid code - and fast. So, you need to assign a valid value to the pointer, by assigning it the address of a newly allocated object of whichever type is required. Only then do you have an address to which you are allowed access, with a living object at it, of the right type. It's then OK to create a cast pointer of the real derived type to call derived methods, but return a pointer-to-base for others to use.
Conditionally calling methods, etc.
Also, those conditional casts and calls to setValue() look suspicious. Why not just make that a virtual method and let the compiler resolve the right variation? Generally, if you have some conditional construct deciding which method to call based on the real type... You should just use virtual functions. Most concern about their overhead is FUD, and most attempts to avoid that overhead are no more efficient to execute and much worse to read.
For instance, do you expect all users of any GameObjectVariable to repeat the same hoop-jumping exercise of checking what type it is and casting to the equivalent type of pointer to call the right (derived, hiding-not-overriding) version of setValue()? Hello, boilerplate spaghetti code, for no reason.
I think this points at more general bad patterns in your design. Rather than having huge functions that repeatedly have to check the type and do different things, with different lists depending on the type, etc. - why not simply check the type specified by the input line, and construct a new object of that type with, for example, the rest of the line as an argument, letting it create and populate whatever type of list and any other specific attributes it needs? Then you'll have tidy methods that do single things, not labyrinths that must constantly remind themselves what kind of object they're working with.
Avoid new
Note that I said said to assign the pointer from "a newly allocated object", not a newly allocated object... Most people should not ever need to use raw new or delete in C++, so you should return a unique_ptr, ideally from std::make_unique<Foo>(args).
There is a fair exception if, as hyde points out in the comments, your new object is of a type that should have its lifetime managed by a parent object to which it is then added. Then new is OK - assuming there's no better way to phrase it, like I dunno, make_floating_reference<Foo>(args). But, as hyde also said, that isn't the case for your GameObjectVariable, so a smart pointer is the way to go for that.
(Normally I would say you probably don't need dynamic allocation at all, but since you appear to need polymorphism and the objects clearly don't comprise a known set on the stack to which you could push non-owning pointers/reference-wrappers into the container, it seems that you do.)

c++ - Checking if an Object is in empty state

I need to check if my object Course is in a safe empty state.
Here is my failed attempt:
const bool Course::isEmpty() const {
if (Course() == nullptr) {
return true;
}
else {
return false;
}
}
Constructors:
Course::Course() {
courseTitle_ = new char[21]; // name
courseTitle_ = '\0';
credits_ = 0;//qtyNeeded
studyLoad_ = 0;//quantity
strcpy(courseCode_, "");//sku
}
Course::Course(const char* courseCode, const char* courseTitle, int credits , int studyLoad ) {
strcpy(courseCode_, courseCode);
courseTitle_ = new char[21];
strcpy(courseTitle_, courseTitle);
studyLoad_ = studyLoad;
credits_ = credits;
}
Apprently, Doing course() == nullptr is not truly checking if the object is in safe empty state, also checking individual variables if they are set to 0 will not work in my program. i need to check if the entire object was set to a safe empty state.
Edit: Some of you are asking what my empty() function is suppose to use. There is a tester that is suppose to test if my isEmpty() works well.
bool isEmptyTest0() {
// empty test
sict::Course c0;
return c0.isEmpty();
}
bool isEmptyTest1() {
// empty test
sict::Course c0("", "title", 3, 3);
return c0.isEmpty();
}
bool isEmptyTest2() {
// empty test
sict::Course c0("code", "", 3, 3);
return c0.isEmpty();
}
bool isEmptyTest3() {
// empty test
sict::Course c0("code", "title", -1, 3);
return c0.isEmpty();
}
bool isEmptyTest4() {
// empty test
sict::Course c0("code", "title", 3, -1);
return c0.isEmpty();
}
bool regularInitTest() {
// regular
sict::Course c5("OOP244", "Object-Oriented Programming in C++", 1, 4);
return (!c5.isEmpty()
&& !strcmp("OOP244", c5.getCourseCode())
&& !strcmp("Object-Oriented Programming in C++", c5.getCourseTitle())
&& (c5.getCredits() == 1)
&& c5.getStudyLoad() == 4
);
}
Note that in regularInitTest() my assignment operators work fine, but it never passes !c5.isEmpty() because it fails. Hopefully i explained it correctly.
Most probably here is what you should do to make the tests pass.
In the 2nd (4-argument) constructor, do some checking of the input, e.g. check if credits is positive. Do check all arguments for all possible errors you can imagine, including those in isEmptyTest0..4. If there is an error, initialize the object the same way as the 1st (0-argument) constructor does. If there is no error, initialize the data members from the arguments.
Here is how to implement the isEmpty method: it should return true iff all the data members of the object have the empty/zero/default value, as initialized by the 1st (0-argument) constructor.
The notion safe empty state in itself still doesn't make sense, but the concept the professor is trying to teach does make sense. I'll try to summarize my understanding here. Constructors can receive invalid arguments, based on which it's not possible to initialize a meaningful and valid object. The programmer should add code for error checking and handling everywhere in the program, including constructors. There are multiple approaches to do input validation and error handling in constructors, e.g. 1. throwing an exception; 2. aborting the entire program with an error message; 3. initializing the object to a special, invalid state; 4. initializing the object to a special, empty state. (This is also an option, but it's strongly disrecommended: 5. keep some data members of the object uninitialized.) Each of these approaches have pros and cons. In this assignment, the professor wants you to implement #4. See the 2nd paragraph in my answer how to do it.
When the professor asks for a safe empty state, he most probably means that you should be doing input validation in the constructor, and in case of an error doing #4 rather than #5.
I agree with pts that safe empty state is ill-defined.
The missing principle, it seems to me after reading the comments, is Resource Acquisition Is Initialization (RAII). A constructor is a transaction, in a way: you get either
a valid object, or
an exception.
Valid here is defined by the class. Usually it means that the passed parameters were incorporated into the object, and all required resources were successfully allocated and/or found.
Aborting the program is rarely an option, and returning an error (from a constructor) never is. Constructing an invalid object is usually done only in environments where exceptions are prohibited.
There is a special case: the default constructor. Sometimes it's desirable to "make an empty" thing that will be fully initialized later.
Consider std::string. It can be constructed with a value, and throws an exception if memory cannot be allocated. Or it can be constructed without a value, and later assigned one. Your class could be similar, in which case safe empty just means a state that the user would be happy to destroy when calling the "init" function. You don't have to test every member variable; you just have to check something that will be true only for a completely initialized object.
Then there's the question of "is valid". An "empty" object can be "initialized", but it can't be used. It's not "valid" for use until fully initialized, whether at construction, or via the 2-step with a default constructor and a subsequent "init".
There is a widely accepted idiom for testing whether an object is "is valid" or not: a user-defined conversion to void *:
...
public:
operator void*() { return is_valid()? this : nullptr; }
...
where is_valid() may be a private function. With that in place, the user can test his instantiated object thus:
class A;
A foo();
...
if (!foo) { foo.open(...); }
I know I haven't answered your question, exactly. I hope I've provided some background that makes it easier for your to answer it yourself.

What should getObjByName() return?

I was working on some c++ code like this:
//c++ code
class MovieInfo;
MovieInfo getMovieInfoByName(String movieName)
{
//search the movieInfoList with movieName
if(FOUND)
return movieInfo;
//TODO: **what should i return if the movieInfo can't be found in the list?**
}
The question is what should i return if the movieInfo can't be found in the list?
You have several options:
Define the MovieInfo class such that an "invalid" instance is possible (similarly to how a default-constructed std::thread doesn't represent an actual thread) and return such an instance.
Make it a precondition of getMovieInfoByName() that the name corresponds to a valid movie info, and simply return a random value if it doesn't (as "violating preconditions leads to undefined behaviour").
Throw an exception when the name is not found.
Return something like boost::optional<MovieInfo>.
Give getMovieInfoByName() an extra parameter of type MovieInfo which would be used as the return value in case no match for the name is found.
It all depends on your intended use of the function.
It depends on the context and preconditions that must be met. For example if you are not sure whether the list contains such a movie by the time you call it, then it would be reasonable to do:
bool getMovieInfoByName(const std::string& movieName, MovieInfo& movieInfo)
{
...
if (FOUND) {
movieInfo = ...;
return true;
}
return false;
}
since the caller will most likely have to know whether the movie with such a movie exists or not.
If it shouldn't happen that getMovieInfoByName will not find the movie, i.e. the caller should already know whether the list contains such a movie by other means, then it is perfectly reasonable to throw an exception since it is exceptional state and rather indicates the wrong usage of this method.
There's also a design pattern called Null Object, which is based on constructing an object, state of which can indicate whether it is a valid / initialized object or it is a dummy instance representing NULL.
In this case the caller would most likely still have to check whether appropriate MovieInfo instance has been returned and this class should provide a method such as bool isValid();.