다음을 통해 공유


Designing .NET Class Libraries: Setting the Stage (January 19, 2005)

Posted: February 14, 2005

Please note: Portions of this transcript have been edited for clarity

Introduction

Moderator:
frankred – MSDN .NET Framework Developer Center Content Strategist

Experts:
Brad Abrams – Lead Program Manager CLR Team
Joe Duffy – Program Manager CLR Team
Krzysztof Cwalina – Program Manager CLR Team

frankred (Moderator):
Hello. Welcome to today’s chat on Designing .NET Class Libraries. The chat will begin in a few minutes, so get your questions ready!

frankred (Moderator):
Now, let’s introduce our knowledgeable experts...

BradA [MS] (Expert):
Hello! I am a PM on the CLR team and I have been working on the Framework Design Guidelines topic for 6+ years now. I hosted the training series that we kicked off this week. Check out my blog at https://blogs.msdn.com/brada

Start of Chat

Joe Duffy (Expert):
Q: What is the current status of the Singleton pattern in the Framework Class Libraries? There are a few places in the Framework that use lazy initialization for static values (like in Environment.OSVersion) which can cause race conditions.
A: Race conditions are tricky to handle, and in a lot of cases we just accept that we'll end up recomputing values in some situations. If this is unacceptable (e.g. due to side effects of recomputing the value), we recommend a double checked lock pattern.

Joe Duffy (Expert):
Q: Are there reasonable tradeoffs for thread-safety in this situation?
A: You need not worry about thread safety if it's OK to recompute a value. Otherwise, you'll need to do a double check. e.g. Checking for null inside a synchronized block of code. It's not even necessary to use volatile for the shared variable (in most cases).

Joe Duffy (Expert):
Q: Joe, are you sure?? https://www.yoda.arachsys.com/csharp/singleton.html
A: Yeah, it's an ongoing debate. Based on the ECMA specification we shipped and implemented the EE based on (pre-Whidbey), it's true that the double checked lock (as written in that article) was incorrect. However, we've made a ton of improvements to strengthen our memory model in Whidbey which are unfortunately not specified or well documented (even here in the CLR team!). The bottom line is that volatility isn't required in this particular case any longer--we do a lot of this for free. I'm actually trying to get this incorporated into the ECMA spec at some point as an Informative section, but it's doubtful this will happen in Whidbey. I'm trying to coerce either Rico or Chris to write up a blog entry... if that doesn't work, I'll try to post something. :)

BradA [MS] (Expert):
Q: How much have the design guidelines changed since work first started on the BCL?
A: Very few of the design guidelines have completely changed since V1, but we have certainly added a bunch. As we learn new things and get more features out of the CLR we find need for new design guidelines. Generics is a good example, we have a bunch of new design guidelines around generics in V2.

BradA [MS] (Expert):
Q: How much of a factor should FxCop be on framework design?
A: FxCop is key. In fact, in many ways the library design guidelines and FxCop evolve together. As we add a new guideline we almost always add a new set of FxCop rules. The truth is, even when I design class libraries I need to check it with FxCop. Some things are just better done with a tool.

Krzysztof [MS] (Expert):
Q: I have been using Beta 1 and love generics. However, there seems to be one critical omission: support for generic operator overloading. Will there be future support for this and what are the current recommendations for working around this?
A: If I remember correctly, we talked briefly about generic operator overloads and the following points were raised:
1. Operator overloads are a rarely used feature in general, so not a big ban for the buck.
2. It is unclear what the syntax would be for languages that don't support type inferencing.
3. Would it be kind of strange to change type in operator overloads? :-)

BradA [MS] (Expert):
Q: I'd like pointers on identifying appropriate code and tips on moving that existing code into a framework for easy reuse in my applications.
A: Moving existing code into the managed world is an important problem. Like most companies, Microsoft has a huge amount of unmanaged code that we need to make available to managed frameworks. The Designing .NET Class Libraries: Understanding Interoperability presentation by Sonja Keserovic presents some very good ideas, so please watch her presentation which will be published on Friday, March 18 and join us for the follow-up chat on Wednesday, March23.

BradA [MS] (Expert):
Q: I would like guidance on API design including:
1. naming conventions
2. logical procedures to decompose an application into components
3. grouping of functions
4. use of data structures as API elements
A: Naming conventions will be covered in detail next week when Designing .NET Class Libraries: Naming Conventions is published on Friday, January 21, so please watch the presentation and join us for the follow-up chat on Wednesday, January 26
Unfortunately, we are not explicitly covering OO design
Grouping of functions and
Use of data structures as API elements will be covered in Designing .NET Class Libraries: Designing Progressive APIs, which will be published on Friday, February 25

