Win a copy of Rust Web Development this week in the Other Languages forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Needing help understanding boolean

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Im following the Head Start Java book and this was an example in the book. Why have boolean canRecord = false; ?

 
Marshal
Posts: 74627
335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch

line 23 should read
if (t.canRecord) {
Using == true and == false is poor style and error‑prone; what if you write = instead of == by mistake.
It would be better to have that boolean as a private field of the tape class and methods to setRecordable() and isRecordable(). Then you would writeThat is equivalent to turning the deck on and off. When you start it is not recordable. like having its recording behaviour turned off. Now it has been turned on and will record.
 
Campbell Ritchie
Marshal
Posts: 74627
335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can alter the record method to read like this:-
{
  System.out.println("Recording tape.");
  canRecord = false;
}

That means it will record once and turn itself off, but it can be turned on again with my setRecordable method.
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sterling Hicks wrote:
Im following the Head Start Java book and this was an example in the book. Why have boolean canRecord = false; ?



One of the fundamental principal of Object Oriented Programming is Encapsulation. And Its always better to bind a attribute (Variable) with a behavior (Method) and not expose the attribute directly. And the behavior should decide on the state of the attribute.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic