7 ms·
Public/protected/private is an unnecessary feature
- Dwedit 1y agoLocking away backing fields from a property is not an unnecessary feature.
- scotty79 1y agoIf somebody needs access to the backing field it's usually for a good reason. And if you restrict it, they'll just fork your code and overwrite whatever they need. It should at most be a soft annotation to prevent it from getting auto-completed, not a restriction.
- tenebrisalietum 1y agoand then they also own future responsibility for that change.
- deleted 1y ago[deleted]
- scotty79 1y agoIt's always app dev responsibility. They can't excuse a bug or lack of functionality with "that's what's in the lib". I can't imagine somebody monkey patching exposing internals of a lib and blaming lib author for poor effects.
- simoncion 1y agoHow are they to distinguish between what are internals and what is the public interface if the internals aren't locked behind something like 'private'? Naming convention? [0] Code comments, or other documentation? A thorough reading of the codebase? [0] Good luck with enforcing the One True Naming Convention.
- scotty79 1y agoThat's why I suggested it should be an annotation at most, so you can convey the intent without limiting the users. It can still be using keywords like public, protected, private. Just make them non-binding. In similar manner how TypeScript types are non-binding. You can ignore them in any program that uses TS lib.
- simoncion 1y ago> ...so you can convey the intent without limiting the users. It can still be using keywords like public, protected, private. Just make them non-binding. Yeah, the users aren't likely to be really limited these days. 1) A huge number of widely-used languages have reflection, so you can get at internal members if you really try. 2) For those languages that don't, just remove the keyword and recompile. Someone who's willing to take on the maintenance burden of directly using parts of the software marked by their author as "internal only do not use" is clearly willing to maintain such a minor fork.
- magicalhippo 1y agoI like Boost's approach[1] of using a separate namespace for these implementation-specific things, rather than visibility modifiers. Then the internals are accessible if you need it for a temporary workaround or such, but it's also very obvious when you are accessing stuff you really shouldn't. And implementers are still free to rearrange the internals as they see fit. [1]: Not saying Boost invented it, just where I saw it first.
- rerdavies 1y agoBoost uses both. Implementation-private namespaces are a slightly different feature. They provide a way to share internal methods between classes within boost that must not be used by client code. That's a scoping feature that c++ doesn't have, but c# (for example) does.
- derefr 1y agoYou're assuming a very simplistic model of API coupling, where there are only "applications" and "libraries that the application compiles into itself." But: • There are also runtimes, installed separately from the application. You might be able to fork the JDK, but people want to run your Java application on their JRE, not yours. • There are proprietary applications that nevertheless expose APIs to code against. A Photoshop plugin author can't fork Photoshop to expose fields of the plugin host. • There is the OS itself. You can fork the Linux kernel (and gcc/clang) to expose some internal data your application needs as a system call — but unless you get all that code upstreamed, your application is now entirely non-portable, running only on your own servers at best. • Most commonly of all, there are system libraries. You can certainly fork (and co-distribute / bake in) a library like libicu or libxml — but no major OS will be willing to ship your app or lib as a system package of its own, if it does that. They'll want your app/lib to depend on the existing packaged version of those libs. None of this matters, of course, if you develop proprietary-service backend software for a living. You can maintain a menagerie of weird lib forks, shove all the build artifacts into a docker image, and it'll work for you. But much (I'd say the majority) of the world's programming is not in proprietary-service backends, and so needs to actually depend on code it doesn't control.
- scotty79 1y agoAll very good arguments about not having private and protected.
- demosthanos 1y ago> And if you restrict it, they'll just fork your code and overwrite whatever they need. More power to them. They can take responsibility for that code and maintain it and I don't have to worry about breaking them when I release a new version. Everyone's happy.
- NBJack 1y agoAnd now they've introduced a tight coupling and some serious potential tech debt should the original ever change its internal workings. Also, you seem to assume we're talking about open source here.
- ctxc 1y agoDo you really want to create an interface for every possible place where you'd use `private` though?
- WorldMaker 1y agoRight, even if it is just syntactic sugar for a "pure" dual of `interface` as the article posits, syntactic sugar still has advantages/merit in many scenarios.
- ctxc 1y agoExactly. Ime most classes are not designed to be inherited but want to expose a clean public API. While true that all classes can be inherited, treating _all_ classes with the assumption that they will be would just lead to a labyrinth of code.
- coderjames 1y ago> most classes are not designed to be inherited but want to expose a clean public API. > While true that all classes can be inherited That's what the 'final' keyword in C++ is for: https://en.cppreference.com/w/cpp/language/final.html https://en.cppreference.com/w/cpp/language/final.html "Specifies that a virtual function cannot be overridden in a derived class, or that a class cannot be derived from."
- WorldMaker 1y agoC# and Java both have `sealed` for that, too.
- throwaway2037 1y agoNitpick: It is called "final" in Java, but your point stands. As I understand, C++ borrowed their "final" keyword from Java/C#. I'm not trolling when I write that last sentence. That is something that has really changed about C+ since the C++-11 committee was started -- and continues. When people write language / library proposals, they now regularly survey the landscape and talk about their experiences with other languages / libraries.
- jonathanlydall 1y agoI primarily work in C# and access modifiers allow me to constrain which types or their members on it are accessible to other types or assemblies. This is particularly useful when authoring libraries as I know that for anything not public, I can refactor to my hearts content (provided the externally observed behaviour is otherwise unchanged). It’s a bit of a pity that it was only relatively recently that Visual Studio changed the template for new classes to use internal instead of public. There are lots of public classes in codebases I work on which are probably only public due to the old default and not used externally so could be refactored, but it’s hard to be sure. Whereas with internal classes I can be sure (unless someone has used reflection, but then that’s their problem).
- kevingadd 1y agoI also wish 'sealed' was the default for classes in templates. Usually you're not thinking about what will happen if someone shows up 5 years later to derive from a random class you created, and it has performance benefits to seal a type. You can always remove the sealed qualifier later on purpose.
- nick_ 1y agoSame here. I recently came across a real use for the newer `private protected` (`FamANDAssembly`) modifier combo. Only derived types that are internal to my assembly can access this member. Beautiful. It re-confirmed my long standing belief that OOP is an incredibly powerful and valid pattern.
- kmeisthax 1y agoI'm assuming this is akin to Rust's pub(crate) keyword?
- colejohnson66 1y ago`internal` maps to `pub(crate)`. But there's no analog for `protected` because Rust doesn’t have inheritance. `private protected` means "only me or anyone inheriting me in this assembly". There's also `protected internal` which means "me, anyone inheriting me, and anyone inside this assembly". An assembly is analogous to a Rust crate.
- xyst 1y agoThey are also optional in some languages :) A long time ago in Java corp world, teams would create their own integration libraries with suspicious/horrible contracts. Ended up just using Java’s reflection api to update access modifiers to get their shitty library to work until they fix it (months later…).
- deepsun 1y agoOr introduce a corporate rule to make everything public, if restricting didn't work anyways.
- jimbob45 1y agoI wish private was a suggestion and not strictly enforced in the same way that types aren't strictly enforced in C. Microsoft loves to make public variables private years during upgrades and it can be impossible to rewrite your application to avoid using that now-inaccessible variable. Looking at you, ASP.NET to .NET Core upgrade...
- kevingadd 1y agoHave you heard of Unsafe Accessors? https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.unsafeaccessorattribute?view=net-9.0 https://learn.microsoft.com/en-us/dotnet/api/system.runtime.... They help solve this problem.
- ziml77 1y agoOh that's awesome that they added that. Ending up needing to access private members already sucks, but reflection makes it even worse due to the performance hit you take.
- baobun 1y agoIn case one is not familiar with the author, they are commonly arguing that inheritance is an antipattern that should not be used in OOP languages. The OP is in that context: private and protected are not useful if you don't have inheritence.
- IshKebab 1y agoI don't think that's really true either.
- simoncion 1y agoIt's not true at all. Even Erlang (very much not an OOP language) has public and private methods, with the default being private. If you don't have a mechanism to indicate which parts of your software's API are internal implementation details and which parts are intended for use by users of that software, then you're going to have to rely on convention. The problem with convention is that no ten people do it the same way... which increases cognitive load... which is to be avoided in a field that has more than enough little things to keep track of already.
- deredede 1y ago> The problem with convention is that no ten people do it the same way "Stuff that starts with one underscore is an internal implementation detail, use at your own risk" in Python is as close to a universal convention as you can get.
- orwin 1y agoIdeally, at least in python, 'true' inheritance should be used in very specific cases, and most of the time, you should only 'inherit' mixins and interfaces. In practice? abstract classes all the way down to technical debt hell.
- alganet 1y ago> Use composition instead. Inheritance was a hack in the first place. Composition is great. It's the preferred way. However, if you take it to the extreme (composition only, never inheritance) you sometimes end up with really weird meaningless objects that have only a single method and a one-to-one relationship with another object. Private methods are ideal for making those abstractions easier to understand. A private method, therefore, is equivalent to an object that has a one-to-one relationship with another object (it's only composed there) and a single method. A protected method is similar, but allows whoever subclasses it to replace that single one-to-one "mini object" inside with another one-to-one "mini object". When used within this mindset, it greatly simplifies code. It lets you simplify a branch that has only a single leaf into something easier to read. Together with classical refactorings (extract method, move method, extract class), they're a precious tool. Of course, typing is a consideration as well, but I'm talking exclusively about their role in granularity control. It is unecessary, but convenient. It can be misused. Composition can also be misused.
- tadfisher 1y ago> However, if you take it to the extreme (composition only, never inheritance) you sometimes end up with really weird meaningless objects that have only a single method and a one-to-one relationship with another object. We can take a cue from the functional languages and make this less code-smelly by using anonymous function types (e.g. lambdas). This removes the one issue with single-purpose/single-method objects, which is naming them.
- alganet 1y agoIt's an extra tool, for sure. There is no silver bullet. No one likes huge inheritance chains, no one likes only tiny lego pieces, no one likes callback hell.
- deleted 1y ago[deleted]
- cosmicgadget 1y ago"Because you can limit visibility with interfaces, limiting visibility without using an interface is unnecessary." No thanks. And I'll continue using inheritance and composition correctly too.
- ysofunny 1y agonow say it in a sociology or economics conference
- cherryteastain 1y agoI agree that it's unnecessary, and Python's success despite not having private members/fields is testament to that. But public/private fields/methods, like pretty much everything in OOP, is a 'social' rather than engineering innovation. Just as a class tells you certain operations and data are inter-related, private methods or fields signal to a class's users that you probably will break things if you interfere with certain parts. Otherwise, at least in C++, you can often bypass the private specifier without much difficulty. Perhaps the laziest and easiest way to do so is #define private public #include "foo.hpp" #undef private
- WalterBright 1y ago#define duck_season wabbit_season #include "shoot.hpp"
- n2d4 1y agoPython absolutely does have private members. If a member starts with two underscores, its class name (and an underscore) is prefixed to the member name, essentially resulting in the same behavior as a private modifier. (Although there are ways to circumvent this in Python, there are also ways to access private fields in most other languages.) But even if that were true, that wouldn't mean that accessibility modifiers are unnecessary in other languages. Python is a certain language with certain idioms, and other languages are more or less OOP and hence some constructs that might not make sense in Python definitely make sense elsewhere.
- NeutralForest 1y agoI see what you mean what I wouldn't really qualify name mangling as private members, you're discouraged to access them but you can access them all the same.
- jjice 1y agoI'd consider it the same, personally. It's a social contract that you can absolutely break if you want, just with a bit of work. Less work in Python than it is Java, but there are ways to get to them in Java, or hell, just modify the source and change it directly. By doing that, you're doing something the developer didn't intend and you shouldn't be surprised if it doesn't work at some point in the future. Same as I'd expect in the Python case.
- PaulDavisThe1st 1y agoI'd like them extended slightly, in fact. I'd like a friend declaration after an access specifier to apply only until the next access specifier. Eg. class Foo { public: void method_A(); protected: friend class Bar; void method_B(); protected: friend class Baz; void method_C(); private: void method_D(); }; anyone can call method_A(), only Bar can call method_B(), only Baz can call method_C() and nobody can call method_D(). You can do this by inheriting from 2 different pure abstract classes, but that feels much kludgier to me.
- leni536 1y agoLook up the passkey idiom.
- PaulDavisThe1st 1y agoNice, but cumbersome with > 1 friend.
- hhhAndrew 1y agoThis is how Eiffel works. Instead of private, protected, public, you specify the set of classes a method can be seen by: `feature {ANY}` for `public:`, feature {NONE} for private, feature {Self} (IIRC) for protected, feature {Foo, Bar} for descendants of Foo and those of Bar, etc.
- aurumque 1y agoAccess modifiers don't give you unlimited protection, they help you reason about the code and how it is used. If I change a public method and break something downstream, that's on me and my team. If I change a private method and break someone else's code which was bypassing using reflection or other mechanisms, that's on them. Languages like Python don't have keywords but enforce using conventions like underscore and 'dunder', the latter of which is actually enforced using obfuscation. It is extremely helpful to signal to users that they should not be using certain methods or fields. When there are no access modifiers available, we still see teams writing methods like "xyx_UNSAFE" or "abc_DO_NOT_USE". It's ridiculous to me to encode this kind of information like this instead of having first class support in the language. Access modifiers also tell the compiler or JIT what is safe or unsafe to manipulate. It has implications beyond users, and can be a determining factor when inlining or making other optimizations. This article is so opinionated (edgy?) that it ends with "Inheritance was a hack in the first place." I think, like all things, we need to consider the broader landscape for object oriented programming instead of just saying these things are irrelevant and absurd and useless.
- lowbloodsugar 1y agoAlso the static members of a “class” are another interface: a distinct interface that also enforces a singleton.
- cyberax 1y agoIMO, the Go model of package-private and public entities is the best compromise. Simply because it reduces the global namespace pollution.
- rerdavies 1y agoPackage-private is a nice feature.
- devjab 1y agoI've worked with a lot of languages over the years, Java, C#, Go, Typescript, C and Python have been the main ones. These days everything is becoming Python around here... well with some C/Zig when needed... and the one thing I miss from any language I've worked with before is the Go model of package-private and public entities.
- julik 1y agoFor most modern languages, something like an @internal annotation would work better. With compiled languages that need to conform to an ABI or export RPC definitions, there is merit to specifying what exactly must be exported (or must never be inlined), but even that could be tackled by an @internal or @nodoc or @private annotation - not a language construct. See also https://steve-yegge.blogspot.com/2010/07/wikileaks-to-leak-5000-open-source-java.html https://steve-yegge.blogspot.com/2010/07/wikileaks-to-leak-5...
- rerdavies 1y agoThat would be fine if the annotations were standardized. But if the annotations are standardized, then they might as well be a direct language feature.
- fc417fc802 1y agoIt's a bit different. You'd expect to be able to have your tooling ignore the annotations and everything should "just work" which eases debugging. Annotations are generally expected to be useful for things like linting, optimization, and documentation (ignoring language extensions that change the semantics of course).
- simoncion 1y ago> You'd expect to be able to have your tooling ignore the annotations and everything should "just work" which eases debugging. I'd expect any language that uses annotations to have a fairly-complete reflection capability. I'd also expect a good debugger to be able to use that to permit me to read, modify, and call methods and members marked as 'private'. It has been decades (so perhaps my memory is incorrect), but I remember being able to access private parts in C++ debuggers. If this was true way back when for C++, I expect it to be a common feature now in debuggers for languages that have reflection & etc.
- fc417fc802 1y ago> in C++ debuggers An awful lot of my debugging is done without a debugger. I generally expect a language to permit me to do anything that can be expressed in a logically coherent manner even when I would clearly be shooting myself in the foot. I also expect a bright neon sign warning me not to proceed. I quite like python in that regard. You can monkey patch just about anything even when you really shouldn't.
- wewewedxfgdf 1y agoAll private does is make it hard for developers further down the track to make changes that they want to make. And if you don't need private then why have public?
- rerdavies 1y agoWhat private does is make it easier for developers further down the track to fix bugs, and prevent consumers of a class from making horrible mistakes by introducing dependencies on implementation details of a class that are not guaranteed to exist in future versions.
- khalic 1y agoAh the good old “xxx considered harmful”
- rerdavies 1y agoPretty much all language features save for a shockingly small set are "unnecessary". The proper question is "are they useful?" The usefulness of public/protected/private is that it provides a way to narrow the surface area through which derived classes can interact with their superclasses. Which is enormously useful from a maintenance perspective. The place where inheritance is better than composition is where base classes provide partial implementations that are used by derived classes.
- mattkrause 1y agoExactly: "Loops are an unnecessary feature"
- dboreham 1y agoQuick note that inheritance existed in assembly language programming (and programs written using the front panel switches if you want to take things to the limit) and were not "invented" in Simula or C++. Those languages invented syntactic sugar for techniques that were quite mature at the time both in assembler and older HLLs such as BCPL and C.
- EPWN3D 1y agoHonestly, subclassing strikes me as mostly unnecessary. Most of those use cases can be addressed with protocols or traits.
- Spivak 1y agoWelcome to the Python community's "subclassing is only for sharing code, user-beware if you try to use it for anything else."
- default-kramer 1y agoI strongly prefer FP over OOP, but... Is there any desktop GUI library that isn't built on subclassing? Winforms, WPF, Swing, Qt, Godot all do. This doesn't prove that subclassing is necessary, but it sure seems like the best approach we've found so far.
- dragonwriter 1y ago> Is there any desktop GUI library that isn't built on subclassing? There are desktop GUI libraries implemented in C, Go, and other languages that do not have subclassing, so, the answer kind of has to be yes.
- throwaway2037 1y agoGtk+ is pure C, but the library essentially implements subclassing manually. It is so painful to use, and so much worse that the C++ equivalent in gtkmm. Again, Win32 API does similar to allow subclassing of widgets. Again, painful.
- SideQuark 1y agoEvery GUI toolkit I've used, which is many, implement subclassing for UI elements whether or not the language supports it. Remember, C++ was originally written in C, so it's clear lack of a native language feature doesn't mean things written in that language also lack that feature.
- 1y ago
- curtisszmania 1y ago[dead]
- aryehof 1y agoOf course they are unnecessary, but then strictly speaking control statements can be omitted in favor of goto statements. Are they unnecessary?
- cryptonector 1y agoWe could write only in the untyped lambda calculus -- it has everything you need...
- m3kw9 1y agoIs so the IDE doesn’t show up stuff when private
- kazinator 1y agoIn Common Lisp, we sort of get this by the separation of exported versus unexported package symbols. Unexported package symbols do two things: - when visibility "windows" are created between packages via the "use" mechanism, unexported symbols are excluded. - unexported symbols require tokens with two colons: you have to write foo::bar, not just foo:bar, to refer to bar if it is unexported from package foo; moreover you must still write foo::bar even if you are using package foo, whereas if it were exported, you would just write bar. CLOS uses symbols for naming entities like generic functions, classes and slots. It has no additional protection mechanisms beyond what the symbols provide, and symbols are agnostic of classes (and everything/anything else which they name).
- NBJack 1y agoPlease don't fall for the clickbait here. Take a look at the history of posts from this site.
- deleted 1y ago[deleted]
- ReptileMan 1y agohttps://steve-yegge.blogspot.com/2010/07/wikileaks-to-leak-5000-open-source-java.html https://steve-yegge.blogspot.com/2010/07/wikileaks-to-leak-5... Brilliant steve yegge article on the topic. Wikileaks To Leak 5000 Open Source Java Projects With All That Private/Final Bullshit Removed On a more serious note. While I can see the reason for private members, the case for private methods has always been much weaker.
- nobodyandproud 1y agoOOP and interfaces are at a bit of tension. With inheritance, you’re breaking some level of encapsulation by choice; it needs to be done carefully. Likewise, the base class needs to be designed thoughtfully.
- burnt-resistor 1y agoOOP is the unnecessary feature that can be replaced with interfaces/traits and composition and proxy pattern. OOP is excessive convenience that led to numerous non-orthogonal features in many languages.