Can a function end its caller's function? - java

Let's say we have the following two methods:
public static void repeat(){
while (1){
otherFunc();
}
}
public static void otherFunc(){
if (something){
//Here
}
}
Is there a way for, in the place of //Here, to cause a break or return in the repeat function?
Initially, I thought definitely not, because of the issue of scope. Also, if it was intended to be used like that, otherFunc could return a boolean and be placed in an if-statement to end the while-loop or the method.
However, I could not find anything to prove that it cannot have that behavior.
Is this possible?
Although I wrote this in Java, it would also be helpful to know if this stays true in C-languages also.

if can you change the code, do it like this:
public static void repeat()
{
while (otherFunc()) ;
}
public static boolean otherFunc()
{
if (something){
return true;
}
//more stuff...
return false;
}

In C you can use longjmp and setjmp functions but it is little bit tricky. More reading also on wikipedia http://en.wikipedia.org/wiki/Setjmp.h

Related

Boolean variable

I thought the default value of boolean is false? Why does it print the true statement instead?
My output is goodbye
public class Test {
public static void main (String [] args) {
if(false)
System.out.print("hello");
else System.out.print("goodbye");
}
}
Your code doesn't use the default value of boolean value.
You always print System.out.print("goodbye");, because this section is true.
To achieve this, use the following code
public class Test {
static boolean defaultValue;
public static void main(String[] args) {
System.out.println("Default value is "+defaultValue);
if(defaultValue)
System.out.println("hello");
else
System.out.println("goodbye");
}
}
What sweeper told you in a comment is correct. You seem to be under a wrong impression regarding the syntax I think. Take the following piece of code you gave as an example.
if (false) {
System.out.print("hello");
}
The code inside the if block will never run because the expression false will always evaluate to the boolean value false. You are asking Java to do the following: 'hey run this code if what I put inside the brackets evaluates to true but what you put inside the brackets will always evaluate to false. Thats why java will always run the code inside the else block in your example.
I hope this clears thing up a bit.

Can I use the Conditional Operators in a non-assignment situation in JAVA?

In case of assignment the situation is simple,
result = testCondition ? value1 : value2;
But what if I want to use it instead of an if statement?
for instance in a logging situation:
logger.shouldDebbug ? logger.log("logging") : (what to do if not?);
In the case I don't what to do anything in the case of false, can I still use this Operator?
Yes you can if you wrap them in a returning function, but no you shouldn't.
In your example of the logger, let your logger output to void, discard the input when debugging isn't enabled.
You do not want to riddle your code with all these logging checks.
Perform a check as least and as central as possible.
Either have a check in the logger.log function if debugging is enabled, or replace the logger with a dummy mock that does nothing except accept input and immediately discard it.
If you use standard logging frameworks like log4j you can set debugging levels, where you show only info or more serious, only warnings or more serious, only errors or more serious.
The same goes for other "quick" checks. If you find yourself using a certain pattern a lot, write a utility class for it with a static method if need be, so you have one place, where you have to change stuff, instead of 200 code points that you have to update when going to production.
You could use it if you insist, by defining a meaningless variable and take advantage of the functions' side-effects, but that's not a very good coding habit. It's purely a work-around.
For example:
public static boolean test() {
return 1>0;
}
public static int success() {
System.out.println("true");
return 0; // has no meaning whatsoever
}
public static int fail() {
System.out.println("false");
return 0; // has no meaning whatsoever
}
public static void main(String[] args) {
int meaningless = test() ? success() : fail();
}
Everything has been explained in comments, so I will put here only some idea:
public class Ternary {
private final boolean condition;
private Ternary(boolean condition) { this.condition = condition; }
public static Ternary of(boolean condition) { return new Ternary(condition); }
public Ternary onTrue(Runnable r) { if (condition) { r.run(); } return this; }
public Ternary onFalse(Runnable r) { if (!condition) { r.run(); } return this; }
}
Example of usage:
Ternary.of(o != null).onTrue(() -> doSomething()).onFalse(() -> doSomethingElse());
But simplier would be to write:
if (o != null) { doSomething(); } else { doSomethingElse(); }

Java recursive method difference

What is the difference between the following two methods:
public boolean recursionMethodOne(Node n) {
System.out.println(n.getValue());
return recursionMethodOne(n.next());
}
public void recursionMethodTwo(Node n) {
System.out.println(n.getValue());
recursionMethodTwo(n.next());
}
Which one do you use for recursion and what is the difference?
Thanks
Both your codes doesn't exits. You need to add a return for a test condition. For example:
public void recursionMethodTwo(Node n) {
if (n == null) {
// Standard way to exit a void function without executing remaing code
// note that return null; doesn't compile
return;
}
System.out.println(n.getValue());
recursionMethodTwo(n.next());
}
Returning a value or not depends on the kind of function.
For example if you need to calculate a factorial you need a result, if you need to print a list you don't.
So for your example seems that the method two is most closer to your needs.
Otherwise you need to ask yourself what is the returning boolean value of the function? If you have a nice answer to this question you can implement the code returning a value.

How to pass different enums as argument?

