Hacker News new | ask | show | jobs
by jstimpfle 3095 days ago
> Don’t all pieces have a location?

Make a table containing locations for each piece.

> Aren’t all pieces movable?

Make a function ("procedure") that moves a piece (e.g. edits the location table).

> Might we want to display pieces?

Make a render function (e.g. gets a piece type and a position)

> Do we want to journal them to files to save game state, or their moves to streams to play remotely?

Write serialization and deserialization routines (again, procedures that get piece type and position).

No need to cram that in to some idea of piece "class". That only glues things together that don't belong together. OO is pretty much crap.

1 comments

People who say this apparently have an inordinate love of switch statements.
Come on, please don't claim that you need to add more piece types independently so absolutely need virtual functions. That's hilarious for a chess game (and most other applications), but even if that was needed, one could still pass function pointers in those few places.

Anyway: No, they design their program to be efficient and readable. There is more often than not an alternative to switch statements: don't mix data of different types together. (Where by types I don't mean crazy artificial types built with a modern language -- but with regards to implementation of a functionality).

If this is about drawing chess pieces, you need only a single draw function for all of them. Just maintain a table that maps a piece to its material (sprite, mesh, whatever). Or alternatively, have a table that maps pieces to "types" and another static one that maps these types to materials. (Much better: Materialized type to simple enum. Can actually use this information, as opposed to overhyped static types).

More general answer: The best way to do it is usually not a switch statement but a data table. Because usually the switching is not about behaviour, but about data. (Not that switch statements are so bad).

Code gets so so simple, robust, and maintainable if developers are not preconcerned about static types, OO, and whatnot.

I'm not sure why that's apparent, but even if it is, is there any reason to believe that switch statements (or pattern matching, or look-up tables, or other related language constructs) couldn't handle any plausible requirement in this case?
The Expression Problem¹ often favours switch statements (sum types even more so).

https://en.wikipedia.org/wiki/Expression_problem