What is the best practice to modify an object passed to a method

后端 未结 2 902
我在风中等你
我在风中等你 2020-12-16 16:23

After passing an object into a method, I would like to change one of its fields. What\'s the best practice to do this task in Java?

2条回答
  •  半阙折子戏
    2020-12-16 16:48

    Simple answer

    As stated in other answers, you can simply call the setter method.

    More philosophical answer

    Generally, it can be dangerous to mutate objects in a scope other than that in which they were created:

    http://en.wikipedia.org/wiki/Functional_programming

    That said, there are often times where you simply want to encapsulate bits of logic in the same logical scope where you would want to modify values of an object passed in. So the rule I would use is that as long as all calling code is fully aware of such mutations, you can call the setter method on the object (and you should create a setter method if you don't have one) in the method to which you're passing the object.

    In general, if you call a function that mutates parameters from multiple places in your codebase, you will find that it becomes increasingly error prone, which is why functional programming pays off.

    So, the moral of the story is: if your caller(s) are fully aware of such mutations, you could change the value in your method, but in general you should try to avoid it and instead change it in the scope in which it was created (or create a copy).

提交回复
热议问题