| name | enforcing-record-constructor-initialization |
| description | Force record instantiation via positional constructor with named arguments instead of property initializer syntax for stronger immutability expression. |
Record ์์ฑ์ ์ด๊ธฐํ ๊ฐ์
์ค๋ช
record๋ฅผ ์ธ์คํด์คํํ ๋ ํ๋กํผํฐ ์ด๊ธฐํ ๊ตฌ๋ฌธ(new Record { Prop = value }) ๋์ ์์ฑ์์ ์ง์ ๊ฐ์ ์ ๋ฌํ๋ ๋ฐฉ์(new Record(Prop: value))์ ์ฌ์ฉํฉ๋๋ค. ์์ฑ์ ์ด๊ธฐํ๋ ์ปดํ์ผ ํ์์ ๋ชจ๋ ํ์ ๊ฐ์ ์ ๋ฌ์ ๊ฐ์ ํ๋ฏ๋ก ๋ ๊ฐํ ๋ถ๋ณ์ฑ์ ํํํ๋ฉฐ, Named Arguments๋ฅผ ์ฌ์ฉํ๋ฉด ๊ฐ๋
์ฑ๋ ์ ์ง๋ฉ๋๋ค.
๊ท์น
record ์ธ์คํด์ค ์์ฑ ์ ํ๋กํผํฐ ์ด๊ธฐํ ๊ตฌ๋ฌธ({ get; init; } + ๊ฐ์ฒด ์ด๊ธฐํ์)์ ์ฌ์ฉํ์ง ์์ต๋๋ค
- ์์ฑ์์ ์ง์ ๊ฐ์ ์ ๋ฌํ๋ ๋ฐฉ์์ ์ฌ์ฉํฉ๋๋ค
- Named Arguments(
Name:, Email: ๋ฑ)๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ๋
์ฑ์ ํ๋ณดํฉ๋๋ค
- ์ด๋ฅผ ์ํด
record ์ ์ ์ positional parameter๋ฅผ ์ฌ์ฉํ๊ฑฐ๋, required ํ๋กํผํฐ ๋์ ์์ฑ์ ๋งค๊ฐ๋ณ์๋ฅผ ํ์ฉํฉ๋๋ค
Worst Case (๋์ ์)
public sealed record Employee
{
public required string Name { get; init; }
public required string Email { get; init; }
public required string Tel { get; init; }
public DateTime Joined { get; init; }
}
var employee = new Employee
{
Name = "๊น์ฒ ์",
Email = "charles@clovf.com",
Tel = "01075312468",
Joined = new DateTime(2018, 3, 7)
};
result.Add(new Employee
{
Name = name,
Email = email,
Tel = tel,
Joined = joined
});
Best Case (์ข์ ์)
public sealed record Employee(
string Name,
string Email,
string Tel,
DateTime Joined);
var employee = new Employee(
Name: "๊น์ฒ ์",
Email: "charles@clovf.com",
Tel: "01075312468",
Joined: new DateTime(2018, 3, 7));
result.Add(new Employee(name, email, tel, joined));
var emp = new Employee(Name: "๋ฐ์ํฌ", Email: "matilda@clovf.com", Tel: "01087654321", Joined: default);
๋น๊ต
| ํญ๋ชฉ | ํ๋กํผํฐ ์ด๊ธฐํ | ์์ฑ์ ์ด๊ธฐํ |
|---|
| ํ์๊ฐ ๋๋ฝ ๋ฐฉ์ง | required๋ก ๊ฐ๋ฅ | ์ปดํ์ผ๋ฌ๊ฐ ๊ฐ์ |
| ๋ถ๋ณ์ฑ ํํ | ์ฝํจ (init ํ์ฉ) | ๊ฐํจ (์์ฑ์ ์ ๋ฌ) |
| ์ฝ๋๋ | ์ฅํฉํจ | ๊ฐ๊ฒฐํจ |
| ๊ฐ๋
์ฑ | ํ๋กํผํฐ๋ช
๋ช
์ | Named Args๋ก ๋์ผ |
with ์ ์ง์ | ์ง์ | ์ง์ |
์ ์ฉ ๋์
- ๋ชจ๋
record ํ์
์ ์ธ์คํด์ค ์์ฑ
- API ์๋ต/์์ฒญ DTO
- ํ์ฑ ๊ฒฐ๊ณผ ๊ฐ์ฒด ์์ฑ
- ํ
์คํธ ๋ฐ์ดํฐ ์์ฑ
- Moq Setup์ ๋ฐํ๊ฐ ์์ฑ