Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

11
  • While I agree that this is a solution from a library designer perspective, I wanted to know of solutions that didn't care as much about the library design. After all, isn't the entire point of OOP and code reuse that I can write code that other people can use easily? It seems bizarre that a library designer has to anticipate every possible way their users might extend their objects. I was just certain there had to be a better way Commented Sep 15, 2021 at 19:37
  • 3
    @Asad-ullahKhan But generics is exactly the solution to allowing other people to re-use your code without having to predict every possible way the consumer might use it! Your question is premised on a poorly built library that is hostile to its consumers. As Doc Brown pointed out, there is little you can do in that situation. This answer is exactly how you avoid that situation in the first place (in the library design) by favoring composition over inheritance. Commented Sep 15, 2021 at 20:39
  • @Asad-ullahKhan The nominal intent behind OOP is to add language features and design patterns that make code reuse easier and more reliable. That doesn’t mean code using those features is inherently easier to reuse; that’s just the intent of the feature. In the general case, trying to have perfectly reusable code is basically equivalent to the halting problem: you can’t predict what a user may want. In this example, the developer didn’t consider that a user may want to associate data with each node. (Inheritance may work, but it may also be brittle.) Commented Sep 15, 2021 at 20:52
  • In this case, you can just use Node<Color>. You only need another class if you need to aggregate more metadata. Commented Sep 15, 2021 at 21:50
  • 1
    @Asad-ullahKhan Anticipating use cases and writing extensible and reusable code is exactly what males writing good libraries so damn hard. Node should be an interface, or it should be generic and have a getData<T> method, or maybe even both! Done that way, it is rather flexible. Commented Sep 15, 2021 at 21:51