NotImplementedException이 존재하는 이유는 무엇입니까?
이것은 정말 정말 저를 자극합니다. 그래서 누군가가 왜 상황이있는 지에 대한 합리적인 정당성을 줄 수 있기를 바랍니다.
NotImplementedException. 내 다리를 당기는 거죠?
아니요, "잠깐만 요, 메서드가 구현되었습니다. NotImplementedException이 발생합니다." 예, 맞습니다. NotImplementedException을 발생시키는 메서드를 구현해야합니다 (C ++의 순수 가상 함수 호출과 달리-이제 말이됩니다!). 그것은 꽤 웃기지 만, 내 마음 속에는 더 심각한 문제가 있습니다.
NotImplementedException이있는 상태에서 누구나 .Net으로 무엇을 할 수 있는지 궁금합니다. 구현되지 않을 수있는 메서드를 방지하기 위해 모든 추상 메서드 호출을 try catch 블록으로 래핑해야합니까? 그러한 예외를 포착하면 도대체 어떻게해야합니까 ??
메서드를 호출하지 않고 실제로 구현되었는지 테스트 할 방법이 없습니다. 호출하면 부작용이있을 수 있으므로 모든 검사를 미리 수행 한 다음 알고리즘을 실행할 수 없습니다. 알고리즘을 실행하고 NotImplementedExceptions를 잡아 내고 내 애플리케이션을 정상 상태로 롤백하는 방법도 있습니다.
미쳤어. 미친. 미친 것 같은. 그래서 질문은 : 왜 NotImplementedException이 존재 합니까?
선제 적 스트라이크로서 나는 "디자이너가 자동 생성 코드에 이것을 넣어야하기 때문에"라고 대답하는 사람을 원하지 않습니다. 이것은 끔찍합니다. 차라리 자동 생성 코드는 구현을 제공 할 때까지 컴파일되지 않습니다. 예를 들어 자동 생성 구현은 "throw NotImplementedException;"이 될 수 있습니다. NotImplementedException이 정의되지 않은 곳!
누구든지 NotImplementedException을 포착하고 처리 한 적이 있습니까? 코드에 NotImplementedException을 남긴 적이 있습니까? 그렇다면 이것이 시한 폭탄 (예 : 실수로 거기에 놓아 두 었음) 또는 설계 결함 (메소드를 구현해서는 안되며 호출되지 않음)을 나타내는 것입니까?
NotSupportedException도 매우 의심 스럽습니다 ... 지원되지 않습니까? 뭐야? 지원되지 않는 경우 왜 인터페이스의 일부입니까? Microsoft의 누군가가 부적절한 상속을 철자 할 수 있습니까? 그러나 내가 이것에 대해 너무 학대받지 않는다면 다른 질문을 시작할 수 있습니다.
추가 정보:
이것은 주제에 대한 흥미로운 읽기입니다.
Brad Abrams 와 "NotImplementedException은 아직 구현되지 않은 기능을위한 것이지만 실제로는 그래야만합니다." 라는 강력한 동의가있는 것 같습니다 . 클래스를 빌드 할 때 시작할 수있는 것과 같은 것 , 모든 메서드를 가져옵니다. NotImplementedException을 던지고 실제 코드로 플러시합니다… "
Jared Parsons의 주석은 매우 약하므로 무시해야합니다. NotImplementedException : 유형이 다른 이유로 메서드를 구현하지 않을 때이 예외를 throw합니다.
MSDN은 단순히 진술, 주제에, 심지어 약한, 즉 "요청 방법 또는 작업이 구현되지 않은 경우에 슬로우되는 예외입니다."
유용한 상황이 하나 있습니다. TDD입니다.
테스트를 작성한 다음 테스트가 컴파일되도록 스텁을 만듭니다. 그 스텁은 throw new NotImplementedException();
. 이렇게하면 기본적으로 테스트가 실패합니다. 더미 반환 값을 사용하면 거짓 긍정이 발생할 수 있습니다. 이제 구현이 없기 때문에 모든 테스트가 컴파일되고 실패하므로 해당 스텁을 처리합니다.
NotImplementedException
다른 상황에서는 절대로 사용하지 않기 때문에 NotImplementedException
어떤 테스트가 항상 실패하게 만들 것이기 때문에 릴리스 코드를 전달하지 않습니다.
여기저기서 잡을 필요는 없습니다. 좋은 API는 발생한 예외를 문서화합니다. 그것들은 당신이 찾아야 할 것들입니다.
편집 : 나는 그들을 찾기 위해 FxCop 규칙을 작성했습니다.
다음은 코드입니다.
using System;
using Microsoft.FxCop.Sdk;
/// <summary>
/// An FxCop rule to ensure no <see cref="NotImplementedException"/> is
/// left behind on production code.
/// </summary>
internal class DoNotRaiseNotImplementedException : BaseIntrospectionRule
{
private TypeNode _notImplementedException;
private Member _currentMember;
public DoNotRaiseNotImplementedException()
: base("DoNotRaiseNotImplementedException",
// The following string must be the assembly name (here
// Bevonn.CodeAnalysis) followed by a dot and then the
// metadata file name without the xml extension (here
// DesignRules). See the note at the end for more details.
"Bevonn.CodeAnalysis.DesignRules",
typeof (DoNotRaiseNotImplementedException).Assembly) { }
public override void BeforeAnalysis()
{
base.BeforeAnalysis();
_notImplementedException = FrameworkAssemblies.Mscorlib.GetType(
Identifier.For("System"),
Identifier.For("NotImplementedException"));
}
public override ProblemCollection Check(Member member)
{
var method = member as Method;
if (method != null)
{
_currentMember = member;
VisitStatements(method.Body.Statements);
}
return Problems;
}
public override void VisitThrow(ThrowNode throwInstruction)
{
if (throwInstruction.Expression != null &&
throwInstruction.Expression.Type.IsAssignableTo(_notImplementedException))
{
var problem = new Problem(
GetResolution(),
throwInstruction.SourceContext,
_currentMember.Name.Name);
Problems.Add(problem);
}
}
}
다음은 규칙 메타 데이터입니다.
<?xml version="1.0" encoding="utf-8" ?>
<Rules FriendlyName="Bevonn Design Rules">
<Rule TypeName="DoNotRaiseNotImplementedException" Category="Bevonn.Design" CheckId="BCA0001">
<Name>Do not raise NotImplementedException</Name>
<Description>NotImplementedException should not be used in production code.</Description>
<Url>http://stackoverflow.com/questions/410719/notimplementedexception-are-they-kidding-me</Url>
<Resolution>Implement the method or property accessor.</Resolution>
<MessageLevel Certainty="100">CriticalError</MessageLevel>
<Email></Email>
<FixCategories>NonBreaking</FixCategories>
<Owner></Owner>
</Rule>
</Rules>
이를 구축하려면 다음이 필요합니다.
참조
Microsoft.FxCop.Sdk.dll
및Microsoft.Cci.dll
라는 파일에 메타 데이터
DesignRules.xml
를 넣고 어셈블리에 포함 된 리소스로 추가합니다.어셈블리 이름을 지정합니다
Bevonn.CodeAnalysis
. 메타 데이터 또는 어셈블리 파일에 다른 이름을 사용하려면 그에 따라 두 번째 매개 변수를 기본 생성자로 변경해야합니다.
그런 다음 결과 어셈블리를 FxCop 규칙에 추가하고 귀중한 코드에서 이러한 예외를 제거하십시오. NotImplementedException이 발생했을 때보고하지 않는 몇 가지 코너 케이스가 있지만 실제로 그러한 cthulhian 코드를 작성하고 있다면 절망적이라고 생각합니다. 정상적인 사용의 경우, 즉 throw new NotImplementedException();
작동하며 그게 중요한 전부입니다.
작동하지만 부분적으로 만 완료된 API 인 상당히 일반적인 사용 사례를 지원하기 위해 있습니다. - 내가 시험을 개발자에게 원하고 내 API 평가 말해 WashDishes()
적어도 내 컴퓨터에서 작업을 시작하지만 최대 코딩 주위에 아직 확보하지 못했 DryDishes()
말할 것도없고 PutAwayDishes()
. 조용히 실패하거나 비밀스러운 오류 메시지를 표시하는 대신 왜 DryDishes()
작동하지 않는지에 대해 명확하게 알 수 있습니다 . 아직 구현하지 않았습니다.
자매 예외 NotSupportedException
는 대부분 공급자 모델에 적합합니다. 대부분의 식기 세척기에는 건조 기능이 있으므로 인터페이스에 속하지만 할인 식기 세척기는 지원하지 않습니다. 나는 그것을 통해 알 수 있습니다NotSupportedException
몇 가지 댓글에 흩어져 있기 때문에 이에 대한 내 견해를 한 곳에서 요약하겠습니다.
NotImplementedException
인터페이스 멤버가 아직 구현되지 않았지만 구현 될 것임을 나타내는 데 사용 합니다. 이를 자동화 된 단위 테스트 또는 QA 테스트와 결합하여 여전히 구현해야하는 기능을 식별합니다.기능이 구현되면
NotImplementedException
. 기능이 제대로 작동하는지 확인하기 위해 새로운 단위 테스트가 작성되었습니다.NotSupportedException
일반적으로 특정 유형에 맞지 않는 기능을 지원하지 않는 제공 업체에 사용됩니다. 이러한 경우 특정 유형은 예외를 발생시키고 클라이언트는이를 포착하여 적절하게 처리합니다.둘 다하는 이유
NotImplementedException
와이NotSupportedException
프레임 워크에 존재는 간단하다 상황이 프레임 워크에서 그들을 정의하는 의미가 있도록 그들에게 리드, 일반적인 것으로, 개발자를 재정의 유지할 필요가 없습니다 그래서. 또한 클라이언트가 잡을 예외를 쉽게 알 수 있습니다 (특히 단위 테스트의 컨텍스트에서). 자신 만의 예외를 정의해야한다면, 어떤 예외를 포착해야하는지 파악해야합니다.이 예외는 최소한 비생산적인 시간 소모이며 종종 부정확합니다.
NotImplementedException이 존재하는 이유는 무엇입니까?
NotImplementedException은 무언가가 아직 준비되지 않았다고 말하는 좋은 방법입니다. 준비되지 않은 이유는 메소드 작성자에게 별도의 질문입니다. 프로덕션 코드에서이 예외를 잡을 가능성은 거의 없지만, 그렇게했다면 무슨 일이 일어 났는지 즉시 볼 수 있고 메서드가 호출 된 이유를 알아내는 것보다 훨씬 낫습니다. "재미있는"부작용.
NotImplementedException은 Java의 UnsupportedOperationException에 해당하는 C #입니까?
아니요, .NET에는 NotSupportedException이 있습니다.
내 알고리즘을 실행하고 NotImplementedExceptions를 포착하고 내 애플리케이션을 정상적인 상태로 롤백하는 방법
좋은 API에는 가능한 예외를 설명하는 XML 메소드 문서가 있습니다.
NotSupportedException도 매우 의심 스럽습니다 ... 지원되지 않습니까? 뭐야? 지원되지 않는 경우 왜 인터페이스의 일부입니까?
수백만 가지 이유가있을 수 있습니다. 예를 들어 새로운 버전의 API를 도입하고 이전 메소드를 지원하거나 지원하지 않을 수 있습니다. 다시 말하지만, 문서를 파거나 타사 코드를 디버깅하는 것보다 설명적인 예외를 보는 것이 훨씬 낫습니다.
NotImplementedException 예외의 주요 용도는 생성 된 스텁 코드에 있습니다. 이렇게하면 구현하는 것을 잊지 않습니다 !! 예를 들어 Visual Studio는 NotImplementedException을 throw하는 본문을 사용하여 인터페이스의 메서드 / 속성을 명시 적으로 구현합니다.
다시 NotImplementedException
-이것은 몇 가지 용도로 사용됩니다. 예를 들어 단위 테스트가 불완전한 작업에 대해 잠글 수있는 단일 예외를 제공합니다. 그러나 또한 실제로 말하는대로 수행합니다. 이것은 단순히 (아직) 존재하지 않습니다. 예를 들어, "mono"는 MS 라이브러리에 존재하지만 아직 작성되지 않은 메서드에 대해이 모든 것을 처리합니다.
다시 NotSupportedException
-모든 것을 사용할 수있는 것은 아닙니다. 예를 들어, 많은 인터페이스에서 "can you do this?"쌍을 지원합니다. / "이 작업을 수행". "이거 할 수있어?" false를 반환합니다. "do this"가 NotSupportedException
. 예는 IBindingList.SupportsSearching
/ IBindingList.Find()
등일 수 있습니다 .
Microsoft의 대부분의 개발자는 NotImplementedException이 적절한 디자인 패턴에 익숙합니다. 사실 꽤 흔합니다.
좋은 예는 여러 개체를 개체의 단일 인스턴스로 처리 할 수 있는 Composite Pattern 입니다. 구성 요소는 (적절하게) 상속 된 리프 클래스의 기본 추상 클래스로 사용됩니다. 예를 들어, File 및 Directory 클래스는 매우 유사한 유형이기 때문에 동일한 추상 기본 클래스에서 상속 할 수 있습니다. 이렇게하면 단일 객체로 취급 할 수 있습니다 (파일과 디렉토리가 무엇인지 생각할 때 의미가 있습니다. 예를 들어 Unix에서는 모든 것이 파일입니다).
따라서이 예제에서는 Directory 클래스에 대한 GetFiles () 메서드가 있지만 File 클래스는이 메서드를 구현하지 않습니다. 그렇게하는 것이 타당하지 않기 때문입니다. 대신 파일에는 디렉토리와 같은 자식이 없기 때문에 NotImplementedException이 발생합니다.
이것은 .NET에 국한되지 않습니다. 많은 OO 언어와 플랫폼에서이 패턴을 보게 될 것입니다.
가능한 모든 예외를 포착해야하는 이유는 무엇입니까? 모든 메서드 호출도 함께 래핑 catch (NullReferenceException ex)
합니까?
스텁 코드 던지기 NotImplementedException
는 자리 표시 자입니다. 릴리스 할 경우 NullReferenceException
.
MS가 프레임 워크에 NotImplementedException을 추가 한 데는 여러 가지 이유가 있다고 생각합니다.
- 편의상; 많은 개발자가 개발 중에 필요로하는데 왜 모든 사람이 스스로 롤링해야합니까?
- 도구는 그 존재에 의존 할 수 있습니다. 예를 들어 Visual Studio의 "Implement Interface"명령은 NotImplementedException을 발생시키는 메서드 스텁을 생성합니다. 프레임 워크에 없으면 가능하지 않거나 적어도 다소 어색합니다 (예 : 자체 NotImplementedException을 추가 할 때까지 컴파일되지 않는 코드를 생성 할 수 있음).
- 일관된 "표준 관행"장려
Frankodwyer는 NotImplementedException을 잠재적 인 시한 폭탄으로 생각합니다. 완성되지 않은 코드는 시간 폭탄이라고 말하고 싶지만 NotImplementedException은 대안보다 무장 해제하기가 훨씬 쉽습니다. 예를 들어 빌드 서버에서이 클래스의 모든 사용에 대한 소스 코드를 스캔하고 경고로보고하도록 할 수 있습니다. 정말로 금지하고 싶다면 그러한 코드의 체크인을 방지하는 사전 커밋 후크를 소스 제어 시스템에 추가 할 수도 있습니다.
물론 자신의 NotImplementedException을 굴리는 경우 최종 빌드에서 제거하여 시한 폭탄이 남아 있지 않은지 확인할 수 있습니다. 그러나 이것은 전체 팀에서 자신의 구현을 일관되게 사용하는 경우에만 작동하며 릴리스하기 전에 제거하는 것을 잊지 않도록해야합니다. 또한 제거 할 수없는 경우도 있습니다. 예를 들어 고객에게 제공되지 않는 코드를 테스트 할 때 허용되는 몇 가지 용도가있을 수 있습니다.
실제로 NotImplementedException을 잡을 이유가 없습니다 . 공격을 받으면 앱이 종료되고 매우 고통 스럽습니다. 그것을 고치는 유일한 방법은 그것을 잡는 것이 아니라 소스 코드를 변경하는 것입니다 (호출 된 메소드를 구현하거나 호출 코드를 변경하는 것).
두 가지 이유 :
메서드는 개발 중에 스텁 처리되고 예외를 발생시켜 개발자에게 코드 작성이 완료되지 않았 음을 상기시킵니다.
설계 상 상속 된 기본 클래스 또는 인터페이스의 하나 이상의 메서드를 구현하지 않는 하위 클래스 인터페이스를 구현합니다. (일부 인터페이스는 너무 일반적입니다.)
이것은 나에게 잠재적 인 지뢰밭처럼 들린다. 먼 과거에 나는 한때 수년간 쉬지 않고 실행되어 하루가 넘어가는 레거시 네트워크 시스템에서 일했습니다. 문제를 추적했을 때 분명히 완성되지 않았고 결코 작동하지 않았던 코드를 발견했습니다. 말 그대로 프로그래머가 코딩하는 동안 중단 된 것처럼 말입니다. 이 특정 코드 경로는 이전에 한 번도 사용되지 않았 음이 분명했습니다.
Murphy의 법칙은 NotImplementedException의 경우에도 비슷한 일이 일어나기를 간청하고 있다고 말합니다. 요즘 TDD 등에서 허용되면 릴리스 전에 선택해야하며 적어도 릴리스 전에 해당 예외에 대한 코드를 grep 할 수 있지만 여전히 그렇습니다.
테스트 할 때 모든 케이스의 적용 범위를 보장하는 것은 어렵고 컴파일 타임 문제 일 수있는 런타임 문제를 만들어 작업을 더 어렵게 만드는 것처럼 들립니다. (나는 유사한 종류의 '기술적 부채'가 '덕 타이핑'에 크게 의존하는 시스템과 함께 제공되지만 매우 유용하다는 것을 인정합니다.)
COM interop에는이 예외가 필요합니다. E_NOTIMPL 입니다. 링크 된 블로그는 다른 이유도 보여줍니다.
Throwing NotImplementedException
은 IDE가 컴파일 링 스텁 코드를 생성하는 가장 논리적 인 방법입니다. 인터페이스를 확장하고 Visual Studio에서이를 스텁 할 때와 같습니다.
약간의 C ++ / COM을 수행했다면 E_NOTIMPL
.
이에 대한 유효한 사용 사례가 있습니다. 인터페이스의 특정 메서드에서 작업하는 경우 코드를 컴파일하여 디버깅하고 테스트 할 수 있습니다. 논리에 따라 인터페이스에서 메서드를 제거하고 컴파일되지 않는 스텁 코드를 주석 처리해야합니다. 이것은 매우 근본주의적인 접근 방식이며 장점이 있지만 모든 사람이 그것을 고수하거나 고수해서는 안됩니다. 게다가 대부분의 경우 인터페이스가 완성되기를 원합니다.
Having a NotImplementedException nicely identifies which methods are not ready yet, at the end of the day it's as easy as pressing Ctrl+Shift+F
to find them all, I am also sure that static code analysis tools will pick it up too.
You are not meant to ship code that has NotImplementedException
exception. If you think that by not using it you can make your code better, go forth, but there are more productive things you can do to improve the source quality.
NotImplementedException
The exception is thrown when a requested method or operation is not implemented.
Making this a single exception defined in the .NET core makes it easier to find and eradicate them. If every developer should create their own ACME.EmaNymton.NotImplementedException
it would be harder to find all of them.
NotSupportedException
The exception is thrown when an invoked method is not supported.
For instance when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.
For instance generated iterators (using yield
keyword) is-a IEnumerator
, but the IEnumerator.Reset
method throws NotSupportedException
.
From ECMA-335, the CLI specification, specificialy the CLI Library Types, System.NotImplementedException, remarks section:
"A number of the types and constructs, specified elsewhere in this Standard, are not required of CLI implementations that conform only to the Kernel Profile. For example, the floating-point feature set consists of the floating-point data types System.Single and System.Double. If support for these is omitted from an implementation, any attempt to reference a signature that includes the floating-point data types results in an exception of type System.NotImplementedException."
So, the exception is intended for implementations that implement only minimal conformance profiles. The minimum required profile is the Kernel Profile (see ECMA-335 4th edition - Partition IV, section 3), which includes the BCL, which is why the exception is included in the "core API", and not in some other location.
Using the exception to denote stubbed methods, or for designer generated methods lacking implementation is to misunderstand the intent of the exception.
As to why this information is NOT included in the MSDN documentation for MS's implementation of the CLI is beyond me.
I can't vouch for NotImplementedException (I mostly agree with your view) but I've used NotSupportedException extensively in the core library we use at work. The DatabaseController, for example, allows you to create a database of any supported type then use the DatabaseController class throughout the rest of your code without caring too much about the type of database underneath. Fairly basic stuff, right? Where NotSupportedException comes in handy (and where I would have used my own implementation if one didn't already exist) is two main instances:
1) Migrating an application to a different database It's often argued this rarely, if ever, happens or is needed. Bullsh*t. Get out more.
2) Same database, different driver Most recent example of this was when a client who uses an Access-backed application upgraded from WinXP to Win7 x64. Being no 64-bit JET driver, their IT guy installed the AccessDatabaseEngine instead. When our app crashed, we could easily see from the log it was DB.Connect crashing with NotSupportedException - which we were quickly able to address. Another recent example was one of our programmers trying to use transactions on an Access database. Even though Access supports transactions, our library doesn't support Access transactions (for reasons outside the scope of this article). NotSupportedException, it's your time to shine!
3) Generic functions I can't think of a concise "from experience" example here but if you think about something like a function that adds an attachment to an email, you want it to be able to take a few common files like JPEGs, anything derived from various stream classes, and virtually anything which has a ".ToString" method. For the latter part, you certainly can't account for every possible type so you make it generic. When a user passes OurCrazyDataTypeForContainingProprietarySpreadsheetData, use reflection to test for the presence of a ToString method and return NotSupportedException to indicate lack of support for said data types that don't support ToString.
NotSupportedException isn't by any means a crucial feature but it's something I find myself using a lot more as I work on larger projects.
Lets say you have this method in your production code
public void DoSomething()
Which one would you take if you want to leave it later to be finished?
public void DoSomething()
{
}
or
public void DoSomething()
{
throw new NotImplementedException();
}
I would certainly take the second. Coupled with Elmah or whatever error logging mechanism you have (implemented as an aspect across your entire application). Together with log/exception filtering to trigger for critial error email notification when one is caught.
The argument that NotImplementedException == unfinished isn't correct either. (1) Catching of unimplemented methods should be left to unit tests/ integration tests. If you have 100% coverage (which you should now do, with so many many mock/stub/code generation tools) with no NotImplementedException, what are your worries? (2) Code generation. Plain simple. Again, if I generate the code, and only use half of the generated code, why wouldn't I have NotImplementedException in the rest of the generated stub?
It's like saying code shouldn't compile unless every nullable input should be checked/handled for null. (AKA the trillion dollar mistake, if not more). Language should be flexible, while tests/contracts should be solid.
Rarely I do use it for interface fixing. Assume that you've an interface that you need to comply but certain method will be never called by anyone, so just stick a NotImplementedException and if someone calls it they will know they are doing something wrong.
NotImplementedException is thrown for some method of .NET (see the parser C# in Code DOM which is not implemented, but the method exist !) You can verify with this method Microsoft.CSharp.CSharpCodeProvider.Parse
They are both hacks for two common problems.
NotImplementedException is a workaround for developers who are architecture astronauts and like to write down the API first, code later. Obviously, since this is not a incremental process, you can't implement all at once and therefore you want to pretend you are semi-done by throwing NotImplementedException.
NotSupportedException is a hack around the limitation of the type systems like those found in C# and Java. In these type systems, you say that a Rectangle 'is a' Shape iff Rectangle inherits all of Shapes characteristics (incl. member functions + variables). However, in practice, this is not true. For example, a Square is a Rectangle, but a Square is a restriction of a Rectangle, not a generalization.
So when you want to inherit and restrict the behavior of the parent class, you throw NotSupported on methods which do not make sense for the restriction.
What about prototypes or unfinished projects?
I don't think this is a really bad idea to use an exception (although I use a messagebox in that case).
Well, I somewhat agree. If an interface has been made in such a way that not all class can implement all bits of it, it should've been broken down in my opinion.
If IList can or cannot be modified, it should've been broken down into two, one for the unmodifiable part (getters, lookup, etc.), and one for the modifiable part (setters, add, remove, etc.).
I have a few NotImplementedExceptions in my code. Often times it comes from part of an interface or abstract class. Some methods I feel I may need in the future, they make sense as being part of the class, but I just don't want to take the time to add unless I actually need it. For example, I have an interface for all the individual kinds of stats in my game. One of those kinds are a ModStat, which is the sum of the base stat plus all the modifiers (ie weapons, armor, spells). My stat interface has an OnChanged event, but my ModStat works by calculating the sum of all stats it references each time it is called. So instead of having the overhead of a ton of ModStat.OnChange events being raised every time a stat changes, I just have a NotImplementedException thrown if anyone tries to add/remove a listener to OnChange.
.NET languages are all about productivity, so why spend your time coding something you won't even use?
Here is one example: In Java, whenever you implement the interface Iterator
, you have to override the obvious methods hasNext()
and next()
, but there is also delete()
. In 99% of the usecases I have I do not need this, so I just throw a NotImplementedException
. This is much better than silently doing nothing.
The NotImplementedException exists only to facilitate development. Imagine you start implementing an interface. You'd like to be able to at least build when you are done implementing one method, before moving to the next. Stubbing the NotImplemented methods with NotImplementedExceptions is a great way of living unfinished code that is super easy to spot later. Otherwise you would run the risk of quickly implementing something that you might forget to fix.
If you don't want to use it then just ignore it. If you have a block of code whose success depends on every piece of it succeeding, but it might fail in between, then your only option is to catch the base Exception
and roll back what needs to be rolled back. Forget NotImplementedException
. There could be tons of exceptions thrown, like MyRandomException
and GtfoException
and OmgLolException
. After you originally write the code I could come by and throw ANOTHER exception type from the API you're calling. One that didn't exist when you wrote your code. Handle the ones you know how to handle and rollback for any others i.e., catch(Exception)
. It's pretty simple, I think... I find it comes in handy too. Especially when you're trying fancy things with the language/framework that occasionally force things upon you.
One example I have is serialization. I have added properties in my .NET library that don't exist in the database (for example, convenient wrappers over existing "dumb" properties, like a FullName
property that combines FirstName
, MiddleName
, and LastName
). Then I want to serialize these data types to XML to send them over the wire (for example, from an ASP.NET application to JavaScript), but the serialization framework only serializes public properties with both get
and set
accessors. I don't want you to be able to set FullName
because then I'd have to parse it out and there might be some unforeseen format that I wrongly parse and data integrity goes out the window. It's easier to just use the underlying properties for that, but since the language and API require me to have a set
accessor, I'll throw a NotImplementedException
(I wasn't aware of NotSupportedException
until I read this thread, but either one works) so that if some programmer down the road does try to set FullName
he'll encounter the exception during testing and realize his mistake.
참고URL : https://stackoverflow.com/questions/410719/why-does-notimplementedexception-exist
'IT Share you' 카테고리의 다른 글
임의의 값으로 배열 만들기 (0) | 2020.11.15 |
---|---|
빈 폴더 구조 커밋 (git 사용) (0) | 2020.11.15 |
IE8 : nth-child 및 : before (0) | 2020.11.15 |
UITextView-XCode 5의 iOS 6에서 글꼴 설정이 작동하지 않음 (0) | 2020.11.15 |
iOS : UISegmentedcontrol의 높이 변경 (0) | 2020.11.15 |