0

Say I have a following function in java, may be not good example but just came in mind ;)

public StudentEntity updateStudent(StudentEntity studentEntity)
{
    studentEntity.setName(...);
    studentEntity.setAddress(...);
    return studentEntity;
}

Is above approach valid?

Can we store a studentEntity in separate variable and update and return it. For example

public StudentEntity updateStudent(StudentEntity studentEntity)
{
    StudentEntity _studentEntity = studentEntity;
    _studentEntity.setName(...);
    _studentEntity.setAddress(...);
    return _studentEntity;
}

Is this correct ? How mutator methods should be? Please make me correct if wrong!

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Prashant Shilimkar
  • 8,402
  • 13
  • 54
  • 89
  • Possible duplicate: http://stackoverflow.com/questions/17655639/bad-programming-practice-to-alter-passed-objects-in-java – Ben Green Aug 01 '14 at 09:25

1 Answers1

3

There is no reason to write

   StudentEntity _studentEntity = studentEntity;

It's just redundant.

If you are just updating and return prefer first way. The second way creates unnecessary confusion while reading the code aswell.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • some thoughts on website confuses. Says do not use out parameters or do not change them. PMD or Sonar reports also says same? – Prashant Shilimkar Aug 01 '14 at 09:28
  • @PrashantShilimkar what do you mean by that. Sorry , Did'nt get you. – Suresh Atta Aug 01 '14 at 09:31
  • His method does return the same object as it receives as a parameter. In most cases this seems redundant. An updateXY method sounds like something that mutates the given object. So no need for a return value. This pattern more reminds me of methods acting on immutable objects like Strings where the return value is a new String object. – mdo Aug 01 '14 at 16:06