0

I am currently making my method call in the following way:

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

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

In VBA I would do something like this

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

So my question is, is there a way to avoid repeating "instrumentsInfo" in the method call in Java?

jule64
  • 487
  • 1
  • 6
  • 19

3 Answers3

3

In a word no although you may want to consider changing

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

to

TrackInstruments trackInstruments = new TrackInstruments(instrumentsInfo);

and then have the constructor take the parameters it needs.

Or perhaps use the builder pattern if you need a lot of parameters.

Or indeed ask yourself why you are constructing InstrumentsInfo outside the TrackInstruments when the latter seems to rely on it so heavily. (Without fully understanding your objects that is)

RNJ
  • 15,272
  • 18
  • 86
  • 131
  • a builder sounds like a good idea as I would keep visibilty on what params I pass in my method. – jule64 Oct 05 '12 at 21:09
1

Yes, you can create a constructor in TrackInstruments that accepts the object type InstrumentsInfo

TrackInstruments trackInstruments = new TrackInstruments(instrumentsInfo);
PbxMan
  • 7,525
  • 1
  • 36
  • 40
0

No, there is no With syntax in Java as such. To avoid repeating "instrumentsInfo", you could, however, just create a constructor which takes the type:

TrackInstruments trackInstruments = new TrackInstruments(instrumentsInfo);

This design, however, leads to the TrackInstruments knowing about an InstrumentsInfo which does not promote loose coupling between objects, so you could use:

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

TrackInstruments trackInstruments = new TrackInstruments(instrumentID, instrumentTickSize, instrumentName);
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Thanks, I thought about doing your suggestion but passing instrumentInfo I would loose visibility on what params I use in my method call, i.e name, ID etc. – jule64 Oct 05 '12 at 21:07