Menu
CoddyTech

속성으로 불변 조건 보호하기

Coddy의 R 개발자를 위한 C# 코스 레슨. 48개 중 34번째.

R S3 객체는 일반적인 리스트이므로, 어떤 호출자든 account$amount <- -10을 작성할 수 있습니다. balance()와 같은 접근자는 관례일 뿐이며, S4 유효성 검사는 validObject()를 호출할 때만 실행됩니다. C# 속성 getter는 해당 속성의 형식과 접근 수준을 선언하며, getter만 있는 public 속성은 다른 코드에서 잘못된 값을 할당하려는 시도를 컴파일 오류로 만듭니다. 메서드는 불변 조건을 유지합니다.

속성은 제어된 접근을 제공하고, private 필드는 불변 조건을 유지합니다. getter는 호출자가 임의의 값을 할당하지 못하게 하면서 상태를 보여 줄 수 있습니다. private setter 또는 getter만 있는 속성을 사용하는 것은 계약에 따른 선택입니다. 업데이트에 유효성 검사가 필요하다면 변경 가능한 필드를 노출하지 마세요.

R 참고 코드

new_account <- function(amount) {
  structure(list(amount = max(0, amount)), class = "account")
}
deposit <- function(account, n) {
  if (n > 0) account$amount <- account$amount + n
  account
}
balance <- function(account) account$amount
account <- new_account(5)
account <- deposit(account, -3)
cat(balance(account), "\n", sep = "")

C# 보조 선언

class Reading { private int raw; public Reading(int raw) { this.raw = raw; } public int Doubled { get { return raw * 2; } } }

Main 안의 C# 문장

var reading = new Reading(3);
Console.WriteLine(reading.Doubled);

이는 핵심 내용을 보여 주는 교육용 발췌문입니다. 챌린지 파일에는 완전한 실행 가능 래퍼가 포함되어 있으며, 위 스니펫은 관련 선언과 문장을 보여 줍니다.

참고 출력:

5

C# 출력:

6
challenge icon

챌린지

쉬움

Account를 완성하세요. 초기 잔액은 0으로 제한되고, 양수 금액을 입금하면 잔액이 증가하며, 0 이하의 금액을 입금하면 무시됩니다. 잔액은 읽을 수 있지만 공개적으로 설정할 수는 없습니다.

잠금 해제된 C# 파일을 수정하세요. 잠긴 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하고, 입력값이 변경되지 않았는지 확인한 다음, 마지막에 개행 문자 하나를 붙여 결과를 출력합니다. 선언된 API를 유지하세요. 두 번째 Main을 추가하거나 진단 출력을 출력하지 마세요.

잠긴 실행기도 Solve 래퍼뿐만 아니라 내보낸 도우미 또는 클래스 API를 별도로 검사합니다.

직접 해보기

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = I(input[0]); string before0=Snapshot(a0);
var a1 = Ints(input[1]); string before1=Snapshot(a1);
var accountOne = new Account(-2); var accountTwo = new Account(5); accountOne.Deposit(3); accountOne.Deposit(-9); if (accountOne.Balance != 3 || accountTwo.Balance != 5) throw new Exception("Account API");
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

R 개발자를 위한 C#의 모든 레슨

직접 연습해 보세요: 온라인 C# 컴파일러