Detect a change in the value of an object passed as a parameter

Now I am working with code similar to this

public String getName(User user) {
     user.setSth(...);
     return user.getName();
}

It seems to me that the wrong practice is to modify objects passed as parameters. Is there a tool that detects such code? I looked at findbugs, pmd and checkstyle, but could not find any check for this.

PS sorry for the bad example.

+3
source share
7 answers

, : Findbugs. , , . , , , .

. , getter . , , Findbugs.

+2

, "getName" "setSth" - . , " " " ", . , getName() , getters .

, , .

, findbugs PMD. . , :

  • "get"
  • body

. . , , " " ( , ). , . , :)

+2

User ( final, final . , , , ).

- "", , newId :

public final class User {
    private final String name;
    private final int id;

    User(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public User newId(int newId) {
        return new User(this.name, newId);
    }

    //getters here;
}

String, Integer,... .

+2

UserView, "getters", UserView .

interface UserView{
 public String getName();
...

class User implements UserView...

public String getName(UserView user) {
     user.setSth(...); // Will not compile
     return user.getName();
}
+1

, ++ const. const, , const - , getters.

Java , , . , , , .

, , , .

+1

- "const" ++, , , . , , .

You claim that it is “bad,” because side effects like this can surprise the user. It is true, but it is only harmful if it is an undesirable surprise.

0
source

Source: https://habr.com/ru/post/1703174/


All Articles