Analysis method or constructor overload

When writing a method that takes a string and populates poco based on this, is it better to have a static Parse(string s) method, like Int32.Parse() , or overload the constructor so that it takes the string?

+6
source share
3 answers

I prefer the design version, but including both is easy, as the designer can just call Parse . This is a template followed by a Guid structure (and probably others).

I should add that if you are not dealing with a struct , then the static method should probably refer to the constructor (or even to a separate method that can invoke the call), since you cannot assign this to the constructor of the class .

EDIT . As TrueWill points out, if you enabled Parse , you should enable TryParse . By the way, Guid is instructive again: the Parse method actually uses TryParse and just throws an exception if TryParse returns false .

+9
source

If the method might fail due to an invalid string, I would lean to Parse and enable TryParse according to the TryParse pattern .

+2
source

I would recommend using .Parse (string s), if it is a simple object, if the object stores more than 1-2 values, you should use a constructor, or, in other words, do not analyze whether the returned value will be an instance with members independent of the value parsing.

0
source

Source: https://habr.com/ru/post/894853/


All Articles