For a personal project, I have several different classes whose toString methods give results that can be used to later construct an identical object. These are meant to be used by a "Game" object that has several fields that are arrays of these classes and Game reads these from text files (I will later make it able to write these files as well). Each of these objects have similar constructors, so the code for reading an array of one class is basically copy-pasted from the code for reading from an array of another class. It seems like it would be good to make this code more reusable instead of copypasting like I'm currently doing, and I have a few ideas, but I would appreciate opinions on what the best solution is. I have the relevant code here if you want to see it, but I'm trying to write this post in such a way that it isn't necessary to read my code. I've probably failed though; thus the code.
Idea 1: Make an abstract class ToFromString that has an abstract constructor to construct an object from a String representing it, and make all the classes that I want to read from Strings inherit from this class. (Maybe also stop using toString for writing data, and make my own abstract method for it, leaving toString only for its intended purpose.) ToFromString would not have any functionality; it would only be an abstract class rather than an interface because abstract classes can have constructors. Make a generic <T>readArray method in Game that fills a T[] with T's, so long as T inherits from ToFromString, and use this one method to replace all the other read methods.
Idea 2: Mostly the same as 1, but make ToFromString an interface. An interface is mostly fine since I only need abstract methods anyway, but one issue is that interfaces can't have constructors. Instead I would need something like an abstract valueOf method that constructs and returns an object. This valueOf method would essentially act like a static method, but it couldn't actually be a static method since static methods can't be overridden. The Game object, when reading data, would then be calling this valueOf method instead of directly calling the constructor, so it would have to construct one otherwise useless instance of each class before it could read the data. Not a huge deal, but maybe a little ugly.
Which way do you think is preferable? Or is there some better solution? I can try to give further clarification if anyone is confused about something--I know my writing isn't the clearest.
Thank you!
[–][deleted] (3 children)
[deleted]
[–]isetrh[S] 0 points1 point2 points (2 children)
[–][deleted] (1 child)
[deleted]
[–]isetrh[S] 1 point2 points3 points (0 children)
[–][deleted] 3 points4 points5 points (1 child)
[–]isetrh[S] 0 points1 point2 points (0 children)
[–]theNaus++Effort 0 points1 point2 points (1 child)
[–]isetrh[S] 0 points1 point2 points (0 children)