Related
I’m very new to programming. Actually less than one month back, I couldn’t name even 3 programming languages. So I’m really new to this.
After I understood the class concept and the object concept in OOP in general, I then realised that every single item present in the whole program is either an object or a class ready to give off objects.
Classes are non other than descriptions of objects, which are the main and sole players.
Moreover, functions or method are non other than sort of behavioural manifestation of an existing object.
( I wonder if the code line that we write for a function to be executed, the line of code in itself is a new object that refers to the existing original object that will perform the function we want , as part of its behaviour )
Now, If what I mentioned was near to be correct, What confused me next in my journey to understand OOP as a world wherein every single item is an object being utilised or destroyed, or brought into existence out of a class (blueprint ), which is nothing but a modifiable written description for objects how to be born.
What confused me here is the nature of “system”, “console”, and “namespace” each one of these, is it an object, so that we can call and utilise it without instantiating, or they are special classes readily instantiated as the program runs, or just ordinary classes ( which contradicts everything I understood ), because I can see "system" and "console" called and utilised only, and never instantiated ( just like an object )
Now, namespace seems to be a class that is instantiated into an object in the written script: ( namespace "the application name" { } ) but neither "system" nor "console" seems to be instantiated by programmer!
System is a namespace, Console is a static class inside the namespace System.
Static classes are classes which do not need to be created with the new keyword, and there is only one instance per application (excluding templated static classes - which you don't need to worry about for the moment)
Console can be written like this:
namespace System { //Namespace defined here!
public static class Console { //Static class defined here!
public static void WriteLine() { //Static method defined here!
//Implementation goes here
}
}
}
Note the keyword static when declaring the class. Removing this keyword would turn it into a normal class, and you'd have to use it like this:
var console = new System.Console();
console.WriteLine();
Based on the comments from Bauss and Physician about static methods.
You can write this, as well:
public class MyClass
{
public static void DoSomethingStatically()
{
}
public void DoSomethingNormally()
{
}
}
Now, you can do this:
MyClass.DoSomethingStatically();
but you cannot do:
MyClass.DoSomethingNormally();
To use the second method, you must create an instance:
var myClass = new MyClass();
myClass.DoSomethingNormally();
Note:
You cannot call a static method on an instance, so it is invalid to do the following:
var myClass = new MyClass();
myClass.DoSomethingStatically();
You can think of namespaces as containers of classes. System is a namespace which contains the Console class. Console is a special kind of class called a static class. A static class is denoted by the static keyword. The Console class's declaration would look something like this:
namespace System {
public static class Console {
//lots of stuff...
}
}
Actually you can read the Console class's source code in http://referencesource.microsoft.com
A static class cannot be instantiated. It just does its own work. It doesn't have objects. One of reasons is that it doesn't make sense to have objects. For example, the Math class is a static class because it doesn't make sense to say "Let's create a Math object!". Because Math is not like Cows or Streams or BinaryFormatters, which all are non static classes Generally, anything that you can prefix with "a" is not static. "a Stream", "a BinaryFormatter" etc.
Now for the namespace concept. You know sometimes the same word may mean different stuff depending on the context. e.g. Stream, in a programming context it means a file stream or some other kind of streams. But in a casual conversation, you say stream to mean a stream of water or something like that. So now you have to create two stream classes but there's a name conflict! That's why we have namespaces. Let's look at a real example. There are at least 2 classes called Path, but they are in different namespaces so it's ok to have the same name. One is in the System.Drawing namespace and the other is in the System.IO namespace. We often refer to those two classes as "System.IO.Path" and "System.Drawing.Path". Or you can write using directives.
Conclusion:
Both System and Console are not objects. They are a namespace and a static class respectively. And the word namespace denotes a namespace so it's not an object either.
I am working on a class library using C#. I have designed 3 main classes to help model our data. They are designed such that class A contains a list of class B instances, and class B contains a reference to a class C instance, ie:
public class Policy
{
public List < PolicyTerm > myTerms;
person Customer;
string PolicyNumber;
}
public class PolicyTerm
{
public Billing myBill;
Datetime effectivedate;
List < Activities > termActivities;
public doAction()
{
use value from Policy, like PolicyNumber;
}
}
public class Billing
{
float remainingBalance;
Datetime nextDueDate;
public void doSomething()
{
reference value from PolicyTerm, such as effective date;
use value from Policy, such as PolicyNumber;
}
}
The problem I have is when I try to use a method within PolicyTerm or Billing that needs data from the containing class. In the example above, this would be the method "doSomething" trying to use a value from PolicyTerm, like the effective date for the term in requesting or saving data to our database.
I am wondering if I have the correct design for my classes because of this scenario. Should I just add a reference to the "parent" class within the child classes, in order to make the parent's data available? Or do I need to rethink the overall structure and design of the code?
I feel like the class design works well for modeling the data and our business rules, but it does create a few limitations like the above situation. I liked the separation of the PolicyTerm and Billing for the ability to allow that code to be modified and tested independently. Also, I feel like it keeps each section smaller and simpler.
Any advice that can be provided would be much appreciated.
Update: Code block was updated to provide more details on the code in question.
If doSomething() always needs the reference to the C object's parent, you should indeed put this reference into C where you can ensure that it refers to the correct B instance. OTOH if that reference is not always the parent, but still it is always going to refer to the same B instance, it still suggests turning it into a member of C. OTOH if doSomething() can be called with varying references, that reference should be kept as a method parameter.
It is not bad per se to put a reference from child to parent, or to have a mutual dependency between two classes - it depends on the context. The consequence of this is that the two classes can not be used separately, so in fact they form a component. This may or may not be acceptable for you.
Components in general can consist of multiple classes - a collection with its items and iterator(s) is in fact a typical example. However, it is advisable to express the logical dependency between these classes on the physical level as well, e.g. by making one class an inner class of the other, or making both classes inner classes in a third class.
This really depends on the situation. In general, unless there is a clear, obvious relationship between classes "B" and "C", it's a red flag that C.doSomething() would require access to B, since C is contained within B...
However, a method in B requiring access to C makes sense, since C is a member within B.
That being said, there are times that this is appropriate. Without knowing your actual classes, and what they represent, its difficult to say more...
Two classes shouldn't, but two interfaces is OK.
Of course, the smaller the interfaces the better. You'll find that if the interfaces are small enough (which they should be - see Interface Segregation Principal), you won't actually need 2 of the same.
Creating a reference to your required class doesn't seem a bad idea at all. If it's required, you could make Class C's constructor take the reference to Class B and store it in a member variable.
I'm working on a project at the moment with a couple of classes behave like this.
Another option which might be a bit more "sane" is to have an event on class C, that's something like "SuchAndSuchDataRequired." Class B could then listen to that event when it gets the instance of C. Class C fires the event from within doSomething() when it needs the data from B, B then returns the data in it's event handler and bingo - class C has the data and doesn't even know it came from class B.
The general rule of thumb is keep the data as close as possible to the functions/methods/classes that will be using it. This will keep things decoupled and you won't have to have both classes referencing each other, which actually makes you have to create an extra object that might not be necessary.
And like ChaosPandion said: please post some more specific code so we can better help you.
Edit:
If you B references C and C references B, then you might want to consider putting the two together as one object. This works best if the two classes are not completely different. If there is no real distinguishable difference, then just put it together in one class ... that could simplify the whole thing.
In my opinion your modelling seems a bit skewed i.e. why is there a property of type person within policy and why have a List of a concrete implementation in Policy i.e. PolicyTerm. This couples the classes together and doesn't feel right - i.e. Policy HAS A customer? Should be Customer HAS A Policy
Can I suggest the following (quickly modelled and not tested but you should be able to see what I'm getting at)
public class Customer()
{
prop name,etc,etc;
public List<IPolicyTerm> Policies{get;set;}//I use public getters and setters throughout but you need to choose what level of encapsulation you want
private Account customerAccount{get;set}
public Customer()
{
//ctor
customerAccount = doDbCall;
Policies = doDbCall;
}
public decimal GetCurrentPolicyCost()
{
decimal cost = 0;
foreach(var policy in Policies)
{
if(policy.DueDate < DateTime.Now){
cost += policy.GetCost(); //for example but you can call whatever is defined at the interface level
}
}
return cost;
}
public bool HasEnoughFunds()
{
return customerAccount.Balance >= GetCurrentPolicyCost();
}
//keeping Account hidden in Person as Person has a reference to Account.
//By doing so there is type coupling between the two classes
//BUT you can still modify Policies away from Person
private class Account
{
//should only contain properties and I assume only one 'Account' per person
}
}
public interface IPolicyTerm
{
object Id{get;set}
DateTime DueDate {get;set;}
decimal GetCost();
}
///now we can have polymorphic Policies i.e. the cost of one can be calculated differently based on policy
public class LifeCoverPolicy : IPolicyTerm
{
public object Id;
public DateTime DueDate{get;set;}
public decimal GetCost()
{
return 10;
}
}
what I mean by that is:
I basically have a class that has too many properties and functions now. To remain performant and understandable, it needs to shrink somehow. But I still need all those properties and methods somewhere.
It's like this right now:
class Apple
float seedCount;
...
...about 25 variables and properties here.
void Update() <-- a huge method that checks for each property and updates if so
In most cases the class needs almost none of those properties. In some cases in needs to be able to grow very selectively and gain a feature or lose a feature.
The only solution I have come up with, is that I create a bunch of classes and place some properties in there. I only initialize this classes object when one of those properties is needed, otherwise it remains null.
class Apple
Seed seed;
Many problems because of that:
I constantly have to check for every single object and feature each frame. If the seed is not initialized I don't have to calculate anything for it. If it is, I have to.
If I decided to put more than 1 property/feature into the Seed class, I need to check every single one of those aswell.
It just gets more and more complicated. The problem I have is therefore, that I need granular control over all the features and can't split them intelligently into larger subclasses. Any form of subclass would just contain a bunch of properties that need to be checked and updated if wanted.
I can't exactly create subclasses of Apple, because of the need for such high granular control. It would be madness to create as many classes as there are combinations of properties.
My main goal: I want short code.
It would be madness to create as many classes as there are combinations of properties.
Sounds like you might be looking for the Decorator Pattern. It's purpose is to make it easier to manage objects that can have many different combinations of properties without an exponentially growing heirarchy. You just have one small subclass for each property or behavior (not necessarily one C# property, just something you can group together) and then you can compose them together at runtime.
In your case, each Apple decorator class will override your Update method, and make the calculations necessary for its parts, and then call base.Update to pass it to the next in line.
Your final answer will heavily depend on exactly what your "Apple" really is.
After reviewing your comments and samples in my other answer, I've thought about the Decorator pattern and how it was being used vs how you want things to work. I've come to the conclusion that Decorator is not right for this purpose. I'm thinking Strategy instead. I have modified the previous sample code for you to take a look at.
I've gotten rid of the decorators altogether. The Broodfather abstract class remains. It has two additional properties an IBroodfatherMagicAbility and an IBroodfatherBloodthirstAbility. This two properties will allow you to access the different attributes that pertain to those abilities, however the key to this all is that the strategy for implementing the abilities can change at runtime (see Strategy pattern).
There are two classes each that implement a "strategy" for both bloodthrist and magic.
IBroodfatherBloodthirstAbility.cs - this is the interface that all "bloodthirst strategies" must implement.
BroodfatherNonBloodThristy.cs - class that implements the attributes for non-bloodthirsty.
BroodfatherBloodThristy.cs - class that implements the attributes for bloodthirsty.
IBroodfatherMagicAbility.cs - this is the interface that all "magical strategies" must implement.
BroodfatherNonMagical.cs - class that implements a strategy for non-magical.
BroodfatherMagical.cs - class that implements a strategy for magical.
BasicBroodfather.cs - this is similar to the previous example, except that now when an instance is created the magic and bloodthrist properties get set to new instances of the non-magical and non-bloodthristy strategy objects.
Program.cs is the driver that shows the classes and how the different strategies can get swapped in and out at runtime.
I think you'll find that more suited to how you wanted things to work.
you may use a nested class in Apple class
http://msdn.microsoft.com/en-us/library/ms173120(VS.80).aspx
I think the key thing here is that you are trying to hold everything in one class. Because of that, the class must be constantly checking what it has and what it doesn't. The solution is to create subclasses or decorators that already know whether or not they have a particular thing. Then they don't have to be checking it each time.
Because you have so many properties which may be combined in different ways, it sounds like the decorator solution is more up your alley.
I think you're in the right path: composition. You compose your class with the other classes that are needed. But you also need to delegate responsibility accordingly. In your example, it's the Seed class that should be responsible for checking it's internal state, and Apple just delegates to it.
As for the optional features problem, maybe you can use null objects instead of null references. This way, you don't need to check for null everytime, and the code is more consistent.
I've been pondering this question for a bit and I've come up with an alternate solution. This may be a bit unorthodox and anti-object oriented, but if you're not faint of heart read on...
Building upon the Apple example: the Apple class can contain many properties, these properties which could be categorized into related groups. For the example I rolled with an Apple class with some properties related to the apple's seeds and others related to the apple's skin.
Apple
a. Seed
a1. GetSeedCount
a2. ...
b. Skin
b1. GetSkinColor
b2. ...
I'm using a dictionary object to store all the apples properties.
I wrote extension methods to define accessors to the properties, using different classes to keep them separate and organized.
By using a dictionary for the properties, you can iterate through all properties stored thusfar at any point (if you have to check all of them, as it sounded like you needed in your update method). Unfortunately you lose strong typing of the data (at least in my sample I did because I'm using a Dictionary< string, string>. You could have separate dictionaries for every type needed, but that would require more plumbing code to route the property access to the correct dictionary.
Using extension methods to define accessors to the properties allows you to separate the code for each logical categories of properties. This keeps things organized into separate chunks of related logic.
Here is a sample I came up with to test how this would work, given with the standard warning that if you were to continue down this path robustification would be in order (validation, error handling, etc.).
Apple.cs
namespace ConsoleApplication1
{
using System.Collections.Generic;
using System.Text;
public class Apple
{
// Define the set of valid properties for all apple objects.
private static HashSet<string> AllowedProperties = new HashSet<string>(
new string [] {
"Color",
"SeedCount"
});
// The main store for all properties
private Dictionary<string, string> Properties = new Dictionary<string, string>();
// Indexer for accessing properties
// Access via the indexer should be restricted to the extension methods!
// Unfortunately can't enforce this by making it private because then extension methods wouldn't be able to use it as they are now.
public string this[string prop]
{
get
{
if (!AllowedProperties.Contains(prop))
{
// throw exception
}
if (Properties.ContainsKey(prop))
{
return this.Properties[prop];
}
else
{
// TODO throw 'property unitialized' exeception || lookup & return default value for this property || etc.
// this return is here just to make the sample runable
return "0";
}
}
set
{
if (!AllowedProperties.Contains(prop))
{
// TODO throw 'invalid property' exception
// these assignments are here just to make the sample runable
prop = "INVALID";
value = "0";
}
this.Properties[prop] = value.ToString();
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (var kv in this.Properties)
{
sb.AppendFormat("{0}={1}\n", kv.Key, kv.Value);
}
return sb.ToString();
}
}
}
AppleExtensions.cs
namespace AppleExtensionMethods
{
using System;
using ConsoleApplication1;
// Accessors for Seed Properties
public static class Seed
{
public static float GetSeedCount(this Apple apple)
{
return Convert.ToSingle(apple["SeedCount"]);
}
public static void SetSeedCount(this Apple apple, string count)
{
apple["SeedCount"] = count;
}
}
// Accessors for Skin Properties
public static class Skin
{
public static string GetSkinColor(this Apple apple)
{
return apple["Color"];
}
public static void SetSkinColor(this Apple apple, string color)
{
apple["Color"] = ValidSkinColorOrDefault(apple, color);
}
private static string ValidSkinColorOrDefault(this Apple apple, string color)
{
switch (color.ToLower())
{
case "red":
return color;
case "green":
return color;
default:
return "rotten brown";
}
}
}
}
Here is a test drive:
Program.cs
namespace ConsoleApplication1
{
using System;
using AppleExtensionMethods;
class Program
{
static void Main(string[] args)
{
Apple apple = new Apple();
apple.SetSkinColor("Red");
apple.SetSeedCount("8");
Console.WriteLine("My apple is {0} and has {1} seed(s)\r\n", apple.GetSkinColor(), apple.GetSeedCount());
apple.SetSkinColor("green");
apple.SetSeedCount("4");
Console.WriteLine("Now my apple is {0} and has {1} seed(s)\r\n", apple.GetSkinColor(), apple.GetSeedCount());
apple.SetSkinColor("blue");
apple.SetSeedCount("0");
Console.WriteLine("Now my apple is {0} and has {1} seed(s)\r\n", apple.GetSkinColor(), apple.GetSeedCount());
apple.SetSkinColor("yellow");
apple.SetSeedCount("15");
Console.WriteLine(apple.ToString());
// Unfortunatly there is nothing stopping users of the class from doing something like that shown below.
// This would be bad because it bypasses any behavior that you have defined in the get/set functions defined
// as extension methods.
// One thing in your favor here is it is inconvenient for user of the class to find the valid property names as
// they'd have to go look at the apple class. It's much easier (from a lazy programmer standpoint) to use the
// extension methods as they show up in intellisense :) However, relying on lazy programming does not a contract make.
// There would have to be an agreed upon contract at the user of the class level that states,
// "I will never use the indexer and always use the extension methods!"
apple["Color"] = "don't panic";
apple["SeedCount"] = "on second thought...";
Console.WriteLine(apple.ToString());
}
}
}
Addressing your comment from 7/11 (the date, not the store) :)
In the sample code you provided, there is a comment that states:
"As you can see, I can't call
BasicBroodmother methods on "monster"
You realize you could do something like this at that point:
BasicBroodmother bm = monster as BasicBroodmother;
if (bm != null)
{
bm.Eat();
}
There isn't much meat to your code, (I understand it was just an example), but when I look at it I get the feeling that you should be able to improve the design. My immediate thought was having an abstract class for broodmother which would contain default implementations of any attributes/actions that are common to all broodmothers. Then specialized broodmothers, like the magical broodmother, would contain any specialized attributes/actions specific to the magical broodmother, but also inherit from the abstract class and if necessary override the nessecary base attributes/actions.
I would take a look at the Strategy pattern for the design of the actions so that the actions (i.e. behaviours like eat, spawn, attack) can be swappable based the type of monster.
[edit 7/13]
Don't have time to go into details right now (need sleep), but I put together some sample code showing a different approach.
The code consists of:
Broodfather.cs - abstract class filled with all things common to different Broodfathers "types."
BasicBroodFather.cs - concrete class that inherits from Broodfather.
BroodfatherDecorator.cs - abstract class to be inherited by all Broodfather decorators.
MagicalBroodfather.cs - this class decorates/wraps a Broodfather with "magic"
BloodthirstyBroodfather.cs - this class decorates/wraps a Broodfather with "bloodthirst"
program.cs - demonstrates two examples: The first starts with a basic broodfather that gets wrapped by magic then by bloodthirst. The second starts with a basic broodfather and wraps it in the other order bloodthirst, then magic.
Maybe your methods are not were they are supposed to be?
If you separated the Seed class from the Apple class, why don't you move the methods that use the Seed information to the Seed class too?
If those methods need information on other Apple properties, you can pass it as a parameter.
By doing this, I guess you can eliminate the initialization checks...
This is a great book about how to solve this kind of problem:
Refactoring
My main goal: I want short code.
Options:
Rewrite all functions as static and create a class for each one.
Rewrite your codebase in Perl.
Remove all comments.
We have a Student class in our business model. something struck me as strange, if we are manipulating one student from another student, the students private members are visible, why is this?
class Program {
static void Main(string[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.SeePrivatePropertiesAndFields(s2);
}
}
public class Student {
private String _studentsPrivateField;
public Student() {
_studentsPrivateField = DateTime.Now.Ticks.ToString();
}
public void SeePrivatePropertiesAndFields(Student anotherStudent) {
//this seems like these should be private, even from the same class as it is a different instantiation
Console.WriteLine(anotherStudent._studentsPrivateField);
}
}
Can i have some thoughts on the design considerations/implications of this. It seems that you can't hide information from your siblings. Is there a way to mark a field or member as hidden from other instances of the same class?
There's an easy way to ensure this:
Don't mess around with private members of other instances of the same class.
Seriously - you're the one writing the Student code.
The easiest way to ensure this is to program to an interface, such as:
class Program
{
static void Main(string[] args)
{
IStudent s1 = new Student();
IStudent s2 = new Student();
s1.ExamineStudentsMembers(s1);
}
}
public interface IStudent
{
void ExamineStudentsMembers(IStudent anotherStudent);
}
public class Student : IStudent
{
private string _studentsPrivateMember;
public Student()
{
_studentsPrivateMember = DateTime.Now.Ticks.ToString();
}
public void ExamineStudentsMembers(IStudent anotherStudent)
{
Console.WriteLine(anotherStudent._studentsPrivateMember);
}
}
This will no longer compile due to ExamineStudentsMembers trying to access a private field.
If you are writing the class, you have complete control over it, so if you don't want one object to be able to modify another, don't write in that functionality.
Classes will often use private variables in other instances to implement efficient comparison and copy functions.
Private just means that the member (field/method/etc.) can be accessed only from the within the code of the parent type. From CSharpOnline
Private members of multiple instances are visible and can be invoked. This comes in handy when you are implementing a "copy constructor" or a "clone" method on your type, where the argument is an instance of the same type. If the designers would have made private fields inaccessible, then you may have to create a bunch of getter methods just for clone/copy to get at them. IMHO, I like it better the way it is. Within the same type, Reading another object's state isn't that bad as writing to it though (which could be a DONT-code-convention for you/your team.)
Accessing a sibling's private data may seem wrong when phrased like:
public void ExamineStudentsMembers(Student anotherStudent) {
//this seems very wrong
Console.WriteLine(anotherStudent._studentsPrivateMember);
}
However, it doesn't seem so odd for methods which require this sort of functionality. What methods require accessing a sibling's private data? Comparison methods (in particular equals) and objects in a data structure (say a tree or linked list).
Comparison methods often compare private data directly rather than just the public data.
For a class of nodes that make up a linked list, graph or tree, being able to access a sibling's private data is exactly what is needed. Code in the know (part of the class) can tinker around with the data structure, but code outside of the data structure cannot touch the internals.
It is interesting to note that these two cases are less common in day-to-day programming than when this language feature were first developed. Back in 1990s and early 2000s, in C++ it would have been much more common to build custom data structures and comparison methods. Perhaps it is a good time to reconsider private members.
i like the second point, you can look, but dont touch those private members.
it's funny you should say that, i knew a teacher once and he said he often had a problem deciding what classes it was ok to look at the members and which ones he could actually have a play with.
An object is just a piece of data; the class contains the functionality. A member method is just a nice trick the compiler plays; it's really more like a static method with an implied argument (sort of like extension methods). With that in mind, protecting objects from each other doesn't make any sense; you can only protect classes from each other. So it's natural that it works that way.
No, this is necessary, the method code is not specific to the instance, it is only specific to the type of the object. (virtual methods) or the declared type of the variable (for non-virtual methods). The non-static fields, on the other hand, are instance specific... That's where you have instance-level isolation.
The only difference between a static method and a non-static method is that the static method is not allowed to access other instance based (non-static) methods or fields. Any method that CAN be made static without modification will not be affected in any way by making it static, except to force compiler to throw errors anywhere it was called using instance-based syntax.
If you intend to examine a given student's information then I would change the method to be static:
public static void ExamineStudentsMembers(Student student)
{
Console.WriteLine(student._studentsPrivateMember);
}
You would then use Student.ExamineStudentsMembers(s1). Using s1.ExamineStudentsMembers(s2) would be invalid.
If this isn't the intended purpose I would rewrite the method as:
public void ExamineStudentsMembers()
{
Console.WriteLine(_studentsPrivateMember);
}
The above would then be used by writing s1.ExamineStudentsMembers()
Private members are to hide implementation details from clients. The clients should only see the interface (public methods / fields / properties).
The purpose is not to protect the programmer from himself.
This is also NOT a security feature because you can always access private fields via reflection.
It's really to separate interface & implementation (black box design), and clients programming against a contract (all public fields).
For example if you have a public get property, it could access some private field directly, or it could calculate the value from some other fields.
The purpose is, the client only knows the contract (the public property) and the implementation can be changed without affecting the client
Object scope does not ever imply security - ever! It is role of the OS to provide runtime security. It is a bug to design a system that relies on language specific object scope to limit runtime object instance data access. If this were not the case, then all non OO languages are, by definition, not secure.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
The C++ friend keyword allows a class A to designate class B as its friend. This allows Class B to access the private/protected members of class A.
I've never read anything as to why this was left out of C# (and VB.NET). Most answers to this earlier StackOverflow question seem to be saying it is a useful part of C++ and there are good reasons to use it. In my experience I'd have to agree.
Another question seems to me to be really asking how to do something similar to friend in a C# application. While the answers generally revolve around nested classes, it doesn't seem quite as elegant as using the friend keyword.
The original Design Patterns book uses it regularly throughout its examples.
So in summary, why is friend missing from C#, and what is the "best practice" way (or ways) of simulating it in C#?
(By the way, the internal keyword is not the same thing, it allows all classes within the entire assembly to access internal members, while friend allows you to give a certain class complete access to exactly one other class)
On a side note.
Using friend is not about violating the encapsulation, but on the contrary it's about enforcing it. Like accessors+mutators, operators overloading, public inheritance, downcasting, etc., it's often misused, but it does not mean the keyword has no, or worse, a bad purpose.
See Konrad Rudolph's message in the other thread, or if you prefer see the relevant entry in the C++ FAQ.
Having friends in programming is more-or-less considered "dirty" and easy to abuse. It breaks the relationships between classes and undermines some fundamental attributes of an OO language.
That being said, it is a nice feature and I've used it plenty of times myself in C++; and would like to use it in C# too. But I bet because of C#'s "pure" OOness (compared to C++'s pseudo OOness) MS decided that because Java has no friend keyword C# shouldn't either (just kidding ;))
On a serious note: internal is not as good as friend but it does get the job done. Remember that it is rare that you will be distributing your code to 3rd party developers not through a DLL; so as long as you and your team know about the internal classes and their use you should be fine.
EDIT Let me clarify how the friend keyword undermines OOP.
Private and protected variables and methods are perhaps one of the most important part of OOP. The idea that objects can hold data or logic that only they can use allows you to write your implementation of functionality independent of your environment - and that your environment cannot alter state information that it is not suited to handle. By using friend you are coupling two classes' implementations together - which is much worse then if you just coupled their interface.
For info, another related-but-not-quite-the-same thing in .NET is [InternalsVisibleTo], which lets an assembly designate another assembly (such as a unit test assembly) that (effectively) has "internal" access to types/members in the original assembly.
In fact, C# gives possibility to get same behavior in pure OOP way without special words - it's private interfaces.
As far as question What is the C# equivalent of friend? was marked as duplicate to this article and no one there propose really good realization - I will show answer on both question here.
Main idea was taking from here: What is a private interface?
Let's say, we need some class which could manage instances of another classes and call some special methods on them. We don't want to give possibility to call this methods to any other classes. This is exactly same thing what friend c++ keyword do in c++ world.
I think good example in real practice could be Full State Machine pattern where some controller update current state object and switch to another state object when necessary.
You could:
The easiest and worst way to make Update() method public - hope
everyone understand why it's bad.
Next way is to mark it as internal. It's good enough if you put your
classes to another assembly but even then each class in that assembly
could call each internal method.
Use private/protected interface - and I followed this way.
Controller.cs
public class Controller
{
private interface IState
{
void Update();
}
public class StateBase : IState
{
void IState.Update() { }
}
public Controller()
{
//it's only way call Update is to cast obj to IState
IState obj = new StateBase();
obj.Update();
}
}
Program.cs
class Program
{
static void Main(string[] args)
{
//it's impossible to write Controller.IState p = new Controller.StateBase();
//Controller.IState is hidden
var p = new Controller.StateBase();
//p.Update(); //is not accessible
}
}
Well, what about inheritance?
We need to use technique described in Since explicit interface member implementations cannot be declared virtual and mark IState as protected to give possibility to derive from Controller too.
Controller.cs
public class Controller
{
protected interface IState
{
void Update();
}
public class StateBase : IState
{
void IState.Update() { OnUpdate(); }
protected virtual void OnUpdate()
{
Console.WriteLine("StateBase.OnUpdate()");
}
}
public Controller()
{
IState obj = new PlayerIdleState();
obj.Update();
}
}
PlayerIdleState.cs
public class PlayerIdleState: Controller.StateBase
{
protected override void OnUpdate()
{
base.OnUpdate();
Console.WriteLine("PlayerIdleState.OnUpdate()");
}
}
And finally example how to test class Controller throw inheritance:
ControllerTest.cs
class ControllerTest: Controller
{
public ControllerTest()
{
IState testObj = new PlayerIdleState();
testObj.Update();
}
}
Hope I cover all cases and my answer was useful.
You should be able to accomplish the same sorts of things that "friend" is used for in C++ by using interfaces in C#. It requires you to explicitly define which members are being passed between the two classes, which is extra work but may also make the code easier to understand.
If somebody has an example of a reasonable use of "friend" that cannot be simulated using interfaces, please share it! I'd like to better understand the differences between C++ and C#.
With friend a C++ designer has precise control over whom the private* members are exposed to. But, he's forced to expose every one of the private members.
With internal a C# designer has precise control over the set of private members he’s exposing. Obviously, he can expose just a single private member. But, it will get exposed to all classes in the assembly.
Typically, a designer desires to expose only a few private methods to selected few other classes. For example, in a class factory pattern it may be desired that class C1 is instantiated only by class factory CF1. Therefore class C1 may have a protected constructor and a friend class factory CF1.
As you can see, we have 2 dimensions along which encapsulation can be breached. friend breaches it along one dimension, internal does it along the other. Which one is a worse breach in the encapsulation concept? Hard to say. But it would be nice to have both friend and internal available. Furthermore, a good addition to these two would be the 3rd type of keyword, which would be used on member-by-member basis (like internal) and specifies the target class (like friend).
* For brevity I will use "private" instead of "private and/or protected".
- Nick
You can get close to C++ "friend" with the C# keyword "internal".
Friend is extremely useful when writing unit test.
Whilst that comes at a cost of polluting your class declaration slightly, it's also a compiler-enforced reminder of what tests actually might care about the internal state of the class.
A very useful and clean idiom I've found is when I have factory classes, making them friends of the items they create which have a protected constructor. More specifically, this was when I had a single factory responsible for creating matching rendering objects for report writer objects, rendering to a given environment. In this case you have a single point of knowledge about the relationship between the report-writer classes (things like picture blocks, layout bands, page headers etc.) and their matching rendering objects.
C# is missing the "friend" keyword for the same reason its missing deterministic destruction. Changing conventions makes people feel smart, as if their new ways are superior to someone else' old ways. It's all about pride.
Saying that "friend classes are bad" is as short-sighted as other unqualified statements like "don't use gotos" or "Linux is better than Windows".
The "friend" keyword combined with a proxy class is a great way to only expose certain parts of a class to specific other class(es). A proxy class can act as a trusted barrier against all other classes. "public" doesn't allow any such targeting, and using "protected" to get the effect with inheritance is awkward if there really is no conceptual "is a" relationship.
This is actually not an issue with C#. It's a fundamental limitation in IL. C# is limited by this, as is any other .Net language that seeks to be verifiable. This limitation also includes managed classes defined in C++/CLI (Spec section 20.5).
That being said I think that Nelson has a good explanation as to why this is a bad thing.
Stop making excuses for this limitation. friend is bad, but internal is good? they are the same thing, only that friend gives you more precise control over who is allowed to access and who isn't.
This is to enforce the encapsulation paradigm? so you have to write accessor methods and now what? how are you supposed to stop everyone (except the methods of class B) from calling these methods? you can't, because you can't control this either, because of missing "friend".
No programming language is perfect. C# is one of the best languages I've seen, but making silly excuses for missing features doesn't help anyone. In C++, I miss the easy event/delegate system, reflection (+automatic de/serialization) and foreach, but in C# I miss operator overloading (yeah, keep telling me that you didn't need it), default parameters, a const that cannot be circumvented, multiple inheritance (yeah, keep telling me that you didn't need it and interfaces were a sufficient replacement) and the ability to decide to delete an instance from memory (no, this is not horribly bad unless you are a tinkerer)
I will answer only "How" question.
There are so many answers here, however I would like to propose kind of "design pattern" to achieve that feature. I will use simple language mechanism, which includes:
Interfaces
Nested class
For example we have 2 main classes: Student and University. Student has GPA which only university allowed to access. Here is the code:
public interface IStudentFriend
{
Student Stu { get; set; }
double GetGPS();
}
public class Student
{
// this is private member that I expose to friend only
double GPS { get; set; }
public string Name { get; set; }
PrivateData privateData;
public Student(string name, double gps) => (GPS, Name, privateData) = (gps, name, new PrivateData(this);
// No one can instantiate this class, but Student
// Calling it is possible via the IStudentFriend interface
class PrivateData : IStudentFriend
{
public Student Stu { get; set; }
public PrivateData(Student stu) => Stu = stu;
public double GetGPS() => Stu.GPS;
}
// This is how I "mark" who is Students "friend"
public void RegisterFriend(University friend) => friend.Register(privateData);
}
public class University
{
var studentsFriends = new List<IStudentFriend>();
public void Register(IStudentFriend friendMethod) => studentsFriends.Add(friendMethod);
public void PrintAllStudentsGPS()
{
foreach (var stu in studentsFriends)
Console.WriteLine($"{stu.Stu.Name}: stu.GetGPS()");
}
}
public static void Main(string[] args)
{
var Technion = new University();
var Alex = new Student("Alex", 98);
var Jo = new Student("Jo", 91);
Alex.RegisterFriend(Technion);
Jo.RegisterFriend(Technion);
Technion.PrintAllStudentsGPS();
Console.ReadLine();
}
There is the InternalsVisibleToAttribute since .Net 3 but I suspect they only added it to cater to test assemblies after the rise of unit testing. I can't see many other reasons to use it.
It works at the assembly level but it does the job where internal doesn't; that is, where you want to distribute an assembly but want another non-distributed assembly to have privileged access to it.
Quite rightly they require the friend assembly to be strong keyed to avoid someone creating a pretend friend alongside your protected assembly.
I have read many smart comments about "friend" keyword & i agree what it is useful thing, but i think what "internal" keyword is less useful, & they both still bad for pure OO programming.
What we have? (saying about "friend" I also saying about "internal")
is using "friend" makes code less pure regarding to oo?
yes;
is not using "friend" makes code better?
no, we still need to make some private relationships between classes, & we can do it only if we break our beautiful encapsulation, so it also isn`t good, i can say what it even more evil than using "friend".
Using friend makes some local problems, not using it makes problems for code-library-users.
the common good solution for programming language i see like this:
// c++ style
class Foo {
public_for Bar:
void addBar(Bar *bar) { }
public:
private:
protected:
};
// c#
class Foo {
public_for Bar void addBar(Bar bar) { }
}
What do you think about it? I think it the most common & pure object-oriented solution. You can open access any method you choose to any class you want.
I suspect it has something to do with the C# compilation model -- building IL the JIT compiling that at runtime. i.e.: the same reason that C# generics are fundamentally different to C++ generics.
you can keep it private and use reflection to call functions. Test framework can do this if you ask it to test a private function
I used to regularly use friend, and I don't think it's any violation of OOP or a sign of any design flaw. There are several places where it is the most efficient means to the proper end with the least amount of code.
One concrete example is when creating interface assemblies that provide a communications interface to some other software. Generally there are a few heavyweight classes that handle the complexity of the protocol and peer peculiarities, and provide a relatively simple connect/read/write/forward/disconnect model involving passing messages and notifications between the client app and the assembly. Those messages / notifications need to be wrapped in classes. The attributes generally need to be manipulated by the protocol software as it is their creator, but a lot of stuff has to remain read-only to the outside world.
It's just plain silly to declare that it's a violation of OOP for the protocol / "creator" class to have intimate access to all of the created classes -- the creator class has had to bit munge every bit of data on the way up. What I've found most important is to minimize all the BS extra lines of code the "OOP for OOP's Sake" model usually leads to. Extra spaghetti just makes more bugs.
Do people know that you can apply the internal keyword at the attribute, property, and method level? It's not just for the top level class declaration (though most examples seem to show that.)
If you have a C++ class that uses the friend keyword, and want to emulate that in a C# class:
1. declare the C# class public
2. declare all the attributes/properties/methods that are protected in C++ and thus accessible to friends as internal in C#
3. create read only properties for public access to all internal attributes and properties
I agree it's not 100% the same as friend, and unit test is a very valuable example of the need of something like friend (as is protocol analyzer logging code). However internal provides the exposure to the classes you want to have exposure, and [InternalVisibleTo()] handles the rest -- seems like it was born specifically for unit test.
As far as friend "being better because you can explicitely control which classes have access" -- what in heck are a bunch of suspect evil classes doing in the same assembly in the first place? Partition your assemblies!
The friendship may be simulated by separating interfaces and implementations. The idea is: "Require a concrete instance but restrict construction access of that instance".
For example
interface IFriend { }
class Friend : IFriend
{
public static IFriend New() { return new Friend(); }
private Friend() { }
private void CallTheBody()
{
var body = new Body();
body.ItsMeYourFriend(this);
}
}
class Body
{
public void ItsMeYourFriend(Friend onlyAccess) { }
}
In spite of the fact that ItsMeYourFriend() is public only Friend class can access it, since no one else can possibly get a concrete instance of the Friend class. It has a private constructor, while the factory New() method returns an interface.
See my article Friends and internal interface members at no cost with coding to interfaces for details.
Some have suggested that things can get out of control by using friend. I would agree, but that doesn't lessen its usefulness. I'm not certain that friend necessarily hurts the OO paradigm any more than making all your class members public. Certainly the language will allow you to make all your members public, but it is a disciplined programmer that avoids that type of design pattern. Likewise a disciplined programmer would reserve the use of friend for specific cases where it makes sense. I feel internal exposes too much in some cases. Why expose a class or method to everything in the assembly?
I have an ASP.NET page that inherits my own base page, that in turn inherits System.Web.UI.Page. In this page, I have some code that handles end-user error reporting for the application in a protected method
ReportError("Uh Oh!");
Now, I have a user control that is contained in the page. I want the user control to be able to call the error reporting methods in the page.
MyBasePage bp = Page as MyBasePage;
bp.ReportError("Uh Oh");
It can't do that if the ReportError method is protected. I can make it internal, but it is exposed to any code in the assembly. I just want it exposed to the UI elements that are part of the current page (including child controls). More specifically, I want my base control class to define the exact same error reporting methods, and simply call methods in the base page.
protected void ReportError(string str) {
MyBasePage bp = Page as MyBasePage;
bp.ReportError(str);
}
I believe that something like friend could be useful and implemented in the language without making the language less "OO" like, perhaps as attributes, so that you can have classes or methods be friends to specific classes or methods, allowing the developer to provide very specific access. Perhaps something like...(pseudo code)
[Friend(B)]
class A {
AMethod() { }
[Friend(C)]
ACMethod() { }
}
class B {
BMethod() { A.AMethod() }
}
class C {
CMethod() { A.ACMethod() }
}
In the case of my previous example perhaps have something like the following (one can argue semantics, but I'm just trying to get the idea across):
class BasePage {
[Friend(BaseControl.ReportError(string)]
protected void ReportError(string str) { }
}
class BaseControl {
protected void ReportError(string str) {
MyBasePage bp = Page as MyBasePage;
bp.ReportError(str);
}
}
As I see it, the friend concept has no more risk to it than making things public, or creating public methods or properties to access members. If anything friend allows another level of granularity in accessibility of data and allows you to narrow that accessibility rather than broadening it with internal or public.
If you are working with C++ and you find your self using friend keyword, it is a very strong indication, that you have a design issue, because why the heck a class needs to access the private members of other class??
B.s.d.
It was stated that, friends hurts pure OOness. Which I agree.
It was also stated that friends help encapsulation, which I also agree.
I think friendship should be added to the OO methodology, but not quite as it in C++. I'd like to have some fields/methods that my friend class can access, but I'd NOT like them to access ALL my fields/methods. As in real life, I'd let my friends access my personal refrigerator but I'd not let them to access my bank account.
One can implement that as followed
class C1
{
private void MyMethod(double x, int i)
{
// some code
}
// the friend class would be able to call myMethod
public void MyMethod(FriendClass F, double x, int i)
{
this.MyMethod(x, i);
}
//my friend class wouldn't have access to this method
private void MyVeryPrivateMethod(string s)
{
// some code
}
}
class FriendClass
{
public void SomeMethod()
{
C1 c = new C1();
c.MyMethod(this, 5.5, 3);
}
}
That will of course generate a compiler warning, and will hurt the intellisense. But it will do the work.
On a side note, I think that a confident programmer should do the testing unit without accessing the private members. this is quite out of the scope, but try to read about TDD.
however, if you still want to do so (having c++ like friends) try something like
#if UNIT_TESTING
public
#else
private
#endif
double x;
so you write all your code without defining UNIT_TESTING and when you want to do the unit testing you add #define UNIT_TESTING to the first line of the file(and write all the code that do the unit testing under #if UNIT_TESTING). That should be handled carefully.
Since I think that unit testing is a bad example for the use of friends, I'd give an example why I think friends can be good. Suppose you have a breaking system (class). With use, the breaking system get worn out and need to get renovated. Now, you want that only a licensed mechanic would fix it. To make the example less trivial I'd say that the mechanic would use his personal (private) screwdriver to fix it. That's why mechanic class should be friend of breakingSystem class.
The friendship may also be simulated by using "agents" - some inner classes. Consider following example:
public class A // Class that contains private members
{
private class Accessor : B.BAgent // Implement accessor part of agent.
{
private A instance; // A instance for access to non-static members.
static Accessor()
{ // Init static accessors.
B.BAgent.ABuilder = Builder;
B.BAgent.PrivateStaticAccessor = StaticAccessor;
}
// Init non-static accessors.
internal override void PrivateMethodAccessor() { instance.SomePrivateMethod(); }
// Agent constructor for non-static members.
internal Accessor(A instance) { this.instance = instance; }
private static A Builder() { return new A(); }
private static void StaticAccessor() { A.PrivateStatic(); }
}
public A(B friend) { B.Friendship(new A.Accessor(this)); }
private A() { } // Private constructor that should be accessed only from B.
private void SomePrivateMethod() { } // Private method that should be accessible from B.
private static void PrivateStatic() { } // ... and static private method.
}
public class B
{
// Agent for accessing A.
internal abstract class BAgent
{
internal static Func<A> ABuilder; // Static members should be accessed only by delegates.
internal static Action PrivateStaticAccessor;
internal abstract void PrivateMethodAccessor(); // Non-static members may be accessed by delegates or by overrideable members.
}
internal static void Friendship(BAgent agent)
{
var a = BAgent.ABuilder(); // Access private constructor.
BAgent.PrivateStaticAccessor(); // Access private static method.
agent.PrivateMethodAccessor(); // Access private non-static member.
}
}
It could be alot simpler when used for access only to static members.
Benefits for such implementation is that all the types are declared in the inner scope of friendship classes and, unlike interfaces, it allows static members to be accessed.