Are protected members/fields really that bad? - c#

Now if you read the naming conventions in the MSDN for C# you will notice that it states that properties are always preferred over public and protected fields. I have even been told by some people that you should never use public or protected fields. Now I will agree I have yet to find a reason in which I need to have a public field but are protected fields really that bad?
I can see it if you need to make sure that certain validation checks are performed when getting/setting the value however a lot of the time it seems like just extra overhead in my opinion. I mean lets say I have a class GameItem with fields for baseName, prefixName, and suffixName. Why should I take the overhead of both creating the properties (C#) or accessor methods and the performance hit I would occur (if I do this for every single field in an application, I am sure that it would adds up at less a little especially in certain languages like PHP or certain applications with performance is critical like games)?

Are protected members/fields really that bad?
No. They are way, way worse.
As soon as a member is more accessible than private, you are making guarantees to other classes about how that member will behave. Since a field is totally uncontrolled, putting it "out in the wild" opens your class and classes that inherit from or interact with your class to higher bug risk. There is no way to know when a field changes, no way to control who or what changes it.
If now, or at some point in the future, any of your code ever depends on a field some certain value, you now have to add validity checks and fallback logic in case it's not the expected value - every place you use it. That's a huge amount of wasted effort when you could've just made it a damn property instead ;)
The best way to share information with deriving classes is the read-only property:
protected object MyProperty { get; }
If you absolutely have to make it read/write, don't. If you really, really have to make it read-write, rethink your design. If you still need it to be read-write, apologize to your colleagues and don't do it again :)
A lot of developers believe - and will tell you - that this is overly strict. And it's true that you can get by just fine without being this strict. But taking this approach will help you go from just getting by to remarkably robust software. You'll spend far less time fixing bugs.
And regarding any concerns about performance - don't. I guarantee you will never, in your entire career, write code so fast that the bottleneck is the call stack itself.

OK, downvote time.
First of all, properties will never hurt performance (provided they don't do much). That's what everyone else says, and I agree.
Another point is that properties are good in that you can place breakpoints in them to capture getting/setting events and find out where they come from.
The rest of the arguments bother me in this way:
They sound like "argument by prestige". If MSDN says it, or some famous developer or author whom everybody likes says it, it must be so.
They are based on the idea that data structures have lots of inconsistent states, and must be protected against wandering or being placed into those states. Since (it seems to me) data structures are way over-emphasized in current teaching, then typically they do need those protections. Far more preferable is to minimize data structure so that it tends to be normalized and not to have inconsistent states. Then, if a member of a class is changed, it is simply changed, rather than damaged. After all, somehow lots of good software was/is written in C, and that didn't suffer massively from lack of protections.
They are based on defensive coding carried to extremes. It is based on the idea that your classes will be used in a world where nobody else's code can be trusted not to goose your stuff. I'm sure there are situations where this is true, but I've never seen them. What I have seen is situations where things were made horribly complicated to get around protections for which there was no need, and to try to guard the consistency of data structures that were horribly over-complicated and un-normalized.

Regarding fields vs. properties, I can think of two reasons for prefering properties in the public interface (protected is also public in the sense that someone else than just your class can see it).
Exposing properties gives you a way to hide the implementation. It also allows you to change the implementation without changing the code that uses it (e.g. if you decide to change the way data are stored in the class)
Many tools that work with classes using reflection only focus on properties (for example, I think that some libraries for serialization work this way). Using properties consistently makes it easier to use these standard .NET tools.
Regarding overheads:
If the getter/setter is the usual one line piece of code that simply reads/sets the value of a field, then the JIT should be able to inline the call, so there is no performance overhad.
Syntactical overhead is largely reduced when you're using automatically implemented properties (C# 3.0 and newer), so I don't think this is an issue:
protected int SomeProperty { get; set; }
In fact, this allows you to make for example set protected and get public very easily, so this can be even more elegant than using fields.

Public and/or protected fields are bad because they can be manipulated from outside the declaring class without validation; thus they can be said to break the encapsulation principle of object oriented programming.
When you lose encapsulation, you lose the contract of the declaring class; you cannot guarantee that the class behaves as intended or expected.
Using a property or a method to access the field enables you to maintain encapsulation, and fulfill the contract of the declaring class.

I agree with the read-only property answer. But to play devil's advocate here, it really depends on what you're doing. I'll be happy to admit i write code with public members all the time (i also don't comment, follow guidelines, or any of the formalities).
But when i'm at work that's a different story.

