• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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: 79151
377
  • 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: 79151
377
  • 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.
 
Live ordinary life in an extraordinary way. Details embedded in this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic