However, I believe there??™s a difference in emphasis. The
nullable version encapsulates the natural return value and the success or failure into a
single variable. It also separates the ???doing??? from the ???testing,??? which puts the emphasis
in the right place in my opinion. Usually, if I call a method in the condition part of an
if statement, that method??™s primary purpose is to return a Boolean value. Here, the
return value is in some ways less important than the output parameter. When you??™re
reading code, it??™s easy to miss an output parameter in a method call and be left wondering
what??™s actually doing all the work and magically giving the answer. With the nullable
version, this is more explicit??”the result of the method has all the information
we??™re interested in. I??™ve used this technique in a number of places (often with rather
more method parameters, at which point output parameters become even harder to
spot) and believe it has improved the general feel of the code. Of course, this only works
for value types.
Another advantage of this pattern is that it can be used in conjunction with the
null coalescing operator??”you can try to understand several pieces of input, stopping
at the first valid one. The normal TryXXX pattern allows this using the short-circuiting
operators, but the meaning isn??™t nearly as clear when you use the same variable for
two different output parameters in the same statement.
Pages:
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279