방프리
22.05.08 Chapter1. 데이터 타입 (Item 8) 본문
Item 8 : 익명 타입은 함수를 벗어나지 않게 사용하라
튜플은 굳이 각 필드 별로 네이밍을 할 필요가 없다. 하지만 기본적으로 설정되는 네이밍은 Item1, Item2와 같이
설정되므로 가독성을 올리기 위해서는 해주는 것이 좋다.
static (T sought, int index) FindFirstOccurrence<T>(
IEnumerable<T> enumerable, T value)
{
int index = 0;
foreach (T element in enumerable)
{
if (element.Equals(value))
{
return (value, index);
}
index++;
}
return (default(T), -1);
}
물론 다른 방식으로도 네이밍 설정이 가능하다.
// 결과를 튜플 변수에 할당
var result = FindFirstOccurrence(list, 42);
Console.WriteLine($"{First {result.sought} is at {result.index}");
// 결과를 각기 다른 변수에 할당
(int number, int index) = FindFirstOccurrence(list, 42);
Console.WriteLine($"First {number} is at {index}");
규모가 커질수록 익명 타입과 튜플은 더 성능을 발휘하게 된다. 프로젝트가 커지고 복잡한 기능이 추가될수록
반복적인 코드가 추가되는데 메서드를 좀 더 잘게 쪼개면 코드의 재사용성을 유지할 수 있다.
public static IEnumerable<TResult> Map<TSource, TResult>
(this IEnumerable<TSource> source, Func<TSource, TResult> mapFunc)
{
foreach (TSource s in source)
yield return mapFunc(s);
}
//사용 예
var sequence = (from x in Utilities.Generator(100,
() => randomNumbers.NextDouble() * 100)
let y = randomNumbers.NextDouble() * 100
select new { x, y }).TakeWhile(
point => point.x < 75);
하지만 익명타입과 튜플도 너무 남용해서는 안된다. 어느정도 반복적으로 사용되는 타입은 구체적 타입으로 변경해서
사용해야한다.
'C# > More Effective C#' 카테고리의 다른 글
23.01.23 Chapter1. 데이터 타입 (Item 10) (0) | 2023.01.23 |
---|---|
22.05.09 Chapter1. 데이터 타입 (Item 9) (0) | 2022.05.08 |
22.05.07 Chapter1. 데이터 타입 (Item 7) (0) | 2022.05.07 |
22.03.13 Chapter1. 데이터 타입 (Item 6) (0) | 2022.03.14 |
22.03.01 Chapter1. 데이터 타입 (Item 5) (0) | 2022.03.01 |
Comments