Reputation: 3005
I'm reading some text files to create objects from. Which class should process the text files according to OOP principles?
I have my GUI object with a method to draw a table and fill it with data. This data is either parsed from an HTML page, or read from a cached text file. I can think of two ways to handle this, and I'd like to know which one is better.
Option 1:
public void drawSchedule()
{
try
{
if (CacheManager.hasData("schedule")) //this is not the complete logic, but enough for this post
{
String cacheString = CacheManager.readData(this, "schedule");
Schedule schedule = new Schedule(cacheString);
}
else
{
//read data from HTML page
}
catch (IOException e)
{
//generic error handling
e.printStackTrace();
}
}
Option 2:
public void drawSchedule()
{
try
{
if (CacheManager.hasData("schedule")) //this is not the complete logic, but enough for this post
{
String cacheString = CacheManager.readData(this, "schedule");
//parse data here so we end up with a bunch of variables
//courseList would be an ArrayList of Courses, if it makes any difference
Schedule schedule = new Schedule(firstDay, courseList);
}
else
{
//Read data from HTML page
}
catch (IOException e)
{
//generic error handling
e.printStackTrace();
}
}
Upvotes: 0
Views: 56
Reputation: 30320
I vote for Option 1.
Schedule
should know how to create itself from a String
or an HTML page. None of that logic should be in drawSchedule
, whose job should simply be, as one might guess, to draw a Schedule
. You want to separate the concerns of building a Schedule
from drawing it.
Since this won't be too hard to do, you might as well do it. But be careful trying to be too elegant too soon. As Bob Martin advises in Agile Software Development, Principles, Patterns, and Practices with "taking the first bullet" and Nathan Marz advises with "suffering-oriented programming," don't be so quick to be as "pretty" as possible. Make everything work first; then refactor to a more elegant approach only when the pain of not doing so makes it worth it.
Upvotes: 1
Reputation: 41208
Honestly, both approaches are valid and it is going to depend a lot on the nature of the data and how the objects are used. In fact it's almost tempting to flag the question as primarily-opinion-based!
If the parsing is incredibly specific to these text files, and if the Schedule
is being used in a number of other places then the parsing code is probably better off being separate.
On the other hand if that parsing could be useful in several places then it would make sense to put it within the Schedule
. Think both of Don't-Repeat-Yourself and encapsulation. You want the code to be visible everywhere it is useful but not anywhere else, and you only want to have the code once.
Examples from the Java library include things like the Date
class, which has a few generic constructors but then there is the DateFormat
class which is able to do all the work to process a Date
to and from a String
.
Upvotes: 2