튜플의 유용함을 느꼈다면 어느 순간 튜플을 남발하고 있는 자신을 보고 있을지도 모릅니다. 그리고 그 끝은 난해한 코드가 됩니다.
C#의 튜플은 기능을 빠르게 프로토타이핑하는 쉬운 방법입니다. 적절하게 사용하고 동작을 확인했으면 축약 record
로 빠르게 변경할 수 있습니다.
튜플을 사용해서 유용한 코드를 작성할 수도 있습니다. 패턴 일치와 결합하는 다음의 코드를 살펴봅시다.
public decimal CalculateDiscount(Customer customer, DateTime time)
{
return (IsStudent(customer), IsHappyHour(time), customer.CustomerType) switch
{
(_, _, CustomerType.Gold) => 0.3m,
(_, _, CustomerType.Premium) => 0.2m,
(_, true, CustomerType.Regular) => 0.15m,
(true, false, CustomerType.Regular) => 0.10m,
(false, false, CustomerType.Regular) => 0.0m
};
}
public bool IsStudent(Customer customer) => customer.Age < 25;
public bool IsHappyHour(DateTime datetime) => datetime.Hour is > 15 and < 20;
깔끔하고 읽기 쉬우며 심지어 코드도 짧습니다.