开发者

What do I call this style of programming?

开发者 https://www.devze.com 2023-01-07 14:38 出处:网络
I am working with a type that passes state through instance variables. So you\'ll see methods like so:

I am working with a type that passes state through instance variables. So you'll see methods like so:

p开发者_如何转开发ublic MyType MyMethod()
{
  DoThisMethod();
  DoThatMethod();
  AndDoThis();

  return _bleh;
}

Is this a recognised approach?

It's a little disconcerting working with this code because if you don't understand the code fully, the instance variable might be transformed without your knowledge by another method. If instead state was passed via method parameters, then you could be very confident of the value of the parameter passsed in.


If the order of those method calls is important I would call this "Bad Programming" - as you've said any method that requires an earlier call should be using method parameters that are indicative of this.

I'm pretty sure Code Complete gives some great examples of this approach.

Basically something like the following, where each method requires the previous invocation's result.

public MyType MyMethod() 
{ 
    thisResult = DoThisMethod(); 
    thatResult = DoThatMethod(thisResult); 
    _bleh = AndDoThis(thatResult ); 

    return _bleh; 
} 

Secondly, I like to keep methods "orthogonal" as much as possible (that is they depend only on the state that you provide them among other things). For a great summary on Orthogonal Code see this article.


Functional decomposition, broadly speaking. The pattern you describe is sometimes indicative of code that is (a) too thoroughly decomposed, leading to the issue that you have to trace the execution path to see the resulting combined behavior, or (b) doing too much. By transforming these methods to take parameters instead of relying on internal state, you can make them more testable and probably more readable. You can mutate state as necessary in the outermost function.


It's the opposite of functional programming. The closest thing I can think of is "stateful programming" but that doesn't seem pejorative enough. It probably qualifies as Structured Programming, though.

As an aside, if you think of HTTP requests as being analogous to method calls, and a "Session" implementation as being like an object instance, then this is exactly the way a lot of websites are designed. And (IMHO) it's not a good design there, either.


Looks like a misunderstanding of why globals are bad. I'm not aware of a name for this particular style, but know that it's almost as bad as using globals -- i imagine things will break if the functions are called out of order.


There is a chance that "sequential coupling" (http://en.wikipedia.org/wiki/Sequential_coupling) can be also recognized if those methods calling order is constrainted.

0

精彩评论

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