It actually depends on if your class is a data class or a behaviour class.
If you keep your behaviour and data separate, it is fine to expose the data of your data classes, as long as they have no behaviour.
If the class is a behaviour class, then it should not expose any data.

Related

Is it a good practice to implement logic in properties

we use ASP.NET with C# and based on open source projects/articles I passed through, I found many properties were including a logic but when I did so the team-leader told me it's not good at all to place logic inside properties but to call the logic through methods...
is that really bad? and why not to use logic in the properties?
thanks,
Property access is expected to be instantaneous (no long waits), consistent (no changing values), and safe (no exceptions). If you can make those guarantees, I think putting logic in properties is OK.
It's fine to have some logic in properties. For example, argument validation in setters and lazy computation in getters are both fairly common.
It's usually a bad idea for a property access to do something expensive such as a database call, however. Developers tend to assume that properties are reasonably cheap to evaluate.
It's a judgement call in the end - but I certainly reject the suggestion that properties should only ever be trivial to the extent that they could be implemented with automatic properties.
Properties are methods. They are just short-cuts for getter/setters. Any logic that would be valid in a getter/setter is reasonable to put in a property. Any logic that you would normally not put in a getter/setter would be inappropriate to put in a property. Generally speaking, if you (as a consumer of the class) couldn't reaonsably expect that setting a property value, or even worse, getting a property value might cause a behavior to take place, then that logic probably belongs elsewhere. In other words, the logic should be related and consistent with getting or setting the property.
Quoting from the linked article above:
Properties are members that provide a
flexible mechanism to read, write, or
compute the values of private fields.
Properties can be used as though they
are public data members, but they are
actually special methods called
accessors. This enables data to be
accessed easily while still providing
the safety and flexibility of methods.
A common answer applies here: It Depends.
Generally, it is not a good idea to implement business logic in getters and setters. If your object is a simple DTO (data transfer object) this would violate Single Responsibility.
However, state-tracking logic and other housekeeping is often found in properties. For example, Entity Framework 4 self-tracking entities have state management logic in every primitive property setter to allow for tracking.
An alternative to logic in properties is Aspect-Oriented Programming (AOP.) Using AOP, you can "inject" logic between objects and the hosting process. Access to objects can be "intercepted" and handled conditionally.
Placing business logic in a setter can get you in trouble if you ever have the need to serialize/deserialize your objects with JSon, XML or an ORM. An example of this may be when using a NoSql datastore like a document database or an ORM. Some of these (e.g. NHibernate) can be configured to access backing fields instead of the setter.
I find that using a public Getter and Private setter along with a method to set the value with additional logic as required is a good approach. Most serializers can access the private setter so what you end up with is an accurate representation of the persisted object without accidentally firing logic that could potentially change values incorrectly when deserialized.
However, if you don't think there will ever be a need to serialize/deserialize then this shouldnt be an issue.
In my opinion this is absolutely ok. The way I see it, the only justification for having properties as a language feature in the first place is that you can have logic in them. Otherwise you may as well just allow direct access to the underlying data members.
Usually, a property only affect 1 variable since it was made mainly for that purpose. But sometime, you want a more high level property that isn't just a 1-to-1 variable. So, in this case, it's normal that it will contains code. But you have to keep in mind that a property is not intended to be used like a function. When you call a function, you know that it will do some processing. When you call a property, you expect it to be fast.
But finally, it's a question of preferences, and like coding standard, following what your superior is telling you is at your discretion. So it's not bad and depends on your judgment.
In my opinion business logic is allowed in Setter/Getter only in certain situations. For exaple: it's alowed to put logic that's responsible for validating the input, becase setters are responsible for maintainging object state, so that state should not be violated. So you should cut that business logic to smallest portion of code that is responsible only for one subject.
The other thing is that your class should be (in best situation) POCO. Why? Because it should be reusable and when class contains logic in Properties reusability can be simply blocked. Think that you have SqlServerPerson with some SQLServer validation in properties then it can be hard to replace it with for example NHibernatePerson when you change the ORM/DB access.

Why does StyleCop recommend prefixing method or property calls with "this"?