I have some enums, all different, and I want to create a function that can find or not if a string is one of enum variable name (not sure it's really understandable).
enum MYENUM {
ONE,
TWO;
}
enum MYENUM1 {
RED,
GREEN;
}
I want to do this (this is just for the example, my enum are more complicated):
if(isInEnum(MYENUM, "one")) ...
if(isInEnum(MYENUM1, "one")) ...
isinEnum function (the code is bad, it's just for understanding):
boolean isinEnum(enum enumeration, String search) {
for(enum en : enumeration.values()){
if(en.name().equalsIgnoreCase(search)) return true;
}
return false;
}
Is this kind of thing possible?
I think not, according to what I can read on the web, but maybe someone has a solution to do this, instead of making one loop for each enum.
Here is a way using reflection...
public class EnumFinder {
public static <T extends Enum<T>> boolean isInEnum(Class<T> clazz, String name) {
for (T e : clazz.getEnumConstants()) {
if (e.name().equalsIgnoreCase(name)) {
return true;
}
}
return false;
}
public static void main(String[] argv) {
System.out.println(isInEnum(MYENUM.class, "one")); // true
System.out.println(isInEnum(MYENUM1.class, "one")); // false
}
}
Your attempt in your answer was actually very close. The only difference is that Java needs an instance of the defining class in order to answers questions about an unknown type dynamically at runtime.
This may not be the cleanest solution because it uses exceptions in the normal program flow, but it is certainly short, because it avoids the loop:
boolean isinEnum(Class<T> enumClass, String search) {
try {
Enum.valueOf(enumClass, search);
return true;
} catch (IllegalArgumentException iae) {
return false;
}
}
Your question is a bit tough to understand, but I think I get the gist of it.
You might be making things a lot tougher on yourself than necessary.
Take a look at Java's map interface / data structure (in java.util) and see if that moves you closer to your solution:
java.util Interface Map<K,V>
If not, repost with any leg-work you've done and I'll see if I can help ya' further. ;-)

is there a equivalent of StringBuilder for boolean in java?

I want my custom functions to modify / toggle a boolean variable. Let's say that I have code like
if (OK2continue) { findANDclick(new String[]{"id", "menuButton"});}
if (OK2continue) { findANDclick(new String[]{"src", ".*homeicon_calendar.*"}); }
if (OK2continue) { findANDclick(new String[]{"src", ".*cycle_templates.*"});
I want to make sure that the flow of execution stops once any of the findANDclick functions toggles the variable OK2continue
I managed my functions to modify a String variable using StringBuilder.
Can I do the same for boolean type of variable?
I can't say it is equivalent. But using MutableBoolean offers you a mutable boolean wrapper, similar to the concept of StringBuilder a mutable sequence of characters. See this JavaDoc for details.
Push this code into its own method, and use a return:
if (findANDclick(new String[]{"id", "menuButton"})) return;
if (findANDclick(new String[]{"src", ".*homeicon_calendar.*"})) return;
if (findANDclick(new String[]{"src", ".*cycle_templates.*"})) return;
Given that all your method calls are the same, you could also use a loop:
String[][] buttons = {
{"id", "menuButton"},
{"src", ".*homeicon_calendar.*"},
{"src", ".*cycle_templates.*"},
};
for (String[] button: buttons) {
if (findANDclick(button)) return;
}
You might or might not find that more readable.
You need to clarify your reference to your usage of StringBuilder.
Assuming:
You pass reference of the StringBuilder to your method. String is changed in method. If this the case, then see #Gordon Murray Dent's answer.
Your boolean flag is visible in the method but is not passed. A simple Boolean will do.
package sof_6232851;
public class SideEffectingMethod {
static Boolean flag = false;
public static void main(String[] args) {
flag = true;
System.out.format ("flag is %b\n", flag);
clickMe();
System.out.format ("flag is %b\n", flag);
}
/** this method side-effects instance variable flag */
public static void clickMe () {
flag = !flag;
}
}
[edit list item #2 to reply to OP comment]:
Note that #2 is not really recommended. You mention your desire for "readable" code. Side-effecting methods works against that goal.
public class ReturnValuesForFunAndProfit {
public static void main(String[] args) {
presentUI();
}
public static void presentUI() {
if(!clickMe("woof")) return;
if(!clickMe("meow")) return;
if(!clickMe("hello")) return;
}
public static boolean clickMe (String blah) {
// your logic here; this ex. always returns true
return true;
}
}
Well, the concept of StringBuilder is to create a mutable and extendable String wrapper (meaning the string can be extended via append and the like :) ). You'd still have to pass it as a parameter to the method in order to modify it (or use a static var - not recommended).
Since boolean can't be extended, the only similarity would be the parameter to be mutable. So you can use MutableBoolean as Gordon suggested, but you'd still have to pass it.
Another option would be to return a boolean from findANDclick(...) and use the boolean opperators like: findAndClick(...) || findAndClick(...) || findAndClick(...) which would only execute the next findAndClick(...) if the previous returned false.
Since that option is somewhat hard to maintain, especially since you might have side effects in findAndClick(...) as well as being quite static and hard to read if you have more calls in there, you might want to use a list of function objects:
class FindAndClickExecutor {
public FindAndClickExecutor(String[] params) {...}
public boolean findAndClick() {...}
}
List<FindAndClickExecutor> faces = ...; //initialize appropriately
for( FindAndClickExecutor face : faces ) {
boolean ok2continue = face.findAndClick();
if( !ok2continue ) {
break;
}
}
Edit: since there seem to be other methods as well, you might use a more general list:
interface Executor {
boolean execute();
}
class FindAndClickExecutor implements Executor {
public boolean execute() {} // findAndClick code here, set parameters using constructor
}
class FindAndSelectOptionExecutor implements Executor {
public boolean execute() {} // findAndSelectOption code here
}
List<Executor> testCase1Sequence = ...; //initialize test case 1
List<Executor> testCase2Sequence = ...; //initialize test case 2
for( Executor ex : testCase1Sequence ) {
boolean ok2continue = ex.execute();
if( !ok2continue) {
break;
}
}
This example could also be expanded on, e.g. by using a more complex return value containing the continue flag and maybe more data (use interface here as well).
Edit 2: you could also use some scripting to define and the builder pattern to generate the list of executors for each test case.

Categories

Resources