Serve Laurijssen
Serve Laurijssen

Reputation: 9753

static construction method vs constructor

In the .NET framework I often see the idiom where a constructor is replaced by a static function to construct a new object from.

For instance with BigInteger there's no constructor taking a string so this is not possible:

BigInteger i = new BigInteger("1000000103453543897");

But there is a static Parse function.

BigInteger i = BigInteger.Parse("1000000103453543897");

Why is a class design like this often chosen?

The only thing I can think of is there's one object less to be created and later thrown away. Is it true that that is the main reason? Or are there other reasons?

BigInteger(string value)
{
  BigInteger result = new BigInteger(); // this one just returned in a Parse function

  // compute bigint

  // copy result to this
  data = new uint[maxLength];
  for (int i = 0; i < result.Length; i++)
    data[i] = result.data[i];

  Length = result.dataLength;  
}

Upvotes: 4

Views: 732

Answers (3)

Moho
Moho

Reputation: 16543

There could be many reasons - research the Factory method pattern.

With your example - many consider it a bad practice to have significant logic in/called from a constructor (I don't want to throw an exception from a constructor unless it's a missing parameter). Using a factory method allows for implementation guaranteed to run at object construction but not in the constructor.

Upvotes: 3

D Stanley
D Stanley

Reputation: 152614

there's no constructor taking a string

There's no technical reason why you couldn't. The designers just chose not to duplicate code that already exists and adds no pragmatic value - it's still one line of code, it's clearer what you're trying to do, reduces the number of errors by passing in a wrong type, etc. etc.

It also makes it consistent with other numeric types that do not have a non-default constructor (you can't say int i = new int(4));

The bottom line is - the value in such a constructor needs to outweigh the cost to implement, test, document, and ship the new feature.

Upvotes: 2

RvdK
RvdK

Reputation: 19800

See @Moho for answer, Factory method pattern.

I personally think BigInteger.Parse covers it better. You have some value in this case a string, and you want it to convert it to a BigNumber. A constructor with a string parameter doesn't not tell wat is going to happen. For all you know it is just doing a Console.WriteLine with the string instead of something different. Parse tells you something more...

Upvotes: 1

Related Questions