Why aren't all fields/properties/methods public? - c#

I know this may sound stupid, but i really want to know :)
im learning c# currently,
and as you know you need to set "object"(button,label,text,variable, etc.) public or whatever you like.
However, you still need to write a code like this:
// my point is you cant just type label1.text you need to type class.label1.text
// so there is no chance of getting bugged
//because there is label1 in each of forms/classes
class Classlol = new class();
classlol.label1.blabla
So what's the point of making it unreachable in other forms ? why every thing isnt public or its not public by default ?
Thanks.

Simply speaking, pretty much the same reason that you wear clothes. Not everything should be exposed to the public at all times. Selected things need to be public so that others can interact with them, but other things are private and should be kept internal to that class.
Although, I probably shouldn't have used the word internal there in that last sentence, because there's a third option: the internal access modifier. The name used in VB.NET (Friend) is probably clearer. This indicates that a piece of data should be visible to all of the other classes within a single assembly, but hidden from outside. A similar analogy applies: there are things that you might share with your closest friends, but still don't want to be public.
There are other more complicated reasons, like to enable information hiding, to maximize the separation between a particular class and the rest of an application, and to maintain a consistent public interface even though implementation details may have been changed between versions, all of which contribute to good object-oriented design. If you really want to understand the nitty-gritty, I suggest picking up a good book on object-oriented programming. It's very difficult, if not impossible, to master an object-oriented language like C# without a solid understanding of the fundamentals.
Things aren't public by default because they might contain sensitive information, or at least information that you don't want to expose as part of the class's public interface. Making something public is a bigger decision with more risks than simply making it private, so you are forced to make that decision explicitly.

The point of using classes is to be able to separate your code into logically related pieces. This makes your code easier to understand and maintain.
For example, if you need to modify code in a class, you can focus more on the way that class functions and less on other parts of your project. However, public members of your class limit this separation somewhat because, if you modify a public member, that can affect other parts of your project.
Keeping as much of your class private as possible (while still usable from your application) maximizes the separation between it and the rest of your application. It makes it easier to think about only the logic in the class you are working on, and it allows you to modify those private members without having to think what other parts of your application might be affected.

I suggest that you read more about abstraction in object oriented programming. Maybe the Wikipedia article on abstraction is a good place to start.
EDIT: Konrad is absolutely right, abstraction does not automatically imply "hiding" information. You could say that it's the role of encapsulation in object oriented programming.
I guess what I wanted to say is that this question is not specific to C#, but rather begs for a bit of reading on general object oriented programming principles.

The default access modifier is internal which means it's public inside the same assembly and private outside the assembly.
If you want to expose certain data as public, for example text of some Label, the best practice is creating public readonly property like this:
public string LabelText
{
get { return MyLabel.Text; }
}
To access it you'll have to use such code:
string text = classInstance.LabelText;
This way the Label itself is not public, but its text can be read by everyone.

Related

How abstraction and encapsulation differ?

