lundi 3 juillet 2023

Is it always bad practice to check if an object's type is a particular subclass in C?

I'm writing a BitTorrent client as a personal project, and the client includes a parser for the Bencode encoding format. The parser stores different types of encoded values (ints, strings, lists, dictionaries) as subclasses of a Bencode abstract class so that I can nest values cleanly (e.g. list is a vector<Bencode *>).

According to the BitTorrent specification, all the data in the ".torrent" file is in a Bencoded dictionary, meaning if the file I got is parseable, I want my Bencode * object to have a subclass dictionary, if not I would like to reject it.

I can do this easily enough with a dynamic_cast as I read in this question: How do I check if an object's type is a particular subclass in C++?

However, one of the answerers to this question suggested that if you have to check the type of a subclass, it probably means there's a design flaw. I can't figure out a clean way to do this otherwise though. Is checking the type bad in this case, and if so why and what are the alternatives?

Aucun commentaire:

Enregistrer un commentaire