Return statement in void method - java

I have the following method that returns void and I need to use it in another method that also returns void.
Can I do the following?
public void doSomething(){}
public void myMethod()
{
return doSomething();
}
Thanks for all your comments, but let me be more specific
I only doSomething if something happens, otherwise I do other things
public void doSomething(){}
public void myMethod()
{
for(...)
if(somethingHappens)
{
doSomething();
return;
}
doOtherStuff();
}
Instead of the code above, can I just write return doSomething(); inside the if statement?

No, just do this:
public void doSomething() { }
public void myMethod()
{
doSomething();
}
or in the second case:
public void doSomething() { }
public void myMethod()
{
// ...
if (somethingHappens)
{
doSomething();
return;
}
// ...
}
"Returning void" means returning nothing. If you would like to "jump" out of myMethod's body, use return; The compiler does not allow writing return void; ("illegal start of expression") or return doSomething(); ("cannot return a value from method whose result type is void"). I understand it seems logical to return "void" or the "void result" of a method call, but such a code would be misleading. I mean most programmers who read something like return doSomething(); would think there is something to return.

void functions don't/can't return anything as such. Simply call the function.

No, returns are unnecessary in Java void functione. Instead, do this:
public void myMethod(){
doSomething();
}
You could put a return after doSomething() if you wanted, but as I said it'd be unnecessary.

You either have to just use doSoemthing like the others have pointed out OR
public (insert data type like int, double, string, etc) myMethod()
{
return doSomething();
}
If do something returns an int
// if you wanted to take 2 numbers and add them
public void myMethod()
{
valueOfX+Y = doSomething();
}
public int doSomething()
{
x = 2;
y = 2;
return X+Y;
}
hope that clears it up

If
the condition (somethingHappens) actually depends on what doSomething() did
and doSomething() is a method you can modify
then you should consider making it return the boolean (or any suitable type) value which tells the callee method if it happened or not.
Code would then look somewhat like this:
public boolean doSomething() {
// internal working
if (internalCondition) {
// something done here
return true;
}
// not done ;
return false;
}
public void myMethod()
{
for(...)
if (doSomething())
{
return;
}
// didn't hit 'doSomething() == true'
doOtherStuff();
}

Related

Passing method as parameter to another method in Java

