Skip to main content
GameDev.net gamedev.net
🔒 Locked

[.net] Private member access

Started by Narf the Mouse May 31, 2010 at 3:17 PM 16 replies 2.4k views
dmatter
dmatter
In C++ there's the friend keyword. You didn't specify a language though. Since this in the .Net forum you might check out InternalsVisibleTo, but I've never used it myself.
AlexKhomich
AlexKhomich
As I know there are no way to allow access to private/protected fields (except reflection).

You should use internal or protected internal access modifiers.

More info in MSDN.

InternalsVisibleTo can be applied to whole assembly only and gives ability to share access to internal fields with other assemblies.
ChaosEngine
ChaosEngine
Quote:
Original post by Narf the Mouse
Is giving another class access to the private and protected members of a class possible and if so, how?


Before doing this, ask yourself why you want to do it? 'cos you better have a damn good reason.

IIRC, it is possible to access private members via reflection. A quick google of "set private member by reflection" should turn up the methods.

Once again, why are you doing this?
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight
Narf the Mouse
Narf the Mouse
...I was thinking it might make my Factory methods more secure, if only they could access the creation functions. *Dry*

Thanks for the info.
Jonny_S
Jonny_S
Quote:
IIRC, it is possible to access private members via reflection. A quick google of "set private member by reflection" should turn up the methods.


It is possible for sure, I wrote a unit test helper that did it, however I'd say that usually there's a better solution to the problem at hand.
TheTroll
TheTroll
The question is do you want to just read the private members or do you want to change the data there?

If you want to change it, then I am going to recommend finding another way. Any time you allow changes to data from another class you lead yourself down a path of debug nightmares.

theTroll
Narf the Mouse
Narf the Mouse
Quote:
Original post by Narf the Mouse
...I was thinking it might make my Factory methods more secure, if only they could access the creation functions. *Dry*

Thanks for the info.

It bears repeating: I was hoping to make the Initialize methods in a class that is created by a factory, private and "friend" such that only the factory could access them.
TheTroll
TheTroll
Why don't you just initialize in the constructor?

theTroll
Narf the Mouse
Narf the Mouse
Quote:
Original post by TheTroll
Why don't you just initialize in the constructor?

theTroll

Separation of logic. A constructor can get large and unwieldy. Plus, then you get multiple constructors. So you make a Set/Initialize method. And then SubSet/SubInitialize methods.

...Or, you make a Factory that makes Whatever according to a pattern.
dmatter
dmatter
Quote:
Original post by Narf the Mouse
A constructor can get large and unwieldy.
I've never suffered from unwieldy constructors, so it makes me wonder what you're doing differently. I'd say it's probably a sign that your class is getting overloaded with responsibility.

Quote:
Plus, then you get multiple constructors. So you make a Set/Initialize method. And then SubSet/SubInitialize methods.
Depending on the language you might be able to use constructor chaining.

