Private positional and primary constructors #7694
Unanswered
jochenz
asked this question in
Language Ideas
Replies: 1 comment
-
The team is interested in exploring primary constructor bodies or final initializers which would make it possible to support validation: #7667 (reply in thread) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi all,
records are a great way to represent "DDD" value types. For example, for a book ID, I could define:
Very nice to have this concise syntax which gives me the readonly record.
A next step is that I wish to introduce validation for the value passed in. So I add a factory method:
Of course, the comment says it all: my validation is only used when the factory method is used. Anyone can still use the positional constructor and bypass validation. So, obviously, I want to make the constructor private. Which means, I need to make it an explicit constructor:
Wouldn't it be nice to just protect against public usage of the constructor and to maintain the conciseness of the record? What about adding private to the positional (or primary) constructor?
public record BookId private(int Value)
This keeps all the super nice conciseness of the record type, but consumers can only create the type through the safe factory. I'd love to be able to do so :-)
Beta Was this translation helpful? Give feedback.
All reactions