I have been trying to follow StyleCop's guidelines on a project, to see if the resulting code was better in the end. Most rules are reasonable or a matter of opinion on coding standard, but there is one rule which puzzles me, because I haven't seen anyone else recommend it, and because I don't see a clear benefit to it:
SA1101: The call to {method or property name} must begin with the 'this.' prefix to indicate that the item is a member of the class.
On the downside, the code is clearly more verbose that way, so what are the benefits of following that rule? Does anyone here follow that rule?
I don't really follow this guidance unless I'm in the scenarios you need it:
there is an actual ambiguity - mainly this impacts either constructors (this.name = name;) or things like Equals (return this.id == other.id;)
you want to pass a reference to the current instance
you want to call an extension method on the current instance
Other than that I consider this clutter. So I turn the rule off.
It can make code clearer at a glance. When you use this, it's easier to:
Tell static and instance members apart. (And distinguish instance methods from delegates.)
Distinguish instance members from local variables and parameters (without using a naming convention).
I think this article explains it a little
http://blogs.msdn.microsoft.com/sourceanalysis/archive/2008/05/25/a-difference-of-style.aspx
...a brilliant young developer at Microsoft (ok, it was me) decided to take it upon himself to write a little tool which could detect variances from the C# style used within his team. StyleCop was born. Over the next few years, we gathered up all of the C# style guidelines we could find from the various teams within Microsoft, and picked out all of best practices which were common to these styles. These formed the first set of StyleCop rules. One of the earliest rules that came out of this effort was the use of the this prefix to call out class members, and the removal of any underscore prefixes from field names. C# style had officially grown apart from its old C++ tribe.
this.This
this.Does
this.Not
this.Add
this.Clarity
this.Nor
this.Does
this.This
this.Add
this.Maintainability
this.To
this.Code
The usage of "this.", when used excessively or a forced style requirement, is nothing more then a contrivance used under the guise that there is < 1% of developers that really do not understand code or what they are doing, and makes it painful for 99% who want to write easily readable and maintainable code.
As soon as you start typing, Intellisence will list the content available in the scope of where you are typing, "this." is not necessary to expose class members, and unless you are completely clueless to what you are coding for you should be able to easily find the item you need.
Even if you are completely clueless, use "this." to hint what is available, but don't leave it in code. There are also a slew of add-ons like Resharper that help to bring clarity to the scope and expose the contents of objects more efficiently. It is better to learn how to use the tools provided to you then to develop a bad habit that is hated by a large number of your co-workers.
Any developer that does not inherently understand the scope of static, local, class or global content should not rely on "hints" to indicate the scope. "this." is worse then Hungarian notation as at least Hungarian notation provided an idea about the type the variable is referencing and serves some benefit. I would rather see "_" or "m" used to denote class field members then to see "this." everywhere.
I have never had an issue, nor seen an issue with a fellow developer that repeatedly fights with code scope or writes code that is always buggy because of not using "this." explicitly. It is an unwarranted fear that "this." prevents future code bugs and is often the argument used where ignorance is valued.
Coders grow with experience, "this." is like asking someone to put training wheels on their bike as an adult because it is what they first had to use to learn how to ride a bike. And adult might fall off a bike 1 in 1,000 times they get on it, but that is no reason to force them to use training wheels.
"this." should be banned from the language definition for C#, unfortunately there is only one reason for using it, and that is to resolve ambiguity, which could also be easily resolved through better code practices.
A few basic reasons for using this (and I coincidentally always prefix class values with the name of the class of which they are a part as well - even within the class itself).
1) Clarity. You know right this instant which variables you declared in the class definition and which you declared as locals, parameters and whatnot. In two years, you won't know that and you'll go on a wondrous voyage of re-discovery that is absolutely pointless and not required if you specifically state the parent up front. Somebody else working on your code has no idea from the get-go and thus benefits instantly.
2) Intellisense. If you type 'this.' you get all instance-specific members and properties in the help. It makes finding things a lot easier, especially if you're maintaining somebody else's code or code you haven't looked at in a couple of years. It also helps you avoid errors caused by misconceptions of what variables and methods are declared where and how. It can help you discover errors that otherwise wouldn't show up until the compiler choked on your code.
3) Granted you can achieve the same effect by using prefixes and other techniques, but this begs the question of why you would invent a mechanism to handle a problem when there is a mechanism to do so built into the language that is actually supported by the IDE? If you touch-type, even in part, it will ultimately reduce your error rate, too, by not forcing you to take your fingers out of the home position to get to the underscore key.
I see lots of young programmers who make a big deal out of the time they will save by not typing a character or two. Most of your time will be spent debugging, not coding. Don't worry so much about your typing speed. Worry more about how quickly you can understand what is going on in the code. If you save a total of five minutes coding and win up spending an extra ten minutes debugging, you've slowed yourself down, no matter how fast you look like you're going.
Note that the compiler doesn't care whether you prefix references with this or not (unless there's a name collision with a local variable and a field or you want to call an extension method on the current instance.)
It's up to your style. Personally I remove this. from code as I think it decreases the signal to noise ratio.
Just because Microsoft uses this style internally doesn't mean you have to. StyleCop seems to be a MS-internal tool gone public. I'm all for adhering to the Microsoft conventions around public things, such as:
type names are in PascalCase
parameter names are in camelCase
interfaces should be prefixed with the letter I
use singular names for enums, except for when they're [Flags]
...but what happens in the private realms of your code is, well, private. Do whatever your team agrees upon.
Consistency is also important. It reduces cognitive load when reading code, especially if the code style is as you expect it. But even when dealing with a foreign coding style, if it's consistent then it won't take long to become used to it. Use tools like ReSharper and StyleCop to ensure consistency where you think it's important.
Using .NET Reflector suggests that Microsoft isn't that great at adhering to the StyleCop coding standards in the BCL anyway.
I do follow it, because I think it's really convenient to be able to tell apart access to static and instance members at first glance.
And of course I have to use it in my constructors, because I normally give the constructor parameters the same names as the field their values get assigned to. So I need "this" to access the fields.
In addition it is possible to duplicate variable names in a function so using 'this' can make it clearer.
class foo {
private string aString;
public void SetString(string aString){
//this.aString refers to the class field
//aString refers to the method parameter
this.aString = aString;
}
}
I follow it mainly for intellisense reasons. It is so nice typing this. and getting a consise list of properties, methods, etc.

