object.enable() anti-pattern

Chris Angelico rosuav at gmail.com
Fri May 10 11:09:04 EDT 2013


On Sat, May 11, 2013 at 12:54 AM, Roy Smith <roy at panix.com> wrote:
> In article <mailman.1531.1368197225.3114.python-list at python.org>,
>  Chris Angelico <rosuav at gmail.com> wrote:
>
>> On Sat, May 11, 2013 at 12:37 AM, Roy Smith <roy at panix.com> wrote:
>> > I suppose, if I had a class like this, I would write a factory function
>> > which called the constructor and post-construction initializer.  And
>> > then I would make the constructor protected.
>>
>> That sounds like a reasonable plan, with the possible exception of
>> protected. Since meeting Python, I've stopped using private and
>> protected anywhere.
>>
>> ChrisA
>
> Each language has its own set of best practices.  Trying to write C++
> code using Python patterns is as bad as trying to write Python code
> using C++ patterns.

Agreed, in generality. But what is actually gained by hiding data from
yourself? Compare:

class Foo
{
    int asdf;
public:
    Foo(int _asdf):asdf(_asdf) {}
    int get_asdf() {return asdf;}
    void set_asdf(int _asdf) {asdf=_asdf;}
    void frob() {printf("Hi, I am %d\n",asdf);}
};

struct Foo
{
    int asdf;
    Foo(int _asdf):asdf(_asdf) {}
    void frob() {printf("Hi, I am %d\n",asdf);}
};

Is there anything worse about the second one? Oh, and by logical
extension, here's something that doesn't (AFAIK) work in C++, but does
in another language that's syntactically similar:

class Foo(int asdf)
{
    void frob() {write("Hi, I am %d\n",asdf);}
}

Now that's brevity. Why bother saying what's patently obvious? (Pike's
"class" keyword is like C++'s "struct", members are public by
default.)

ChrisA



More information about the Python-list mailing list