Quote:
...Or, you make a Factory that makes Whatever according to a pattern.
You still need to construct and initialise the object though, so either you still have the constructors (so you haven't gained anything) or you have lots of setters/properties for all internal variables (which is foul).
Telastyn
Telastyn
Quote:
Original post by Narf the Mouse
Quote:
Original post by TheTroll
Why don't you just initialize in the constructor?

theTroll

Separation of logic. A constructor can get large and unwieldy. Plus, then you get multiple constructors. So you make a Set/Initialize method. And then SubSet/SubInitialize methods.

...Or, you make a Factory that makes Whatever according to a pattern.


The constructor is inherent to the class. Its logic should not be separate. If you have invariants to setup, set them up. If not, don't.

Slim constructors lead to better code.
Narf the Mouse
Narf the Mouse
Put your money where your mouths are. Here's my roguelike map generation code that I wrote today. Refactor it to a better state, changing only the constructor use.

Any comments about any other part of the code (Which is rough draft) will be ignored.
            Map map = Map.Create(sizeX, sizeY);            List<Room> rooms = new List<Room>();            rooms.Add(Room.Create(map, RoomType.Room, new Point(8, 8)));            List<Door> unusableDoors = new List<Door>();            Door[] doors;            Room currentRoom;            Room tempRoom;            int n = 0;            int retryDoorsCount = 0,                maxRetryDoorsCount = 25;            {                for (n = 0; n < rooms.Count; ++n)                {                    unusableDoors.Clear();                    currentRoom = rooms[n];                    doors = currentRoom.GetDoors;                    tempRoom = null;                    foreach (Door door in doors)                    {                        RoomType roomType = (RoomType)GeneralData.Random.Next((int)RoomType.Total);                        if (roomType == RoomType.Hallway)                            tempRoom = Room.Create(map, roomType, door, new Point(15, 15));                        else if (roomType == RoomType.Room)                            tempRoom = Room.Create(map, roomType, door, new Point(8, 8));                        if (tempRoom != null                            && rooms.FindOrDefault(a => { return Room.Intersection(tempRoom, a) && tempRoom != a; }) == null)                        {                            rooms.Add(tempRoom);                        }                        else                            unusableDoors.Add(door);                    }                    if (unusableDoors.Count > 0)                    {                        currentRoom.RemoveDoors(unusableDoors);                        if (currentRoom.GetDoors.Length == 0 &&                            retryDoorsCount < maxRetryDoorsCount)                        {                            currentRoom.GenerateDoors(map);                            --n;                            ++retryDoorsCount;                        }                        else                            retryDoorsCount = 0;                    }                    else                        retryDoorsCount = 0;                }            }            foreach (Room room in rooms)            {                map.Carve(room);                map.Draw();            }            foreach (Room room in rooms)                foreach (Door door in room.GetDoors)                    map.Carve(door);            return map;
ChaosEngine
ChaosEngine
Quote:
Original post by Narf the Mouse
Put your money where your mouths are. Here's my roguelike map generation code that I wrote today. Refactor it to a better state, changing only the constructor use.

Any comments about any other part of the code (Which is rough draft) will be ignored.
*** Source Snippet Removed ***


Do your own damn work. I'm not going to fix your code for you and I'm certainly not going to attempt to fix up a snippet of code without any context.
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight
Narf the Mouse
Narf the Mouse
Quote:
Original post by ChaosEngine
Quote:
Original post by Narf the Mouse
Put your money where your mouths are. Here's my roguelike map generation code that I wrote today. Refactor it to a better state, changing only the constructor use.

Any comments about any other part of the code (Which is rough draft) will be ignored.
*** Source Snippet Removed ***


Do your own damn work. I'm not going to fix your code for you and I'm certainly not going to attempt to fix up a snippet of code without any context.

No, of course not. You're just going to criticize the way I do it. I guess I can now put that criticism in the proper context, too.


...Right, less grouchy: All I asked *you to do was a cosmetic fix on a short piece of code to prove your assertation. I don't see any place where my code is wrong, aside from being somewhat of a rough draft mess. All I asked was to be shown how it could be done better.

* In general
Telastyn
Telastyn
What parts do you have problems with?

I mean there's very few constructors actually being invoked directly in that code. Personally, I don't see a Room as having any invariants it needs to keep (except perhaps a Map reference to set some readonly field), so it should have a very simple constructor.
ernow
ernow
Quote:
Original post by Narf the Mouse
...I was thinking it might make my Factory methods more secure, if only they could access the creation functions. *Dry*

Thanks for the info.


A way of getting the desired effect is by adding the factory methods as static methods to the class itself. That way you can make the properties/methods/constructors private and have the static Factory method access them.

BTW: I am not too fond of using statics but this might be one of those times.

A nicer design, if you are that concerned about 'security', is by using internal and putting the class and its factory class in one assembly (dll).
Narf the Mouse
Narf the Mouse
Quote:
Original post by Telastyn
What parts do you have problems with?

I mean there's very few constructors actually being invoked directly in that code. Personally, I don't see a Room as having any invariants it needs to keep (except perhaps a Map reference to set some readonly field), so it should have a very simple constructor.

Mostly that it's rough-draft code. I, myself, don't have any other problems with it.
Quote:
Original post by ernow
Quote:
Original post by Narf the Mouse
...I was thinking it might make my Factory methods more secure, if only they could access the creation functions. *Dry*

Thanks for the info.


A way of getting the desired effect is by adding the factory methods as static methods to the class itself. That way you can make the properties/methods/constructors private and have the static Factory method access them.

BTW: I am not too fond of using statics but this might be one of those times.

A nicer design, if you are that concerned about 'security', is by using internal and putting the class and its factory class in one assembly (dll).

I use both, at times. Sometimes, I just collect tools because they might be useful. Although, I've never stuck a class inside its own, specific dll.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.