PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 25, 2022

[FIXED] What is the best way to repeatedly access a field value of an object in Java and why?

 October 25, 2022     java, oop     No comments   

Issue

Suppose, I have a class Book.

public class Book {
  private Author author;
  private int pageCount;
  // ... getters and setters
}

And another class Author.

public class Author {
  private String name;
  private int age;
  // ... getters and setters
}

Now, which one of the following is the best way to access the auther name of a book repeatedly from any other class?

void doSomethingA(Book book) {
   print(book.getAuthor().getName());
   publish(book.getAuthor().getName());
}

Or,

void doSomethingB(Book book) {
   Author author = book.getAuthor();
   print(author.getName());
   publish(author.getName());
}

Or,

void doSomethingC(Book book) {
   Author author = book.getAuthor();
   String authorName = author.getName();
   print(authorName);
   publish(authorName);
}

Solution

We want to avoid bugs, by making the code easy to read, and removing duplication (because with duplication we may make a change in only opne place when it should have been made in several places)

So none of your options are best. The best is:

void doSomethingC(Book book) {
   String authorName = book.getAuthor().getName();
   print(authorName);
   publish(authorName);
}

Now if we decide that we need to do something to the author name, we can change the code to:

void doSomethingC(Book book) {
   String authorName = massageAuthor(book.getAuthor().getName());
   print(authorName);
   publish(authorName);
}

And the new value is used in both places.



Answered By - tgdavies
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing