0Pricing
C# Academy · 강의

구현과 테스트

Rectangle, Circle, Triangle을 구현하고, 기본 입력 검사를 추가하며, 프레임워크 없이 작은 임시 테스트를 작성합니다.

구현과 테스트은(는) CoddyKit의 무료 C# Academy 강의입니다. 이것은 3개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 C# Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. C# Academy 강의에는 총 3개의 강의가 포함되어 있습니다.

구현 계획

목표: 도형을 구현하고 검증합니다.

  • Rectangle, Circle, Triangle을 구현합니다.
  • 잘못된 입력을 방어합니다.
  • 작은 Assert 도우미를 추가합니다.
  • Main에서 빠른 확인을 실행합니다.

Rectangle 및 Circle

생성자에서 크기가 양수인지 간단히 검사합니다. 수식은 짧고 명확하게 유지합니다.

using System;

public interface IShape
{
  double Area();
  double Perimeter();
}

public sealed class Rectangle : IShape
{
  private readonly double _w, _h;

  public Rectangle(double w, double h)
  {
    if (w <= 0 || h <= 0) throw new ArgumentOutOfRangeException("w/h must be > 0");
    _w = w; _h = h;
  }

  public double Area() { return _w * _h; }
  public double Perimeter() { return 2 * (_w + _h); }
}

public sealed class Circle : IShape
{
  private readonly double _r;

  public Circle(double r)
  {
    if (r <= 0) throw new ArgumentOutOfRangeException("r must be > 0");
    _r = r;
  }

  public double Area() { return 3.14159 * _r * _r; }
  public double Perimeter() { return 2 * 3.14159 * _r; }
}

public class Program
{
  public static void Main(string[] args)
  {
    IShape a = new Rectangle(3, 4);
    IShape b = new Circle(2);
    Console.WriteLine("Rect A=" + a.Area() + " P=" + a.Perimeter());
    Console.WriteLine("Circ A=" + b.Area() + " P=" + b.Perimeter());
  }
}

검사를 포함한 Triangle

변의 유효성을 검사합니다(삼각형 부등식). 잘 알려진 수식을 사용하고 숫자를 읽기 쉽게 유지합니다.

using System;

public interface IShape
{
  double Area();
  double Perimeter();
}

public sealed class Triangle : IShape
{
  private readonly double _a, _b, _c;

  public Triangle(double a, double b, double c)
  {
    if (a <= 0 || b <= 0 || c <= 0) throw new ArgumentOutOfRangeException("sides must be > 0");
    // triangle inequality: each side < sum of other two
    if (a >= b + c || b >= a + c || c >= a + b) throw new ArgumentException("invalid triangle");
    _a = a; _b = b; _c = c;
  }

  public double Perimeter() { return _a + _b + _c; }

  // Herons formula for area
  public double Area()
  {
    double s = (_a + _b + _c) / 2.0;
		double value = s * (s - _a) * (s - _b) * (s - _c);
		return Math.Sqrt(value);
		}
}

public class Program
{
  public static void Main(string[] args)
  {
    IShape t = new Triangle(3, 4, 5);
		Console.WriteLine("Tri A=" + t.Area() + " P=" + t.Perimeter());
		}
}

임시 Assert 도우미

작은 Assert 클래스를 만듭니다. double 값은 허용 오차를 두고 예상값과 실제값을 비교합니다.

using System;

		public static class Assert
			{
			// Approx compare for doubles (tolerance)
										  public static void AreClose(double expected, double actual, double eps, string msg)
  {
		if (Math.Abs(expected - actual) > eps)
			{
			throw new Exception("Assert failed: " + msg + " expected=" + expected + " actual=" + actual);
    }
    Console.WriteLine("OK: " + msg);
  }
}

public interface IShape
{
  double Area();
  double Perimeter();
}

