Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Is it ok to have a method that passes private field values into another class' method?

I have a class with a bunch of fields, all private (subclasses access a few with protected getters). I need to pass most of those fields into a method in another class that will format them and generate output. Is it ok to have a method in the class with the fields that'll pass them all across? Or do these circumstances suggest that I should implement some other relationship between the two classes, as they seem closely coupled because of this?

Further information: class A represents Employees, class B's only responsibility is to format the output of the program.

like image 320
false_azure Avatar asked Apr 09 '13 10:04

false_azure


1 Answers

Are you asking if it is OK to do the following?

public class A {
 private B myB = new B();
 private String myUnformattedName = "some information";

 public String getFormattedInfo() {
   return myB.formatInfo(myUnformattedName);
 }
}

That's perfectly OK.

Marking a field as private just means that only the containing class should be able to access it...

If you mean something else it's best to pop some code in your question to give people the context


OK, so there's no way to set the values here but you can see here two different ways to call the formatter. When the parameter list gets past three or four items then it gets difficult to read.

In this instance I'd just pass A into the formatter and have a get method for each value you want B to be able to read.

public class A {
 private B myB = new B();
 private String myUnformattedName = "some information";
 private String myUnformattedNameOne = "some information";
 private String myUnformattedNameTwo = "some information";
 private String myUnformattedNameThree = "some information";
 private String myUnformattedNameFour = "some information";
 private String myUnformattedNameFive = "some information";
 private String myUnformattedNameSix = "some information";

 public String getFormattedInfo() {
   //pass the object itself and use get methods
   return myB.formatInfo(this); 
 }

 public String getFormattedInfoLong() {
   //this is OK but gets difficult to read the longer the 
   //parameter list gets
   return myB.formatInfo(myUnformattedName, myUnformattedNameOne, 
      myUnformattedTwo, myUnformattedNameThree, myUnformattedNameFour,
      myUnformattedNameFive, myUnformattedNameSix); 
 }

 //getters
 public String getUnformattedName() {
    return myUnformattedName;
 }

 public String getUnformattedNameOne() {
    return myUnformattedNameOne;
 }

 //etc

}
like image 184
Paul D'Ambra Avatar answered Nov 15 '22 09:11

Paul D'Ambra