Method getElementById() returns null - java

I set id attribute the following way:
Element node = document.createElement("something");
node.setAttribute("id", "1");
node.setIdAttribute("id", true);
Then I check if this is really id attribute:
node.getAttributeNode("id").isId());
returns true
But when I try to get the node by its id
document.getElementById("1");
or even
document.getElementById(node.getAttributeNode("id").getValue())
I get null
What I'm doing wrong?

Despite the fact that you put the wrong tag, it looks like you defined the ID of your element to be "1" So that means to reference it, you should also reference it by "1"
document.getElementById("1");
would return you the DOM object in your markup, so long as it exists in the markup. Depending on the frameworks, it might be pulled from the Dom, but that is not always the case for beginner programming.
As a note for you, a ID should be unique, but at the same time it is good to name it something human readable. The reason for it is that you will come back to this code later and have absolutely no clue what it does.
If you name things accordingly, it will make it easier on you, also allowing you to create and follow the best practices for programming in general.

Apart from that in the previous answers.
The problem with your code is that the created node
var node = document.createElement("sector");
node.setAttribute("id", "1");
is not in the document yet. You must add it.
Example
// Adding the node to the body.
document.body.append(node)
and now
document.getElementById(1)

Related

Best Practice: Java attributes might be null

So I have a constructor with 5 different variables, where three of which might be null. It accepts user input and the user does not have to enter anything for three of the five attributes.
Therefore, if the user did not enter anything, the object is created using null for all missing values.
obj = new Object(String, null, null, null, String);
Now I am wondering what would be best practice to cope with this.
I can think of three different scenarios:
Deal with it only in the class using the constructor, i.e. always query whether the value is null (e.g. if(getSomeAttribute == null) { //do something }
Deal with it within the object class, i.e. always return some default value for each missing attribute instead of null
Deal with it within the object lcass, i.e. have helper-methods like isAttributeSet(), returning a boolean value indicating whether the attributes are set, that is: not null.
Although I have problems with the last two, as I think I might run into problems with default values, as sometimes it might hard to know if it is a default value; if I'd always check I could just as well check for null instead of inserting a default value first;
Same with the last one, if I have to check the helper-method, I could just as well check for null directly.
What my problem is with this situation, is that sometimes I might not be the one using the getter and setter methods; how should the one using it know there might be null attributes and which that are.
I know, I should document that within my object class, but still I am wondering if there is a "best practice" way to cope with this.
I believe it should be unusual to always check the documentary (or if there is none, the whole class) for something as simple as this.
Maybe I should not even start with null values within my constructor in the first place? But I think I would run into the same kinds of problems, anyway, so that would not really solve my problem
Read Bloch, Effective Java, 2nd ed. Item 2: "Consider a builder when faced with many constructor parameters."
Excellent advice in an excellent book.
Using a builder pattern would help with the constructor, however the main problem is to do with the design of the class - you want to be sure when you call a get/set method that it isn't one of the null/optional members.
You could use polymorphism to have two objects each with an interface that only exposes the getters and setters supported by the concrete implementation. This makes it impossible to call the wrong getters/setters and it is obvious what the intention is.

Non existing xml tag handling in java code

I have this issue which showed up in a very particular case. My XML is like
<xo:USAddress>
<xo:Street>990 STANLEY CT</xo:Street>
<xo:City>ERIE</xo:City>
<xo:County>BOULDER</xo:County>
<xo:State>COLORADO</xo:State>
<xo:ZipCode>80516</xo:ZipCode>
</xo:USAddress>
My code assumes that county information will always be there for US address but in certain cases like Virgin island, we don't get the county.
In my service class, I have below :
usAddress_Svc.setCounty(usAddress_PAS.getCounty().getStringValue());
In case , there is no county information in xml - how should i handle this condition. tried null check but that does not solve the purpose, please suggest.
You indeed would not typically get a null, as most XML parsers assume an empty string (which in Java is not the same as a null value). Try instead using address.getCounty().isEmpty() to determine whether or not the county is simply a blank value.
The only time you might have null is if the county field is not present, and the county value is not initialized. For cases like this, the best way to go might be to use a Java 8 Optional field (http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html).
If the field is initialized to Optional.empty(), then you can use a simple expression to access its contents or return a default value, with this:
String county = address.getCounty().orElse("N/A");
This would return either the county, or the value "N/A". There are quite a few other useful methods.

Recursively Search on a Binary Tree

can anybody help me to trace this piece of code if its correct or incorrect.i am studying recursion these days.
boolean search(Element element) {
Element c=first;
if(c==null)
return false;
else if(element.asset < c.asset)
if(c.left==null)
return false;
else
return search(c.left);
else if(element.data>c.data)
if(c.right==null)
return false;
else
return search(c.right);
else
return element.asset==c.asset;
}
it lacks stop condition. you should check if t.left == null, or you will get NullPointerException. also, you should return t.left.isExist(..) OR t.right.isExist(...) and not isExist [you will want to invoke this method on the son]
currently, this version will get into infinite loop - because you will always check in the same root node.
Your code isn't symmetric.
for one side, you call isExist(t.left), for another you call isExist(a.right)
You probably want to call t.left.isExist(a) and t.right.isExist(a), but that is purely speculative as you do not have a complete SSCCE for us to look at.
It is syntactically correct Java. But I don't see how it could possibly be doing what you intend.
It appears that the 'element' parameter is the thing you are searching for and the 'first' field in the current class is the root of the binary tree.
It's unclear if the key for the binary tree and search (in the Element class) is 'asset' or 'data'. The 'less than' test uses 'asset', while the 'greater than' test uses 'data'. It seems likely that both lines should use the same field. It might be that one of these two fields ('asset' or 'data') should not be referenced in this method at all. Maybe the last line of the method should be just 'return true;'?
(I suspect that the "stop condition" and the "code isn't symmetric" answers above are both incorrect. But I could be wrong: It's hard to tell with only the code given.)
I agree that infinite looping is likely: I suspect that you need to create a second 'search' function that accepts two 'Element' parameters -- one being the thing to search for (like the current 'element' parameter) and the other being the next Element to search -- the equivalent of current local variable 'c'. I would do the "Extract Method" refactoring on everything in the body of the current 'search' method except the first line, and then change the two recursive calls to use the new method.
(Some of this is speculative, based on me guessing what you want or intend, given limited information. So I could, of course, be quite wrong.)

null pointer exception

the value memanufacturer is retrieved from xml document using jdom and when this value is assigned to meman array it throws NullPointerException.
Element memanufacturer = (Element) row27.get(j9);
meman[0] = memanufacturer.getValue();
what could be the posssible mistake.
Thanks
Assuming the exception by the second line of code, there are two obvious possibilities:
memanufacturer may be null
meman may be null
We can't tell which of these is the case, but you should be able to.
EDIT: Okay, so now we know that meman is null, that's the problem. I would suggest you use a List<String> instead:
List<String> meman = new ArrayList<String>();
...
Element memanufacturer = (Element) row27.get(j9);
meman.add(memanufacturer.getValue());
Using a List<String> instead of an array means you don't need to know the size before you start.
However, the fact that you didn't understand the error suggests you should really read a good introductory Java book before going any further with a real project. You should definitely understand how arrays, collections etc work before dealing with XML and the like. It will save you a lot of time in the long run.

Smarter setter? Good or Bad Idea?

In a GWT solution. (so this is java code that is then compiled to javascript).
There are of course some classes.
Is it a good idea to make the setter check for Null on a String field?
something like this
public void setSomeField(String someField){
if (null != someField)
this.someField = someField;
else
this.someField = String.Empty;
}
Is this a good or bad idea? On the one had it will make coding easier as i wont have to check for null , on the other hand it would make me probably forget that I have to do this for other strings.
Thoughts?
Thanks
I say if such a logic is needed in your application, the setter is the place to put it. The main reason to have a get/set wrap around a private var is to be able to put logic around the access.
To answer the question of to default or not to default:
In my application it made sence to have a set of properties fall back to string.empty for display reasons. Although people could argue that the view should then cover these possibilities and check for nulls and display nothing, it was a lot of bloat all over my pages to do a check on every property.
That's why I started implementing SafeXX properties. So say I had 'myObj.Name' that could possibly have a null value, there would also be a property 'myObj.SafeName' that caught the null in the getter and returned a string.empty in stead. The little naming convention gives away that it is not the regular getter.
Here's something to consider. Would you expect this unit test to pass or fail?:
yourClass.setSomeField(null);
assertNull(yourClass.getSomeField());
If you're changing the null value to an empty string and returning that in getSomeField, then the client now has to check two conditions when testing...a String and a null String. Not a big deal, but what happens if you've got twenty String properties in the class...you'd probably better try to be consistent amongst all of the setters, and if you're not then the reason should probably be more obvious than just the documentation saying so.
There are certain conventions around getters and setters; certain expectations. If I call a setter on an object, then I usually expect the getter to return what I set. I don't expect it to return some representation of what I passed in that is more convenient for the class to work with internally. I don't care about the internals of the class, and don't want to.
If null really should be changed to "" for a valid reason (for example, it might mean "I don't care" and the default could be ""), go for it(but document it).
Otherwise, like if you just caught a NullPointerException and are trying to fix it this way, don't do it. If callers use obviously invalid values, the exception should be raised as soon as possible so that the caller notices the problem and fixes it before it bubbles up to a catastrophic, unexplainable error in a probably completely unrelated component.
In general, it is not a good idea to check for null values because the caller (the one who invokes the setter) may really want to set the value to null.
Suppose you query for 'someField' with this:
select * from ... where someField is null
If you set it as the empty string, the query above would fail.
If you don't want a field set to null, then don't set it to null.
This can be a good idea if you have no control over the code doing the setting, but if you do, it better to fix the problem at the source rather than put in work arounds like this.
That is hard to answer. On the first look it seems to make the usage better because you don't have to check for null all the time. But you loose the quality of null that means nothing is assigned. If you do String.Empty you already have ambiguity if someone gave you a String.Empty as parameter. Maybe it doesn't matter.
I personally (if at all) wouldn't do it in the setter. Inside your class null should have a value of its own. If you are for convenience a getter
return (this.someField != null) ? this.someField: String.Empty;
will do. You would keep the null internally to deal with but the outside has a more convenient method.
Generally and personally speaking I wouldn't do it. It looks good at first and makes a lot of things harder at later time.

Categories

Resources