While parsing internet content of HTML pages there is common thing that due to mistakes in HTML code some chars are absent - for example closing " or > or something else. And when a parser meet this situation sometimes it occurs "out of bounds exception". I am thinking about the best way to work around this issue - try\catch is good but slow enough. A series of if/else perhaps would be better but may be you know some mechanism that allow to skip this abnormal situations?
You can always use an if else chain, testing for each necessary char at a time. A while loop could probably also used to do this. Those are the best two I know of.
To test if a char exists with Strings, use the following tests
int exists = s.indexOf('<'); //Or any char
int close = s.lastIndexOf('>'); //Or other pair of char
if (exists != -1 && close != -1) { //Could be modified depending on the situation
//Perform logic
}
To test for '"'s, or any other identical braces I would do this
int exists = s.indexOf('"');
int close = s.lastIndexOf('"');
if (exists != close || (exists != -1 && close != -1) {
//Perform logic
}
Related
I'm learning about exceptions in java. I have come across the following problem:
String bigstring = myscanner.nextLine();
String[] splited = bigstring.split("\\s+");
try {
smallstring1 = splited[0];
smallstring2 = splited[1];
smallstring3 = splited[2];
} catch(java.lang.ArrayIndexOutOfBoundsException exc) {
smallstring3 = null;
}
This would work if the user wants to type 2 words only.
What if he wants to type one word?
Can we somehow specify a value which we get in error after the colon?
Like:
java.lang.ArrayIndexOutOfBoundsException: 2
or
java.lang.ArrayIndexOutOfBoundsException: 1
Can we somehow use (for this example) this "2" or "1" in try/catch block?
java.lang.ArrayIndexOutOfBoundsException is not a exception designed to be recoverable. It conveys a programming error.
So rather than trying to understand the index that causes problem in the catch, you should rather ensure that the exception doesn't occur.
In your case you should check the size of the array before trying to get the value of it.
Here is an example :
int arraySize = splited.length;
if (arraySize == 3){
smallstring1=splited[0];
smallstring2=splited[1];
smallstring3=splited[2];
}
else if (arraySize == 2){
smallstring1=splited[0];
smallstring2=splited[1];
}
else if (arraySize == 1){
smallstring1=splited[0];
}
You probably shouldn't use exceptions for normal program flow. Exceptions should usually be "exceptional".
Anyway, although you cannot do that, you can use if statements inside your catch block. You can also check splited.length to check how big the array is.
Which is better in terms of best practice / efficiency?
if (x == 1
&& y == 1
&& z == 1)
{ do things }
or
if (x != 1 ||
y != 1 ||
z != 1)
{ don't do things and go to a different bit of logic.}
Is there any difference in efficiency when short circuiting ANDs and ORs? Is it (generally) better to check positively or negatively when multiple logical assertions need to be made?
For pure optimization of the code it depends case-by-case. The scenario that will on average do the least amount of comparisons.
For code design it is also case-by-case. The if-cases should match what you are actually looking for. A function that tests if a string is inputted correctly for example. (the tests are made up)
public boolean isValidString (string s) {
if (s.isEmpty())
return false;
if (s.length() < 12)
return false;
if (s...)
return false
return true;
}
In this case the most logical approach is the ||. It could be written.
public boolean isValidString (string s) {
if (s.isEmpty() || s.length() < 12 || s...)
return false;
return true;
}
With http://en.wikipedia.org/wiki/De_Morgan%27s_laws this could be rewritten to not and. However it is not what we want to test, even though they yield the same result.
So stick to the logical approach in general cases.
If you think about efficiency then think about how often each case will occur. The most likely one should be put in front so the whole expression is shortcircuited immediately.
Better you use "==" instead of going for "!=".
This is also recommended with PMD.
The following is good and improves redability.
If(true){
//
}else{
//
}
than
If(!true){
//
}else{
//
}
Well, in some JVM implementations boolean values are stored as integers in the JVM. int value 1 meaning true and int value 0 meaning false. Also, comparison logic at processor level is architecture dependent. Some machines might subtract 2 operands, then add and then compare, others might compare byte by byte etc.. So, unless you are looking at a specific hardware architecture (which you shouldn't.. atleast for java programming language), I don't think this matters much..
I'm getting what I think is a spurious warning from Eclipse on the following code, used to count the number of times a given element appears in a binary tree:
public int count(E item)
{
int count = 0;
Node crnt = root;
//First seek the item in the tree
while (crnt != null)
{
int compare = crnt.data.compareTo(item);
if (compare > 0)
crnt = crnt.right;
else if (compare < 0)
crnt = crnt.left;
else
{
//Shortcut if not allowing duplicate entries
if (!allowDuplicates)
return 1;
count++;
//Duplicates are always stored to the right
while (crnt != null) // <--Warning appears here
{
crnt = crnt.right;
if (crnt.data.compareTo(item) == 0)
count++;
else
break;
}
}
}
return count;
}
(I could show you the Node class, but it's nothing surprising. Just an `E for the data and two Node pointers for left and right children.)
Am I missing something or is this a bug in Eclipse? Because it seems like it's perfectly possible, and in fact expected for crnt to be possibly null in this case, once it runs out of right children. Granted it won't be null the first time it hits this loop, but usually the IDE is smart enough to realize when the value of the variable changes within the loop. Not this time, however. Eclipse is suggesting I put a #SuppressWarnings("null") on this, or I could go into the settings and turn off this warning altogether, but I don't think it should be necessary, and I hate suppressing or ignoring warnings where they might be useful.
crnt will still be different from null because it is in the else clause of the if-elseif-else statement that might change crnt. Its value will never have changed when it hits the second while statement.
It's doing exactly as it should: telling you that the value of crnt will never be null when that code hits and that the additional check in the while unnecessary is.
Per avice by David Wallace: there is no possibility that the inner loop will be null because the crnt object is already accessed prior to that by the line int compare = crnt.data.compareTo(item);, essentially forming a prerequisite that crnt must not be null.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
The code:
public String getTemperatureMessage(double temp)
{
if(temp < 32)
return "Freezing";
else if(temp < 60)
return "Brr";
else if(temp < 80)
return "Comfortable";
else
return "Too hot";
}
Regarding the code snippet above, the else ifs are technically superfluous and don't change the behavior at all. However, I tend to like to put them in there to emphasize that the conditions are exclusive. What are your thoughts? Unnecessary or more clear?
The only feasible alternative in this particular case is to grab the conditional operator ?:.
public String getTemperatureMessage(double temp) {
return temp < 32 ? "Freezing"
: temp < 60 ? "Brr"
: temp < 80 ? "Comfortable"
: "Too hot";
}
Left behind the question how that's readable to starters.
References
JLS 15.25 Conditional Operator ?:
The operator is right-associative, thus such nesting of the operator will work "as expected"
Related questions
To ternary or not to ternary?
It depends on a lot of things like how complex your code is. With a simple example like this, I'd put the returns on the same line as the ifs, and not use elses. The structure and behaviour is clear:
public String getTemperatureMessage(double temp)
{
if(temp < 32) return "Freezing";
if(temp < 60) return "Brr";
if(temp < 80) return "Comfortable";
return "Too hot";
}
When I have more complex code I find it useful to not break out from the nesting with returns or continue/break, but to assign to state or result variables. I will then also include {} even if the block is a single statement, mostly to keep the consistency in how the structure is represented in code, but also to slightly reduce the risk that later edits will forget to change a statement to a block.
If this example was more complex, I'd probably code it like this:
public String getTemperatureMessage(double temp) {
String result;
if(temp < 32) {
result = "Freezing";
} else {
if(temp < 60) {
result = "Brr";
} else {
if(temp < 80) {
result = "Comfortable";
} else {
result = "Too hot";
}
}
}
return result;
}
If a function has multiple "successful" return values, I'll use if/else to select among them. If a function has a normal return value, but one or more ways that may abnormally exit early, I generally won't use an "else" for the normal path. For example, I think it's far more "natural" to say:
int do_something(int arg1)
{
if (arg1 > MAX_ARG1_VALUE)
return ARG1_ERROR;
... main guts of code here
return 0;
}
than to say:
int do_something(int arg1)
{
if (arg1 > MAX_ARG1_VALUE)
return ARG1_ERROR;
else
{
... main guts of code here
return 0;
}
}
or
int do_something(int arg1)
{
if (arg1 <= MAX_ARG1_VALUE)
{
... main guts of code here
return 0;
}
else
return ARG1_ERROR;
This distinction becomes especially significant if there are multiple things that can "go wrong", e.g.
int do_something(int arg1)
{
if (arg1 > MAX_ARG1_VALUE)
return ARG1_ERROR;
... some code goes here
if (something_went_wrong1)
return SOMETHING1_ERROR;
... more code goes here
if (something_went_wrong2)
return SOMETHING2_ERROR;
... more code goes here
if (something_went_wrong3)
return SOMETHING3_ERROR;
return 0;
}
Nested 'if/else' statements in such cases can get ugly. The most important caveat with this approach is that any cleanup code for early exits must be given explicitly, or else a wrapper function must be used to ensure cleanup.
Some would say that multiples return would be the problem here. But it's not really my point.
For my point of view, the if/else if is really important, because even if in your case you return some value, removing the elses would mean that you wouldn't put them anyway, and that would mean a totally different thing if the returns were not here.
Plus, imagine someday someone want to edit your code, and clean it up for a single return, this person could misunderstand your code and do a grave mistake like this :
public String getTemperatureMessage(double temp){
String message;
if(temp < 32)
message = "Freezing";
if(temp < 60)
message = "Brr";
if(temp < 80)
message = "Comfortable";
else
message = "Too hot";
return message;
}
To clarify my point of view, keep the elses, it keep your code clear.
For simple 1-liners I tend to leave out the else but if there's more complex if blocks I tend to prefer the else to make it clear that the conditions are mutually exclusive.
public String getTemperatureMessage(double temp)
{
String retval = null;
if(temp < 32)
retval = "Freezing";
else if(temp < 60)
retval = "Brr";
else if(temp < 80)
retval = "Comfortable";
else
retval = "Too hot";
return retval;
}
For a simple if statement without too many lines of code having multiple returns is no problem. However, nothing infuriates me quite so much as:
function doTemperatureCalculations(double temperature) {
if (temperature < 20) {
/*
Gazillion lines of code here .....
*/
return "Very cold!";
} else if (temperature < 40) {
/*
Another gazillion loc .....
*/
return "Summer in the North Pole.";
} else {
/*
Multiple returns embedded throughout ....
*/
}
}
In this case it is more clear. In the general case you may want to leave the elses off as they can contribute to more nesting and code complexity. For example:
if (error condition) {
do some stuff;
return;
} else {
do stuff;
if (other error condition) {
do some stuff1;
return;
} else {
do some other stuff;
return
}
}
The code below keeps the level of nesting down which reduces code complexity:
if (error condition) {
do some stuff;
return;
}
do stuff;
if (other error condition) {
do some stuff1;
return;
}
do some other stuff;
return;
In your example it is easy either way. But in many cases you would be better off using a lookup table for this sort of thing and reading the values from a file/database. For efficiency in C often this would be coded as an array of structs.
The else does add some clarity in that it makes it clear that the cases are mutually exclusive. However the idiom of returning like you do is obvious to many programmers, so either way the majority will know what you meant.
I can think of an advantage of the elses. If you want to add a new last case, without the elses you might forget to add an if to the currently "Too Hot Condition" if say you wanted to add "Dying" at 120 or something. while with the elses you know that you need the final else to be in front of "Dying" so you will be more likely to think about putting the else if in front of "Too Hot". Also if you just put an else on "Dying" you will get a compile error which forces you to think.
Personally, I think the elses are unnecessary. Since this question is tagged as [language-agnostic], I'm going to provide a couple of examples of how I would write it:
def temperature_message(temp)
return 'Freezing' if temp < 32
return 'Brr' if temp < 60
return 'Comfortable' if temp < 80
'Too hot'
end
This is typical guard clause style, which both I personally and the Ruby community in general use quite often.
def temperature_message(temp)
case
when temp < 32
'Freezing'
when temp < 60
'Brr'
when temp < 80
'Comfortable'
else
'Too hot'
end
end
This is a typical switch as you would find it in some less powerful languages. This is probably one that I would not use, I would refactor it like this:
def temperature_message(temp)
case temp
when (-1.0/0.0)...32
'Freezing'
when 32...60
'Brr'
when 60...80
'Comfortable'
else
'Too hot'
end
end
Although I must admit I still find the first one easiest to read.
Since this is basically a mapping table, I would try to format it as such, so that everybody who reads the code, immediately sees the "table-ness":
def temperature_message(temp)
case temp
when (-1.0/0.0)...32 then 'Freezing'
when 32...60 then 'Brr'
when 60...80 then 'Comfortable'
else 'Too hot'
end
end
This also applies to your original Java implementation:
public String getTemperatureMessage(double temp) {
if(temp < 32) return "Freezing";
if(temp < 60) return "Brr";
if(temp < 80) return "Comfortable";
else return "Too hot";
}
Of course, since it is basically a mapping table, you might just as well implement it as a map:
def temperature_message(temp)
{
(-1.0/0.0)...32 => 'Freezing',
32...60 => 'Brr',
60...80 => 'Comfortable',
80..(1.0/0.0) => 'Too hot'
}.detect {|range, _| range.include?(temp) }.last
end
The redundant elses make me cringe. The extra syntax and indentation makes it harder for me to read. I just got through removing a bunch of these from some code I inherited.
Most cases of redundant code are mistakes, so by implication a redundant 'else' looks like a mistake to me even if you put it there on purpose. The impression I get is of code that was originally written without embedded returns, then someone rewrote it to have the embedded returns, but they were too lazy to remove the elses.
A single if/return is easy to understand; so are 4 in a row. It's "that case is done; let's move on". A long chain of if/elses can be a pain to read; you need to read all the way to the bottom before you find out what happens. The saving grace is it allows a single return to be used -- a feature that is overrated IMO but I'll admit it does provide some value. However a long chain of if/elses combined with returns mixed in amongst the elses is the worst of both worlds -- all the disadvantages of multiple returns, and made to look like one large construct you have to get in your head all at once. Ugh.
From a theoretical perspective consider this: The zone between the return and the else is essentially unreachable code. Sure, it only contains whitespace, but the zone shouldn't even be there at all.
Finally, an example of if/return/else taken to its redundant conclusion. I've seen a few of these lately. Why in the world is there an else block? The code in the else block executes under the same conditions as the code directly after it:
...
if (temp < 35)
{
foo.status = TOO_COLD;
return;
}
else
{
foo.status = TEMP_OKAY;
}
launch_the_rocket(now);
return;
I agree that the elses makes it more clear. The final else especially helps to make a visual distinction between the case where every branch has a return, and the cases where only some branches have a return (which could be a smell).
There's no point. You're adding needless semantic and other overheads for absolutely zero benefit. When you return, you return and control is over. Pretending anything else is superfluous and just makes you look like you don't know what the return statement does.
Who uses IF/ELSE IF... when you can use a SWITCH statement?
My preference is for the single RETURN statement - multiple return statements can make debugging a pain...
I don't think I'd write in this way in the first place, but going along with the premise, I'm guessing that any compiler would crank out the same code whichever method you chose to write, so there is no technical reason that I can think would favour one over the other.
The argument is therefore Single or Compound statement.
I think the rule of "least surprise" should be used, which in this case would call FOR the superfluous else statements to be included.
PS. I would always send a temperature in degrees centigrade, oops, just broke your function!
it's good. without "else", this line
if(temp < 80)
return "Comfortable";
would be unconvincing. with "else", it's clear that there are other preconditions.
I prefer case statements myself but that would make this a language specific topic and not language-agnostic topic.
Dim Temp As Integer
Dim Message As String
Select Case Temp
Case Is < 32
Message = "Freezing"
Case Is < 60
Message = "Just Right"
Case Is < 80
Message = "Too Hot"
Case Else
Message = "What was I doing?"
End Select
I find these alot easier to read then if..else statements.
I've heard that using while(true) is a bad programming practice.
So, I've written the following code to get some numbers from a user (with default values). However, if the user happens to type in -1, then it will quit the program for them.
How should this be written then without a while(true)? I can think of a condition to make the while loop go off that will get caught right away without continuing on until the next iteration?
Here is how I have it now:
public static void main(String[] args)
{
System.out.println("QuickSelect!");
while (true)
{
System.out.println("Enter \"-1\" to quit.");
int arraySize = 10;
System.out.print("Enter the size of the array (10): ");
String line = input.nextLine();
if (line.matches("\\d+"))
{
arraySize = Integer.valueOf(line);
}
if (arraySize == -1) break;
int k = 1;
System.out.print("Enter the kth smallest element you desire (1): ");
line = input.nextLine();
if (line.matches("\\d+"))
{
k = Integer.valueOf(k);
}
if (k == -1) break;
List<Integer> randomData = generateRandomData(arraySize, 1, 100);
quickSelect(randomData, k);
}
}
while (true) is fine. Keep it.
If you had a more natural termination condition, I'd say to use it, but in this case, as the other answers prove, getting rid of while (true) makes the code harder to understand.
There is a Single Entry Single Exit (SESE) school of thought that suggests that you should not use break, continue or abuse exceptions to do the same for some value of abuse). I believe the idea here is not that you should use some auxiliary flag variable, but to clearly state the postcondition of the loop. This makes it tractable to formerly reason about the loop. Obviously use the stands-to-reason form of reasoning, so it is unpopular with the unwashed masses (such as myself).
public static void main(String[] args) {
...
do {
...
if (arraySize == -1) {
...
if (k != -1) {
...
}
}
} while (arraySze == -1 || k == -1);
...
}
Real code would be more complex and you would naturally(!) separate out the inputing, outputting and core "business" logic, which would make it easier to see what is going on.
bool exit = false;
while (!exit) {
...
...
if (k == -1) {
exit = true;
}
else {
List <Integer> ....;
quickselect(.......);
}
}
But as has been said before, your while loop is a valid usage in this situation. The other options would simply build upon the if statements to check for the boolean and exit.
While having a loop like this is not technically wrong, some people will argue that it is not as readable as the following:
bool complete = false;
while (!complete)
{
if (arraySize == -1)
{
complete = true;
break;
}
}
Additionally, it is sometimes a good idea to have a safety loop counter that checks to make sure the loop has not gone through, say, 100 million iterations, or some number much larger than you would expect for the loop body. This is a secure way of making sure bugs don't cause your program to 'hang'. Instead, you can give the user a friendly "We're sorry but you've discovered a bug.. program will now quit.." where you set 'complete' to true and you end the program or do additional error handling. I've seen this in production code, and may or may not be something you would use.
while ( true ) is perfectly fine here, since the condition is really "while the user doesn't want to quit"!
Alternatively you could prompt for both the inputs on one line to simplify the logic, and use "q" for quit: this allows you to refactor the loop to "while ( !line.equals("q") )".
The problem is that you're doing an awful lot in that loop, rather than separating the functionality into simple methods.
If you want to stick to a procedural approach, you could move the reading of the array size and k into separate methods, and use the fact that the result of an assignment is the assigned value:
for (int arraySize; ( arraySize = readArraySize ( input ) ) != -1;) {
final int k = readKthSmallestElement ( input );
List<Integer> randomData = generateRandomData(arraySize, 1, 100);
quickSelect(randomData, k);
}
However that's still a bit ugly, and not well encapsulated. So instead of having the two != -1 tests on separate variables, encapsulate arraySize, k and randomData in an object, and create a method which reads the data from the input, and returns either a QuickSelect object or null if the user quits:
for ( QuickSelect select; ( select = readQuickSelect ( input ) ) != null; ) {
select.generateRandomData();
select.quickSelect();
}
You might even want to go to the next stage of creating a sequence of QuickSelect objects from the input, each of which encapsulate the data for one iteration:
for ( QuickSelect select : new QuickSelectReader ( input ) ) {
select.generateRandomData();
select.quickSelect();
}
where QuickSelectReader implements Iterable and the iterator has the logic to create a QuickSelect object which encapsulates arraySize, k, the list and the quick select operation. But that ends up being quite a lot more code than the procedural variants.
I'd only do that if I wanted to reuse it somewhere else; it's not worth the effort just to make main() pretty.
Also note that "-1" doesn't match the regex "\\d+", so you really do have an infinite loop.
If you really don't like while(true) you can always go for for(;;). I prefer the latter because it seems less redundant.