A Named Constructor as a Class Method

A class method can provide a meaningful alternate way to build an object while receiving the class used in the call.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. Name the conversion
  2. Keep validation consistent

Name the conversion

A duration class can provide a construction operation named from milliseconds that converts 1500 to 1.5 seconds internally. The name communicates a unit boundary before an ordinary instance has been created.

Keep validation consistent

A parsed negative duration may still violate a rule forbidding negative time spans. Route it through the same valid-state rule as direct construction. See constructor invariants.[1]

References

  1. Python Software Foundation, Python Tutorial: Classes ↩