11 ms·
One of the most memorable eye-opening moments in my (admittedly fractured) education was when when my software engineering professor listed the 3 fundamental te
by macintux 8y ago
One of the most memorable eye-opening moments in my (admittedly fractured) education was when when my software engineering professor listed the 3 fundamental tenets of OO—inheritance, encapsulation, and polymorphism—and then asked us which one was optional.
Ever since then I've been on an anti-inheritance kick, although for the last several years it's polymorphed into an anti-OO kick.
Anyway, I suspect most readers here have heard the idea that inheritance should be used in limited circumstances (or not at all), but I wonder what proportion of college students get that message today.
- kazinator 8y agoIt was a trick question: two are optional. (I pity the educator if he or she didn't know this.)
- macintux 8y agoIf you eliminate polymorphism and inheritance, is what's left really all that useful?
- kazinator 8y agoThe one we can dispense with is encapsulation. Polymorphism, no; I mean, how can we substitute different kinds of objects into the same situations dynamically without polymorphism. OOP is almost synonymous with polymorphism. But we do not have to bundle code and data representation together; there are other approaches to OOP, like generic functions.
- yourbandsucks 8y agoI mean, you can do pure functions. And those pure functions can operate on structs. And, once you're there, it's probably good hygiene to keep all the functions operating on a given struct in one file. Congrats, you're back to 'encapsulation'! Encapsulation is actually the only important tool in that particular toolkit. We're mortals, we need coping tools to keep programs manageable.
- erikpukinskis 8y agoWould you be interested in doing a podcast together about programming? I'm a radical javascript programmer (search ONNEMI-4211). You seem smart. I've never made a podcast before.
- yourbandsucks 8y agoOn the one hand, you've got some amazing satire here, on the other hand, I'm a little insulted that it's directed at me of all people. Upvoted anyways :)
- erikpukinskis 8y agoSatire?
- TeMPOraL 8y agoThat kind of "encapsulation" is simply storing code together with the data it belongs to (good practice) and possibly namespacing it together. It's not what they mean by "encapsulation" in OO courses, though it's arguably the only benefits "encapsulation" give you.
- mikekchar 8y agoI don't think we can dispense with encapsulation and still have OO, though. Sure you can program without it. You can even make good programs without it. You may even be able to make better programs without it :-) However, it won't be OO. The idea behind OO is to move away from data-centric programming. If I have a system dealing with geometry, I can have a Point object that has an x and y coordinate. However, once I have a Point, I should be trying to make my system so that I no longer access x and y directly. X and y are "encapsulated" in the Point. Collaborators should use the functionality on Point to do what they need to do, rather than trying to pry Point apart and get at the data. Of course, barely anybody writes "OO" code like that, even if they espouse to follow "encapsulation". I would argue as well that generic functions do not, in themselves offer an OOP environment. You need one more thing: partially applied functions. If you can create a partially applied function, you can bake in some program state and pass it around, offering functionality on that program state. However, nobody on the outside can access that state. This is the encapsulation necessary for OO.
- deleted 8y ago[deleted]
- jnwatson 8y agoPython is build entirely around the idea that encapsulation is mostly useless. "We're all consenting adults" is the general philosophy. As long as there's a convention as to what properties are "public" and which are not, a motivated user of a class should be able to do what they want with it. There's no point in putting a "private/public/protected" security model in a programming language. It isn't a security boundary. This vastly simplified the design of OO in Python, and it makes testing far far easier. There's no need to go through the dependency injection acrobatics in order to change one method for testing or proxying. (There technically is a way to munge a property name in Python but its use is discouraged).
- scarface74 8y agoThere's no point in putting a "private/public/protected" security model in a programming language. It isn't a security boundary. It’s about intention. If I mark a property or method as private, it means that I can get rid of it, rename it or change the expected behavior without considering it a breaking chance.
- maxxxxx 8y ago"The one we can dispense with is encapsulation." To me this is the most important part. I like to have private or public, protected is not needed. I agree that code representation should be kept separate.
- masklinn 8y ago> To me this is the most important part. I like to have private or public, protected is not needed. OO's encapsulation is about bundling data and operation, not about information hiding, and as kazinator noted generic functions (as in CLOS) prove you can have OO just fine without. As to information hiding, there are many fine OO languages which don't have it either (Python probably being the prime example there, but I'd say it also applies to languages like Ruby where you can trivially override existing ACL) so it's clearly not necessary either, let alone "the most important part". Especially as conversely many non-OO languages do have access control, hinting that the two are quite likely orthogonal. Information hiding is useful for engineering and resilience, not for object orientation. As to private / protected / public, I'd argue it's private which is the least useful (since we've already ascertained none is actually needed): it's literally just hiding stuff from yourself. I think removing that level of ACLs is one of the few good idea Go had.
- TeMPOraL 8y agoACLs also seem to mix concerns. The "private" concept is essentially making life difficult for yourself, but having a built-in mechanism for separating public interface from internal code, that's a bit more than just convention, is useful. For instance, in Common Lisp there's no language-enforced ACL, but when building modules (that may or may not involve a class, or many classes), I assign a package for each module and make it export only the symbols that represent its public interface. In code using that module, this becomes a syntactic difference in a way you refer to these symbols - module:foo means "foo exported from package 'module'", while module::foo means "foo internal to package module". That simple isolation, completely overridable with an extra colon character, is enough to clearly communicate what is and what isn't a part of an abstraction.
- mschuetz 8y agoI like to use classes almost exclusively as a way to couple an object with methods directly related to it. Basically structs with methods. Useful enough for me.
- diminoten 8y agoThis very article ends with '"¿Por qué no los dos?", which means "Why not both?"'. I agree, use both, but don't get carried away with either. If you exclusively use composition you're basically reinventing inheritance anyway, with more steps. But the linked article is reasonable. Less reasonable articles like this one exist, however: https://codeburst.io/inheritance-is-evil-stop-using-it-6c4f1caf5117 https://codeburst.io/inheritance-is-evil-stop-using-it-6c4f1... These are the articles where someone saw that the "cool kids" don't like/use inheritance, and so adopted the position to try and be "cool". Don't try to be cool, try to understand. Inheritance doesn't say, "Create a complex inheritance tree of interdependent classes". That's the strawman. Remember that.
- seanmcdirmid 8y agoThat is one subjective question, OO is not that well defined beyond being oriented around objects. Heck, the Treaty of Orlando from 1988 says a lot more about the open definition of OO.
- mehrdadn 8y ago> when my software engineering professor listed the 3 fundamental tenets of OO—inheritance, encapsulation, and polymorphism—and then asked us which one was optional. None of these is a fundamental tenet. See the article linked here [1]. The fundamental tenets are the five "SOLID" [2] principles. Object-oriented design is not well-taught in general. The impression most people normally have of it is quite different from what it actually is. P.S. You may also find [3] interesting. [1] https://news.ycombinator.com/item?id=18250255 https://news.ycombinator.com/item?id=18250255 [2] https://en.wikipedia.org/wiki/SOLID https://en.wikipedia.org/wiki/SOLID [3] https://news.ycombinator.com/item?id=16468796 https://news.ycombinator.com/item?id=16468796
- weberc2 8y agoThis seems very much like a semantic debate. Either OOP is characterized by inheritance—which is consistent with the notoriously “OOP” languages like Java, C#, and C++<11 and probably the overwhelming majority of intro-to-OOP literature—or you exclude inheritance as a hallmark and make it so general as to be indistinguishable from many other paradigms, many of whom came before it. If the latter, why bother fighting the semantic debate at all? If OOP really is that unremarkable, why advocate for it as a meaningful label instead of advocating for SOLID generally?
- JamesBarney 8y agoI'm not a huge fan of SOLID. It's treated as a pillar of software development, but I feel like some of the advice sounds good or is right but isn't terribly useful(SL), one was so terrible it was rebranded(O), and some are a useful tool more than a design goal(ID). Single responsibility principle - something we can all agree on but doesn't help you decide between two non hideous designs Open/Closed Principle - the original advice was so terrible that we ignore it and pretend it means something else that has very little to do with open/closed Liskov - technically true but very few applications are bad or incorrect because of this violation(especially with the recent move away from inheritance) Interface Segregation - Sure it's useful to split up interfaces sometimes. Dependency Injection - Sometimes useful for testing or IOC.
- harimau777 8y ago
- lolptdr 8y agoWith all this angst against OOP, what other alternatives should a programmer consider or what patterns of hierarchical logic do people suggest?
- cuddlecake 8y agoThe first question should be whether we need hierarchical logic, or what hierarchical logic is supposed to be.
- weberc2 8y agoUse composition for reuse and interfaces for polymorphism. These can do the same as inheritance and more, and they do it more cleanly. Reuse and polymorphism are orthogonal concerns that inheritance tries to fuse awkwardly together. Try Go if you’d like a familiar language without the inheritance that you can pick up in an afternoon.
- tonyedgecombe 8y agoIt's not compulsory even in a language that supports it, I'm working on a medium sized C# project that has minimal use of inheritance and only then to fit in with the requirements of a library feature.
- weberc2 8y agoYeah, I meant it as a learning suggestion, not a “switch your main language” suggestion. Fully agree with you.
- collyw 8y agoAren't most large systems organized in an OOP manner?
- barrkel 8y agoHierarchy - a single ontology - is one of the problems with OO. Ontologies - note the plural - are useful, but choosing just one ontology privileges some axis of abstraction over others, but there are different lenses you can put on things that may make you want to classify by different criteria. For example, you might have a bunch of things, some of which: (a) can be rendered in some display - could be console, HTML, print output, screen, don't care; (b) can be serialized to a variety of media; (c) have some common configuration, that interacts with some configuration management system; etc. If you try and shoe-horn these commonalities into a hierarchy, you end up with classes that advertise being able to do too much and need to have "not implemented" error conditions, breaking the Liskov substitution principle. Interfaces are a way of breaking out. They're additive, rather than hierarchical, from the implementing class perspective. The other big problem (a bigger problem IMO) with inheritance is coupling. I don't think there's any closer coupling between two pieces of code in an OOP system than inheritance. Changes in a base class can radically alter behaviour in all descendants. Depending on the implementation of overriding, descendant behaviour can be accidentally hijacked with no compile time or run time warning merely by updating a dependency. The API by which base class and descendant class interact is bidirectional, with the flavours of both library (you call them) and framework (we'll call you), and intermediate internal state when e.g. overridden protected methods are being called is usually sorely undocumented and liable to change.
- keithnz 8y agothose 3 annoy me... I'd go with 2:- - messages - objects that have conversations with other objects through messages to achieve a cohesive purpose inheritence is essentially a method of sharing code without going through a message, so not really OO, you can use any sharing mechanisim you like to make cohesive objects.
- la_barba 8y agoI assume you pass pointers around to share data? How do you handle cleanup?
- dnautics 8y agothat's too vague. Most OO PLs don't actually use messages in any way under the hood (except maaaybe ruby? I hear things but haven't peeked at the MRI code) and use messages as a "conceptual framework" but let's be honest - is calling a method owned by object A.do_something(B::target_type, C::parameter_type)... What sort of a message is that? moreover, plenty of FPs (I'm looking at you erlang) use message passing all over the place, as, arguably the most important feature of the language, with things that vaguely look like objects (gen_servers) but I would not really call erlang an OO language, except maybe to joke to an OO programmer that an FP is truer to the original intent.
- keithnz 8y agoInheritance / encapsulation / polymorphisim are kind of vague too. actually, Alan Kay said Erlang was most like his concept of OO. Ruby has some nice hooks for when an object doesn't have a method, at which point you can dynamically resolve it. Much advice in the OO world and its principles are really just to do with message routing, and a lot of Design Patterns are about how to do it when the type system fights you but even if you are stuck with your C++/Java/C# type languages, then I think it is still useful. I've often seen in the first 10-15 minutes with "traditional" advice that set off down a path of design that ultimately causes a lot of struggle between OO and the typing system, most often because of naming things too early warping the mental rather than recognizing traits of interactions.
- jillesvangurp 8y agoExactly. I learned pretty early that inheritance relations can be trivially refactored into a delegation based design and that there's a difference between type inheritance (aka. interfaces) and implementation inheritance. IMHO inheritance and especially deep inheritance hierarchies are almost always the wrong thing to do. I know of few exceptions and have ended up regretting breaking that rule on the few occasions I allowed that to happen. These days I just don't use it at all on principle. I'm very weary of using frameworks that depend on or over use inheritance. E.g. much of Spring looks problematic and convoluted to me. I use it but I tend to avoid the stuff that is too hard to understand. Five or more layers of classes is just insanely misguided IMHO. Most of those layers are just working around the previous (wrong) decision to use inheritance. It's like the broken windows theory. Inheritance leads to more inheritance. It causes all sorts of problems down the line and you can't change it once you have users extending your classes. I love that modern languages disable this. E.g. Kotlin has closed classes by default (the opposite of Java) and does not allow inheritance between data classes at all. This is great and communicates clearly that you should not be littering your code base with 'open'. This encourages good design that does not depend on scattering functionality all over the inheritance hierarchy or the endless levels of indirection. They even provide a compiler plugin to deal with spring that re-opens classes at compile team so that Spring and other legacy Java framworks can do it's dirty business of reflectively extending classes without requiring the code to be compromised. I find it ironic that e.g. the Javascript community has worked hard to get classes and inheritance and are essentially repeating all the same mistakes people were making with Java 20 years ago by overusing inheritance. Most of 'modern' javascript to me looks like a blast from the past.
- masklinn 8y ago> I find it ironic that e.g. the Javascript community has worked hard to get classes and inheritance and are essentially repeating all the same mistakes people were making with Java 20 years ago by overusing inheritance. Most of 'modern' javascript to me looks like a blast from the past. IME JS classes are less about inheritance (which remains compositional anyway, though classes do make these easier what with not having to maintain the prototype chain or hand-roll super calls) and more about the various syntactical convenience of class declarations, namely that you don't have to deal with the Function / Function.prototype crap, the hand-rolling of `new` mandates (a class ctor is always called through new), the requirement of explicit strict mode (class declarations are always strict), method shorthands (they do exist on object literals, they don't exist when adding to a prototype property by property), …
- jmkni 8y agoI was taught that there were 4 tenents, inheritance, encapsulation, polymorphism and abstraction.
- cygx 8y agoI'm not a fan of that as a definition: To me, object-orientation means modelling computation as communication between stateful objects. An object-oriented programming language has features that facilitate such a design. Inheritance would be such a feature, but it could easily be substituted with other ways of subtyping and code reuse.
- bsaul 8y agoAbsolutely. Tight coupling between data set instance and function that manipulates this data seems to be the current definition of object-orientation (as opposed to something more philosophical like "living entities communicating together", which is a bit vague IMHO). Rather than having one big memory chunk, and one big function chunk (like the old DATA DIVISION and PROCEDURE DIVISION of cobol), you divide thoses into smaller data+procedure bits that idealy map to existing concepts from your domain. That seems like a much more effective way of seeing the thing. Although once you start adding parallelism and asynchronous communication, you do probably end-up in something closer to the Kay definition.
- TeMPOraL 8y agoI've noticed OO education has a habit of appropriating every good idea from software engineering as if it was a distinctive feature of OO approach. I think reading SICP opened my eyes to that for the first time. As it turns out, you can do abstraction without objects just fine.
- seanmcdirmid 8y agoWhat OO education? I find that people just fling around random tenants when they talk about OO, even worse when they talk about FP. Even crazier is when some darling FP technique like entity component systems specifically use a synonym for object (entity) to avoid being called OO.
- noego 8y agoI agree with "anti-inheritance" as a general guideline, but its adherents have to recognize the significant practical upsides of inheritance in many situations. Imagine you have an interface with 20+ methods, such as the List interface. And you want to create a new implementation of this interface, which is almost identical to an existing implementation, except for one tiny difference. Example, you want an CustomArrayList implementation that doesn't allow the number 666 to be populated into the list. With inheritance, you can accomplish this in just a few lines of code. Extend the existing implementation, and override just the methods that need to be overridden. Whereas with composition, you now need to manually implement all 20+ methods in the interface, just to make the pass-through call. This adds a tremendous amount of boilerplate to the code. Depending on how many methods are in the interface and how invasive the changes are, this boilerplate is sometimes worth it and sometimes not worth it. Ideally, languages will add built-in support to facilitate this pattern without the associated verbosity. But until then, people will continue to use inheritance just because of how much less verbose it is.
- ntzm 8y agoDuplication is better than the wrong abstraction
- Vanderson 8y agoCan you clarify this idea some? I have used inheritance in a way to make accessing code more seamless and easier for development. But without inheritance, I end up with a lot of boilerplate code, imports, etc... Doesn't duplication go against the DRY principle? I know you are saying "wrong inheritance", but some people are saying all inheritance is wrong...
- michaelcampbell 8y agoInheritance is not necessarily the wrong abstraction, too.
- gerbilly 8y agoMaybe, but who says inheritance is the wrong abstraction?
- umvi 8y agoSeems like in some languages, inheritance is not optional if you want to use polymorphism. AFAIK in C++ you must use inheritance if you want polymorphism since there is no real concept of interfaces.
- batty_alex 8y agoYou can use templates to perform static polymorphism and duck-type the calls. If you want to do things the Java or C# way, then you're correct. You'd want a pure virtual interface, which mimics what you'd get with Java or C#.
- voodootrucker 8y agoSandi Metz does a far better job explaining the proper use of OOP in this video: [0] I highly encourage anyone with doubts about OOP to actually complete that Kata. In short, inheritance should be confined to removing conditionals in problems with shallow-wide [1] inheritance graphs, where things truly "is-a" thing, not "have-a" thing [2] Real life examples I've encountered: * buttons in a toolbar implementing a command interface * database drivers extending a base implementation * web-server endpoints extending a base implementation Some of the most complex software in the world is currently modeled using OOP. If one is ever in doubt, look into creating plugins for IntelliJ. The whole program is a massive exercise in OOP modelling, and it works pretty well (if not a little slow some times) [3] [0] https://www.youtube.com/watch?v=8bZh5LMaSmE https://www.youtube.com/watch?v=8bZh5LMaSmE [1] http://cek.io/blog/2014/05/26/poodr-ch-7/ http://cek.io/blog/2014/05/26/poodr-ch-7/ [2] https://stackoverflow.com/questions/2218937/has-a-is-a-terminology-in-object-oriented-language https://stackoverflow.com/questions/2218937/has-a-is-a-termi... [3] https://www.jetbrains.org/intellij/sdk/docs/basics/getting_started.html https://www.jetbrains.org/intellij/sdk/docs/basics/getting_s...
- marcosdumay 8y ago> and then asked us which one was optional Python manages quite well without encapsulation.
- toddh 8y agoIdentity is the most important characteristic of OO. Objects have identity.