logoalt Hacker News

wduquettetoday at 4:55 PM1 replyview on HN

Using `switch` is not a better approach if the design allows for outsiders to add their own shapes at a later time. Using `switch` probably is a better approach if the range is shapes is fixed and new shapes can't be added, especially if the language's `switch` statement requires that all valid cases be included.


Replies

jacklingtoday at 5:09 PM

Sure, but I don't see what this has to do with what I said? I was arguing against the parents assertion that the author's example was a strawman.

For your point, what part of the design shows claims that shapes are to be added/removed by outsiders? You should design for what you know and can reasonably predict. Nothing in the article seems to claim that this problem is situated on outsiders adding their own shapes?

Let's ground the example. Suppose I was writing some 2D collision checking library where these operations we're useful. Now I did Triangles, Rectangles and Circles. If I predict that arbitrary shapes should be added, how should I go about it?

The vtable way could work, but as the author showed, you're likely going to get hit with a fairly significant performance impact. Now if you can reason about your use case and see that its not in a hot loop, then the vtable way should be good to go. But if it was called a lot, then you want that to be performant and find a different method.

Some thinking can lead you to the fact that you don't need a new class at all, you just need a general Polygon object, and use the switch method. Or going by the article, you can precompute the information you need that is constant, area, # of points and add those to a dynamically allocated array (or large enough statically allocated one), and have the best of both worlds.

My point is, you can't really say which one is better until you actually know what your use case and the constraints on your system/users. We need to know how the code is used. People complain about this being a simple example, but its an example that was in the "Clean Code" book. What's important is to realize that the Clean Code version might not be worse in terms of hard to measure things, like maintainability or eligibility, but it is empirically worse for performance, and that trade off matters for many use cases.

show 1 reply