In Java: I have a class Students. I would like to read a list of students from a file. Which one is more elegant:
Reading and constructing the list in main(), and creating a Student object with the new list passed to the constructor
Passing a FileReader to the constructor, who does the reading?
Something else?
-
you should concrete more your question. You can get thousands of answersiberbeu– iberbeu03/15/2013 15:10:30Commented Mar 15, 2013 at 15:10
-
1Try to read file in other method. This method can b private and be invoke by other public method.user1929959– user192995903/15/2013 15:12:36Commented Mar 15, 2013 at 15:12
-
@iberbeu Why do you need more information? What I need is just that.user1377000– user137700003/15/2013 15:15:13Commented Mar 15, 2013 at 15:15
5 Answers 5
Create a dumb object of student.
Create a method to read each line of the file creating a new student object so you end up with a list of students.
Separate the logic of building up the list from determining which bit of the text file holds which attribute of the student object.
Just remember to follow rules like separation of concern and the principles of SOLID.
-
Up-vote just for the SOLID reference! :)StormBringerX– StormBringerX03/15/2013 15:16:32Commented Mar 15, 2013 at 15:16
Sounds like the factory pattern is required, something along the lines of a StudentFactory
which generates the students object.
You should have that as an interface and a FileStudentFactory
implementation which does the reading of the file and then if you wanted a different provider later you change out the implementation.
Use a separate method, which does the reading and the initialization of the Student
object. The benefit of this is, that you can reuse this wherever you need it, not only in main
or while constructing a new Student
.
You could also implement the Serializable
interface.
Which one is more elegant
Elegance (in programming) is a matter of personal taste. You need to make up your own mind.
Other things to consider are:
- whether a particular approach provides the required functionality,
- whether the API is easy to understand, and
- whether the API supports use-cases other than the current one; i.e. whether it is reusable.
If you create class student you probably need to create a method which returns name of students like this
public String getName(){
return this.name;
}
and in main class you create Student Object in an array
or ArrayList
like this:
Student [] students = new Student [size];
and then you have setName(String name)
and getName()
Then :
Create DefaultListModel
add names to the model then add model to the list like This
DefaultListModel model = new DefaultListModel ();
for(int i = 0; i< students.length; i++){
model.addElement(students[i].getName());
}
list.setModel(model);
I didn't test it hope you get the idea.