[英]Possible to pass constant value to function parameter?
I'm a computer science student, and I was studying homework earlier last night. 我是计算机科学专业的学生,昨晚我正在学习作业。 I stumbled upon a function in my book that I thought was redundant, but upon further inspection I have gotten rather "confused" 我在书中偶然发现了一个我认为是多余的功能,但经过进一步检查,我变得相当“困惑”
public int refundBalance() {
int amountToRefund = balance;
balance = 0;
return amountToRefund;
}
As I looked at this, I thought that having to create a new local variable to store and pass data around was rather redundant, so I thought up this: 当我查看此内容时,我认为必须创建一个新的局部变量来存储和传递数据非常多余,因此我想到了:
refundBalance(balance);
public int refundBalance(int amount) {
balance = 0;
return amount;
}
But obviously, i'm just "trading lines". 但显然,我只是“交易线”。
Question: Is there any way to always pass the same parameter to a function, without having to pass the value on call? 问题:有什么方法可以始终将同一参数传递给函数,而不必在调用时传递值?
Optional Question : How would/could you optimize this function? 可选问题 :您如何/将如何优化此功能? (If even possible) (即使有可能)
Thanks all <3 (PS this is not a homework assignment, it's just basic curiosity.) 感谢所有<3(PS不是家庭作业,只是基本的好奇心。)
In reality, you actually probably want to access the balance atomically and protect it from multiple threads having access. 实际上,您实际上可能想自动访问平衡并保护它不受具有访问权限的多个线程的影响。 If that's the case, you can use an AtomicInteger to do this in one shot via getAndSet
. 如果是这样,您可以使用AtomicInteger通过getAndSet
一次完成此getAndSet
。
import java.util.concurrent.atomic.AtomicInteger;
private final AtomicInteger balance = new AtomicInteger();
public int refundBalance() {
return balance.getAndSet(0);
}
This is actually what I'd recommend on top of using synchronized
on the method and writing it as you have above. 实际上,这是我建议在方法上使用synchronized
并像上面一样编写它的建议。 It also happens to be one line :-). 它也恰好是一行:-)。
The original code is a fine, standard object oriented practice. 原始代码是一种很好的,标准的面向对象的实践。
There is a state, a private field balance
, which you can only modify by public methods, ensuring that accountancy is safe. 有一个状态,一个私有字段balance
,您只能通过公共方法进行修改,以确保会计安全。
Now for doing the function without local variable: 现在执行不带局部变量的函数:
public int refundBalance() {
try {
return balance;
} finally {
balance = 0;
}
}
This should do: 应该这样做:
If you mean via a default parameter, then no. 如果您通过默认参数表示,则否。 Since refundBalance is a public method and the class that encloses it stores the balance variable, it wouldn't make sense for an outside object to be able to determine the amount to refund - you could provide a refundAmount method with an amount parameter if you wanted that functionality. 由于fundamentalBalance是一个公共方法,并且包含它的类存储余额变量,因此外部对象能够确定要退款的金额没有意义-如果需要,您可以提供带有amount参数的returnAmount方法该功能。
As for the optional question, I think that trying to optimize that function is pointless - it's fine as it is and you wouldn't gain any performance increase. 至于可选的问题,我认为尝试优化该功能是没有意义的,因为它很好,您不会获得任何性能提升。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.