Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove the section about deprecating a record's constructor. #1863

Merged
merged 1 commit into from
Nov 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 4 additions & 29 deletions value/userguide/records.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,8 @@ methods, but you might want to keep a factory method in some records. Perhaps
for compatibility reasons, or because you are normalizing input data to
different types, such as from `List` to `ImmutableList`.

In this event, you can still *discourage* calling the constructor by marking it
deprecated. More on this [below](#deprecating).

Clever ways do exist to make calling the constructor impossible, but it's
probably simpler to keep using AutoValue.
If you don't want users to call your constructor at all, records are not a good
fit. You probably want to continue using AutoValue in that case.

### Superclass

Expand Down Expand Up @@ -482,31 +479,9 @@ public record Person(String name, int id) {
Person p = Person.builder().name("Priz").id(6).build();
```

#### <a id="deprecating"></a>Deprecating the constructor

As mentioned [above](#staticfactory), the primary constructor is always visible.
In the preceding example, the builder will enforce that the `name` property is
not null (since it is not marked @Nullable), but someone calling the constructor
will bypass that check. You could deprecate the constructor to discourage this:

```java
public record Person(String name, int id) {
/** @deprecated Obtain instances using the {@link #builder()} instead. */
@Deprecated
public Person {}

public static Builder builder() {
return new AutoBuilder_Person_Builder();
}

@AutoBuilder
public interface Builder {
Builder name(String name);
Builder id(int id);
Person build();
}
}
```
So you cannot assume that instances of your record will always be built with the
builder. Any data validation should be performed in the constructor.

### Custom `toString()`

Expand Down