I am preparing for an interview and decided to brush up my OOP concepts.
There are hundreds of articles available, but it seems each describes them differently.
Some says
Abstraction is "the process of identifying common patterns that have
systematic variations; an abstraction represents the common pattern
and provides a means for specifying which variation to use" (Richard
Gabriel).
and is achieved through abstract classes.
Some other says
Abstraction means to show only the necessary details to the client of
the object
and
Let’s say you have a method "CalculateSalary" in your Employee class,
which takes EmployeeId as parameter and returns the salary of the
employee for the current month as an integer value. Now if someone
wants to use that method. He does not need to care about how Employee
object calculates the salary? An only thing he needs to be concern is
name of the method, its input parameters and format of resulting
member,
I googled again and again and none of the results seem to give me a proper answer.
Now, where does encapsulation fit in all these?
I searched and found a stack overflow question. Even the answers to that questions were confusing
Here, it says
Encapsulation is a strategy used as part of abstraction. Encapsulation
refers to the state of objects - objects encapsulate their state and
hide it from the outside; outside users of the class interact with it
through its methods, but cannot access the classes state directly. So
the class abstracts away the implementation details related to its
state.
And here another reputed member says,
They are different concepts.
Abstraction is the process of refining away all the
unneeded/unimportant attributes of an object and keep only the
characteristics best suitable for your domain.
Now I m messed up with the whole concept. I know about abstract class, inheritance, access specifiers and all. I just want to know how should I answer when I am asked about abstraction and/or encapsulation in an interview.
Please don't mark it as a duplicate. I know there are several similar questions. But I want to avoid the confusion among the conflicting explanations. Can anyone suggest a credible link? A link to stackoverflow question is also welcome unless it creates confusion again. :)
EDIT: I need answers, a bit c# oriented
Encapsulation: hiding data using getters and setters etc.
Abstraction: hiding implementation using abstract classes and interfaces etc.
Abstraction means to show only the necessary details to the client of the object
Actually that is encapsulation. also see the first part of the wikipedia article in order to not be confused by encapsulation and data hiding. http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
keep in mind that by simply hiding all you class members 1:1 behind properties is not encapsulation at all. encapsulation is all about protecting invariants and hiding of implementation details.
here a good article about that.
http://blog.ploeh.dk/2012/11/27/Encapsulationofproperties/
also take a look at the articles linked in that article.
classes, properties and access modifiers are tools to provide encapsulation in c#.
you do encapsulation in order to reduce complexity.
Abstraction is "the process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use" (Richard Gabriel).
Yes, that is a good definition for abstraction.
They are different concepts.
Abstraction is the process of refining away all the unneeded/unimportant attributes of an object and keep only the characteristics best suitable for your domain.
Yes, they are different concepts. keep in mind that abstraction is actually the opposite of making an object suitable for YOUR domain ONLY. it is in order to make the object suitable for the domain in general!
if you have a actual problem and provide a specific solution, you can use abstraction to formalize a more generic solution that can also solve more problems that have the same common pattern. that way you can increase the re-usability for your components or use components made by other programmers that are made for the same domain, or even for different domains.
good examples are classes provided by the .net framework, for example list or collection. these are very abstract classes that you can use almost everywhere and in a lot of domains. Imagine if .net only implemented a EmployeeList class and a CompanyList that could only hold a list of employees and companies with specific properties. such classes would be useless in a lot of cases. and what a pain would it be if you had to re-implement the whole functionality for a CarList for example. So the "List" is ABSTRACTED away from Employee, Company and Car. The List by itself is an abstract concept that can be implemented by its own class.
Interfaces, abstract classes or inheritance and polymorphism are tools to provide abstraction in c#.
you do abstraction in order to provide reusability.
Image source
Abstraction: is shown in the top left and the top right images of the cat. The surgeon and the old lady designed (or visualized) the animal differently. In the same way, you would put different features in the Cat class, depending upon the need of the application. Every cat has a liver, bladder, heart, and lung, but if you need your cat to 'purr' only, you will abstract your application's cat to the design on top-left rather than the top-right.
Encapsulation: is demonstrated by the cat standing on the table. That's what everyone outside the cat should see the cat as. They need not worry whether the actual implementation of the cat is the top-left one or the top-right one, or even a combination of both.
Another detailed answer here.
I will try to demonstrate Encapsulation and Abstraction in a simple way.. Lets see..
The wrapping up of data and functions into a single unit (called
class) is known as encapsulation. Encapsulation containing and hiding
information about an object, such as internal data structures and
code.
Encapsulation is -
Hiding Complexity,
Binding Data and Function together,
Making Complicated Method's Private,
Making Instance Variable's Private,
Hiding Unnecessary Data and Functions from End User.
Encapsulation implements Abstraction.
And Abstraction is -
Showing Whats Necessary,
Data needs to abstract from End User,
Lets see an example-
The below Image shows a GUI of "Customer Details to be ADD-ed into a Database".
By looking at the Image we can say that we need a Customer Class.
Step - 1: What does my Customer Class needs?
i.e.
2 variables to store Customer Code and Customer Name.
1 Function to Add the Customer Code and Customer Name into Database.
namespace CustomerContent
{
public class Customer
{
public string CustomerCode = "";
public string CustomerName = "";
public void ADD()
{
//my DB code will go here
}
Now only ADD method wont work here alone.
Step -2: How will the validation work, ADD Function act?
We will need Database Connection code and Validation Code (Extra Methods).
public bool Validate()
{
//Granular Customer Code and Name
return true;
}
public bool CreateDBObject()
{
//DB Connection Code
return true;
}
class Program
{
static void main(String[] args)
{
CustomerComponent.Customer obj = new CustomerComponent.Customer;
obj.CustomerCode = "s001";
obj.CustomerName = "Mac";
obj.Validate();
obj.CreateDBObject();
obj.ADD();
}
}
Now there is no need of showing the Extra Methods(Validate(); CreateDBObject() [Complicated and Extra method] ) to the End User.End user only needs to see and know about Customer Code, Customer Name and ADD button which will ADD the record.. End User doesn't care about HOW it will ADD the Data to Database?.
Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction.
So making those Complicated and Extra method as Private instead Public(i.e Hiding those methods) and deleting the obj.Validate(); obj.CreateDBObject(); from main in class Program we achieve Encapsulation.
In other words Simplifying Interface to End User is Encapsulation.
So now the complete code looks like as below -
namespace CustomerContent
{
public class Customer
{
public string CustomerCode = "";
public string CustomerName = "";
public void ADD()
{
//my DB code will go here
}
private bool Validate()
{
//Granular Customer Code and Name
return true;
}
private bool CreateDBObject()
{
//DB Connection Code
return true;
}
class Program
{
static void main(String[] args)
{
CustomerComponent.Customer obj = new CustomerComponent.Customer;
obj.CustomerCode = "s001";
obj.CustomerName = "Mac";
obj.ADD();
}
}
Summary :
Step -1: What does my Customer Class needs? is Abstraction.
Step -3: Step -3: Private the extra and complicated methods which doesn't involves End User's Interaction is Encapsulation.
P.S. - The code above is hard and fast.
UPDATE:
There is an video on this link to explain the sample:
What is the difference between Abstraction and Encapsulation
Below is a semester long course distilled in a few paragraphs.
Object-Oriented Analysis and Design (OOAD) is actually based on not just two but four principles. They are:
Abstraction: means that you only incorporate those features of an entity which are required in your application. So, if every bank account has an opening date but your application doesn't need to know an account's opening date, then you simply don't add the OpeningDate field in your Object-Oriented Design (of the BankAccount class). †Abstraction in OOAD has nothing to do with abstract classes in OOP.
Per the principle of Abstraction, your entities are an abstraction of what they are in the real world. This way, you design an abstraction of Bank Account down to only that level of detail that is needed by your application.
Inheritance: is more of a coding-trick than an actual principle. It saves you from re-writing those functionalities that you have written somewhere else. However, the thinking is that there must be a relation between the new code you are writing and the old code you are wanting to re-use. Otherwise, nobody prevents you from writing an Animal class which is inheriting from BankAccount, even if it is totally non-sensical.
Just like you may inherit your parents' wealth, you may inherit fields and methods from your parent class. So, taking everything that parent class has and then adding something more if need be, is inheritance. Don't go looking for inheritance in your Object Oriented Design. Inheritance will naturally present itself.
Polymorphism: is a consequence of inheritance. Inheriting a method from the parent is useful, but being able to modify a method if the situation demands, is polymorphism. You may implement a method in the subclass with exactly the same signature as in parent class so that when called, the method from child class is executed. This is the principle of Polymorphism.
Encapsulation: implies bundling the related functionality together and giving access to only the needful. Encapsulation is the basis of meaningful class designing in Object Oriented Design, by:
putting related data and methods together; and,
exposing only the pieces of data and methods relevant for functioning with external entities.
Another simplified answer is here.
† People who argue that "Abstraction of OOAD results in the abstract keyword of OOP"... Well that is incorrect.
Example: When you design a University in an application using object oriented principles, you only design an "abstraction" of the university. Even though there is usually one cash dispensing ATM in almost every university, you may not incorporate that fact if it's not needed for your application. And now though you have designed only an abstraction of the university, you are not required to put abstract in your class declaration. Your abstract design of university will be a normal class in your application.
I think they are slightly different concepts, but often they are applied together. Encapsulation is a technique for hiding implementation details from the caller, whereas abstraction is more a design philosophy involving creating objects that are analogous to familiar objects/processes, to aid understanding. Encapsulation is just one of many techniques that can be used to create an abstraction.
For example, take "windows". They are not really windows in the traditional sense, they are just graphical squares on the screen. But it's useful to think of them as windows. That's an abstraction.
If the "windows API" hides the details of how the text or graphics is physically rendered within the boundaries of a window, that's encapsulation.
my 2c
the purpose of encapsulation is to hide implementation details from the user of your class e.g. if you internally keep a std::list of items in your class and then decide that a std::vector would be more effective you can change this without the user caring. That said, the way you interact with the either stl container is thanks to abstraction, both the list and the vector can for instance be traversed in the same way using similar methods (iterators).
One example has always been brought up to me in the context of abstraction; the automatic vs. manual transmission on cars. The manual transmission hides some of the workings of changing gears, but you still have to clutch and shift as a driver. Automatic transmission encapsulates all the details of changing gears, i.e. hides it from you, and it is therefore a higher abstraction of the process of changing gears.
Encapsulation: Hiding implementation details (NOTE: data AND/OR methods) such that only what is sensibly readable/writable/usable by externals is accessible to them, everything else is "untouchable" directly.
Abstraction: This sometimes refers specifically to a type that cannot be instantiated and which provides a template for other types that can be, usually via subclassing. More generally "abstraction" refers to making/having something that is less detailed, less specific, less granular.
There is some similarity, overlap between the concepts but the best way to remember it is like this: Encapsulation is more about hiding the details, whereas abstraction is more about generalizing the details.
Abstraction and Encapsulation are confusing terms and dependent on each other.
Let's take it by an example:
public class Person
{
private int Id { get; set; }
private string Name { get; set; }
private string CustomName()
{
return "Name:- " + Name + " and Id is:- " + Id;
}
}
When you created Person class, you did encapsulation by writing properties and functions together(Id, Name, CustomName). You perform abstraction when you expose this class to client as
Person p = new Person();
p.CustomName();
Your client doesn't know anything about Id and Name in this function.
Now if, your client wants to know the last name as well without disturbing the function call. You do encapsulation by adding one more property into Person class like this.
public class Person
{
private int Id { get; set; }
private string Name { get; set; }
private string LastName {get; set;}
public string CustomName()
{
return "Name:- " + Name + " and Id is:- " + Id + "last name:- " + LastName;
}
}
Look, even after addding an extra property in class, your client doesn't know what you did to your code. This is where you did abstraction.
As I knowit, encapsulation is hiding data of classes in themselves, and only making it accessible via setters / getters, if they must be accessed from the outer world.
Abstraction is the class design for itself.
Means, how You create Your class tree, which methods are general ones, which are inherited, which can be overridden,which attributes are only on private level, or on protected, how Do You build up Your class inheritance tree, Do You use final classes, abtract classes, interface-implementation.
Abstraction is more placed the oo-design phase, while encapsulation also enrolls into developmnent-phase.
I think of it this way, encapsulation is hiding the way something gets done. This can be one or many actions.
Abstraction is related to "why" I am encapsulating it the first place.
I am basically telling the client "You don't need to know much about how I process the payment and calculate shipping, etc. I just want you to tell me you want to 'Checkout' and I will take care of the details for you."
This way I have encapsulated the details by generalizing (abstracting) into the Checkout request.
I really think that abstracting and encapsulation go together.
Abstraction
In Java, abstraction means hiding the information to the real world. It establishes the contract between the party to tell about “what should we do to make use of the service”.
Example, In API development, only abstracted information of the service has been revealed to the world rather the actual implementation. Interface in java can help achieve this concept very well.
Interface provides contract between the parties, example, producer and consumer. Producer produces the goods without letting know the consumer how the product is being made. But, through interface, Producer let all consumer know what product can buy. With the help of abstraction, producer can markets the product to their consumers.
Encapsulation:
Encapsulation is one level down of abstraction. Same product company try shielding information from each other production group. Example, if a company produce wine and chocolate, encapsulation helps shielding information how each product Is being made from each other.
If I have individual package one for wine and another one for
chocolate, and if all the classes are declared in the package as
default access modifier, we are giving package level encapsulation
for all classes.
Within a package, if we declare each class filed (member field) as
private and having a public method to access those fields, this way
giving class level encapsulation to those fields
Let's go back 6 million years,
Humans are not fully evolved. To begin with, evolution created a hole next to each body part to inject nutrients, which you can decide on yourself.
However, as humans get older, the nutrient requirements for each body part change Humans don't know which body parts need how much of which nutrient.
Evolution realised that exposing the hole next to each body part was a mistake, so it corrected it by encapsulating the entire body in skin and exposing only one opening, later it was called as "mouth." 
Also, it abstracted the whole implementation of nutrient allocation through digestive system. All you have to do is keep eating through your mouth. The digestive system will take care of the body's nutrient composition changes to meet your needs. 
In the software world, requirements will keep changing.
Encapsulating the internal data and exposing only the required functions will help with better maintenance. As a result, you have greater control over what occurs within your class/module/framework. 
Abstraction makes it easier for the client to consume a class/module/framework. So clients don't have to do(know) 100 different steps to get the desired output. Exposed function/class will do all the work. In our example, you don't have to worry about which nutrients are required for which body part. Just eat it. 

C# automatic properties vs regular local variables [duplicate]

We're often told we should protect encapsulation by making getter and setter methods (properties in C#) for class fields, instead of exposing the fields to the outside world.
But there are many times when a field is just there to hold a value and doesn't require any computation to get or set. For these we would all do this number:
public class Book
{
private string _title;
public string Title
{
get => _title;
set => _title = value;
}
}
Well, I have a confession, I couldn't bear writing all that (really, it wasn't having to write it, it was having to look at it), so I went rogue and used public fields.
Then along comes C# 3.0 and I see they added automatic properties:
public class Book
{
public string Title { get; set; }
}
Which is tidier, and I'm thankful for it, but really, what's so different than just making a public field?
public class Book
{
public string Title;
}
In a related question I had some time ago, there was a link to a posting on Jeff's blog, explaining some differences.
Properties vs. Public Variables
Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
You can't databind against a variable.
Changing a variable to a property is a breaking change. For example:
TryGetTitle(out book.Title); // requires a variable
Ignoring the API issues, the thing I find most valuable about using a property is debugging.
The CLR debugger does not support data break points (most native debuggers do). Hence it's not possible to set a break point on the read or write of a particular field on a class. This is very limiting in certain debugging scenarios.
Because properties are implemented as very thin methods, it is possible to set breakpoints on the read and write of their values. This gives them a big leg up over fields.
Changing from a field to a property breaks the contract (e.g. requires all referencing code to be recompiled). So when you have an interaction point with other classes - any public (and generally protected) member, you want to plan for future growth. Do so by always using properties.
It's nothing to make it an auto-property today, and 3 months down the line realize you want to make it lazy-loaded, and put a null check in the getter. If you had used a field, this is a recompile change at best and impossible at worst, depending on who & what else relies on your assemblies.
Just because no one mentioned it: You can't define fields on Interfaces. So, if you have to implement a specific interface which defines properties, auto-properties sometimes are a really nice feature.
A huge difference that is often overlooked and is not mentioned in any other answer: overriding. You can declare properties virtual and override them whereas you cannot do the same for public member fields.
It's all about versioning and API stability. There is no difference, in version 1 - but later, if you decide you need to make this a property with some type of error checking in version 2, you don't have to change your API- no code changes, anywhere, other than the definition of the property.
Another advantage of auto-implemented properties over public fields is that you can make set accessors private or protected, providing the class of objects where it was defined better control than that of public fields.
There is nothing wrong in making a field public. But remember creating getter/setter with private fields is no encapsulation. IMO, If you do not care about other features of a Property, you might as well make it public.
Trivial properties like these make me sad. They are the worst kind of cargo culting and the hatred for public fields in C# needs to stop. The biggest argument against public fields is future-proofing: If you later decide you need to add extra logic to the getter and setter, then you will have to do a huge refactor in any other code that uses the field. This is certainly true in other languages like C++ and Java where the semantics for calling a getter and setter method are very different from those for setting and getting a field. However, in C#, the semantics for accessing a property are exactly the same as those for accessing a field, so 99% of your code should be completely unaffected by this.
The one example I have seen of changing a field into a property actually being a breaking change at the source level is something like:
TryGetTitle(out book.Title); // requires a variable
To this I have to ask, why TF are you passing some other class's field as a reference? Depending on that not being a property seems like the real coding failure here. Assuming that you can directly write to data in another class that you know nothing about is bad practice. Make your own local variable and set book.Title from that. Any code that does something like this deserves to break.
Other arguments I have seen against it:
Changing a field to a property breaks binary compatibility and requires any code that uses it to be recompiled: This is a concern iff you are writing code for distribution as a closed-source library. In that case, yes, make sure none of your user-facing classes have public fields and use trivial properties as needed. If however you are like 99% of C# developers and writing code purely for internal consumption within your project, then why is recompilation a big concern? Just about any other change you make is going to require recompilation too, and so what if it does? Last I checked, it is no longer 1995, we have fast computers with fast compilers and incremental linkers, even larger recompilations shouldn't need more than a few minutes, and it has been quite some time since I have been able to use "my code's compiling" as an excuse for swordfighting through the office.
You can't databind against a variable: Great, when you need to do that, make it into a property.
Properties have features that make them better for debugging like reflection and setting breakpoints: Great, one you need to use one of those things, make it into a property. When you're done debugging and ready to release, if you don't still need those functionalities, change it back into a field.
Properties allow you to override behavior in derived classes: Great, if you are making a base class where you think such a scenario is likely, then make the appropriate members into properties. If you're not sure, leave it as a field and you can change it later. Yes, that will probably require some recompilation, but again, so what?
So in summary, yes there are some legitimate uses for trivial properties, but unless you are making a closed source library for public release, fields are easy enough to convert into properties when needed, and an irrational fear of public fields is just some object oriented dogma that we would do well to rid ourselves of.
For me, the absolute deal breaker for not using public fields was the lack of IntelliSense, showing the references:
Which is not available for fields.
If you decide later to check that the title is unique, by comparing to a collection or a database, you can do that in the property without changing any code that depends on it.
If you go with just a public attribute then you will have less flexibility.
The extra flexibility without breaking the contract is what is most important to me about using properties, and, until I actually need the flexibility, auto-generation makes the most sense.
One thing you can do with Fields but not with Properties (or didn't used to be able to ... I'll come to that in a moment) is that Fields can be designated as readonly whereas Properties cannot. So Fields give you a clear way of indicating your intention that a variable is there to be set (from within the constructor) at object-instantiation time only and should not be changed thereafter. Yes, you can set a Property to have a private setter, but that just says "this is not to be changed from outside the class", which is not the same as "this is not to be changed after instantiation" - you can still change it post-instantiation from within the class. And yes you can set the backing field of your property to be readonly, but that moves post-instantiation attempts to change it to being run-time errors rather than compile-time errors. So readonly Fields did something useful which Properties cannot.
However, that changes with C# 9, whereby we get this helpful syntax for Properties:
public string Height { get; init; }
which says "this can get used from outside of the class but it may only be set when the object is initialized", whereupon the readonly advantage of Fields disappears.
One thing I find very useful as well as all the code and testing reasons is that if it is a property vs a field is that the Visual Studio IDE shows you the references for a property but not a field.
My pov after did some researches
Validation.
Allow overriding the accessor to change the behaviour of a property.
Debugging purpose. We'll be able to know when and what the property change by setting a breakpoint in the accessor.
We can have a field set-only. For instance, public set() and private get(). This is not possible with the public field.
It really gives us more possibility and extensibility.

Why Not Use Public Member Functions

Even if I make class member functions public and it is consumed by
other client applications, implementation details of
functions will never get exposed to client. Why make member functions protected or private?
For example, if my class is Math, with public function sum(int, int b) then only interface/declaration part will be exposed to client and not implementation.
public class Math
{
public int sum(int, int b)
{
//Implementation
}
}
public class Client
{
Math objMath = new Math();
objMath.Sum(4,10);//It will not display implementation inside sum than why to avoid
}
The more public your methods (and types) are, the more code they're exposed to. That increases the chance that other code (even code under your company's control) will start depending on that code working the way it currently does... which limits the flexibility to change the implementation later.
To give a concrete example, I'm working on an open source project called Noda Time. Now admittedly we haven't had our first public release yet, but I've recently been making a load of changes to various internal types - including changing the type hierarchies fairly significantly, and even removing methods. If those had been public types or public methods (and if we'd already gone to v1.0) then we could have broken code which depended on that specific implementation.
By hiding everything you don't know to be useful to clients, you buy yourself a lot of flexibility. It's incredibly important to put a lot of thought into your public API, because that's really hard to change later - but if you've kept a lot of your implementation internal, you can refactor to your heart's content to make it more elegant, more flexible, or perhaps faster... all without breaking any of the code depending on your library.
Obviously some things need to be exposed - at least in class libraries - but you should be careful just how much you expose, unless you're happy to break all callers later on (or live with every decision you make, forever).
There's nothing wrong with public member functions- they're quite essential, although the necessity of an object in your case is more than somewhat dubious. However, protected/private functions are for when you need to re-use some code that shouldn't be part of the public interface.
Because some methods may be part of internal implementation, and not of public interface. For example, some private method can change state of object to invalid one, but it is only used as intermediate step in some other public method. Definetely you don't want it to be called by client.

C# protected field to private, add property--why?

In Visual Studio 2008 Team System, I just ran Code Analysis (from the Analyze menu) on one of my C# projects. One of the warnings produced was the following:
Microsoft.Design : Because field 'Connection._domain' is visible outside of its declaring type, change its accessibility to private and add a property, with the same accessibility as the field has currently, to provide access to it.
It's referring to the following field:
public abstract class Connection
{
protected string _domain;
}
I don't understand the reasoning behind the suggestion. This is what I think it wants me to do:
public abstract class Connection
{
private string _domain;
protected string Domain { get { return _domain; } set { _domain = value; } }
}
Two questions:
Did I understand correctly what the suggestion wants me to do, code-wise?
Why does it want me to do this?
Yes, I think you understood correctly - although in later versions of C#, there's a more concise way to write it:
public string Domain { get; set; }
Why? It's all about encapsulation. If you do as it suggests, you can later change the definition of the Domain property without affecting any calling code that uses that property. Since your class is public, and might conceivably be called by code that you didn't write, that's potentially quite important.
This is because if you ever wanted to change the field to a property in the future you would break any other assemblies that depend on it.
It is good practice to keep all fields private and wrap them in properties so that you have the option of adding validation or other logic in the future without recompiling all consumers (or in this case inheritors) of your class.
Yep. That's the suggestion. You shouldn't have any accessibility higher than private exposed as direct instance fields.
It's one of the main principles of OOD - encapsulation also referred to as 'data-hiding'.
Yes, you did correct the problem code wise.
It is about encapsulation. _domain is data about your object. Rather then exposing it directly so that any client has unfiltered access, you should provide an interface for them to access it. Practically this might be adding validation to the setter so that it can't be set to any value. It might seem silly if you are the only one writing code because you know how your API works. But try to think about things on a large enterprise level, it is better to have an API so that your object can be seen as a box that accomiplishes a task. You might say you will never have the need to add something like validation to that object, but things are done that way to hold for the possibility of it, and also to be consistent.
Your translation is correct. The same argument for can be made for using 'protected' properties as can be made for using 'public' properties instead of exposing member variables directly.
If this just leads to a proliferation of simple getters and setters then I think the damage to code readablity outweighs the benefit of being able to change the code in the future. With the development of compiler-generated properties in C# this isn't quite so bad, just use:
protected string Domain { get; set; }
In answer to your question... yes.
However, I would just use the auto-property syntax:
public abstract class Connection
{
protected string Domain { get; set; }
}
Basically, properties provide more than returning or setting a member. They allow you to add logic that could verify a proper input format, range validation, etc.
The selected answer from the link puts it best, "Properties provide encapsulation. You can encapulate any needed validation/formating/conversion in the code for the property. This would be difficult to do for fields."
http://social.msdn.microsoft.com/Forums/en-IE/netfxbcl/thread/985f4887-92ae-4ec2-b7ae-ec8cc6eb3a42
In addition to the other answers mentioned here, public/protected members that begin with an underscore are not CLS-compliant, in that there is no requirement for .NET languages to support members with leading underscores, so someone inheriting from your class in a different .NET language may not be able to access that particular protected member.
I know, it probably doesn't apply to you, but it might be part of the reason for the code analysis warning.

Are there any plans for "extension properties" in a future version of C#?

I've thought of this before and it came to mind again when reading this question.
Are there any plans for "extension properties" in a future version of C#?
It seems to me they might be pretty stright-forward to implement with a little more "compiler magic". For example, using get_ and set_ prefixes on extension method names would turn that method into an extension property:
public class Foo
{
public string Text { get; set; }
}
public static class FooExtensions
{
public static string get_Name(this Foo foo)
{
return foo.Text;
}
public static void set_Name(this Foo foo, string value)
{
foo.Text = value;
}
}
Are there any technical restrictions which would prevent this? Would this create too much stuff going on behind the scenes? Not important enough to be worth the effort?
The official site for feature requests is http://connect.microsoft.com/VisualStudio.
There has already been a request for extension properties here.
Microsoft's answer on 7/29/2008 included the following:
Extension properties are a common
request, and we actually got quite far
with a design for the next version of
the language, but ultimately had to
scrap it because of various
difficulties. It is still on our
radar.
Generally I think this would encourage poor practice.
Properties are supposed to represent some kind of state about the object in question, whereas methods should represent units of work. But many developers tend to put computationally intensive or relatively long-running code in the getters and setters where they would be much more appropriate as methods.
Extending an object is not the same as deriving from it. If you need to add properties, from a philosophical perspective you're talking about needing to add stateful information to the object. That should be done by deriving from the class.
Although I don't think what you're proposing is a good idea, you can get pretty much the same thing with the upcoming dynamic type in C# 4. Part of what is planned is to allow new properties and methods to be added at runtime to existing objects and types. One difference is that you won't have the compile-time checking of an extension property.
There might be something to be said about that kind of trick.
Just look at Attached properties in WPF. They do give tremendous power for declarative behavior attachment. But I'm not sure what that would look like outside of a declarative context...
I'm not sure how that would work. Extensions have to be static, so the property itself would have to static. The means whatever you use to back these properties would also be static. But expect your planned use for these expects them to be associated with the instances indicated by the this keyword rather than the type itself.
"Extension properties" are available today via inheritance. Adding such a beast would encourage poor oop practices and generaly be more trouble than its worth.

Categories