Creating a Catch-All AppToolbox Class - Is this a Bad Practice?

Never sure where to place functions like:
String PrettyPhone( String phoneNumber ) // return formatted (999) 999-9999
String EscapeInput( String inputString ) // gets rid of SQL-escapes like '
I create a Toolbox class for each application that serves as a repository for functions that don't neatly fit into another class. I've read that such classes are bad programming practice, specifically bad Object Oriented Design. However, said references seem more the opinion of individual designers and developers more than an over-arching consensus. So my question is, Is a catch-all Toolbox a poor design pattern? If so, why, and what alternative is there?
Great question. I always find that any sufficiently complex project require "utility" classes. I think this is simply because the nature of object-oriented programming forces us to place things in a neatly structured hierarchical taxonomy, when this isn't always feasible or appropriate (e.g. try creating an object model for mammals, and then squeeze the platypus in). This is the problem which motivates work into aspect oriented programming (c.f. cross cutting concern). Often what goes into a utility class are things that are cross-cutting concerns.
One alternative to using toolbox or utility classes, are to use extension methods to provide additional needed functionality to primitive types. However, the jury is still out on whether or not that constitutes good software design.
My final word on the subject is: go with it if you need, just make sure that you aren't short-cutting better designs. Of course, you can always refactor later on if you need to.
I think a static helper class is the first thing that comes to mind. It is so common that some even refer to it as part of the object-oriented design. However, the biggest problem with helper classes is that they tend to become a large dump. I think i saw this happen on a few of the larger projects i was involved in. You're working on a class and don't know where to stick this and that function so you put it in your helper class. At which point your helpers don't communicate well what they do. The name 'helper' or 'util' itself in the class name doesn't mean anything. I think nearly all OO gurus advocate against helpers since you can very easily replace them with more descriptive classes if you give it enough thought. I tend to agree with this approach as I believe that helpers violate the single responsibility principle. Honestly, take this with a grain of salt. I'm a little opinionated on OOP :)
In these examples I would be more inclined to extend String:
class PhoneNumber extends String
{
public override string ToString()
{
// return (999) 999-9999
}
}
If you write down all the places you need these functions you can figure out what actually uses it and then add it to the appropriate class. That can sometimes be difficult but still something you should aim for.
EDIT:
As pointed out below, you cannot override String in C#. The point I was trying to make is that this operation is made on a phone number so that is where the function belongs:
interface PhoneNumber
{
string Formatted();
}
If you have different formats you can interchange implementations of PhoneNumber without littering your code with if statements, e.g.,
Instead of:
if(country == Countries.UK) output = Toolbox.PhoneNumberUK(phoneNumber);
else ph = Toolbox.PhoneNumberUS(phoneNumber);
You can just use:
output = phoneNumber.Formatted();
There is nothing wrong with this. One thing is try to break it up into logical parts. By doing this you can keep your intellisense clean.
MyCore.Extensions.Formatting.People
MyCore.Extensions.Formatting.Xml
MyCore.Extensions.Formatting.Html
My experience has been that utility functions seldom occur in isolation. If you need a method for formatting telephone numbers, then you will also need one for validating phone numbers, and parsing phone numbers. Following the YAGNI principle, you certainly wouldn't want to write such things until they're actually needed, but I think it's helpful to just go ahead and separate such functionality into individual classes. The growth of those classes from single methods into minor subsystems will then happen naturally over time. I have found this to be the easiest way to keep the code organized, understandable, and maintainable over the long term.
When I create an application, I typically create a static class that contains static methods and properties that I can't figure out where to put anywhere else.
It's not an especially good design, but that's sort of the point: it gives me a place to localize a whole class of design decisions that I haven't thought out yet. Generally as the application grows and is refined through refactoring, it becomes clearer where these methods and properties actually ought to reside. Mercifully, the state of refactoring tools is such that those changes are usually not exceptionally painful to make.
I've tried doing it the other way, but the other way is basically implementing an object model before I know enough about my application to design the object model properly. If I do that, I spend a fair amount of time and energy coming up with a mediocre solution that I have to revisit and rebuild from the ground up at some point in the future. Well, okay, if I know I'm going to be refactoring this code, how about I skip the step of designing and building the unnecessarily complicated classes that don't really work?
For instance, I've built an application that is being used by multiple customers. I figured out pretty early on that I needed to have a way of separating out methods that need to work differently for different customers. I built a static utility method that I could call at any point in the program where I needed to call a customized method, and stuck it in my static class.
This worked fine for months. But there came a point at which it was just beginning to look ugly. And so I decided to refactor it out into its own class. And as I went through my code looking at all the places where this method was being called, it became extremely clear that all of the customized methods really needed to be members of an abstract class, the customers' assemblies needed to contain a single derived class that implements all of the abstract methods, and then the program just needed to get the name of the assembly and the namespace out of its configuration and create an instance of the custom features class at startup. It was really simple for me to find all of the methods that had to be customized, since all I needed to do was find every place that my load-a-custom-feature method was being called. It took me the better part of an afternoon to go through the entire codebase and rationalize this design, and the end result is really flexible and robust and solves the right problem.
The thing is, when I first implemented that method (actually it was three or four interrelated methods), I recognized that it wasn't the right answer. But I didn't know enough to decide what the right answer was. So I went with the simplest wrong answer until the right answer became clear.
I think the reason it's frowned upon is because the "toolbox" can grow and you will be loading a ton of resources every time you want to call a single function.
It's also more elegant to have the methods that apply to the objects in the actual class - just makes more sense.
That being said, I personally don't think it's a problem, but would avoid it simply for the reasons above.
I posted a comment, but thought I'd elaborate a bit more.
What I do is create a Common library with namespaces: [Organisation].[Product].Common as the root and a sub namespace Helpers.
A few people on here mention things like creating a class and shoving some stuff they don't know where else to put in there. Wrong. I'd say, even if you need one helper method, it is related to something, so create a properly named (IoHelper, StringHelper, etc.) static helper class and put it in the Helpers namespace. That way, you get some structure and you get some sort of separation of concerns.
In the root namespace, you can use instance utility classes that do require state (they exist!). And needless to say also use an appropriate class name, but don't suffix with Helper.