Krzysztof [MS] (Expert):
Q: Why are there no interfaces like IQueue for System.Collections.Queue? Most of the methods in those classes are no longer virtual, but there is no workaround for this.
A: We try to be very careful with introducing interfaces to the base class namspaces. We want to be absolutely sure that the interface is useful b/c too many interfaces just adds to the complexity of the APIs. By useful, I mean that there are interesting algorithms that would take IQueue that would not take ICollection instead.

Krzysztof [MS] (Expert):
Q: Users ask to be able to override Enqueue and Dequeue or define their own collection. See FDBK20200 :-((
A: I will take a look at FDBK20200. But if you want to implement a custom queue, I would just implement ICollection.

BradA [MS] (Expert):
Q: Why was the .NET Framework 2.0 designed with so much backward compatibility with v1.0?
A: Backwards compatibility of the Framework from V1.0 to V2.0 is a great issue. It is one that I personally spend hours each week discussing with folks here at MS and with customers. I feel very passionately that the framework has to continue to get better each release. In fact, I believe that Whidbey is, overall, more consistent than V1.0 or V1.1 of the Framework. We put better processes in place and had more accountability for “good” designs. And WinFX will be even better. That said, our customers have apps and more importantly experience with the framework, so we MUST honor their investments or they will not continue to invest in the platform.

Joe Duffy (Expert):
Q: In .NET Framework 2.0 are more of the exception types overloaded to take an Exception type parameter to set their inner exception property? This has been very frustrating for me in 1.0 and 1.1, especially with ArgumentNull and its derived classes.
A: Yes. This overload has been added for v2.0. This is actually a very strict design guideline that we have --implementation of all of the standard exception constructors (ctor(), ctor(string), ctor(string, exception)). And we have FxCop rules that enforce this, too. Recently, we went thru our codebase and scrubbed places that were inconsistent. I just checked the code recently, and we did indeed add this overload to ArgumentNullException.

BradA [MS] (Expert):
Q: How will the documentation of the API change going forward? Are there plans to improve the descriptions and samples across the board?
A: You raise a good point, that just designing APIs themselves is not enough. We have to make the APIs useable and great sample code is part of that. While we are always working on getting more samples into the docs, the feature of MSDN that I am really looking forward to in Whidbey is “annotations” where you will be able to share sample code for APIs with other developers. I think this will result in the community doing more and better samples that we could ever do alone.

Joe Duffy (Expert):
Q: You mention API complexity. Do you have any procedure to measure the complexity of the API numerically?
A: You might be interested in checking out the "cognitive dimensions" framework. Our usability folks use it to grade API complexity along a number of axes, but it's not as simple as cranking out a number. What it does is it actually maps an API to what you think your target audience is, so you can validate the tradeoffs you have chosen to make. https://blogs.msdn.com/stevencl/ has further information. Check along the left sidebar (bottom)--there are links to Steven's posts on the topic. He's a major contributor to the framework in terms of providing usability studies, evaluations, etc.

Krzysztof [MS] (Expert):
Q: You mention API complexity. Do you have any procedure to measure the complexity of the API numerically?
A: We don't have any automated tools. I played with some ideas for a while, but it varies so much from namespace to namespace. What's complex for base types, may not be considered complex for DataGrid control. I think one of the best measures of complexity is: can a non expert describe the feature/namespace/API after playing with it for 15-30 minutes. In fact, we do studies like that in our usability labs all the time.

Krzysztof [MS] (Expert):
Q: Thank you, I read Steven Clarke's paper: The “cognitive dimensions” seem hard to apply in practice. I am interested in simpler measures and wondered if you followed for instance 'rules of thumb' such as limiting the number of interfaces, etc.
A: Yes, we do look at some macro measurements (e.g. # of interfaces, methods, parameters) but I do it on intuition and adjust based on what the APIs I happen to be reviewing are. I was not able to put enough smarts in the tool prototypes I mentioned above to make them useful.

Joe Duffy (Expert):
Q: Will the entire series be available for download after all of them are available? I expect the series will be a great training tool to new team members. Saving it off for local access would be a plus.
A: Yes, we plan to make the presentations available for download at the end of the series.

BradA [MS] (Expert):
Q: We need to know what are the important points for designing .NET Framework class libraries?
A: Well, I’d say the first point is to “know thy customer”. Know what they want, when and why they want it. The 2nd point is to focus on developer productivity. That is really what framework design is all about, making developers more productive. If you keep those two things in mind, you will at least be in the right ball park.

frankred (Moderator):
Q: Can you give some pointers to good reading on class design & OO, preferably reading that uses C# terms? I'm looking for something not just on the very basics, but going a bit further in, perhaps for "intermediate" level of reader.
A: I would recommend checking out:
Design Patterns
by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides

Design Patterns C#
by Steven John Metsker

Enterprise Solution Patterns Using Microsoft .Net: Version 2.0 : Patterns & Practices
By Microsoft Corporation

BradA [MS] (Expert):
Q: The datatable uses an arraylist to store the data in 1.x. Large tables can be very slow when deleting, for obvious reasons. Has this been replaced with some sort of more efficient hashtable or custom red-black tree to improve the speed of datatables?
A: Sorry, I don't know. If you'd like me to follow up use the "contact me" link off my blog on https://blogs.msdn.com/brada

BradA [MS] (Expert):
Q: Is it possible to use a .NET Framework 1.1 DLL with the .NET Framework 2.0 without recompilation?
A: Yes. That is the backward compatibility item we talked about earlier in the chat. There are a handful of known problems, but they are fairly niche. Please try it out and report a bug if does not work for you.

Joe Duffy (Expert):
Q: Are there any future plans to be able to track all the stack traces (& show multiple stack traces)? For example, to detect where exceptions were caught and rethrown without wrapping inside another exception?
A: This is already possible. There are two ways to "re-throw" an exception. Using C# as the sample language, from within a "catch (Exception e) { ... }" for example, you can either "throw;" or "throw e;" where e is the caught exception. The first example just rethrows the existing caught exception, so it preserves the stack trace and adds a new stack entry. The second wipes out and creates a new stack trace. If you want to preserve the trace, you should use the plain "throw;".

Joe Duffy (Expert):
Q: Simply "throw;" does not add anything. ;-) There is only one StackTrace property. Currently, the only way is to chain exceptions, but this will loose details about the original exception type. :-(
A: What are you trying to accomplish? A throw enables you to deal with an exception (roll back critical state, etc) before letting the exception propagate. Doing this maintains all of the details about the original exception, and once it escapes the enclosing call stack, it'll get tagged on top of the existing stack trace. It maintains and extends the existing StackTrace property.

Joe Duffy (Expert):
Q: If you have a lot of catch() { rethrow; } statements, sometimes the user gets an exception that you did not expect, in which case there is no information about who has seen it and who decided to rethrow it.
A: Ahhhhh... I see. So basically, you want to tag the exception somehow to let people know "hey, I saw this, and decided it wasn't worth my time to handle... so I rethrew it." That is a pretty interesting problem, and does involve some debugging to figure it out. I guess the best advice is: you need to choose whether to rethrow and preserve the stack trace, or wrap it and get rid of the trace. (Which consequently is what you said in your 1st question, I believe.) For debuggability, I think the 1st solution is better. At least you can find the origin, and pretty easily track down the handler that decided to rethrow.

Joe Duffy (Expert):
Q: One more question, in the case an “if” code inside a catch( ) block results in another exception, is there any way to see both the original exception and new one? Like a "Got NillPointerException (stacktrace) while dispatching AccessViolationException(another stack)"
A: This would only happen if your code explicitly wrapped it, which is a bit difficult to do since InnerException only has a getter. In general, the meaning of InnerException is used for somewhat different things, such as when you're wrapping an underlying exception into a uniform exception type to propagate up to your API callers. So to answer your question: no, there isn't a straightforward way to do this.

Joe Duffy (Expert):
Q: TAG, that last question you just asked is easily handled with a custom exception. Catch IndexOutOfRange, handle it, log it, whatever, send it to a ctor for a custom exception of yours that gets rethrown with the information.
A: Agreed. If you know precisely which exception you need to catch and wrap, you can do this. However, it's tough to do it in a generic fashion.

Krzysztof [MS] (Expert):
Q: Are there plans for covariant and contravariant support in the future? I recall reading about why IEnumerable inherits IEnumerable in BradA’s blog, but it sounds like a hack to overcome the current lack of covariant and contravariant functionality.
A: The CLR already supports variance. Microsoft programming languages don't and most language designers at the company believe they will not add the support to the languages. The main reason is that the CLR variance annotations apply to the whole type (not on a member by member basis) and there are just not that many interesting types that are fully co- or contra- variant. IEnumerable is, but ICollection for example is not.

BradA [MS] (Expert):
**Q:**Will naming conventions be discussed for both Visual Basic .NET and Visual C# .NET?
A: Yes. We cover the guidelines for a multi-language framework, one that is targeted by C# and VB. But keep in mind; we don't talk about implementation details, just the public shape of the APIs.

BradA [MS] (Expert):
Q: The Designing .NET Class Libraries looks like it will be an AWESOME series! Is there any way for me to watch the whole presentation now, or must I wait until April 15 to be able to see the whole thing?

A: Thanks! We certainly find it valuable internally! The only way to see the entire series is to join us each week until the entire series is published. Once the entire series is published, it will remain public for as long as the content is relevant. In the meantime, you can take a look at the Design Guidelines doc from V1.1 which served as the basis for a large chunk of the material. The Design Guidelines docs are up on MSDN: https://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconnetframeworkdesignguidelines.asp.

BradA [MS] (Expert):
Q: Is there a way to tell which classes/class members are part of the CLI and which ones are additional from MS?
A: Yes. Of course there is, buy my book! The SLAR covers that data... https://www.amazon.com/exec/obidos/redirect?tag=bradabramsblo-20&path=ASIN%2F0321154894%2Fref%253Dpe%255Fsnp%255F894. Also you can check out the ECMA specs up on the .NET Framework Developer Center. https://msdn.microsoft.com/netframework/programming/clr/

BradA [MS] (Expert):
Oh, I just had to the plug the book, you know. BTW, you know I don't get any money from the book.

Krzysztof [MS] (Expert):
Q: What are the main concerns regarding the security while designing .NET framework class libraries.
A: Security in libraries is a very broad subject. I would search for PAG on writing secure code. A few things that pop up for me are: making sure data that should be read-only is truly read-only. For example, don't give external code access to internal arrays. Of course, making sure you don't Assert CAS permissions without a good reason. Also, regular buffer overrun issues when working in unsafe blocks.

frankred (Moderator):
Q: These Designing .NET Class Libraries chat sessions could perhaps benefit if there was additional information (perhaps a powerpoint/web page) to go along containing useful links regarding the subject. Like past/future webcasts, etc. Much work though…
A: Great suggestion. The plan is to evolve/expand the Designing .NET Class Libraries section https://msdn.microsoft.com/netframework/programming/classlibraries/ over time to do just that. So, so stay tuned! And be sure to let us know what you think.

BradA [MS] (Expert):
Q: Will the ECMA-335 and ISO/IEC 23271 standards be appropriately updated to correspond with the new Whidbey release?
A: Yes. The CLI (and BCL) and C# standard currently located on the .NET Framework Developer Center at https://msdn.microsoft.com/netframework/programming/clr/ will be updated to match V2.0. The major new feature is generics of course. In addition C++\CLI is in the standards world.

frankred (Moderator):
Q: Is there something special in .net to control the dllhost in the task manager. I mean, multiple instances while using com+ components?
A: Launch Component Services Explorer
Click on “COM+ Applications”.
Choose the “details” view (on toolbar).
Note the PID.
Launch Task Manager.
Choose View.Columns.
Pick PID.
Locate the PID of the COM+ Application in question.

Or try:

tlist –k (from the command prompt)

If a running dllhost.exe is a COM+ application, you will see something like:

3116 dllhost.exe Mts: System Application

Krzysztof [MS] (Expert):
Q: Are there any plans to update the current design guidelines? Some of the guidelines are no longer correct, e.g. deriving new exceptions from ApplicationExceptions, and many additions have been published via blogs.
A: Yes, we are going to update the MSDN guidelines around the time when Whidbey ships. We are also working on a way to ship the guidelines in an off-line form, as many people have requested. Maybe a book?

BradA [MS] (Expert):
Q: When you mention the design guidelines are contentious by nature, is this due to the multiple ways things can be done or do you have something else in mind? How contentious was the overall API design process for .NET?
A: Well... do you want to buy me a beer? :D Many of the guidelines are easy sells... they have a clear benifit and a clear solution. Other guidelines are more subjective... like the naming issues.. those are harder and have some heated debates, but it is all about our team wanting to make you more productive, but we don't always agree on what exactly that means in all cases.

BradA [MS] (Expert):
Q: Where to send a beer for Brad?
A: I might be coming to a city near you soon... https://blogs.msdn.com/brada/archive/2005/01/19/355988.aspx

Krzysztof [MS] (Expert):
Q: For the record, thank you for nullable types.
A: Thanks for all the questions and comments. I hope we will talk more at the next session. Bye

Joe Duffy (Expert):
Thanks for coming along! Ciao!

BradA [MS] (Expert):
Thanks again for coming, I hope you will join us next week when we will talk about naming conventions… And please forward this series to co-works that you think could use a little help in this area ;-) All are welcome.

frankred (Moderator):
Alright, it looks like we’re out of time. I hope everyone had a good time and got answers to all of their questions. If you have more questions please visit the CLR team blogs https://msdn.microsoft.com/netframework/community/blogs/default.aspx section on the .NET Framework developer center. Please join us again next Wednesday for the next chat in the Designing .NET Class Libraries https://msdn.microsoft.com/netframework/programming/classlibraries/ series.

Top of pageTop of page