英文:
How to create a function that can add or subtract numbers based on a given parameter? And is that a good practice?
问题
以下是翻译好的内容:
我对Java相对陌生,正在尝试使用Java代码。我有两个函数,一个函数用于相加两个整数,另一个函数用于相减两个整数。它们之间唯一不同的是符号(+或-)。我考虑创建一个函数来统一加法和减法。
例如:
public class Foo {
public int add(int x, int y) {
return x + y;
}
public int subtract(int x, int y) {
return x - y;
}
// 不是实际的代码,只是为了展示意图
private int addOrSubtract(int x, int y, someType sign) {
return x sign y;
}
// 目标是能够像这样使用addOrSubtract(不是实际的代码,只是为了展示意图):
// public int subtract(int x, int y) {
// return addOrSubtract(x, y, -);
// }
}
我的问题是:
- 如何创建这样的函数(addOrSubtract)?
- 在Java中,这被认为是良好的实践吗?
- 假设我们创建了函数(addOrSubtract),它的访问修饰符应该是什么?
英文:
I'm relatively new to Java, and I am trying to play around with Java code. I have two functions, one that adds two integers, and the other subtracts two integers. The only thing different between them is the sign (+ or -). I am considering creating a function to unify addition and subtraction.
For example:
public class foo {
public int add(int x, int y) {
return x + y;
}
public int subtract(int x, int y) {
return x - y;
}
// Not intended as actual code but rather to show intention
private int addOrSubtract(int x, int y, someType sign) {
return x sign y;
}
// The objective is to be able to use addOrSubtract like (Not intended as actual code but rather to show intention):
// public int subtract(int x, int y) {
// return addOrSubtract(x, y, -);
// }
}
My questions are:
- How do I create such function (addOrSubtract)?
- Is that considered a good practice in Java?
- Assuming we create the function (addOrSubtract) what should it's access modifier be?
答案1
得分: 1
这里是如何使用 enum
和 switch
来实现清晰的代码:
enum Operation {
ADD {
public int op(int x, int y) {
return x + y;
}
},
SUBTRACT {
public int op(int x, int y) {
return x - y;
}
};
public abstract int op(int x, int y);
}
现在在您的代码中使用 switch 语句:
```java
switch(sign) {
case '+':
return doOp(Operation.ADD, x, y);
case '-':
return doOp(Operation.SUBTRACT, x, y);
//...
}
其中 `doOp(..)` 方法如下:
```java
private int doOp(Operation op, int x, int y) {
return op.op(x, y);
}
英文:
Here is how you can do this cleanly using enum
and switch
:
enum Operation {
ADD {
public int op(int x, int y) {
return x + y;
}
},
SUBTRACT {
public int op(int x, int y) {
return x - y;
}
};
public abstract int op(int x, int y);
}
Now use a switch statement in your code as:
switch(sign) {
case '+':
return doOp(Operation.ADD, x, y);
case '-':
return doOp(Operation.SUBTRACT, x, y);
//...
}
where doOp(..)
is:
private int doOp(Operation op, int x, int y) {
return op.op(x, y);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论