I have 3 methods which does the same thing but at the end the 3 methods call a diff method. So instead of having 3 methods, I want to have a single method which will accept a method as parameter which it will call at the end
How can I do this please, I tried having a look at the java reflection that did not work, Not sure if interfaces is the right way for this.
please suggest
Thanks
R
class A {
doSameThingA(int x) {
//do same thing with x
methodA()
}
doSameThingB(int x) {
//do same thing with x
methodB()
}
doSameThingC(int x) {
//do same thing with x
methodC()
}
//I WANT TO WRITE A SINGLE FUNCTION replacing the above three
doSameThing(int x, Method method) {
//do same thing with x
method()
}
}
An operator exists in java known as the double colon operator. It is also known as the method reference operator because it refers to methods and this feature I believe will allow you to solve your problem by parameterizing your method. Kind of like lambdas.
class A {
public static void main(String... args) {
new A().doSameThing(1, MethodClass::printSomething);
}
void doSameThing(int x, Runnable method) {
method.run();
}
}
class MethodClass {
public static void printSomething() {
System.out.println("Hello World");
}
}
The above is an example. MethodClass contains the method you want to run (such as your methodA(), methodB(), methodC(), and so forth. The doSameThing method takes in a Runnable, which is a functional interface that takes no parameters and returns no value. By passing the method printSomething, which takes no parameters and returns no value, we can run that method within the doSameThing method.
Of course, the type of functional interface you use would depend on what your methods are designed to accomplish.
Furthermore, if your other methods (methodA(), methodB(), ...) aren't used anywhere else in your code, you can implement the runnable interface in place with an anonymous class. Below is the previous example written in that form:
class A {
public static void main(String... args) {
new A().doSameThing(1, new Runnable() {
public void run() {
System.out.println("Hello World");
}
});
}
void doSameThing(int x, Runnable method) {
method.run();
}
}
Since Runnable is a functional interface, you could even go as far as using a lambda expression for this.
class A {
public static void main(String... args) {
new A().doSameThing(1, () -> {
System.out.println("Hello World");
});
}
void doSameThing(int x, Runnable method) {
method.run();
}
}
If you can use java 1.8 (and above), you can pass the method as a function
Function<Integer> method = (x) -> { //do something here }
And in doSameThing
doSameThing(int x, Function<Integer> fn) {
fn.apply(x)
}

How can I split a methods functionality using an enum as condition?

I have the following code:
enum Example {
ex1,ex2
}
public void method(Example exType) {
if(exType.equals(ex1)) {
//do similar stuff
method2(exType)
} else if(exType.equals(ex2)) {
//do similar stuff
method2(exType)
} else {
//throw exception
}
}
public void method2(Example exType) {
if(exType.equal(ex1)) {
//do similar stuff
} else if(exType.equals(ex2)) {
//do similar stuff
} else {
//throw exception
}
}
The problem is the method calls other methods that behave in the same way. So it doesn't look very good as an implementation. How can i split this behavior?
Edit:
Using enum is not mandatory. Similar means they call same-named method and update same-named fields, one just does less than the other. Inside the //Do similar stuff it calls another method with the enum as a parameter and that method has the same structure of code.
Edit 2:
Added some more code. This just doesn't seem like the right approach
It's worth remembering that Enum values are objects rather than int values like they are in other languages. This allows you to use polymorphism with them removing the need for switch statements in many cases.
interface IExample {
// you can use interfaces if you need them
void method1();
}
enum Example implements IExample {
ex1 {
public void method1() {
// do stuff
method2();
}
public void method2() {
// do other stuff
}
},
ex2 {
public void method1() {
// do stuff
method2();
}
public void method2() {
// do other stuff
method3(); // not all methods need to be different.
}
};
public abstract void method1(); // only needed if you don't use an interface
public abstract void method2(); // does it need to be public as well?
public void method3() { /* added as an example */ }
}
There is no need to throw an exception as your code won't compile if you forget to provide an implementation for a new enum value.
The IExample might be an existing interface or it might be needed for extention. e.g.
class Example2 implements IExample {
int x;
public Example2(int x) { this.x = x; }
public void method1() {
// uses x
}
}
Now you can write
IExample e = Example.ex1; // fixed value
IExample e2 = new Example2(5); // extendable at runtime.
Why would you do this?
There is an example I use.
SystemTimeProvider - a singleton implemented as an enum
SetTimeProvider a class where each instance can have a different fixed time for testing purposes.
I would use a switch instead. Also with Enums you can use ==, but you don't need that when using a switch. What about this!
enum Example {
ex1,ex2
}
public void method(Example exType) {
switch (exType) {
case ex1:
// do 1
break;
case ex2:
// do 2
break;
default:
//throw exception
}
}
First of all its better to use switch case because in case in future there are more no of enums and then more no of if conditions then code becomes less readable.
One of the approach could be
enum Example {
ex1,ex2
}
public void method(Example exType) {
switch (exType) {
case ex1:
methodEx1();
break;
case ex2:
methodEx1();
break;
default:
//throw exception
}
}
Function methodEx1(); and methodEx2(); add all the codes corresponds to enum in a single function instead of writing of multiple function for same enum.

How to jump to another method?

Is there any function in java that lets you jump to another method?
This is an example how it should work:
if (boolean expression(){
jump to public void something;
if (boolean expression) {
jump to public void something2;
} else{
jump to public void 3;
}
This is needed for a program that checks 3 numbers, and they have different methods linked to them.
If by jump, you mean calling a method:
if (boolean expression(){
something();
if (boolean expression(){
something2();
}
else{
something3();
}
Simply invoke it, in your example
if (boolean expression(){
something();
} else if (boolean expression(){
something2();
} else{
something3();
}
instead of jump to public void something just call something()
There is no syntax called "jump to" although you can easily call a method by firstly making a method.
public void myMethod(){
// do something
}
now when you have done this, you call it from another method by invoking it's name myMethod();. You might know that a method can either return a variable or return nothing (void) if you give it a return-type you MUST return a variable with the same type as your method.
For example:
public int oneplusone(){
int integer = 1 + 1;
return integer;
}
and a void would be like this:
public void oneplusone(){
int integer = 1 + 1;
System.out.println(integer);
}
When you've specified your method you need to call it by invoking its name from another place in your program. Final example:
public class Snippet(){
public static void main(String args[]){ // THIS IS THE MAIN METHOD OF YOUR PROGRAM!
Snippet snippet = new Snippet();
System.out.println(snippet.oneplusone());
}
public int oneplusone(){
int integer = 1 + 1;
return integer;
}
}
I suggest you should check out thenewboston java tutorials explaning java for beginners. Good luck!
if you have the mothod call in the class just call the method like
something(int i);
if your method is in another class make sure you have an object of that class if the method isn't static and call your method
Foo foo = new Foo();
foo.something(10);

Can I use an If statement to check which method made the call?

I want to make an if statement that checks to see which method made the call to a secondary method.
I will write what i want in pseudo code so you can see what I mean.
public static void methodOne() {
methodToCall();
}
public static void methodTwo() {
methodToCall();
}
public static void methodThree() {
methodToCall();
}
public static void methodToCall() {
if (methodOne made the call == true) {
execute this
} else if (methodTwo made the call == true){
execute this
} else if (methodThree made the call == true){
execute this
} else {
System.out.println("How did you get here?");
}
}
That's about the gist of it. I want a simple check to see which method made the call so I can choose which operation is relevant to the call.
Is this possible?
If it is not possible, is there a work around?
This is called 'state orientation', and it was debated extensively in the 1970s, possibly even the 1960s. The conclusion was that if you need to know this sort of thing you are already doing something seriously wrong, by introducing a two-way dependency into the code. What happens for example when you add another caller?
Use three short methods, instead of combining the logic of three short methods into one larger method. Once the short methods are created Just call the appropriate method from each calling method.
public static void methodOne() {
methodToCall1();
}
public static void methodTwo() {
methodToCall2();
}
public static void methodThree() {
methodToCall3();
}
public static void methodToCall1() {
int x = 0;
x = x - 3; //some custom logic to prep argument
commonLogic(x);
}
public static void methodToCall2() {
//Method 2 logic
int x = 0;
x = x + 3; //some custom logic to prep argument
commonLogic(x);
}
public static void methodToCall3() {
//Method 3 logic
int x = 0;
x = x * 3; //some custom logic to prep argument
commonLogic(x);
}
public static void commonLogic(int arg1){
//peform common logic
}
If these three methods would contain duplicate code, abstract the duplicate code into another method then call that method from within each of the smaller methods. The idea is to prepare the arguments to call the common function in each of the three smaller functions, then call the common function with those arguments.
A great deal of the abstraction afforded by methods comes from the fact that they do not need to know who is calling them, so the answer to your question is "no". It does not mean that you cannot make it work, though: make the callers pass some sort of a token (say, an enum value) identifying themselves to the callee. This would let you dispatch on that identity inside your method's implementation:
enum CallerContext {CALLER1, CALLER2, CALLER3};
...
public static void methodToCall(CallerContext context) {
...
}
This is not the most Object-Oriented way of doing things, however: very often, a better approach would be letting the callers supply the logic to be executed, rather than supplying a token identifies that logic. See Visitor Pattern for details on that approach.
You can do it by examining the call stack via Thread.getStackTrace():
public static void methodToCall(Action action) {
String callingMethod = Thread.currentThread().getStackTrace()[2].getMethodName();
if (callingMethod.equals("methodOne")) {
execute this0
} else if (callingMethod.equals("methodTwo")) {
execute this
} else if (callingMethod.equals("methodThree")) {
execute this
} else {
System.out.println("How did you get here?");
}
}
but you shouldn't - it's a bit anti-OO. Instead, change your method signature to something like this:
public enum Action {ONE, TWO, THREE}
public static void methodToCall(Action action) {
if (action == ONE) {
execute this
} else if (action == TWO) {
execute this
} else if (action == THREE) {
execute this
} else {
System.out.println("How did you get here?");
}
}
If you end up using an enum, then make sure to take advantage of the fact that enums in Java are no less than singleton instances of classes. Therefore you can declare the method as abstract in the enum definition and then override it in each instance, instead of passing the enum as a paramater to some method defined outside of the enum's context.
So it would look something like:
enum Method {
Mode1 {
#Override
void call() {
// do stuff
}
}, Mode2 {
#Override
void call() {
// do stuff differently
}
}, Mode3 {
#Override
void call() {
// do stuff even more differently
}
};
abstract void call();
}
And then you either don't need your wrapping methods, or, if they were supposed to do anything more, you write:
public static void methodOne() {
// some code
Method.Mode1.call();
// some code
}

How can I dispatch based on a value of a parameter in Java?

There is a recurring pattern when I have for example an enum or a String and I want to dispatch based on the value of that parameter:
public void myMethod(String parameter) {
if(parameter.equals(something)) {
doSomething();
} else if(parameter.equals(somethingElse)) {
doSomethingElse();
}
}
What is the idiomatic way to get rid of the lengthy if or case statements? I'm thinking about something like the single dispatch generic functions in python but I want to dispatch based on value not on type.
#fun.register(int)
def _(arg, verbose=False):
if verbose:
print("Strength in numbers, eh?", end=" ")
print(arg)
#fun.register(list)
def _(arg, verbose=False):
if verbose:
print("Enumerate this:")
for i, elem in enumerate(arg):
print(i, elem)
I find that this is most common when dealing with forms (as an example) that have multiple "actions". Although this may seem overkill, a lot of times it's actually much cleaner (and in many ways, easier) to simply "register" action handlers.
public class Dispatcher {
private Map<String, ActionHandler> actionHandlerMap = new HashMap<String, ActionHandler>();
public void perform(String action) {
ActionHandler handler = actionHandlerMap.get(action);
if (null == handler) {
// no handler - throw an exception?
}
handler.execute();
}
public void addActionHandler(ActionHandler handler) {
actionHandlerMap.put(handler.getAction(), handler);
}
}
public interface ActionHandler {
public String getAction();
public void execute();
}
It is absolutely more code, but it's extensible, clean, and allows for a better separation of concerns. It's also much more easily testable which is always a good thing.
you could use method overriding in java.. so the equivalent should be something like
public void doSomething(String arg) {
//do something when param is string
}
public void doSomething(List<String> arg) {
//do something else when param is a List of String
}
In Java enum is a class as well, so you could extextend it and use it as :
interface Doable {
void doSomething();
}
enum Stuff implements Doable {
ONE() {
public doSomething() { System.out.println("do one");};
},
TWO() {
public doSomething() { System.out.println("do two");};
}
}
Doable s = Stuff.valueOf("ONE");
s.doSomething();

Categories

Resources