My application has InstrumentFactory – the only place where I create Instrument instance. Each instrument instance contains several fields, such as Ticker=MSFT and GateId=1 and also unique Id =1.
And now I realized that I almost never need Instrument instance. In 90% of cases I just need Id. For example now I have such method:
public InstrumentInfo GetInstrumentInfo(Instrument instrument)
{
return instrumentInfos[instrument.Id];
}
We know that we should not pass in parameters more information than required. So this code probably should be refactored to:
public InstrumentInfo GetInstrumentInfo(int instrumentId)
{
return instrumentInfos[instrumentId];
}
90% of my code can now be refactored to use instrumentId instead of Instrument.
Should I do that? Changing everywhere Instrument to instrumentId will make it as a hard requirement (each Instrument should have exactly one unique id). But what benefits will I have? In return of “hard requirements” I want to have some benefits for that… (speed, readability?) But I don’t see them.
Using ids everywhere instead of the object is wrong approach and it goes against the spirit of OOP.
There are two big advantages to using the object itself:
Personto the first version, but you can accidentally passperson.Idto the second.longids, or some other way to identify a uniqueInstrument, you won’t need to change the calling code.And you should probably change your dictionary too, it should be something like
Dictionary<Instrument, InstrumentInfo>, notDictionary<int, InstrumentInfo>, like you have now. This way, you get both of the advantages there too. To make it work, you need to implement equality inInstrument, which means properly overridingEquals()andGetHashCode()and ideally also implementingIEquatable<Instrument>.