Why won't anyone accept public fields in C#?

Seems like every C# static analyzer wants to complain when it sees a public field. But why? Surely there are cases where a public (or internal) field is enough, and there is no point in having a property with its get_ and set_ methods? What if I know for sure that I won't be redefining the field or adding to it (side effects are bad, right?) - shouldn't a simple field suffice?
Because it breaks encapsulation -- this is why most people use accessors heavily. However, if you think it's the right solution for your task, ignore it (meaning the strict encapsulation complaints) and do what's right for your project. Don't let the OO nazis tell you otherwise.
It's really about future-proofing your code. When you say (emphasis mine):
What if I know for sure that I won't
be redefining the field or adding to
it (side effects are bad, right?) -
shouldn't a simple field suffice?
That's an absolute statement, and as we know (as well as most static analyzers), there are only two absolutes in life.
It's just trying to protect you from that. If it is an issue, you should be able to tell the analyzer to ignore it (through attributes that are dependent on the analysis tool you are using).
Given the fact that current C# 3.0 allows for automatic properties whose syntax is like:
public int Property {get; set;}
the extra work required for using Properties over public fields is almost zero. The thing is you can never be completely sure a field won't be used differently or the accessor won't ever change and given the trade off in work there's no reason not to implement a property.
Anyway, the analyzer complains about things that in a high percentage (in this case like 99.99% of the cases) are bad programming practices... but anyway it is just complaining. Fields can be made public and there are some extreme cases where its direct use may be justified. As ever, use your common sense... but keep in mind the elemental rule for best programming practices ... Is there a really good reason to break the convention? If there's then go ahead, if not or if the answer is "it involves more work" then stick to the practice...
Because changing public fields later to have get/set accessors will break code.
See this answer for more information
In general, it's a good idea to hide fields behind properties, even if you "know for sure" that you won't be redefining the field. All too often, what you "know for sure" today changes tomorrow. And, making a property to refer to a field is just a little bit of trouble.
That said, static analyzers are no substitute for thought. If you're happy with your design and in your judgement the analyzer is wrong, then ignore or (if possible) suppress that warning in that circumstance.
I think the point is that generally you don't know for sure that you won't be redefining the field or adding to it later. The whole point of encapsulating and hiding the data is that you are then free to do these things without changing the public interface and subsequently breaking dependent classes. If your property accessors are just simple get/sets then they'll be compiled down to that anyway, so ther are no performance concerns - given this your question should be is there any good reason not to use them?
One other benefit properties bring to the table is when doing Reflection. When you reflect over your class, you can get all the properties in one shot, rather than having to get the properties AND the fields.
And let's not forget that accessors give you flexibility when working with multiple threads.

