Side effects in Java methods

This may be a trivial question, but I need to clarify

public Example someMethod() {

    // ... different lines here

    Example example = new Example();
    example = doSomethingHere(example,param1,param2,...);    

    // ... different lines here

    return example;
}

private Example doSomethingHere(Example example,'some additional params here') {

    // ... modify example's fields here ...

    return example;
}

So, do I allow methods to be split in this way or prohibit such side effects, but should I deal with a fairly long method, which will certainly break the rules of clean code on short methods?

Update (more specific name of sub method)

public Example someMethod() {

    // ... different lines here

    Example example = new Example();
    example = setExampleFields(example,...);    

    // ... different lines here

    return example;
}

private Example setExampleFields(Example example,'some additional params here') {

    // ... modify example's fields here ...

    return example;
}

Solution

As JB nizet commented, if it is the only effect, it is not actually a side effect, so any package statement of "all side effects are bad" does not apply here

However, the main question remains: is this effective?

First, let's talk about principles. Side effects are usually dangerous for two reasons:

>They make concurrency more difficult > they blur / hide information

In your example, there is some hidden information You can call this a potential side effect and expose it through the following question: "does this dosomethinghere method create a new object or modify the object I passed in?" The answer is important, especially if it is a public method Finding answers by reading dosomething here should be trivial, especially if you keep your method 'clean', but the information is still hidden / blurred

In this particular case, I will let dosomethinghere return void In this way, it is impossible for people to think that you have created a new object This is just a personal method - I'm sure many developers say you should return the object you modify Alternatively, you can choose a "good" method name "Modifyexampleinplace" or "changesomefieldsinplace" is a very secure name for your specific example IMO

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>