lundi 10 mai 2021

Best practices for when to use the Try pattern in C#

After reading a bit on the topic, I am still unsure of when to provide TryGet*(someParameter, out someValue) methods. I understand how it can be useful when there exists a variant of the method that can throw exceptions in the case of failure, but I can't really form a general rule that I can use to help me decide when to provide either type of method.

Some questions that come to mind about this:

  • Why not just have the non-try method not throw exceptions?
  • When would throwing an exception be better than just returning null?
  • If the decision comes down to having one type of method that just returns a nullable type (or some Result type), should this always be reflected in the method's name in the sense that it has to be prefixed with "Try"?
  • Is providing both types of methods always better in every case?

I am specifically working with manipulating a collection, and what I have is a bunch of methods like: void GetAt(position) bool TryGet(position, out item)

I'm not sure whether this is needed or not, but it feels like what I'm doing is wrong in some way.

Aucun commentaire:

Enregistrer un commentaire