Can you ever have too many "protected virtual" methods?

Here's a question for those of you with experience in larger projects and API/framework design.
I am working on a framework that will be used by many other projects in the future, so I want to make it nice and extensible, but at the same time it needs to be simple and easy to understand.
I know that a lot of people complain that the .NET framework contains too many sealed classes and private members. Should I avoid this criticism and open up all my classes with plenty of protected virtual members?
Is it a good idea to make as many of my methods and properties protected virtual as possible? Under what situations would you avoid protected virtual and make members private.
Your class includes data members; methods that perform basic internal operations on those data members where the functionality should never change should always be private. So methods that do basic operations with your data members such as initialization and allocation should be private. Otherwise, you run the risk of "second order" derivative classes getting an incomplete set of behaviors enabled; first derivative members could potentially redefine the behavior of the class.
That all said, I think you should be very careful with defining methods as "protected virtual". I would use great caution in defining methods as "protected virtual", because doing so not only declares the possibility of overriding the functionality, but in some ways define an expectation of overridden functionality. That sounds to me like an underdefined set of behaviors to override; I would rather have a well-defined set of behaviors to override. If you want to have a very large set of overridable behaviors, I would rather look into Aspect Oriented Programming, which allows for that sort of thing in a very structured way.
When you mark a method with the word virtual, you're allowing the users to change the way that piece of logic is executed. For many purposes, that is exactly what you want. I believe you already know that.
However, types should be designed for this sort of extension. You have to actively pick out the methods, where it makes sense to let the user change the behavior. If you just slap on virtual all over the place you risk ruining the integrity of the type, it doesn't really help the user to understand the type, and you may introduce a number of bugs including security related issues.
I prefer the conservative approach. I mark all my classes with sealed unless I specifically want to enable inheritance and in those (few) cases I only make the required methods virtual.
It is easy to remove the sealed tag if the class needs to change to allow inheritance in the future. However, if you want to change a class, which is already being used as a base class for some other type, you risk breaking the subclass when you change the base class.
My point of view is:
If you can user events, its preferred to protected methods.
Try to avoid protected methods as possible, if not possible then you have to use it ;-).
Choosing protected over private is a deliberate design decision. You are stating that your class explicitly supports having that function used, with all the overhead (design and implementation effort) that comes with that. I would only use protected in those situations where I know that it is necessary, largely because I am doing it myself. (You'll also find comments from BCL developers along the same lines as what I have said.)
The virtual/non-virtual performance difference is irrelevant on any machine that is powerful enough to run the .NET Framework.
No, you can't have "too many." However, the idea that we should just make every protected instead of private or avoid "sealed" at all costs is just silly. I would keep "helper methods" and internal data structures private.
Is it a good idea to make as many of my methods and properties protected virtual as possible?
Not as good idea.
Protected virtual methods provide extensibility points in the framework while adding coupling.
There are more promising techniques to provide extensibility: Composition and Delegation.

Categories

Resources