public sealed class Rectangle : IShape
{
  private readonly double _w, _h;
  public Rectangle(double w, double h) { if (w <= 0 || h <= 0) throw new ArgumentOutOfRangeException(); _w = w; _h = h; }
  public double Area() { return _w * _h; }
  public double Perimeter() { return 2 * (_w + _h); }
}

public class Program
{
  public static void Main(string[] args)
  {
    Rectangle r = new Rectangle(3, 4);
    Assert.AreClose(12.0, r.Area(), 0.0001, "rectangle area");
    Assert.AreClose(14.0, r.Perimeter(), 0.0001, "rectangle perimeter");
  }
}

빠른 테스트 실행

몇 가지 테스트를 Main에 묶습니다. 예상 결과는 단순하고 읽기 쉽게 유지합니다.

using System;

public static class Assert
{
  public static void AreClose(double expected, double actual, double eps, string msg)
  {
    if (Math.Abs(expected - actual) > eps)
      throw new Exception("Assert failed: " + msg + " expected=" + expected + " actual=" + actual);
    Console.WriteLine("OK: " + msg);
  }
}

public interface IShape
{
  double Area();
  double Perimeter();
}

public sealed class Circle : IShape
{
  private readonly double _r;
  public Circle(double r) { if (r <= 0) throw new ArgumentOutOfRangeException(); _r = r; }
  public double Area() { return 3.14159 * _r * _r; }
  public double Perimeter() { return 2 * 3.14159 * _r; }
}

public sealed class Triangle : IShape
{
  private readonly double _a, _b, _c;
  public Triangle(double a, double b, double c)
  {
    if (a <= 0 || b <= 0 || c <= 0) throw new ArgumentOutOfRangeException();
    if (a >= b + c || b >= a + c || c >= a + b) throw new ArgumentException("invalid triangle");
    _a = a; _b = b; _c = c;
  }
  public double Perimeter() { return _a + _b + _c; }
  public double Area()
  {
    double s = (_a + _b + _c) / 2.0;
    return Math.Sqrt(s * (s - _a) * (s - _b) * (s - _c));
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    double eps = 0.001;

    Circle c = new Circle(2);
    Assert.AreClose(12.56636, c.Area(), eps, "circle area r=2");
    Assert.AreClose(12.56636, c.Perimeter(), eps, "circle peri r=2");

    Triangle t = new Triangle(3, 4, 5);
    Assert.AreClose(12.0, t.Perimeter(), eps, "triangle perimeter 3-4-5");
    Assert.AreClose(6.0, t.Area(), eps, "triangle area 3-4-5");
  }
}

구현 팁

확인 목록:

  • 생성자에서 입력값의 유효성을 검사합니다.
  • 수식은 짧게 유지하고 π에는 지역 상수를 사용합니다.
  • 임시 테스트를 위한 작은 Assert를 만듭니다.
  • 각 도형에 대해 Area와 Perimeter를 모두 테스트합니다.

임시 테스트 아이디어

빠른 확인: 테스트 프레임워크 없이 작은 라이브러리를 테스트하는 간단한 방법은 무엇입니까?

복습

복습: 명확한 검사 로직을 포함해 도형을 구현한 다음, Main의 최소한의 Assert 도우미로 검증합니다. 테스트는 작고 결정적으로 유지합니다.

자주 묻는 질문

“구현과 테스트” 강의는 무료인가요?

네 — “구현과 테스트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 C# Academy 강의 전체를 잠금 해제할 수 있습니다. C# Academy 강의에는 총 3개의 강의가 포함되어 있습니다.

“구현과 테스트”에서 뭘 배우나요?

Rectangle, Circle, Triangle을 구현하고, 기본 입력 검사를 추가하며, 프레임워크 없이 작은 임시 테스트를 작성합니다. 브라우저에서 직접 실행하는 실습 코드로 C# Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

C# Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 C# Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 2번째 강의입니다.

“구현과 테스트” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 C# Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 C# Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 설계(인터페이스와 상속)
  2. 구현과 테스트
  3. 다형적 동작
← C# Academy(으)로 돌아가기