-
[.NET] 유효성(Validation)검사 코드를 간결하게 작성하는데 도움주는 GuardClauses 소개.NET/유용한 라이브러리 2021. 9. 25. 22:03반응형
프로그램 개발을 진행하다보면 특정 변수값에 대해 유효성검사를 해야 한다. 특정 유효성은 개발하는 시스템에 관련된 사항에 따라 직접 작성해야 하지만 일반적으로 null이면 안되는데, null이 들어오거나, 0이 들어오면 안되는데 0이 들어오는 문제에 대해선 어느 프로그램을 개발해도 공통적으로 처리해야할 검사코드가 될 것이다.
이번에 소개할 라이브러리는 일반적인 상황에 대한 유효성검사 코드 작성을 간결하는데 도움을 주는 GuardClauses 란 라이브러리이다.
아래 코드는 GuardClauses 를 적용하기 전 소스코드이다. Order 라는 객체를 생성하는데, 유효하지 않은 매개변수를 받아 처리하려고 한다.
class Program { static void Main(string[] args) { try { var order = new Order(null, 0, 0, 0, DateTime.Now); } catch(Exception ex) { Console.WriteLine(ex.Message); } } } public class Order { private string _name; private int _quantity; private long _max; private decimal _unitPrice; private DateTime _dateCreated; public Order(string name, int quantity, long max, decimal unitPrice, DateTime dateCreated) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException($"{nameof(name)} is null or whitespace"); if (quantity <= 0) throw new ArgumentException($"{nameof(quantity)} is negative or zero"); if (max == 0) throw new ArgumentException($"{nameof(max)} is zero"); if (unitPrice < 0) throw new ArgumentException($"{nameof(unitPrice)} is zero"); if (dateCreated < SqlDateTime.MinValue) throw new ArgumentException($"{nameof(dateCreated)} is cl"); _name = name; _quantity = quantity; _max = max; _unitPrice = unitPrice; _dateCreated = dateCreated; } }
나름 간결하게 작성해 보았지만 GuardClauses를 보면 더 간결해지는 코드를 확인할 수 있을 것이다.
class Program { static void Main(string[] args) { try { var order = new Order(null,0, 0, 0, DateTime.Now); } catch(Exception ex) { Console.WriteLine(ex.Message); } } } public class Order { private string _name; private int _quantity; private long _max; private decimal _unitPrice; private DateTime _dateCreated; public Order(string name, int quantity, long max, decimal unitPrice, DateTime dateCreated) { _name = Guard.Against.NullOrWhiteSpace(name, nameof(name)); _quantity = Guard.Against.NegativeOrZero(quantity, nameof(quantity)); _max = Guard.Against.Zero(max, nameof(max)); _unitPrice = Guard.Against.Negative(unitPrice, nameof(unitPrice)); _dateCreated = Guard.Against.OutOfSQLDateRange(dateCreated, nameof(dateCreated)); } }
Order 생성자 부분이 절반으로 줄어들었음을 확인할 수 있다. 오류 발생시 나타나는 메시지를 직접 작성하고 싶다면 각 유효성검사 체크 함수의 message 옵션 파라메터 값을 사용해주면 된다.
public Order(string name, int quantity, long max, decimal unitPrice, DateTime dateCreated) { _name = Guard.Against.NullOrWhiteSpace(name, nameof(name), $"{nameof(name)} is null or whitespace"); _quantity = Guard.Against.NegativeOrZero(quantity, nameof(quantity), $"{nameof(quantity)} is negative or zero"); _max = Guard.Against.Zero(max, nameof(max), $"{nameof(max)} is zero"); _unitPrice = Guard.Against.Negative(unitPrice, nameof(unitPrice), $"{nameof(unitPrice)} is zero"); _dateCreated = Guard.Against.OutOfSQLDateRange(dateCreated, nameof(dateCreated), $"{nameof(dateCreated)} is cl"); }
보다 자세한 사항은 Github 에서 확인가능하다.
ardalis/GuardClauses: A simple package with guard clause extensions. (github.com)
GitHub - ardalis/GuardClauses: A simple package with guard clause extensions.
A simple package with guard clause extensions. Contribute to ardalis/GuardClauses development by creating an account on GitHub.
github.com
반응형'.NET > 유용한 라이브러리' 카테고리의 다른 글
[.NET] ASP.NET Core MVC에 View 영역을 Vite 프로젝트로 개발할 수 있게 도와주는 Vite.AspNetCore 소개 (0) 2024.07.13 [.NET Tools] 웹 기반 dotnet playground 서비스 sharplab.io (0) 2021.06.05 [.NET] 메모리가 폭발하는 ClosedXML (1) 2021.01.30 [.NET] 상업 목적에서도 무료로 사용할 수 있는 엑셀(Excel) 편집 라이브러리 ClosedXML 소개. (feat. EPPlus 사용시 주의사항) (0) 2021.01.28