So I had a simple program that was roughly click a button and it preformed a task, nothing fancy, very simple. Now, I have added a LOT more features task for it to do. It does about 5 different main more complex tasks. The task have little input in the sense of like the common class/namespace examples dealing with insert name, address, phone number, etc. The task is more like set up the settings(check/uncheck the checkboxes) on how you want to preform the task and then click the button to preform it. The code has grown out of control. So I am now trying to organize it. I am self taught, so I am running into some trouble, but this is what I am thinking so far for organization. Any comments about the proper way to organize this would be appreciated.
namespace namespaceName
class task1Name
methods for task1
class task1Name
methods for task2
class task2Name
methods for task3
class task3Name
methods for task4
class task5Name
methods for task5
Now I also have a windows form for the program and another windows form for the pop up settings window. The big question is where do these fit in exactly? public partial class className : Form? Will this setup allow the methods in the different task classes to still interact with the form webbrowser control? The form has a couple of webbrowser controls and the task are prformed in the webbrowser control.
I guess in general I am just trying to find the best way to manage the code and to properly setup/structure the code. From reading this How to use separate .cs files in C#? maybe I just stick with the one class/file, since the task involve the webbrowser in windows form.
Ive been looking at http://msdn.microsoft.com/en-us/library/w2a9a9s3%28v=vs.100%29.aspx and the related sections listed below the code example
Breaking out your program into more maintainable chunks - the art of refactoring - can be a very challenging, but also a very rewarding, part of programming. Like #Keith said, you'll learn by doing.
The most important advice is to refactor in small, self-contained steps.
There are a number of ways that you could start this. If you want detailed advice, it would help to know what some of the code looks like. For example, what are the "task" methods' signatures (their names, arguments, and return type) and how do they interact with the "settings".
Here's one suggestion I would make. The single-responsibility principle suggests that the separate tasks should be in separate classes (and, usually, that means they should be in separate files - but that doesn't matter to the compiler at all, it's just for readability). If the tasks are in separate classes, they'll need a way to know what the settings on the form are. But the tasks don't care about the fact that the settings are on a form - they just want the values of the settings. So, create a data structure that contains all the settings from the form. Then, write a single method in the form class that reads all the settings from the controls, so you have that all in one place. Then, in your button click handler for each task's button, just call that method to get the settings, and pass the settings to the particular task that you're trying to run. Presto!
Your code would then look something like this: EDIT: I forgot that the WebBrowser control needs to be passed to the tasks. Fixed.
// Note: All classes and structs go in the same namespace, but each goes in its own .cs file.
// Use a struct, rather than a class, when you just need a small set of values to pass around
struct MySettings
{
public int NumberOfWidgets { get; set; }
public string GadgetFilename { get; set; }
public bool LaunchRocket { get; set; }
}
partial class MyForm
{
// ...constructor, etc.
private void ButtonForTask1_Clicked(object sender, EventArgs e)
{
var settings = ReadSettingsFromControls();
var task1 = new Task1(settings);
task1.DoTheTask(ref this.WebBrowserControl1);
}
private void ButtonForTask2_Clicked(object sender, EventArgs e)
{
var settings = ReadSettingsFromControls();
var task2 = new Task2(settings);
task2.DoTheTask(ref this.WebBrowserControl1);
}
// ... and so on for the other tasks
private MySettings ReadSettingsFromControls()
{
return new MySettings
{
NumberOfWidgets = int.Parse(this.txt_NumWidgetsTextBox.Text),
GadgetFilename = this.txt_GadgetFilenameTextBox.Text,
LaunchRocket = this.chk_LaunchPermission.Checked
};
}
}
class Task1
{
// Readonly so it can only be set in the constructor.
// (You generally don't want settings changing while you're running. :))
private readonly MySettings _settings;
public Task1(MySettings settings)
{
_settings = settings;
}
public void DoTheTask(ref WebBrowser browserControl)
{
// TODO: Do something with _settings.NumberOfWidgets and browserControl
// You can use private helper methods in this class to break out the work better
}
}
class Task2 { /* Like Task1... */ }
Hope that helps! Again, if you post some example code, you'll probably get much better advice on how to refactor it.
I'm currently in the process of working in a class design for a web application I'm building. I'm relatively new to OOP (although I have done some). For the most part I'm fairly confident that I know what I'm doing in the paradigm: I know that it's not good practice for one class to access the internal workings of another class, that unsafe static methods are unsafe because they can modify global state, and that generally speaking, the more purely functional and modular I can keep my code the better off I will be.
I'm a little unsure of what to do in this situation though. I have multiple web pages which all have their own GridView control. Some logic will go through each row and change the color of the row based on certain conditions. Would it be considered bad practice, for example, to keep one static class encapsulating these style changes, which will be accessed by every page? Technically this means that this class would be modifying a member of another class. How should I go about this? I would prefer not to duplicate my code through each class, as I try to adhere to the DRY principle as much as possible.
EDIT: Here's what I'm thinking.
public static class RowStyle
{
public static void SetRed(GridViewRow row)
{
row.BackColor = Color.Red;
}
// More methods here
}
And each page will pass many GridViewRows to this class, and then have them modified.
Generally, static methods are not so much of a problem if they dont modify static state. Therefore, as long as everything it needs is either encapsulated in the method, or passed in via params then there is less of an issue.
Eg, following your example, the following would IMO be fine
public static class Colorizer
{
public static void Colorize(GridView gv)
{
// do you're funky logic here.
}
}
And use that method in each of your pages that need the logic.
However, this would be bad bad bad:
public static class Colorizer
{
private static bool haveIAlreadyColorized = false;
public static void Colorize(GridView gv)
{
if(!haveIAlreadyColorized)
// do you're funky logic here.
}
}
I'd recommend creating a custom UserControl containing your GridView and add all associated logic there. That is the best way to do it within the ASP.NET platform.
If same color codes you will follow then, you can follow this:
Create a common class. Make it static.
Create a method as that will be called in the rowdatabound event and based on event you can change color
I think it would be fine to have a static class with a method like this:
public static System.Drawing.Color GetRowColor(GridRow row)
...
If the rules which govern the value of the color are global, then this is proper.
I would encapsulate the style changes in a single place (web.config would be my choice), and create a helper method that takes a GridView instance as parameter. That helper method's sole purpose in life would be read the style info from the config file, to apply it to the passed GridView instance.
Any pages containing a GridView to which those style changes should be applied, would call the helper method.
I want an architecture to make my UI interact with the database without writing excess code for the UI...i.e. the code behind...
Use the Business Object / User Interface / Business Logic / Data Access architecture.
BO------UI
| |
--------BL
| |
--------DA
A starting point is to define some simple rules of thumb. A good rule of thumb is to have as little code as possible in the Form class. All code in the Form class should be basic UI mapping really.
I personally like using the DAO pattern for organising my database access logic. This pattern neatly encapsulates the code accessing & storing the data, so it can easily be switched and changed. Depending on the complexity of the database, I will normally have 1 DAO per table but for simple databases maybe even just 1 DAO per database.
MVC is a popular way to seperate presentation and other logic as well, but may be overkill for a simple project. Use cases are also a good way to encapsulate logic and seperate it out from the form.
An example of what a basic framework may look like, see below (note: not complete! read the full DAO article to properly implement it). The point of this code is to show that no database logic is in the Form class, it is a simple one-liner when the button is clicked (or whatever) mapping the UI to an action. If you decided to swap from database storage to file storage, it would not be hard to write a FileMyDAO : IMyDAO class and then have the factory return this instead. Notice that none of the UI code changes if you do this!
public interface IMyDAO
{
void InsertData(int data);
}
public class SqlMyDAO : IMyDAO
{
public void InsertData(int data) { throw new NotImplementedException(); }
}
public class DAOFactory
{
public static IMyDAO GetMyDAO() { return new SqlMyDAO(); }
}
public class MyForm : Form
{
private void Button_Click(object sender, EventArgs e)
{
DAOFactory.GetMyDAO().InsertData(123);
}
}
Data Binding is something that you should look into. This will lead you onto more studies but you will certainly get to know the staff you need.
buddy you can use the premitive architecture:
BusinessObjectLayer
BusinessLogicLayer
DataAccessLayer
UILayer
There are already developed free architectural frameworks there waiting to be used.. check..
Nido framework - more flexible, but only for your back end architecture
or
Rocket framework
In the form.cs file I have two buttons,a memo and a timer.My question is: How do I access the timer or the memo from another cs file?
I've tried to make the objects public,but it didn't work,please give me a source or a project,so I can see where I'm mistaken.
Thanks!
Select your button in designer, go to it's properties and change "Modifiers" property from Private to Public.
Then you can get access to it from another class, something like this:
public static class Test
{
public static void DisalbeMyButton()
{
var form = Form.ActiveForm as Form1;
if (form != null)
{
form.MyButton.Enabled = false;
}
}
}
Note: it's just an example and definitely not a pattern for good design :-)
I worry whenever I hear someone talking about "another .cs file" or "another .vb file". It often (though not always) indicates a lack of understanding of programming, at least of OO programming. What's in the files? One class? Two?
You're not trying to access these things from another file, you're trying to access them from a method of a class, or possibly of a module in VB.
The answer to your question will depend on the nature of the class and method from which you're trying to access these things, and the reason why you want to access them.
Once you edit your question to include this information, the answers you receive will probably show you that you shouldn't be accessing these private pieces of the form in classes other than the form class itself.
There is Form object already instanced in Program.cs, except it have no reference. With simple editing you can turn
Application.Run(new Form1());
to
Application.Run(formInstance = new Form1());
declare it like
public static Form1 formInstance;
and use
Program.formInstance.MyFunction(params);
Although I agree with John Saunders, one thing you may be doing wrong, assuming that you have everything accessible through public modifiers, is that you don't have the instance of that form.
For example, this is how you would do it:
Form1 myForm = new Form1;
string theButtonTextIAmLookingFor = myForm.MyButton.Text;
I am assuming that you may be trying to access it like it's static, like this:
string theButtonTextIAmLookingFor = Form1.MyButton.Text;
Just something you might want to check.
The intuitive option is simply to make the control field public
Here is a very good solution to solve this issue..
http://searchwindevelopment.techtarget.com/answer/In-C-how-can-I-change-the-properties-of-controls-on-another-form
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.