【问题标题】:Equivalent of VBA With statement in Java [duplicate]Java中VBA With语句的等价物[重复]
【发布时间】:2012-09-27 01:12:14
【问题描述】:

我目前正在通过以下方式调用我的方法:

InstrumentsInfo instrumentsInfo = new InstrumentsInfo();
String shortInstruName = "EURUSD"

TrackInstruments trackInstruments = new TrackInstruments(instrumentsInfo.getInstrumentID(shortInstruName), instrumentsInfo.getInstrumentTickSize(shortInstruName), instrumentsInfo.getInstrumentName(shortInstruName));

在 VBA 中我会做这样的事情

With instrumentsInfo
 TrackInstruments(.getInstrumentID(shortInstruName), .getInstrumentTickSize(shortInstruName), .getInstrumentName(shortInstruName));

所以我的问题是,有没有办法避免在 Java 的方法调用中重复“instrumentsInfo”?

【问题讨论】:

标签: java vba with-statement


【解决方案1】:

不,Java 中没有 With 这样的语法。但是,为避免重复“instrumentsInfo”,您可以创建一个采用以下类型的构造函数:

TrackInstruments trackInstruments = new TrackInstruments(instrumentsInfo);

然而,这种设计导致TrackInstruments 知道InstrumentsInfo 不会促进对象之间的松散耦合,因此您可以使用:

Integer instrumentID = instrumentsInfo.getInstrumentID(shortInstruName);
Integer instrumentTickSize = instrumentsInfo.getInstrumentTickSize(shortInstruName);
String instrumentName = instrumentsInfo.getInstrumentName(shortInstruName);

TrackInstruments trackInstruments = new TrackInstruments(instrumentID, instrumentTickSize, instrumentName);

【讨论】:

  • 谢谢,我想过做你的建议,但通过 instrumentInfo 我会失去对我在方法调用中使用的参数的可见性,即名称、ID 等。
【解决方案2】:

总之不,虽然你可能想考虑改变

TrackInstruments trackInstruments = new TrackInstruments(instrumentsInfo.getInstrumentID(shortInstruName), instrumentsInfo.getInstrumentTickSize(shortInstruName), instrumentsInfo.getInstrumentName(shortInstruName));

TrackInstruments trackInstruments = new TrackInstruments(instrumentsInfo);

然后让构造函数获取它需要的参数。

如果您需要大量参数,也可以使用builder 模式。

或者确实问自己为什么要在TrackInstruments 之外构建InstrumentsInfo,而后者似乎如此依赖它。 (没有完全理解你的对象)

【讨论】:

  • 构建器听起来是个好主意,因为我会保持对我在方法中传递的参数的可见性。
【解决方案3】:

是的,您可以在 TrackInstruments 中创建一个接受对象类型 InstrumentsInfo 的构造函数

TrackInstruments trackInstruments = new TrackInstruments(instrumentsInfo);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 2023-02-22
    • 2016-02-15
    相关资源
    最近更新 更多