0

I have a class called book consists off the book name and List of chapters. I read the information about the chapters ( such as the chapters name, chapter number ... etc) from some txt file on the hard desktop.

The book object itself is meaningless without loading the chapters. For best practices, should I write a build method and I build my object like the below ?

Book newBook = new Book(bookName).build();

Where build has the logic of loading the file form hard disk and filling the chapters list, or I should just make this build method private and create an object like the below.

Book newBook = new Book(bookName);

and inside the constructor of the book I should call the private method called build ?

John Donvan
  • 554
  • 8
  • 22
  • Are you planning on reading the file asynchronously? – ssoBAekiL May 31 '20 at 01:20
  • Does this answer your question? [Is doing a lot in constructors bad?](https://stackoverflow.com/questions/7048515/is-doing-a-lot-in-constructors-bad) – Ivo Mori May 31 '20 at 01:50
  • This is a very open question, and will result in opinionated answers from my point of view. Try to ask a more specific question. Have a look at [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). – Ivo Mori May 31 '20 at 01:53
  • Book's chapters is very import,but we may not use it immediately when a Book created,so I think lazy init of charters is good. – TongChen May 31 '20 at 02:30

2 Answers2

1

Move reading the file part into a separate class. Inject an object of that class into the Book. This will allow you to separate your domain from the technical details of the I/O handling. In future if you decide to move the data to a DB you will only have to swap the dependency. Also, this will allow to mock out the I/O object for unit testing.

RCT
  • 1,044
  • 1
  • 5
  • 12
1

Since the book object is incomplete or stale without the details of chapter and chapter numbers. The process of object creation cannot be considered as complete without filling the chapter details.

But doing a heavy operation of reading file and creating chapter in the book object is not needed. Instead, create the chapter objects before creating the book objects. And dependency injection can be used while creating the book object.

James
  • 161
  • 1
  • 6