Hacker News new | ask | show | jobs
by AnimalMuppet 3152 days ago
> Here's a thought exercise: Design an API for manipulating graphs, nodes and edges. The concrete representation of these three types must be hidden from the user by language-enforced mechanisms. Using `friend` is not allowed. Using the pimpl pattern is not allowed. Bypassing type safety is not allowed.

Perhaps I am not understanding your example, but...

I'd have a Node class, an Edge class, and a Graph class. None would be friends of any of the others. Many of the API functions would take a Graph (plus other parameters), but you might like them to be able to operate on an Edge or even a Node as well. But the way I think you handle this is by having a conversion operator (which is also a constructor). That is, if I have a Graph constructor that takes an Edge parameter, and one that takes a Node parameter, now I can use an Edge or a Node as a parameter to a function that takes a Graph.

Note that this does not require Graph to know about the internal details of Edge or Node. Also, it does not bypass type safety. It does sometimes return a different type than you passed in, but I'd argue that you want that: If you call addEdgeToGraph you expect to get a Graph back, and you will, even if you passed in a Node in place of the Graph.