开发者

Input-output arguments vs. no arguments with side-effects

Is it better to write methods that take no arguments and have side-effects, changing the object state, or one-argument methods taking an argument and processing it? If the second alternative is preferable, is it better to return the input argument explicitly or just process it, since the caller is supposed to have a reference to it.

To be more precise: I am processing XML and having read the first chapters of the Clean Code book I am trying开发者_C百科 to split the Big Processing method into many small ones, so this method can be read like a story, in the lines of :

cleanHeader();

extractMetaInfo();

appendStuff();

and so on, where these methods all operate on the XML document stored as member.

IMHO, the best practices of reducing the parameter count vs. having no side effects seem to contradict each other here. Would it be better to write as follows?

doc = cleanHeader(doc);

doc = extractMetaInfo(doc);

doc = appendStuff(doc);

Is there a definite "right" on that issue? How much more context would a definite answer depend on? Or is there a third alternative i did not think about?

EDIT : found a related question with contradictory answers. Care to elaborate?


If your algothimen could be used by several threads in parallel then the way recommended in the clean code book (statfull but whithout arguments) would not work. In this case you must use the parameter way!


I would argue this from an OO design perspective. If you have a bunch of methods that operate on the same object like doc, then you probably need a class that wraps that object and encapsulates the behavior into a bigProcessingMethod() that calls the smaller processing methods it you want to break the task down further.

public class DocUtil { private String doc;

public DocUtil(String doc)
{
     this.doc = doc;
}

public bigProcessingMethod()
{
     cleanHeader(doc);

 extractMetaInfo(doc);

 appendStuff(doc);

}

//etc. }

I misunderstood your question. I didn't realize you were already inside of a wrapper class like DocUtil.

Whether you pass the doc variable explicitly to each of the processing methods or not, you're doing work on the same object at the same memory location. The only reason I'd pass it each time is to be explicit that these are methods that work on the variable doc.

It's up to you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