Andre Paris wrote:So what would you do differently? Or are you just making a joke?
Jokingly serious. You should give more sensible defaults or throw an IllegalArgumentException for the attributes that are mandatory if they are not provided. For string fields, "**UNKNOWN**" might be a more sensible default that you'd assign when the value provided is null or empty. I wouldn't use a condition like length < 3 though since that would preclude any legitimate titles like "It" and other similarly short titled books.
The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
Exercises like this one aren't usually constrained by real-life data, they're just intended to give the learner something to practice with. In real life, for example, books can be written by a person with only one name (not first and last name). There were books written before 1998, and an ISBN has 13 digits. But if you have an assignment which says to use a particular validation, you should use that validation even if it's contrary to how things actually work in real life. That even holds true if you're working and writing an application for a company or other organization -- design errors like that will eventually be noticed.
So if your specs for the application say that if the user enters a title of less than three characters then it should be replaced by "Harry Potter" then you should definitely write code which does that. But if you're making up the specs, then be prepared for people questioning your specs when they disagree with reality.
Of course there is a way to avoid all those checks completely, to call new Book() That will allow all your fields to be null (or 0 for primitives) and it will allow all sorts of strange errors or exceptions later on. I suggest you get rid of the no‑arguments constructor. If the instructions require it, query the instructions with your teacher.
posted 3 years ago
Here is an updated, also this is not by me, just a lazy friend who can't take the time to start his own account on this forum. I have some programming experience but not much and not in Java. thanks for all your help up to this point
posted 3 years ago
Have you come across the this. idiom in constructors and setXXX methods?If you are using Strings and primitives the copying step becomes unnecessary. That has the advantage of avoiding awkward field names, as you have, and “exposes” the well‑chosen field names. It is the one circumstance where name shadowing is regarded as good style. Beware: that Java® Language Specification link may be difficult to read.