hn.today

Constructors Shouldn't Throw

t3.at3 points13 comments
Screenshot of Constructors Shouldn't Throw

It argues that constructors should never throw exceptions, perform asynchronous work, or cause side effects; they should only put objects into a simple, valid state. Practical recommendations include moving parsing and I/O out of constructors: implement a Date.parse(string) that uses a parser and calls a private constructor, make a Database type a state machine with an uninitialized state and an explicit connect() method (which unit tests will appreciate), and perform API requests in factory functions that pass resolved data into constructors. Minor side effects like logging are tolerated, but anything that can fail or has latency belongs outside the constructor.

The rationale draws on both C++ practice and general design principles: in C++ noexcept default constructors avoid half-constructed objects, resource leaks, and complicated cleanup during container operations, and similar predictability is desirable in other languages. Keeping construction simple enforces separation of concerns, makes object lifecycles explicit, and prevents surprising failures where objects are created in different places than they’re used. When objects require complex setup, the API should expose explicit lifecycle transitions or factory methods rather than hiding work in constructors.

Read on t3.at13 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

Linux 7.3 Released

Linux 7.3 Released

Linux kernel 7.3 has been released, featuring 18,765 commits from over 3,000 developers, including many first-timers. Major updates include new filesystem features, performance improvements, and system call enhancements. (lwn.net)

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.