• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What's best practice in this inheritance case?

 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
imagine i'v these classes:


in order to protect my data, i cant expose it directly to other classes

in case i want to reuse (inherit) name in class TaxPayer i'd have to declare it protected in class Person, but then it becomes exposed to other classes that also belong to package foo.

what's the right procedure in similar cases?

TiA
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Provide a constructor in Person that gets the name as an argument, and call that constructor in the TaxPayer constructor.

Or simply call setName instead of trying to set the name directly.
 
S Herod
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use a setter.



A tool like eclipse makes the rather boring task of generating getters and setters a right-click breeze (of course, its a bit more useful than that).

I wouldn't make 'name' protected because I just never access data directly, always through the getters and setters.

It saves your bum later on, esp if you need to restrict the length of name, or make it upper case always (just throw code into the setter to normalize the data).
 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Ilja
of course both work, but i slightly prefer calling super() (dont ask why)

Now, another Q, pls
i like to code like this:

but then i'v to downcast:

Is this the regular way of coding these situations?

TiA
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by miguel lisboa:
i slightly prefer calling super()


I do, too!

(dont ask why)


Good developer instinct?


Now, another Q, pls
i like to code like this:

but then i'v to downcast:

Is this the regular way of coding these situations?


If at the time of the assignment I already know that later I will need to access the TaxPayer method, I don't see any reason for declaring payer as a Person - the code will fail if it isn't a TaxPayer, anyway, so I'd prefer it to fail at compile time.

There *are* situaions in which you definitely don't want the code between the assignment and the call to getTaxPayerId to know that payer is a TaxPayer. In those cases, casting is one valid option. Others include trying to find a more general method that will work for all subclasses of Person, or using the Visitor pattern. Which one is the best strongly depends on the situation (and sometimes even more on philosophy... )
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic