I\'ve just had an argument with someone I work with and it\'s really bugging me. If you have a class which just has methods like calculateRisk
or/and calc
I would avoid making these static. Whilst at the moment that may make sense, you may in the future want to add some behaviour. e.g. at the moment you would have a default calculation engine (strategy):
CalcService cs = new CalcService();
cs.calcPrice(trade, date);
and later on you may want to add a new calculation engine:
CalcService cs = new CalcService(new WackyCalculationStrategy());
cs.calcPrice(trade, date);
If you make this class instantiatable, then you can create different instances and pass them around, instantiate on the fly etc. You can give them long-running behaviour (e.g. how many calculations involving trade X has this object done ? etc.)
if the methods need information in a Trade instance to do their work, then why aren't these methods non-static members of the Trade class?
If you make it static, you can't inject a different implementation easily.
There is no longer any runtime cost to calling non-static methods, so for new code avoid static as far as sensible.
OTOH, refactoring tools can replace all calls to a static method fairly easily, so it's not critical one way or another.
I don't know whether the calculation of prices or risks can vary in your domain. If there are different strategies, passing a stateless strategy implementation around may have benefits. But it's more code, and there's a good chance that YAGNI.
I would say yes, but an argument could also be made in this case for just putting those methods on the Trade object.
In my opinion they should be static. You might even get performance improvements because the compiler/jit might inline the methods
In this case, I would probably make a couple of static methods. I would assume that the calc function does not depend upon other resources to calculate the values, and it is generally segregated from the rest of the code.
In general, however, I tend to shy away from doing overly complicated things in static methods. If you were unit testing and wanted to swap in a MockCalcService, having the static calls spread out across your code would make it very difficult.