summaryrefslogtreecommitdiff
path: root/Documentation/Patterns.md
diff options
context:
space:
mode:
authorTim Schumacher <timschumi@gmx.de>2023-01-26 18:52:02 +0100
committerLinus Groh <mail@linusgroh.de>2023-01-26 20:24:16 +0000
commit1971bff31455306b6976fe7e69db851c94a30794 (patch)
tree2b00e3c3ac8958a0e14495b85c2987b8114ee62f /Documentation/Patterns.md
parent03c3d7edbc98c874f159a8aae8b58624a1ffac98 (diff)
downloadserenity-1971bff31455306b6976fe7e69db851c94a30794.zip
Documentation: Document the "Fallible Constructor" pattern
Diffstat (limited to 'Documentation/Patterns.md')
-rw-r--r--Documentation/Patterns.md39
1 files changed, 39 insertions, 0 deletions
diff --git a/Documentation/Patterns.md b/Documentation/Patterns.md
index 488b8508d5..cc429952af 100644
--- a/Documentation/Patterns.md
+++ b/Documentation/Patterns.md
@@ -88,6 +88,45 @@ ErrorOr<void> insert_one_to_onehundred(Vector<int>& vector)
}
```
+## Fallible Constructors
+
+The usual C++ constructors are incompatible with SerenityOS' method of handling errors,
+as potential errors are passed using the `ErrorOr` return type. As a replacement, classes
+that require fallible operations during their construction define a static function that
+is fallible instead.
+
+This fallible function (which should usually be named `create`) will handle any errors while
+preparing arguments for the internal constructor and run any required fallible operations after
+the object has been initialized. The resulting object is then returned as `ErrorOr<T>` or
+`ErrorOr<NonnullOwnPtr<T>>`.
+
+### Example:
+
+```cpp
+class Decompressor {
+public:
+ static ErrorOr<NonnullOwnPtr<Decompressor>> create(NonnullOwnPtr<Core::Stream::Stream> stream)
+ {
+ auto buffer = TRY(CircularBuffer::create_empty(32 * KiB));
+ auto decompressor = TRY(adopt_nonnull_own_or_enomem(new (nothrow) Decompressor(move(stream), move(buffer))));
+ TRY(decompressor->initialize_settings_from_header());
+ return decompressor;
+ }
+
+... snip ...
+
+private:
+ Decompressor(NonnullOwnPtr<Core::Stream::Stream> stream, CircularBuffer buffer)
+ : m_stream(move(stream))
+ , m_buffer(move(buffer))
+ {
+ }
+
+ CircularBuffer m_buffer;
+ NonnullOwnPtr<Core::Stream::Stream> m_stream;
+}
+```
+
## The `serenity_main(..)` program entry point
Serenity has moved to a pattern where executables do not expose a normal C