可以将常量值传递给函数参数吗?
我是一名计算机科学专业的学生,昨晚早些时候我正在学习作业。我在书中偶然发现了一个我认为多余的函数,但经过进一步检查,我变得相当“困惑”
public int refundBalance() {
int amountToRefund = balance;
balance = 0;
return amountToRefund;
}
当我看到这个时,我认为必须创建一个新的局部变量来存储和传递数据是相当多余的,所以我想到了这个:
refundBalance(balance);
public int refundBalance(int amount) {
balance = 0;
return amount;
}
但显然,我只是“交易线”。
问题:有没有办法始终将相同的参数传递给函数,而不必在调用时传递值?
可选问题:您将/能够如何优化此功能? (如果可能的话)
谢谢大家<3(PS这不是作业,这只是基本的好奇心。)
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 (P.S. this is not a homework assignment, it's just basic curiosity.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上,您实际上可能希望以原子方式访问余额并保护它免受多个线程的访问。如果是这种情况,您可以使用 AtomicInteger 通过
getAndSet
一次性完成此操作。这实际上是我在方法上使用
synchronized
并按照上面的方式编写的建议。它也恰好是一行:-)。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
.This is actually what I'd recommend on top of using
synchronized
on the method and writing it as you have above. It also happens to be one line :-).原始代码是一种优秀的、标准的面向对象实践。
有一个状态,一个私有字段
balance
,只能通过公共方法修改,保证记账安全。现在执行没有局部变量的函数:
应该这样做:
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.Now for doing the function without local variable:
This should do:
如果您的意思是通过默认参数,那么不行。由于refundBalance是一个公共方法,并且包含它的类存储余额变量,因此外部对象能够确定退款金额是没有意义的 - 如果需要,您可以提供带有金额参数的refundAmount方法该功能。
至于可选问题,我认为尝试优化该功能是毫无意义的 - 它本身就很好,并且您不会获得任何性能提升。
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.
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.