Why dynamic languages don't have private member definition feature in classes (like objective c or python)? [closed]

StackOverflow https://stackoverflow.com/questions/13424373

Question

Why do dynamic languages lack the ability to define private members in classes? Is there any implementation concern on this feature? Is it possible for this feature to be implemented for a dynamic language?

Was it helpful?

Solution

This can be implemented for dynamic languages. Indeed, in Smalltalk, all members are always private.

The reason why this is not common is that there is no point in having both public and private members. External code should not access the internals of other classes as a matter of design. This can be achieved by just not doing that - it is not easy to do that accidentally.

Python solves this by having everything be public, and allowing programmers to do this if necessary, which creates maximum flexibility. Smalltalk solves this by having everything be private, and forcing programmers to create accessors if access from other code is desired.

As to implementation concerns, access checks are relatively expensive (in that for at least some attribute accesses, there will be extra operations, and the more subtle the rules, the more complex the checks), so the all private and all public models are much more attractive than anything with intermediate access levels.

OTHER TIPS

There are countless answers to this sort of thing, "Why doesn't language X have feature Y?" And the answer is simply because the people involved in creating/evolving the language didn't put it there. Computer languages are like <insert anything here that has variations across members in the set>, not all are the same. (Which most of us are thankful for. ;)

Oy, moving target question...

I'm not an expert in Objective-C, but a quick Googling for "private member function in dynamic languages" turned up some hits that seem to imply that Objective-C does have private member support for classes.

You can use a class expansion in Objective-C to make something not visible to other classes. Ex.

//at the top of MyClass.m
@interface MyClass ()
@property (strong, nonatomic) id myPrivateProperty;
@end

Other than that, there's not much to say as it's too broad a question (still).

Or, in addition the answer by @Mettable:

@interface MyObject : NSObject {
    @private
    id _myIvar;
    id _myOtherIvar;
}

.
.
.

@end

I don't know about Python, but I think this SO answer might help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top