TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Class Hierarchies? Don't Do That

333 点作者 johanbrook大约 11 年前

46 条评论

timr大约 11 年前
<i>&quot;the real world doesn’t work that way. It really doesn’t work that way. In zoology, for example, we have penguins, birds that swim. And the bat, a mammal that flies. And monotremes like the platypus, an animal that lays eggs but nurses its young with milk.&quot;</i><p>Former biologist here. Actually...most living things <i>do</i> work that way. A human ISA primate. Genetically. Functionally.<p>If you merely focus on <i>outward behavior</i>, you get to the same place that early biologists got to with what was called &quot;morphological classification&quot; -- you find the weird examples of convergent evolution (e.g. <i>&quot;OMG egg-laying mammal!&quot;</i>), and you&#x27;re tempted to throw out the whole classification system, even though it <i>mostly</i> works, and the errors are merely distracting from the inherent truth of the idea (that we&#x27;re all related by genetic phylogeny; we <i>literally share implementation</i>).<p>Anyway, programmers, learn from biology: when you see these kinds of errors it probably means that you&#x27;re classifying things incorrectly, not that you should stop classifying altogether.
评论 #7497850 未加载
评论 #7498925 未加载
评论 #7500303 未加载
评论 #7498459 未加载
评论 #7499671 未加载
评论 #7499779 未加载
评论 #7500731 未加载
评论 #7498495 未加载
评论 #7501442 未加载
评论 #7499002 未加载
评论 #7498109 未加载
评论 #7498635 未加载
评论 #7498184 未加载
评论 #7502248 未加载
评论 #7498467 未加载
评论 #7505348 未加载
评论 #7497860 未加载
jdlshore大约 11 年前
Okay, having read the article, I think it goes too far.<p>Inheritance hierarchies have their issues, and raganwald touches on them, but there&#x27;s a strawman argument here.<p>(Incidentally, raganwald, I&#x27;ve noticed this about all your OO articles. You seem to have a bias against class-based design. It&#x27;s causing your essays to be less brilliant than they could be.)<p>Fundamentally, you can think of inheritance as a special case of composition. It&#x27;s <i>composition</i> combined with <i>automatic delegation</i>.<p>In other words, if you have A with method foo() and B with method bar(), &quot;A extends B&quot; is equivalent [1] to &quot;A encapsulates an instance of B and exposes &#x27;function bar() { return this._b.bar(); }&#x27;.&quot;<p>This is <i>very useful</i> when you want polymorphism. Writing those delegators is a pain in the butt.<p>More importantly, it tells us how to use inheritance safely. Only use inheritance when 1) you want to automatically expose all superclass methods, and 2) don&#x27;t access superclass variables.<p>Now, JavaScript does have the specific problem that you can accidentally overwrite your superclass&#x27;s variables, and that&#x27;s worth talking about. But I think that saying &quot;inheritance is bad&quot; goes too far. The article would be stronger if talked about <i>when inheritance is genuinely useful</i>, <i>the problems it causes</i>, and <i>how to avoid them</i>.<p><i>Edit:</i> In particular, I want to see more about polymorphism. Polymorphism is OOP&#x27;s secret superpower. <i>Edit 2:</i> I&#x27;m not saying polymorphism requires inheritance.<p>[1] Not quite equivalent.
评论 #7497571 未加载
评论 #7497606 未加载
评论 #7497400 未加载
评论 #7497273 未加载
评论 #7498476 未加载
评论 #7497627 未加载
评论 #7497377 未加载
评论 #7497281 未加载
hibikir大约 11 年前
Inheritance is easily overused, but that doesn&#x27;t mean that we should just avoid it altogether.<p>The problem IMO is that we are stuck in a view that inheritance is really about ontology, when what we really mean, and want, is code reuse. It&#x27;s very hard to make a 5 level deep ontology not break down. This is why we have this whole &#x27;prefer composition over inheritance&#x27; business.<p>But while we are stuck with that kind of mindset in Java (at least pre java 8), we miss the capability of using inheritance as a way of adding mixins. There is much power in using mixins as a way to clarify composition, while we still keep the inheritance tree very shallow.<p>That&#x27;s one thing we get with judicious use of the Scala cake pattern, which you could easily reproduce in javascript: Composition without really having to write a bunch of useless boilerplate. There&#x27;s a nice talk out there about it. Cake Pattern: The Bakery from the Black Lagoon.<p>The trick, as with most other programming techniques, is to use it carefully.
评论 #7497231 未加载
评论 #7497389 未加载
评论 #7498053 未加载
kenjackson大约 11 年前
Good article, but I think the real message isn&#x27;t to not use inheritance, but to use with great care.<p>Inheritance gives you a great characteristic -- isa relationships. And this is something you don&#x27;t get with composition.<p>That said, the fragility with poorly constructed base classes is real. But a succinct base class can be very valuable and useful, and not that brittle. Just don&#x27;t stuff cruft in it that is of questionable value. Ask yourself what&#x27;s the least you can put in the base class and still provide value.<p>And this is where interfaces are also useful. You can get the isa relationship w&#x2F;o much of the brittleness as there is no internal state associated with the interface. But you are still creating a hierarchy (just not of classes, but of interfaces).<p>It&#x27;s a useful article, especially for those new to the idea. But the takeaway should be to use care. Not to avoid at all costs.
评论 #7497192 未加载
评论 #7497275 未加载
评论 #7497215 未加载
评论 #7497257 未加载
评论 #7497694 未加载
hifier大约 11 年前
There are some contradictions here. For example the author the following statement about encapsulation violations being permitted, but not followed as best practice:<p>&quot;JavaScript does not enforce private state, but it’s easy to write well-encapsulated programs: simply avoid having one object directly manipulate another object’s properties. Forty years after Smalltalk was invented, this is a well-understood principle.&quot;<p>However, the author doesn&#x27;t seem to really understand this as he makes the case that access to private state and behavior of a &quot;superclass&quot; violates encapsulation:<p>&quot;In JavaScript (and other languages in the same family), classes and subclasses share access to the object’s private properties. It is not possible to change an implementation detail for Account without carefully checking every single subclass and the code depending on those subclasses to see if our internal, “private” change will break them.&quot;<p>Well, yes they do allow access, but that doesn&#x27;t mean you have to use it! This is considered bad practice when extending any class in other languages that I&#x27;m familiar with (C++, Ruby). Please take some of your own advice.<p>I do agree that hierarchies do not fit the real world as well the contrived examples from my first OOP classes and they should be used with extreme caution. Let&#x27;s not throw out the baby with the bath water, however.
kwamenum86大约 11 年前
I used to find these types of articles useful. But now I see them more as dogma. Great engineers don&#x27;t struggle with things like JavaScript inheritance because they understand best practices and trade offs. So in general, I find it more useful to read about best practices and trade offs than &quot;xyz considered harmful&quot; articles that don&#x27;t present viable alternatives to xyz.<p>That said whenever I see something on raganwald.com I&#x27;ll still read it :)
评论 #7498690 未加载
cwp大约 11 年前
The substance of the article is spot on, but I have to take issue with the terminology it uses. The problem he&#x27;s talking about isn&#x27;t classes, it&#x27;s inheritance.<p>This is an important distinction. Javascript doesn&#x27;t have classes, but it <i>does have inheritance</i>. The problems raganwald points out with the Account example come not from the organization of the code into pseudo-classes, but from the fact that it uses Javascript&#x27;s inheritance mechanism.<p>It would be perfectly possible to write a version of the example that exhibited the &quot;fragile prototype problem,&quot; and conversely, one can easily write a version in Smalltalk that uses composition instead of inheritance and thus has no fragile base classes.
mercurial大约 11 年前
It&#x27;s just as true in other languages. More often than not, programmers thinking about code reuse attempt to solve it via inheritance, which is almost always the wrong answer. With some persistence, you can end up with a nice four or five level deep inheritance tree with 10 methods randomly overriden at various levels in the tree. Good luck figuring out how the damn thing actually works if you didn&#x27;t write it.
评论 #7497113 未加载
nabla9大约 11 年前
We want to use classes because we want to want to be able to invoke an operation and have the exact behavior determined by the type of the object or objects on which the operation was invoked.<p>Common Lisp philosophy of classes and OO fits the thicketness of the real world better. Generic functions, multimethods, mixings etc. Just embracing the notion that classes and encapsulation might be orthogonal issue opens up the way to use class system better ways.
cmbaus大约 11 年前
I am bit concerned that the standard committee is going to make the language worse while trying to fix it.<p>Yes it is inconvenient to do traditional OO programming with JavaScript, but I&#x27;m not convinced that is a bad thing. Encouraging subclassing, as pointed out by the author, could actually be detrimental.
评论 #7497253 未加载
评论 #7497292 未加载
tmsh大约 11 年前
Class hierarchies are easily fragile, easily do not model things correctly over time.<p>The cruft, the lack of DRY as the mapping between what is being modeled and what is represented in the code -- accumulates with class hierarchies for sure.<p>But the idea of inheritance and tree structures <i>has</i> been around and strong for the past 50 years -- not because people are inherently lazy -- but because it models something very primitive about programming: the evolutionary nature of development and thinking.<p>This is extremely non-mathematical, but extremely non-trivial.<p>Tree structures (and by extension &#x27;hierarchies&#x27;) are perhaps the most fundamental way to organize data. There is nothing more sophisticated than a tree search -- it is the basis of all exponential &#x2F; efficient access times and all knowledge and organization of memory. It&#x27;s why evolution proceeds in tree structures. We organize data in our mind in tree structures. Life over millennia organizes itself in tree structures.<p>I&#x27;m sad to report that the world will not quickly become clear and abstract and orthogonal a la Haskell or other pure languages. Knowledge, life, everything proceeds via evolution, not something a priori. The sooner one <i>really</i> accepts that, the sooner one has new ways to interface with this reality more practically and effectively.<p>People sometimes make the point of use the right tool for the job - as a reason for still using OOP, etc. I&#x27;d not say that -- but that the right tool for the job where the <i>job</i> is an evolving code base is actually something object-oriented with inheritance. Except where the domain is very precise and known ahead of time. Otherwise, the manner in which it models evolution is actually quite useful (despite the fragility of inheritance and the quick ability to spin out of any orthogonal clarity).<p>People who program purely in Clojure or Haskell put the burden of this evolution in their own development as a programmer (there is no extension, there is just clarity and then rewrite). That&#x27;s ok. People who use Java or whatever in the enterprise because it&#x27;s easier for other people to get on board with it -- put the burden in the code. But the cost of modeling a problem that evolves goes somewhere.
评论 #7499985 未加载
_getify大约 11 年前
Huge fan of this article. Makes some really great points! Wish I could share and vote it up a thousand times. :)<p>I have been writing about exactly this topic, of why classes don&#x27;t make sense (specifically for JS), in my second title of the &quot;You Don&#x27;t Know JS&quot; book series, &quot;this &amp; Object Prototypes&quot;.<p>In particular, Chapter 6 makes the case for an alternate pattern to class-orientation design, which I call OLOO (objects-linked-to-other-objects) style code. OLOO implements the &quot;behavior delegation&quot; design pattern, and embraces simply peer objects linked together, instead of the awkwardness of parent-child abstract class semantics.<p><a href="https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch6.md" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;getify&#x2F;You-Dont-Know-JS&#x2F;blob&#x2F;master&#x2F;this%...</a>
评论 #7497135 未加载
评论 #7497343 未加载
V-2大约 11 年前
&quot;Only, the real world doesn’t work that way. It really doesn’t work that way. In morphology, for example, we have penguins, birds that swim. And the bat, a mammal that flies.&quot;<p>Yes but we have Single Responsibility Principle and while an animal is one object in physical world, it doesn&#x27;t mean it should be a single object in OOP. Start breaking it down...<p>public interface BodyType {}<p>public class TwoArmsTwoLegs implements BodyType {}<p>public class FourLegs implements BodyType {}<p>public interface Locomotion&lt;B extends BodyType&gt; { void walk(B body); }<p>public class BipedWalk implements Locomotion&lt;TwoArmsTwoLegs&gt; { public void walk(TwoArmsTwoLegs body) {} }<p>public class Slither implements Locomotion&lt;NoLimbs&gt; { public void walk(NoLimbs body) {} }<p>public class Animal { BodyType body; Locomotion locomotion; }<p>Animal human = new Animal(new TwoArmsTwoLegs(), new BipedWalk());<p>(Code sample from an article in Software Development Journal by Łukasz Baran)
aturek大约 11 年前
tl;dr: Superclasses make your code brittle. <a href="https://en.wikipedia.org/wiki/Fragile_base_class" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Fragile_base_class</a><p>How many people still try to fit their software design into the class hierarchy model? I&#x27;ve been on the composition-not-inheritance side for so long I can&#x27;t do &quot;traditional OO&quot; justice, but I&#x27;d love to hear the counter-arguments in case I&#x27;m wrong.
评论 #7497150 未加载
评论 #7497160 未加载
评论 #7497933 未加载
dclowd9901大约 11 年前
Ever since I&#x27;ve started writing Objective-C, a lot of Javascript&#x27;s glaring issues have started to melt away. Yes, JS doesn&#x27;t have an understanding of protocol, but that&#x27;s just a matter of implementing convention and being disciplined. JS is remarkable in that it is so malleable that one can use myriad patterns with it.<p>I&#x27;ve found that the delegate pattern, for instance, can be incredibly powerful when used in conjunction with JS, especially when it comes to extending classes functionality that may not be inherent to its topology (think class Ant, to describe an Ant, and class FlyingAnimal -- wings, etc. --, to describe a queen ant).
benrhughes大约 11 年前
Although I&#x27;m very, very sympathetic to the idea that class hierarchies often cause more pain than they&#x27;re worth, using JS to make that point is a bad idea.<p>In most actual OO languages, there <i>is</i> a clearly defined interface between a base class and it&#x27;s inheritors: eg in c# you have protected (to expose state), abstract to force implementation and virtual to optionally allow implementation. In no way are you forced to expose all internal state (even though people often do).<p>I think there&#x27;s a case to be made against class hierarchies, and also against using OO in javascript. But I&#x27;m not sure Ragan made either of them well here.
einhverfr大约 11 年前
What is missing from the discussion here is that where domain knowledge is less important. For example, almost every widget system I have ever looked at uses class inheritance because it makes it relatively easy to manage consistent interfaces across classes. This is true of GTK, wxwidgets, and many more.<p>It is true that the natural world doesn&#x27;t necessarily admit of perfect neat classifications generally, much less trees. However, when we are talking about purely engineered solutions, the same arguments don&#x27;t apply in the same way.<p>Here&#x27;s an example. In LedgerSMB 1.4, we use (shallow) class inheritance in a reporting framework. It works, and works well. Reports inherit an abstract class with lots of hooks for customization but a lot of defaults.<p>In future versions we will likely be moving away from an inheritance-based approach, not because of the arguments here or the maintenance issues (which will crop up any time you rely on external components) but because we think we can create clearer code by moving from a class&#x2F;inheritance approach to a DSL approach.<p>I am not sure that class contracts and DSL syntax contracts are necessarily any different from a maintenance perspective other than the fact that the latter strikes me as resulting in clearer code.
al2o3cr大约 11 年前
Anybody have an original source for &quot;prefer composition over inheritance&quot;? I&#x27;ve heard it for years, but never with an attribution.<p>FWIW, I noticed that in my old C++ book (Stroustrup &#x27;91) there&#x27;s some <i>really</i> bogus inheritance examples - window -&gt; window_w_banner -&gt; window_w_menu -&gt; window_w_banner_and_menu etc etc etc.
评论 #7497352 未加载
评论 #7497431 未加载
monokrome大约 11 年前
&quot;Hey, guys. Here&#x27;s a really poorly considered hierarchy of classes, where I haven&#x27;t really made any real effort to separate concerns or otherwise prepare for the problems which I am specifically creating.<p>Now, look at all these bad things that I&#x27;ve done! NEVER DO ANYTHING SIMILAR EVER.&quot;<p>That pretty much sums it up.
V-2大约 11 年前
Yet another post titled &quot;don&#x27;t do X&quot;, which actually reads as &quot;do not exaggerate with X&quot; or &quot;did you know? X has some caveats&quot;.<p>Of course inheritance is not a solution for everything. Avoid using deep inheritance hierarchies, you&#x27;ll paint yourself into a corner. It&#x27;s advisable to prefer composition over inheritance. You should not be that guy who only has a hammer and everything looks like a nail to him. But it doesn&#x27;t translate into: &quot;hammer? don&#x27;t do that!&quot;<p>All the examples he&#x27;s giving either demonstrate abusing the inheritance concept or just show that it has certain limitations. There are well known solutions and guidelines for dealing with problems such as fragile base class, other than throwing the whole paradigm out of the window
DrJokepu大约 11 年前
It&#x27;s difficult to argue with this article. I can count on one hand the number of times non-trivial class hierarchies (that is, more more than 2-3 classes) made my life easer and every time that was the case I writing a compiler or a code generator or something similar.
评论 #7497164 未加载
porker大约 11 年前
&gt; It turns out that our knowledge of the behaviour of non-trivial domains (like zoology or banking) does not classify into a nice tree, it forms a directed acyclic graph. Or if we are to stay in the metaphor, it’s a thicket.<p>That completely chimes with my experience. I wondered if I was doing OOP wrong, as any time the size&#x2F;complexity of a project (or module) gets above a certain level, a Thicket results in my code.<p>&gt; Classes are the wrong semantic model, and the wisdom of fifty years of experience with them is that there are better ways to compose programs.<p>Where&#x27;s your source&#x2F;links? What? This needs expanding - if there are better ways, outline your evidence and show us where we&#x27;re going wrong :)
评论 #7499064 未加载
评论 #7498403 未加载
skybrian大约 11 年前
This is generally true. On the other hand, interfaces are a <i>good</i> thing, especially in a language like Go where you can explicitly declare them and then pass in anything that happens to match that interface. (In JavaScript, this is unfortunately implicit, so it requires better documentation and sometimes runtime checks to ensure sanity.)<p>If you implement an interface using delegation, you get something quite like subclassing, except that the subclass-superclass interface is explicit and the superclass&#x27;s type is entirely hidden. Sadly, few languages make this easy so it often requires some boilerplate or meta-programming.
评论 #7497280 未加载
malandrew大约 11 年前
I like these articles, but I think there are more than enough of them out there and not enough of those that show you how to use composition.<p>Everyone who has spent enough time with OO and classical inheritance knows the problems, but most have never seen how to convert a mess of classes and inheritance into a more functional approach with composition.<p>Don&#x27;t get me wrong, there was good content here, but I was hoping that after the conclusion, the post was going to go into how to use composition as an alternative.
foobarz24大约 11 年前
This reminds me of a design question I recently faced when building a simple multi-player game. The idea was pretty standard; The server sent events (player dies, player moves to pos, etc.) to its clients over a TCP socket. When programming the client in Java (for Android) I wanted a clean way to update the world based on the event type. In Haskell I would have done something like<p>data Event = PlayerDied Player Reason | PlayerMove Player Coords | ...<p>and use pattern matching on the event type. In C I would have used a combination of unions and structs with an event type. But how to do that in Java? I ended up with<p>interface Event { public update(Game g); }<p>and used e.g.<p>class DeathEvent implements Event {<p><pre><code> DeathEvent(String player, String reason) { ... } update(Game g) { g.killPlayer(player, reason); }</code></pre> }<p>Combined with a parsing function (public Event parse(String line) {...}) I could read from the socket and update the game in a convenient way, but to be fair I used that mostly because Java guys discourage you to use instanceof although it seemed clearer.<p>So is this the preferred way to do something like this? I think &quot;they&quot; (the OOP warriors) call this the Visitor pattern. However I really find the data-type encapsulation in Haskell and other languages (in Python a tuple (type, object) would do) superior. But maybe my Java just got rusty.
gboudrias大约 11 年前
In javascript*<p>I think this highlights a problem with javascript more than OOP: We&#x27;re trying to fit it into uses cases that are simply too complex for its design. It wasn&#x27;t made to build your goddamn bank accounting system, it was made so that &quot;nonprofessional programmers&quot; could animate things on websites.<p>But it also highlights a problem it doesn&#x27;t take about: Language in computer science and how it affects how we think about things.<p>In this instance, public and private are terrible names. They had to tell us in programming classes that they&#x27;re not related to security, which means that the privacy metaphor is a terrible idea because it&#x27;s not instinctual.<p>This in turn causes us to shoehorn class design into things they perhaps shouldn&#x27;t be. At this point, for complex programs we should be describing things in a much more complex way than &quot;accessible from the outside or not&quot;. As the article points out, it doesn&#x27;t <i>matter</i> that the classes are external, because you can just as well break things from the inside.<p>This is a complex problem, but I think the beginning of a solution is to a) Depend on meta-information (or better implement a flexible, non-arbitrary &quot;access&quot; structure) and b) Use the right tool for the right job, in this case not JS.
protez大约 11 年前
Class hierarchies are just mental tools, not how machines&#x2F;programs&#x2F;automatas actually work. If the mental tools implode due to exceptions and complexities, that&#x27;s the problem of their uses, not tools by themselves. Before blaming hierarchies, you should blame yourself for using tools in wrong ways.
mcv大约 11 年前
Isn&#x27;t he mostly complaining about lack of encapsulation? So what if you do encapsulate your data? That&#x27;s totally possible in most programming languages, and it&#x27;s even possible in javascript if you drop prototype inheritance. You can use closures to encapsulate your data.
platz大约 11 年前
This is interesting, reading some of the linked documents, my naive generalization is that it pushes the entities into using things like maps and dictionaries instead of static properties. The &quot;system manager&quot; stuff just pulls things out of the maps and feeds them to functions to do work, so it is very much &#x27;data-driven&#x27; and I must assume more work is put into &quot;configuration&quot; of the entities, just like a data-driven business process requires &quot;configuration&quot; of the order processing pipeline. <a href="http://www.richardlord.net/blog/what-is-an-entity-framework" rel="nofollow">http:&#x2F;&#x2F;www.richardlord.net&#x2F;blog&#x2F;what-is-an-entity-framework</a>
评论 #7498024 未加载
dangoor大约 11 年前
Something I haven&#x27;t seen mentioned in this discussion so far is the Data, Context, Interaction (DCI) pattern.<p><a href="https://en.wikipedia.org/wiki/Data,_Context,_and_Interaction" rel="nofollow">https:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Data,_Context,_and_Interaction</a><p>As mentioned at points in this thread, some objects need different behavior based on their context. DCI is a thought provoking way to represent that (though one that not in common use and that is often described as &quot;being done wrong&quot; on the object composition mailing list[1]).<p>[1]: <a href="https://groups.google.com/forum/#!forum/object-composition" rel="nofollow">https:&#x2F;&#x2F;groups.google.com&#x2F;forum&#x2F;#!forum&#x2F;object-composition</a>
epx大约 11 年前
Cocoa is good because, among other things, is treads lightly on class hiearchies.
sktrdie大约 11 年前
Personally I believe that software design is a highly subjective art. People that are meant to maintain a piece of code are different. Some may be more creative and less pragmatic, others may be more structured and clean in their design.<p>The truth is that there&#x27;s no silver bullet. You can build software based on hierarchy of classes because your mind works better with that structure, but others may find it completely inappropriate. We&#x27;re human and our mind works differently from one another.<p>In that sense I truly believe software is much closer to art than engineering.
tristan_juricek大约 11 年前
This approach to discussing inheritance treats JavaScript as if you&#x27;re a Java or C++ programmer, and completely lacks any clarity with how inheritance in JavaScript really works.<p>Best intro I&#x27;ve read on the topic I&#x27;m talking about is from Alex Sexton (just read the last example, it really hits the nail on the head):<p><a href="https://alexsexton.com/blog/2013/04/understanding-javascript-inheritance/" rel="nofollow">https:&#x2F;&#x2F;alexsexton.com&#x2F;blog&#x2F;2013&#x2F;04&#x2F;understanding-javascript...</a><p>So you <i>might</i> want a wee bit of hierarchy, if you&#x27;re thinking like those &quot;shared options&quot; scenario, but not in the &quot;OO type abstraction tree&quot;.<p>So, you might have something like a &quot;Account.prototype.primeInterestRate&quot; property that you can change in a running program, and then all the other types of account can calculate interest based on that shared property.<p>However, the more experienced jS developers I&#x27;ve met might take those &quot;Account.prototype.balance&quot; and &quot;Account.prototype.deposit&quot; methods, and push those into a &quot;mixin&quot; type (like &quot;CurrentBalance&quot;) where those methods are <i></i>copied<i></i> (not inherited) onto the child class prototype, and those methods, might have initializer helpers to set up the &quot;currentBalance&quot; property they use. This mixin approach only gets gnarly if there&#x27;s any feature envy. (Document your object properties clearly, folks. This is where javaScript&#x27;s flexibility often becomes a crutch - lots of issues happen if mixin code uses &quot;this.foo&quot; for different things.)<p>Anyhow, what&#x27;s interesting here is that Account carries the property that&#x27;s shared, but CurrentBalance carries &quot;behaviors&quot;, and is <i>not shared</i>, and your &quot;child classes&quot; like VisaDebitAccount embed both in different ways. It is a very different way of thinking about object relationships, and often works smoothly.<p>But if you&#x27;re using classes in JavaScript like you would Java, well, then, you&#x27;re not really using JavaScript, right? And, this whole talk about biological-style ontology just becomes the wrong metaphor, because while &quot;humans are a primate&quot; we can&#x27;t change aspects of primates to add behavior to people!
iamwil大约 11 年前
That inheritance doesn&#x27;t get encapsulated was the same way I felt about modules in ruby. You could include them into a class or other modules, but the interface was never well defined, and you could cause incompatibilities by relying on the implementation of the class you include into, unless you&#x27;re disciplined enough to only use methods, and not attributes.<p>On the other hand, defining all the interfaces all the time, like in java was painstaking. I hope for some sort of middle ground.
buzzybee大约 11 年前
The most challenging aspect of inheritance modelling is to recognize it on its intrinsics - the deliberate creation of coupled properties and behaviors associated with the &quot;isa&quot; declaration - and not simply as a form of taxonomy.<p>Programmers are still inclined to use hierarchies. They are implicit to source code in a more general sense, with indentation, nested logic, etc. But we also need affordances to break up hierarchies and keep them limited.
menzoic大约 11 年前
<p><pre><code> ChequingAccount.prototype.process = function (cheque) { this.setBalance(this.getBalance() - cheque.amount()); return this; } </code></pre> ...
EGreg大约 11 年前
From a practical point of view, mixing in behavior and implementing via encapsulation is usually easier to maintain and extend than inheritance.
graycat大约 11 年前
Another battle in the 60 year language wars based on criteria that are so obscure that have battles just over the darned criteria.
twfarland大约 11 年前
My js style began with a heavy usage of classes. I then left that for prototype composition. Recently, I&#x27;ve arrived at a style influenced by Haskell&#x27;s separation of functions and data - namespaced objects of functions that act on plain json-serializable data. Flexible, simple, and perfomant. I don&#x27;t miss &#x27;this&#x27; at all.
golergka大约 11 年前
&gt; That kind of ontology is useful for writing requirements, use cases, tests, and so on. But that doesn’t mean that it’s useful for writing code the code that implements bank accounts.<p>Isn&#x27;t good, easy readable code look very similar to requirements it was written upon?
sgy大约 11 年前
It&#x27;s pretty much a promotion&#x2F;defense for SmallTalk. Why everybody has grudges against JavaScript?
ajuc大约 11 年前
Class hierarchies are OK when they have one level. It&#x27;s essentially object oriented switch statatement with bells and whistles.<p>I can&#x27;t remember one class hierarchy more than one level deep that was worth it.<p>They save a little code - true, but at the cost of coupling, making it harder to change, and forcing early debatable decisions on programmer (which classification is more important and goes first for example).
SixSigma大约 11 年前
&quot;Object Oriented design is the Roman Numerals of Computing&quot; - Rob Pike<p>For more quotes see :<p><a href="http://harmful.cat-v.org/software/OO_programming/" rel="nofollow">http:&#x2F;&#x2F;harmful.cat-v.org&#x2F;software&#x2F;OO_programming&#x2F;</a><p>Another, seeing as it&#x27;s PG :<p>&quot;The phrase &#x27;object-oriented&#x27; means a lot of things. Half are obvious, and the other half are mistakes.&quot; — Paul Graham
评论 #7498173 未加载
bayesianhorse大约 11 年前
In idiomatic Python, the only reason for class inheritance is for code reuse.<p>In other languages, especially Java, class hierarchies are a matter of self-esteem.<p>Javascript programmers could do worse than emulate Python in this regard.
ssmoot大约 11 年前
Ow
vermooten大约 11 年前
Please can yo make the type in your blog even less readable? I think knocking back the grey so that it matches the background should do it - you&#x27;re almost there just needs a tad more.
评论 #7498117 未加载