答:
Make a class that has one public method only and keeps the internal state needed for the suboperations in its instance variables.

The problem I see with this approach is that the state of this class makes sense only internally, and can't do anything with its instances except call their only public method.

Option 1 is a good example of encapsulation used correctly.  You want the internal state to be hidden from outside code.

If that means your class only has one public method, then so be it.  It'll be that much easier to maintain.

In OOP if you have a class that does exactly 1 thing, has a small public surface, and keeps all its internal state hidden, then you are (as Charlie Sheen would say) WINNING.

Make a bunch of functions without a class and pass the various internally needed variables between them (as arguments).

The problem I see with this is that I have to pass a lot of variables between functions.
Also, the functions would be closely related to each other, but wouldn't be grouped together.

Option 2 suffers from low cohesion.  This will make maintenance more difficult.

Like 2. but make the state variables global instead of passing them.

Option 3, like option 2, suffers from low cohesion, but much more severely!

History has shown that the convenience of global variables is outweighed by the brutal maintenance cost it brings.  That's why you hear old farts like me ranting about encapsulation all the time.

The winning option is #1.

Title: Should I create a class if my function is complex and has a lot of variables?

Body:
This question is somewhat language-agnostic, but not completely, since Object Oriented Programming (OOP) is different in, for example, Java, which doesn't have first-class functions, than it is in Python.

In other words, I feel less guilty for creating unnecessary classes in a language like Java, but I feel like there might be a better way in the less boilerplate-y languages like Python.

My program needs to do a relatively complex operation a number of times.
That operation requires a lot of "bookkeeping", has to create and delete some temporary files, etc.

That's why it also needs to call a lot of other "suboperations" - putting everything into one huge method isn't very nice, modular, readable, etc.

Now these are approaches that come to my mind:

1. Make a class that has one public method only and keeps the internal state needed for the suboperations in its instance variables.

It would look something like this:

```<code>class Thing:

    def __init__(self, var1, var2):
        self.var1 = var1
        self.var2 = var2
        self.var3 = []

    def the_public_method(self, param1, param2):
        self.var4 = param1
        self.var5 = param2
        self.var6 = param1 + param2 * self.var1
        self.__suboperation1()
        self.__suboperation2()
        self.__suboperation3()

    def __suboperation1(self):
        # Do something with self.var1, self.var2, self.var6
        # Do something with the result and self.var3
        # self.var7 = something
        # ...
        self.__suboperation4()
        self.__suboperation5()
        # ...

    def suboperation2(self):
        # Uses self.var1 and self.var3

#    ...
#    etc.
</code>```

The problem I see with this approach is that the state of this class makes sense only internally, and it can't do anything with its instances except call their only public method.

```<code># Make a thing object
thing = Thing(1,2)

# Call the only method you can call
thing.the_public_method(3,4)

# You don't need thing anymore
</code>```

2. Make a bunch of functions without a class and pass the various internally needed variables between them (as arguments).

The problem I see with this is that I have to pass a lot of variables between functions. Also, the functions would be closely related to each other, but they wouldn't be grouped together.

3. Like 2. but make the state variables global instead of passing them.

This would be no good at all, since I have to do the operation more than once, with different input.

Is there a fourth, better, approach? If not, which one of these approaches would be better, and why? Is there something I'm missing?


问:
What revision control has the best merging engine?
When it comes to merging, each control version has it's engine to do it. Conflicts are unavoidable but the question is - which revision control has best AI to avoid conflict.

Is it possible to measure such thing?

More specifically, we are thinking to move to GIT cause it has nice hype and rumour that handles conflict better...

Any comment is appreciated...

答:
There's a small test suite called merge-this which compares revision control system against real world merge scenarios.  For each scenario, it makes sure a VCS can do the following correctly:

merge the branch without conflicts

produce code that compiles

produce code that behaves correctly

Based on the number of passing tests on merge-this, it appears that there are two tiers of performance:

Darcs, Git

Bazaar, Mercurial

Depending on which programming languages you're trying to merge, the exact test results may matter. See the project's website for a detailed comparison table.

ContentLicense: CC BY-SA 3.0


问:
Is reinventing the wheel really all that bad?
Its common knowledge in programming that reinventing the wheel is bad or evil.

But why is that?

I am not suggesting that it's good. I believe it to be wrong. However, I once read an article that said, if someone is doing something wrong (programming wise) explain to them why its wrong, if you can't, then maybe you should be asking yourself if it is really wrong.

That leads me to this question:

If I see someone is clearly reinventing the wheel by building their own method of something that is already built into the language/framework. First, for arguments sake, lets assume that their method is just as efficient as the built in method. Also the developer, aware of the built in method, prefers his own method.

Why should he use the built in one over his own?

答:
Being "bad" or even "evil" is rather strong words.

As always there are reasons for choosing a personal implementation over a built-in one.  In the old days a C program might encounter bugs in the runtime library, and therefore simply have to provide its own implementation.

This doesn't apply for Java programs as the JVM is very strictly defined, but some algorithms are still very hard to get right.  For instance Joshua Bloch describes how the deceivingly simple binary search algorithm in the Java runtime library contained a bug, which it took nine years to surface:

http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html

It was found, fixed and distributed in future Java distributions.

If you use the builtin binary search you just saved time and money by having Sun do the hard work finding, fixing and distributing this bugfix.  You can leverage their work just by saying "you need at least Java 6 update 10".

If you use your own implementation - which would very likely contain this error too - you first need the bug to manifest itself.  Given that this particular one only shows on LARGE datasets, it is bound to happen in production somewhere, meaning at least one of your customers will be affected and most likely loose real money while you find, fix and distribute the bugfix.

So, it is perfectly valid to prefer your own implementation, but the reason better be really good, as it is bound to be more expensive than leveraging the work of others.

ContentLicense: CC BY-SA 2.5


问:
OAuthv2 authorization grants
I just read this excellent tutorial on OAuthv2 but am still missing some important concepts regarding authorization grants.

I'm fundamentally not understanding the necessity for the two request/response cycles between client app and authorization server, where:

First the user is redirected to the auth server during an Authorization Request, whereby (on successful authentication), they receive an auth code; and then

Next, the client app makes a second Token Request to the auth server, whereby the auth server validates the client's ID, secret and auth code, and sends back an access token for it to use

Auth codes vs. access tokens

What is the difference between this "auth code" and this "access token"? Why do I need to first generate an auth code so that I can, subsequently, obtain an access token?!? Why not just do all this in 1 roundtrip and get an access token upon successful authentication?

Access tokens and resource servers

I assume that the main point of the access token is to act as a hall pass for future requests, so that client apps aren't re-authenticating each subsequent request. Ergo I assume that, with a valid access token, client apps can now "speak directly" with resource servers. And I assume that, upon receiving each request, the resource servers probably validate access tokens with their respective auth servers. Am I on track here or way off base?

Access tokens and SSO?

Can access tokens be used in an SSO scenario where you have multiple resource servers all using the same auth server? Meaning, once I authenticate with an auth server and receive my access token from it when I'm inside 1 SSO app, can I then migrate to another SSO app, and apply the same access token (assuming it hasn't expired yet) and be "signed in" to that second app, without having to re-authenticate?

答:
Using the authorization code grant brings you two things that other grants are lacking.

it gives you authentication of both the user and the client. It does client authentication by sending the client id and client secret when acquiring the access token.

it keeps the access token hidden from the user agent (typically a browser), where they could be stolen much more easily.

The implicit grant actually does this all in one round trip and therefore exposes the access token to the user-agent and does not authenticate the client itself (only the user).

You are correct that a client can access the resources on the resource server using the access token without re-authenticating each request. The resource server does not need to communicate with the authorization server to validate the token as it uses digital signatures to trust the contents of the token.

Access tokens can be used in SSO scenarios, but typically your user-agent would go back to the authorization server to get another access token to talk to another resource server. Your user-agent would establish a session (likely cookies) with the authorization server to prevent re-authentication.

Title: OAuthv2 authorization grants


问:
Is the benefit of the IO monad pattern for handling side effects purely academic?
Sorry for yet another FP + side effects question, but I couldn't find an existing one which quite answered this for me.

My (limited) understanding of functional programming is that state/side effects should be minimised and kept separate from stateless logic.

I also gather Haskell’s approach to this, the IO monad, achieves this by wrapping stateful actions in a container, for later execution, considered outside the scope of the program itself.

I’m trying to understand this pattern, but actually to determine whether to use it in a Python project, so want to avoid Haskell specifics if poss.

Crude example incoming.

If my program converts an XML file to a JSON file:

```<code>def main():
    xml_data = read_file('input.xml')  # impure
    json_data = convert(xml_data)  # pure
    write_file('output.json', json_data) # impure
</code>```

Isn’t the IO monad’s approach effectively to do this:

```<code>steps = list(
    read_file,
    convert,
    write_file,
)
</code>```

then absolve itself of responsibility by not actually calling those steps, but letting the interpreter do it?

Or put another way, it’s like writing:

```<code>def main():  # pure
    def inner():  # impure
        xml_data = read_file('input.xml')
        json_data = convert(xml_data)
        write_file('output.json', json_data)
    return inner
</code>```

then expecting someone else to call inner() and saying your job is done because main() is pure.

The whole program is going to end up contained in the IO monad, basically.

When the code is actually executed, everything after reading the file depends on that file’s state so will still suffer from the same state-related bugs as the imperative implementation, so have you actually gained anything, as a programmer who will maintain this?

I totally appreciate the benefit of reducing and isolating stateful behaviour, which is in fact why I structured the imperative version like that: gather inputs, do pure stuff, spit out outputs. Hopefully convert() can be completely pure and reap the benefits of cachability, threadsafety, etc.

I also appreciate that monadic types can be useful, especially in pipelines operating on comparable types, but don’t see why IO should use monads unless already in such a pipeline.

Is there some additional benefit to dealing with side effects the IO monad pattern brings, which I’m missing?

答:
The whole program is going to end up contained in the IO monad, basically.

That's the bit where I think you're not seeing it from the Haskellers' perspective.  So we have a program like this:

```<code>module Main

main :: IO ()
main = do
  xmlData <- readFile "input.xml"
  let jsonData = convert xmlData
  writeFile "output.json" jsonData

convert :: String -> String
convert xml = ...
</code>```

I think a typical Haskeller's take on this would be that convert, the pure part:

Is probably the bulk of this program, and by far more complicated than the IO parts;

Can be reasoned about and tested without having to deal with IO at all.

So they don't see this as convert being "contained" in IO, but rather, as it being isolated from IO.  From its type, whatever convert does can never depend on anything that happens in an IO action.

When the code is actually executed, everything after reading the file depends on that file’s state so will still suffer from the same state-related bugs as the imperative implementation, so have you actually gained anything, as a programmer who will maintain this?

I'd say that this splits into two things:

When the program runs, the value of the argument to convert depends on the state of the file.

But what the convert function does, that doesn't depend on the state of the file.  convert is always the same function, even if it is invoked with different arguments at different points.

This is a somewhat abstract point, but it's really key to what Haskellers mean when they talk about this.  You want to write convert in such a way that given any valid argument, it will produce a correct result for that argument.  When you look at it like that, the fact that reading a file is a stateful operation doesn't enter into the equation; all that matters is that whatever argument is fed to it and wherever that may have come from, convert must handle it correctly.  And the fact that purity restricts what convert can do with its input simplifies that reasoning.

So if convert produces incorrect results from some arguments, and readFile feeds it such an argument, we don't see that as a bug introduced by state.  It's a bug in a pure function!

Body:
The whole program is going to end up contained in the IO monad, basically.

That's the bit where I think you're not seeing it from the Haskellers' perspective.  So we have a program like this:

module Main

main :: IO ()
main = do
  xmlData <- readFile "input.xml"
  let jsonData = convert xmlData
  writeFile "output.json" jsonData

convert :: String -> String
convert xml = ...

I think a typical Haskeller's take on this would be that convert, the pure part:

Is probably the bulk of this program, and by far more complicated than the IO parts;

Can be reasoned about and tested without having to deal with IO at all.

So they don't see this as convert being "contained" in IO, but rather, as it being isolated from IO.  From its type, whatever convert does can never depend on anything that happens in an IO action.

When the code is actually executed, everything after reading the file depends on that file’s state so will still suffer from the same state-related bugs as the imperative implementation, so have you actually gained anything, as a programmer who will maintain this?

I'd say that this splits into two things:

When the program runs, the value of the argument to convert depends on the state of the file.

But what the convert function does, that doesn't depend on the state of the file.  convert is always the same function, even if it is invoked with different arguments at different points.

This is a somewhat abstract point, but it's really key to what Haskellers mean when they talk about this.  You want to write convert in such a way that given any valid argument, it will produce a correct result for that argument.  When you look at it like that, the fact that reading a file is a stateful operation doesn't enter into the equation; all that matters is that whatever argument is fed to it and wherever that may have come from, convert must handle it correctly.  And the fact that purity restricts what convert can do with its input simplifies that reasoning.

So if convert produces incorrect results from some arguments, and readFile feeds it such an argument, we don't see that as a bug introduced by state.  It's a bug in a pure function!


问:
How do you safely refactor in a language with dynamic scope?
For those of you who have the good fortune not to work in a language with dynamic scope, let me give you a little refresher on how that works. Imagine a pseudo-language, called "RUBELLA", that behaves like this:

```<code>function foo() {
    print(x); // not defined locally => uses whatever value `x` has in the calling context
    y = "tetanus";
}
function bar() {
    x = "measles";
    foo();
    print(y); // not defined locally, but set by the call to `foo()`
}
bar(); // prints "measles" followed by "tetanus"
</code>```

That is, variables propagate up and down the call stack freely - all variables defined in foo are visible to (and mutatable by) its caller bar, and the reverse is also true. This has serious implications for code refactorability. Imagine that you have the following code:

```<code>function a() { // defined in file A
    x = "qux";
    b();
}
function b() { // defined in file B
    c();
}
function c() { // defined in file C
    print(x);
}
</code>```

Now, calls to a() will print qux. But then, someday, you decide that you need to change b a little bit. You don't know all the calling contexts (some of which may in fact be outside your codebase), but that should be alright - your changes are going to be completely internal to b, right? So you rewrite it like this:

```<code>function b() {
    x = "oops";
    c();
}
</code>```

And you might think that you haven't changed anything, since you've just defined a local variable. But, in fact, you've broken a! Now, a prints oops rather than qux.

Bringing this back out of the realm of pseudo-languages, this is exactly how MUMPS behaves, albeit with different syntax.

Modern ("modern") versions of MUMPS include the so-called NEW statement, which allows you to prevent variables from leaking from a callee to a caller. So in the first example above, if we had done NEW y = "tetanus" in foo(), then print(y) in bar() would print nothing (in MUMPS, all names point to the empty string unless explicitly set to something else). But there is nothing that can prevent variables from leaking from a caller to a callee: if we have function p() { NEW x = 3; q(); print(x); }, for all we know, q() could mutate x, despite not explicitly receiving x as a parameter. This is still a bad situation to be in, but not as bad as it probably used to be.

With these dangers in mind, how can we safely refactor code in MUMPS or any other language with dynamic scoping?

There are some obvious good practices for making refactoring easier, like never using variables in a function other than those you initialize (NEW) yourself or are passed as an explicit parameter, and explicitly documenting any parameters that are implicitly passed from a function's callers. But in a decades-old, ~108-LOC codebase, these are luxuries one often does not have.

And, of course, essentially all good practices for refactoring in languages with lexical scope are also applicable in languages with dynamic scope - write tests, and so forth. The question, then, is this: how do we mitigate the risks specifically associated with the increased fragility of dynamically-scoped code when refactoring?

(Note that while How do you navigate and refactor code written in a dynamic language? has a similar title to this question, it is wholly unrelated.)

答:
Wow.

I do not know MUMPS as a language, so I do not know whether my comment applies here. Generally speaking - You must refactor from inside out. Those consumers (readers) of global state (global variables) must be refactored into methods/ functions/procedures using parameters. The method c should look like this after refactoring:

```<code>function c(c_scope_x) {
   print c(c_scope_x);
}
</code>```

all usages of c must be rewritten into (which is a mechanical task)

```<code>c(x)
</code>```

this is to isolate the "inner" code from the global state by using local state. When you are done with that, you will have to rewrite b into:

```<code>function b() {
   x="oops"
   print c(x);
}
</code>```

the x="oops" assignment is there to keep the side effects. Now we must consider b as polluting the global state. If you only have one polluted element consider this refactoring:

```<code>function b() {
   x="oops"
   print c(x);
   return x;
}
</code>```

end rewrite each use of b with x=b(). Function b must use only methods already cleaned up (you may want ro rename c o make that clear) when doing this refactoring. After that you should refactor b to not pollute the global environment.

```<code>function b() {
   newvardefinition b_scoped_x="oops"
   print c_cleaned(b_scoped_x);
   return b_scoped_x;
}
</code>```

rename b to b_cleaned. I guess you will have to play a bit with that to get accoustomed to that refactoring. Sure not every method can be refactored by this but you will have to start from the inner parts. Try that with Eclipse and java (extract methods) and "global state" a.k.a. class members to get an idea.

```<code>function x() {
  fifth_to_refactor();
  {
    forth_to_refactor()
    ....
    {
      second_to_refactor();
    }
    ...
    third_to_refactor();
  }
  first_to_refactor()
}
</code>```

hth.

Question: With these dangers in mind, how can we safely refactor code in MUMPS or any other language with dynamic scoping?

Maybe someone else can give a hint.

Question: How do we mitigate the risks specifically associated with the increased fragility of dynamically-scoped code when refactoring?

Write a program, which does the safe refactorings for you.

Write a program, which identifis safe candidates / first candidates.

Body:
Wow.

I do not know MUMPS as a language, so I do not know whether my comment applies here. Generally speaking - You must refactor from inside out. Those consumers (readers) of global state (global variables) must be refactored into methods/ functions/procedures using parameters. The method c should look like this after refactoring:

function c(c_scope_x) {
   print c(c_scope_x);
}

all usages of c must be rewritten into (which is a mechanical task)

c(x)

this is to isolate the "inner" code from the global state by using local state. When you are done with that, you will have to rewrite b into:

function b() {
   x="oops"
   print c(x);
}

the x="oops" assignment is there to keep the side effects. Now we must consider b as polluting the global state. If you only have one polluted element consider this refactoring:

function b() {
   x="oops"
   print c(x);
   return x;
}

end rewrite each use of b with x=b(). Function b must use only methods already cleaned up (you may want ro rename c o make that clear) when doing this refactoring. After that you should refactor b to not pollute the global environment.

function b() {
   newvardefinition b_scoped_x="oops"
   print c_cleaned(b_scoped_x);
   return b_scoped_x;
}

rename b to b_cleaned. I guess you will have to play a bit with that to get accoustomed to that refactoring. Sure not every method can be refactored by this but you will have to start from the inner parts. Try that with Eclipse and java (extract methods) and "global state" a.k.a. class members to get an idea.

function x() {
  fifth_to_refactor();
  {
    forth_to_refactor()
    ....
    {
      second_to_refactor();
    }
    ...
    third_to_refactor();
  }
  first_to_refactor()
}

hth.

Question: With these dangers in mind, how can we safely refactor code in MUMPS or any other language with dynamic scoping?

Maybe someone else can give a hint.

Question: How do we mitigate the risks specifically associated with the increased fragility of dynamically-scoped code when refactoring?

Write a program, which does the safe refactorings for you.

Write a program, which identifis safe candidates / first candidates.


问:
PHP: when to use arrays, and when to use objects for mostly-data-storing code constructs?
PHP is a mixed paradigm language, allowing to use and return non-object data types, such as arrays. I pose a question to try to clarify some guidelines for selection of arrays vs objects when deciding upon what programming construct to use in a particular situation.

This is really a question about ways to encode data using PHP language constructs and when one way is to be more likely picked over another for data passing purposes (i.e. Service-Oriented Architecture or web services).

Example

Suppose you have an item type consisting of {cost, name, part_number, item_count}.  Your program calls for display of several such item types, to where you decide to use an array as an outer container to hold each of the item types.  [You can also use PHP's ArrayObject for OO paradigm, but my question is not about that (outer) array].  My question is about how to encode the item type data, and about which paradigm to use.  PHP allows you to use PHP Native Arrays or PHP Objects.

I can encode such data, in two ways here, like so:

```<code>//PHP's associative arrays:
$ret = array(
    0 => array(
        'cost' => 10.00,
        'name' => 'item1',
        'part_number' => 'zyz-100',
        'item_count' => 15
        ),
    1 => array(
        'cost' => 34.00,
        'name' => 'item2',
        'part_number' => 'abc-230',
        'item_count' => 42
        ),
  );
</code>```

vs

```<code>//here ItemType is encapsulated into an object
$ret = array(
  0 => new ItemType(10.00, 'item1', 'zyz-100', 15),
  1 => new ItemType(34.00, 'item2', 'abc-230', 42),
);

class ItemType
{
    private $price;
    private $name;
    private $partNumber;
    private $itemCount;

    function __construct($price, $name, $partNumber, $itemCount) {..}
}
</code>```

What I am thinking

Array encoding is light-weight, and more JSON-ready, but can be easier to mess up.  Misspell one of the associative array keys and you may have an error that is more difficult to catch.   But it is also easier to change on a whim.  Say I don't want to store item_count anymore, I can use any text-processing software to easily remove all item_count instances in the array and then update other functions that use it accordingly.  It may be a more tedious process, but it is simple.

Object oriented encoding calls upon IDE and PHP language facilities and makes it easier to catch any errors beforehand, but is harder to program and code up in the first place.  I say harder, because you have to think a bit about your objects, think ahead, and OO coding takes a bit higher cognitive load than typing up array structures. That said, once it is coded up, some changes maybe easier to implement, in a sense, that removing item_count, for example, will require changing less lines of code.  But changes themselves may still require a higher cognitive load in comparison with the array method, since higher-level OO facilities are involved.

Question

In some cases it is clear, like cases where I will need to perform manipulations on the data.  But in some cases, where I need to just store a few lines of "Item Type" data, I don't have clear guidelines or considerations to lean on when trying to decide whether to use arrays or whether to construct objects.  It seems I can just toss a coin and pick one.  Is that the case here?

答:
The way I see this, it depends on what you intend to do with the data afterwards. Based on a few simple checks you can determine which of the two data structures is better for you:

Does this data have any logic associated with it?

For example, is $price stored as an integer number of cents, so a product with a price of $9.99 would have price = 999 and not price = 9.99? (Probably, yes) Or does partNumber need to match a specific regex? Or, do you need to be able to easily check if the itemCount is available in your inventory? Will you need to do these these functions in the future? If so, then your best bet is to create a class now. This means that you can define constraints and logic built into the data structure: private $myPrice is set to 999 but $item->getPriceString() returns $9.99 and $item->inStock() is available to be called in your application.

Are you going to be passing this data to multiple PHP functions?

If so, then use a class. If you're generating this data once to perform some transformations on it, or just to send as JSON data to another application (JavaScript or otherwise) then an array is an easier choice. But if you have more than two PHP functions which accept this data as a parameter, use a class. If nothing else, that lets you define someFunction(MyProductClass $product) { and it's very clear what your functions expect as input. As you scale out your code and have more functions it will be much easier to know what type of data each function accepts. Seeing someFunction($someArrayData) { is not nearly as clear. Also, this does not enforce type consistency and means that (as you said) the flexible structure of the array can cause development pain later on

Are you building a library or shared code base?

If so, use a class! Think about some new developer who is using your library, or another developer somewhere else in the company who has never used your code before. It will be much easier for them to look at a class definition and understand what that class does, or see a number of functions in your library which accept objects of a certain class, than to try and guess what structure they need to generate in a number of arrays. Also, this touches on the data consistency issues with #1: if you're developing a library or shared code base, be nice to your users: give them classes which enforce data consistency and protect them from making errors with the design of your data.

Is this a small part of an application or just a transformation of data? Do you not fit into any of the above?

A class might be too much; use an array if it suits you and you find it easier. As mentioned above, if you're just generating structured data to send as JSON or YAML or XML or whatever, don't bother with a class unless there's a need to. If you are writing a small module in a larger application, and no other modules/teams need to interface with your code, maybe an array is sufficient.

Ultimately, consider the scaling needs of your code and consider than a structured array might be a quick fix, but a class is a much more resilient and scalable solution.

Also, consider the following: if you have a class, and you want to output to JSON, there's no reason you can't define a json_data() method of your class which returns a JSON-ifiable array of the data in the class. This is what I did in my PHP applications where I needed to send class data as JSON. As an example:

```<code>class Order {
    private $my_total;
    private $my_lineitems;

    public function getItems() { return $this->my_lineitems; }
    public function addItem(Product $p) { $this->my_lineitems[] = $p; }
    public function getTotal() { return $this->my_total; }

    public function forJSON() {
        $items_json = array();
        foreach($this->my_lineitems as $item) $items_json[] = $item->forJSON();
        return array(
            'total' => $this->getTotal(),
            'items' => $items_json
        );
    }
}

$o = new Order();
// do some stuff with it
$json = json_encode($o->forJSON());
</code>```

Body:
The way I see this, it depends on what you intend to do with the data afterwards. Based on a few simple checks you can determine which of the two data structures is better for you:

Does this data have any logic associated with it?

For example, is $price stored as an integer number of cents, so a product with a price of $9.99 would have price = 999 and not price = 9.99? (Probably, yes) Or does partNumber need to match a specific regex? Or, do you need to be able to easily check if the itemCount is available in your inventory? Will you need to do these these functions in the future? If so, then your best bet is to create a class now. This means that you can define constraints and logic built into the data structure: private $myPrice is set to 999 but $item->getPriceString() returns $9.99 and $item->inStock() is available to be called in your application.

Are you going to be passing this data to multiple PHP functions?

If so, then use a class. If you're generating this data once to perform some transformations on it, or just to send as JSON data to another application (JavaScript or otherwise) then an array is an easier choice. But if you have more than two PHP functions which accept this data as a parameter, use a class. If nothing else, that lets you define someFunction(MyProductClass $product) { and it's very clear what your functions expect as input. As you scale out your code and have more functions it will be much easier to know what type of data each function accepts. Seeing someFunction($someArrayData) { is not nearly as clear. Also, this does not enforce type consistency and means that (as you said) the flexible structure of the array can cause development pain later on

Are you building a library or shared code base?

If so, use a class! Think about some new developer who is using your library, or another developer somewhere else in the company who has never used your code before. It will be much easier for them to look at a class definition and understand what that class does, or see a number of functions in your library which accept objects of a certain class, than to try and guess what structure they need to generate in a number of arrays. Also, this touches on the data consistency issues with #1: if you're developing a library or shared code base, be nice to your users: give them classes which enforce data consistency and protect them from making errors with the design of your data.

Is this a small part of an application or just a transformation of data? Do you not fit into any of the above?

A class might be too much; use an array if it suits you and you find it easier. As mentioned above, if you're just generating structured data to send as JSON or YAML or XML or whatever, don't bother with a class unless there's a need to. If you are writing a small module in a larger application, and no other modules/teams need to interface with your code, maybe an array is sufficient.

Ultimately, consider the scaling needs of your code and consider than a structured array might be a quick fix, but a class is a much more resilient and scalable solution.

Also, consider the following: if you have a class, and you want to output to JSON, there's no reason you can't define a json_data() method of your class which returns a JSON-ifiable array of the data in the class. This is what I did in my PHP applications where I needed to send class data as JSON. As an example:

class Order {
    private $my_total;
    private $my_lineitems;

    public function getItems() { return $this->my_lineitems; }
    public function addItem(Product $p) { $this->my_lineitems[] = $p; }
    public function getTotal() { return $this->my_total; }

    public function forJSON() {
        $items_json = array();
        foreach($this->my_lineitems as $item) $items_json[] = $item->forJSON();
        return array(
            'total' => $this->getTotal(),
            'items' => $items_json
        );
    }
}

$o = new Order();
// do some stuff with it
$json = json_encode($o->forJSON());


问:
Should I create a class if my function is complex and has a lot of variables?
This question is somewhat language-agnostic, but not completely, since Object Oriented Programming (OOP) is different in, for example, Java, which doesn't have first-class functions, than it is in Python.

In other words, I feel less guilty for creating unnecessary classes in a language like Java, but I feel like there might be a better way in the less boilerplate-y languages like Python.

My program needs to do a relatively complex operation a number of times.
That operation requires a lot of "bookkeeping", has to create and delete some temporary files, etc.

That's why it also needs to call a lot of other "suboperations" - putting everything into one huge method isn't very nice, modular, readable, etc.

Now these are approaches that come to my mind:

1. Make a class that has one public method only and keeps the internal state needed for the suboperations in its instance variables.

It would look something like this:

```<code>class Thing:

    def __init__(self, var1, var2):
        self.var1 = var1
        self.var2 = var2
        self.var3 = []

    def the_public_method(self, param1, param2):
        self.var4 = param1
        self.var5 = param2
        self.var6 = param1 + param2 * self.var1
        self.__suboperation1()
        self.__suboperation2()
        self.__suboperation3()

    def __suboperation1(self):
        # Do something with self.var1, self.var2, self.var6
        # Do something with the result and self.var3
        # self.var7 = something
        # ...
        self.__suboperation4()
        self.__suboperation5()
        # ...

    def suboperation2(self):
        # Uses self.var1 and self.var3

#    ...
#    etc.
</code>```

The problem I see with this approach is that the state of this class makes sense only internally, and it can't do anything with its instances except call their only public method.

```<code># Make a thing object
thing = Thing(1,2)

# Call the only method you can call
thing.the_public_method(3,4)

# You don't need thing anymore
</code>```

2. Make a bunch of functions without a class and pass the various internally needed variables between them (as arguments).

The problem I see with this is that I have to pass a lot of variables between functions. Also, the functions would be closely related to each other, but they wouldn't be grouped together.

3. Like 2. but make the state variables global instead of passing them.

This would be no good at all, since I have to do the operation more than once, with different input.

Is there a fourth, better, approach? If not, which one of these approaches would be better, and why? Is there something I'm missing?

答:
On the one hand, the question is somehow language agnostic; but on the other hand, the implementation depends on the language and its paradigms. In this case it is Python, which supports multiple paradigms.

Besides your solutions, there is also a possibility, to do the operations complete stateless in a more functional way, e.g.

```<code>def outer(param1, param2):
    def inner1(param1, param2, param3):
        pass
    def inner2(param1, param2):
        pass
    return inner2(inner1(param1),param2,param3)
</code>```

It all comes down to

readability

consistency

maintainability

But -If your codebase is OOP, it violates consistency if suddenly some parts are written in a (more) functional style.

Body:
On the one hand, the question is somehow language agnostic; but on the other hand, the implementation depends on the language and its paradigms. In this case it is Python, which supports multiple paradigms.

Besides your solutions, there is also a possibility, to do the operations complete stateless in a more functional way, e.g.

def outer(param1, param2):
    def inner1(param1, param2, param3):
        pass
    def inner2(param1, param2):
        pass
    return inner2(inner1(param1),param2,param3)

It all comes down to

readability

consistency

maintainability

But -If your codebase is OOP, it violates consistency if suddenly some parts are written in a (more) functional style.


问:
Why do Haskell and Scheme use singly-linked lists?
A doubly linked list has minimal overhead (just another pointer per cell), and allows you to append to both ends and go back and forth and generally have a lot of fun.</p>

答:
Well, if you look a bit deeper, both actually include arrays in the base language as well:

The 5th revised Scheme Report (R5RS) includes the vector type, which are fixed-size integer-indexed collections with better than linear time for random access.

The Haskell 98 Report has an array type as well.

Functional programming instruction, however, has long emphasized single-linked lists over arrays or double-linked lists.  Quite likely overemphasized, in fact.  There are several reasons for it, however.

First one is that single-linked lists are one of the simplest and yet most useful recursive data types.  A user-defined equivalent of Haskell's list type can be defined like this:

```<code>data List a           -- A list with element type `a`...
  = Empty             -- is either the empty list...
  | Cell a (List a)   -- or a pair with an `a` and the rest of the list.
</code>```

The fact that lists are a recursive data type means that the functions that work on lists generally use structural recursion.  In Haskell terms: you pattern match on the list constructors, and you recurse on a subpart of the list.  In these two basic function definitions, I use the variable as to refer to the tail of the list.  So note that the recursive calls "descend" down the list:

```<code>map :: (a -> b) -> List a -> List b
map f Empty = Empty
map f (Cell a as) = Cell (f a) (map f as)

filter :: (a -> Bool) -> List a -> List a
filter p Empty = Empty
filter p (Cell a as)
    | p a = Cell a (filter p as)
    | otherwise = filter p as
</code>```

This technique guarantees that your function will terminate for all finite lists, and also is a good problem-solving technique—it tends to naturally splits problems into simpler, more tenable subparts.

So single-linked lists are probably the best data type to introduce students to these techniques, which are very important in functional programming.

The second reason is less of a "why single-linked lists" reason, but more of a "why not double-linked lists or arrays" reason: those latter data types often call for mutation (modifiable variables), which functional programming very often shies away from.  So as it happens:

In an eager language like Scheme you can't make a double-linked list without using mutation.

In a lazy language like Haskell you can make a double-linked list without using mutation.  But whenever you make a new list based off that one, you are forced to copy most if not all of the structure of the original.  Whereas with single-linked lists you can write functions that use "structure sharing"—new lists can reuse the cells of old lists when appropriate.

Traditionally, if you used arrays in an immutable manner it meant that every time you wanted to modify the array you had to copy the whole thing.  (Recent Haskell libraries like vector, however, have found techniques that greatly improve on this problem).

The third and final reason applies to lazy languages like Haskell primarily: lazy single-linked lists, in practice, are often more similar to iterators than to in-memory lists proper.  If your code is consuming the elements of a list sequentially and throwing them out as you go, the object code will only materialize the list cells and its contents as you step forward through the list.

This means that the whole list doesn't need to exist in memory at once, only the current cell.  Cells before the current one can be garbage collected (which wouldn't be possible with a double-linked list); cells later than the current one don't need to be computed until you get there.

It goes even further than that.  There's technique used in several popular Haskell libraries, called fusion, where the compiler analyzes your list-processing code and spots intermediate lists that are being generated and consumed sequentially and then "thrown away."  With this knowledge, the compiler can completely eliminate the memory allocation of those lists' cells.  This means that a single-linked list in a Haskell source program, after compilation, might actually get turned into a loop instead of a data structure.

Fusion is also the technique that the aforementioned vector library uses to generate efficient code for immutable arrays.  Same goes for the extremely popular bytestring (byte arrays) and text (Unicode strings) libraries, that were built as a replacement for Haskell's not-very-great native String type (which is the same as [Char], single-linked list of character).  So in modern Haskell there is a trend where immutable array types with fusion support are becoming very common.

List fusion is facilitated by the fact that in a single-linked list you can go forward but never backwards.  This brings up a very important theme in functional programming: using the "shape" of a data type to derive the "shape" of a computation.  If you want to process elements sequentially a single-linked list is a data type that, when you consume it with structural recursion, gives you that access pattern very naturally.  If you want to use a "divide and conquer" strategy to attack a problem, then tree data structures tend to support that very well.

A lot of people drop out of the functional programming wagon early on, so they get exposure to the single-linked lists but not to the more advanced underlying ideas.

Body:
Well, if you look a bit deeper, both actually include arrays in the base language as well:

The 5th revised Scheme Report (R5RS) includes the vector type, which are fixed-size integer-indexed collections with better than linear time for random access.

The Haskell 98 Report has an array type as well.

Functional programming instruction, however, has long emphasized single-linked lists over arrays or double-linked lists.  Quite likely overemphasized, in fact.  There are several reasons for it, however.

First one is that single-linked lists are one of the simplest and yet most useful recursive data types.  A user-defined equivalent of Haskell's list type can be defined like this:

data List a           -- A list with element type `a`...
  = Empty             -- is either the empty list...
  | Cell a (List a)   -- or a pair with an `a` and the rest of the list.

The fact that lists are a recursive data type means that the functions that work on lists generally use structural recursion.  In Haskell terms: you pattern match on the list constructors, and you recurse on a subpart of the list.  In these two basic function definitions, I use the variable as to refer to the tail of the list.  So note that the recursive calls "descend" down the list:

map :: (a -> b) -> List a -> List b
map f Empty = Empty
map f (Cell a as) = Cell (f a) (map f as)

filter :: (a -> Bool) -> List a -> List a
filter p Empty = Empty
filter p (Cell a as)
    | p a = Cell a (filter p as)
    | otherwise = filter p as

This technique guarantees that your function will terminate for all finite lists, and also is a good problem-solving technique—it tends to naturally splits problems into simpler, more tenable subparts.

So single-linked lists are probably the best data type to introduce students to these techniques, which are very important in functional programming.

The second reason is less of a "why single-linked lists" reason, but more of a "why not double-linked lists or arrays" reason: those latter data types often call for mutation (modifiable variables), which functional programming very often shies away from.  So as it happens:

In an eager language like Scheme you can't make a double-linked list without using mutation.

In a lazy language like Haskell you can make a double-linked list without using mutation.  But whenever you make a new list based off that one, you are forced to copy most if not all of the structure of the original.  Whereas with single-linked lists you can write functions that use "structure sharing"—new lists can reuse the cells of old lists when appropriate.

Traditionally, if you used arrays in an immutable manner it meant that every time you wanted to modify the array you had to copy the whole thing.  (Recent Haskell libraries like vector, however, have found techniques that greatly improve on this problem).

The third and final reason applies to lazy languages like Haskell primarily: lazy single-linked lists, in practice, are often more similar to iterators than to in-memory lists proper.  If your code is consuming the elements of a list sequentially and throwing them out as you go, the object code will only materialize the list cells and its contents as you step forward through the list.

This means that the whole list doesn't need to exist in memory at once, only the current cell.  Cells before the current one can be garbage collected (which wouldn't be possible with a double-linked list); cells later than the current one don't need to be computed until you get there.

It goes even further than that.  There's technique used in several popular Haskell libraries, called fusion, where the compiler analyzes your list-processing code and spots intermediate lists that are being generated and consumed sequentially and then "thrown away."  With this knowledge, the compiler can completely eliminate the memory allocation of those lists' cells.  This means that a single-linked list in a Haskell source program, after compilation, might actually get turned into a loop instead of a data structure.

Fusion is also the technique that the aforementioned vector library uses to generate efficient code for immutable arrays.  Same goes for the extremely popular bytestring (byte arrays) and text (Unicode strings) libraries, that were built as a replacement for Haskell's not-very-great native String type (which is the same as [Char], single-linked list of character).  So in modern Haskell there is a trend where immutable array types with fusion support are becoming very common.

List fusion is facilitated by the fact that in a single-linked list you can go forward but never backwards.  This brings up a very important theme in functional programming: using the "shape" of a data type to derive the "shape" of a computation.  If you want to process elements sequentially a single-linked list is a data type that, when you consume it with structural recursion, gives you that access pattern very naturally.  If you want to use a "divide and conquer" strategy to attack a problem, then tree data structures tend to support that very well.

A lot of people drop out of the functional programming wagon early on, so they get exposure to the single-linked lists but not to the more advanced underlying ideas.

ContentLicense: CC BY-SA 4.0


答:
I think #1 is actually a bad option.

Let's consider your function:

```<code>def the_public_method(self, param1, param2):
    self.var4 = param1
    self.var5 = param2
    self.var6 = param1 + param2 * self.var1
    self.__suboperation1()
    self.__suboperation2()
    self.__suboperation3()
</code>```

Which pieces of data does suboperation1 use? Does it collect data used by suboperation2? When you pass data around by storing it on self, I cannot tell how the pieces of functionality are related. When I look at self, some of the attributes are from the constructor, some from the call to the_public_method, and some randomly added in other places. In my opinion, its a mess.

What about number #2? Well, firstly, let's look at the second problem with it:

Also, the functions would be closely related to
  each other, but wouldn't be grouped together.

They would be in a module together, so they would totally be grouped together.

The problem I see with this is that I have to pass a lot of variables
  between functions.

In my opinion, this is good. This makes explicit the data dependencies in your algorithm. By storing them whether in global variables or on a self, you hide the dependencies and make them seem less bad, but they are still there.

Usually, when this situation arises, it means that you've not found the right way to decompose your problem. You are finding it awkward to split into multiple functions because you are trying to split it the wrong way.

Of course, without seeing your actual function its hard to guess at what would be a good suggestion. But you give a bit of hint of what you are dealing with here:

My program needs to do a relatively complex operation a number of
  times. That operation requires a lot of "bookkeeping", has to create
  and delete some temporary files etc.

Let me pick an example of something that sorta fits your description, an installer. An installer has to copy a bunch of files, but if you cancel it part way through, you need to rewind the whole process including putting back any files that you replaced. The algorithm for this looks something like:

```<code>def install_program():
    copied_files = []
    try:
        for filename in FILES_TO_COPY:
           temporary_file = create_temporary_file()
           copy(target_filename(filename), temporary_file)
           copied_files = [target_filename(filename), temporary_file)
           copy(source_filename(filename), target_filename(filename))
     except CancelledException:
        for source_file, temp_file in copied_files:
            copy(temp_file, source_file)
     else:
        for source_file, temp_file in copied_files:
            delete(temp_file)
</code>```

Now multiply that logic out for having to do registry settings, program icons, etc, and you've got quite a mess.

I think that your #1 solution looks like:

```<code>class Installer:
    def install(self):
        try:
            self.copy_new_files()
        except CancellationError:
            self.restore_original_files()
        else:
            self.remove_temp_files()
</code>```

This does make the overall algorithm clearer, but it hides the way the different pieces communicate.

Approach #2 looks something like:

```<code>def install_program():
    try:
       temp_files = copy_new_files()
    except CancellationError as error:
       restore_old_files(error.files_that_were_copied)
    else:
       remove_temp_files(temp_files)
</code>```

Now its explicit how pieces of the data move between functions, but it is very awkward.

So how should this function be written?

```<code>def install_program():
    with FileTransactionLog() as file_transaction_log:
         copy_new_files(file_transaction_log)
</code>```

The FileTransactionLog object is a context manager. When copy_new_files copies a file it does it through the FileTransactionLog which handles making the temporary copy and keep track of which files have been copied. In the case of exception it copies the original files back, and in the case of success it deletes the temporary copies.

This works because we've found a more natural decomposition of the task. Previously, we were intermixing the logic about how to install the application with the logic about how to recover a cancelled install. Now the transaction log handles all of the details about temporary files and bookkeeping, and the function can focus on the basic algorithm.

I suspect that your case is in the same boat. You need to extract out the bookkeeping elements into some sort of object so that your complex task can expressed more simply and elegantly.

Body:
I think #1 is actually a bad option.

Let's consider your function:

def the_public_method(self, param1, param2):
    self.var4 = param1
    self.var5 = param2
    self.var6 = param1 + param2 * self.var1
    self.__suboperation1()
    self.__suboperation2()
    self.__suboperation3()

Which pieces of data does suboperation1 use? Does it collect data used by suboperation2? When you pass data around by storing it on self, I cannot tell how the pieces of functionality are related. When I look at self, some of the attributes are from the constructor, some from the call to the_public_method, and some randomly added in other places. In my opinion, its a mess.

What about number #2? Well, firstly, let's look at the second problem with it:

Also, the functions would be closely related to
  each other, but wouldn't be grouped together.

They would be in a module together, so they would totally be grouped together.

The problem I see with this is that I have to pass a lot of variables
  between functions.

In my opinion, this is good. This makes explicit the data dependencies in your algorithm. By storing them whether in global variables or on a self, you hide the dependencies and make them seem less bad, but they are still there.

Usually, when this situation arises, it means that you've not found the right way to decompose your problem. You are finding it awkward to split into multiple functions because you are trying to split it the wrong way.

Of course, without seeing your actual function its hard to guess at what would be a good suggestion. But you give a bit of hint of what you are dealing with here:

My program needs to do a relatively complex operation a number of
  times. That operation requires a lot of "bookkeeping", has to create
  and delete some temporary files etc.

Let me pick an example of something that sorta fits your description, an installer. An installer has to copy a bunch of files, but if you cancel it part way through, you need to rewind the whole process including putting back any files that you replaced. The algorithm for this looks something like:

def install_program():
    copied_files = []
    try:
        for filename in FILES_TO_COPY:
           temporary_file = create_temporary_file()
           copy(target_filename(filename), temporary_file)
           copied_files = [target_filename(filename), temporary_file)
           copy(source_filename(filename), target_filename(filename))
     except CancelledException:
        for source_file, temp_file in copied_files:
            copy(temp_file, source_file)
     else:
        for source_file, temp_file in copied_files:
            delete(temp_file)

Now multiply that logic out for having to do registry settings, program icons, etc, and you've got quite a mess.

I think that your #1 solution looks like:

class Installer:
    def install(self):
        try:
            self.copy_new_files()
        except CancellationError:
            self.restore_original_files()
        else:
            self.remove_temp_files()

This does make the overall algorithm clearer, but it hides the way the different pieces communicate.

Approach #2 looks something like:

def install_program():
    try:
       temp_files = copy_new_files()
    except CancellationError as error:
       restore_old_files(error.files_that_were_copied)
    else:
       remove_temp_files(temp_files)

Now its explicit how pieces of the data move between functions, but it is very awkward.

So how should this function be written?

def install_program():
    with FileTransactionLog() as file_transaction_log:
         copy_new_files(file_transaction_log)

The FileTransactionLog object is a context manager. When copy_new_files copies a file it does it through the FileTransactionLog which handles making the temporary copy and keep track of which files have been copied. In the case of exception it copies the original files back, and in the case of success it deletes the temporary copies.

This works because we've found a more natural decomposition of the task. Previously, we were intermixing the logic about how to install the application with the logic about how to recover a cancelled install. Now the transaction log handles all of the details about temporary files and bookkeeping, and the function can focus on the basic algorithm.

I suspect that your case is in the same boat. You need to extract out the bookkeeping elements into some sort of object so that your complex task can expressed more simply and elegantly.


答:
Since the only apparent drawback of method 1 is its suboptimal usage pattern, I think the best solution is to drive encapsulation one step further: Use a class, but also provide a free standing function, that only constructs the object, calls the method and returns:

```<code>def publicFunction(var1, var2, param1, param2)
    thing = Thing(var1, var2)
    thing.theMethod(param1, param2)
</code>```

With that, you have the smallest possible interface to your code, and the class that you use internally really becomes just an implementation detail of your public function. Calling code never needs to know about your internal class.

Body:
Since the only apparent drawback of method 1 is its suboptimal usage pattern, I think the best solution is to drive encapsulation one step further: Use a class, but also provide a free standing function, that only constructs the object, calls the method and returns:

def publicFunction(var1, var2, param1, param2)
    thing = Thing(var1, var2)
    thing.theMethod(param1, param2)

With that, you have the smallest possible interface to your code, and the class that you use internally really becomes just an implementation detail of your public function. Calling code never needs to know about your internal class.


答:
I guess your best shot is to bring the full code base under your control, and make sure you have an overview about the modules and their dependencies.

So at least you have a chance of doing global searches, and have a chance to add regression tests for the parts of the system where you expect an impact by a code change.

If you do not see a chance to accomplish the first, my best advice is: do not refactor any modules which are reused by other modules, or for which you do not know that others rely on them. In any codebase of a reasonable size the chances are high you can find modules on which no other module depends. So if you have a mod A depending on B, but not vice versa, and no other module depends on A, even in a dynamically scoped language, you can make changes to A without breaking B or any other modules.

This gives you a chance to replace the dependency of A to B by a dependency of A to B2, where B2 is a sanitized, rewritten version of B. B2 should be a newly written with the rules in mind you mentioned above to make the code more evolvable and easier to refactor.

Title: How do you safely refactor in a language with dynamic scope?

Body:
For those of you who have the good fortune not to work in a language with dynamic scope, let me give you a little refresher on how that works. Imagine a pseudo-language, called "RUBELLA", that behaves like this:

```<code>function foo() {
    print(x); // not defined locally => uses whatever value `x` has in the calling context
    y = "tetanus";
}
function bar() {
    x = "measles";
    foo();
    print(y); // not defined locally, but set by the call to `foo()`
}
bar(); // prints "measles" followed by "tetanus"
</code>```

That is, variables propagate up and down the call stack freely - all variables defined in foo are visible to (and mutatable by) its caller bar, and the reverse is also true. This has serious implications for code refactorability. Imagine that you have the following code:

```<code>function a() { // defined in file A
    x = "qux";
    b();
}
function b() { // defined in file B
    c();
}
function c() { // defined in file C
    print(x);
}
</code>```

Now, calls to a() will print qux. But then, someday, you decide that you need to change b a little bit. You don't know all the calling contexts (some of which may in fact be outside your codebase), but that should be alright - your changes are going to be completely internal to b, right? So you rewrite it like this:

```<code>function b() {
    x = "oops";
    c();
}
</code>```

And you might think that you haven't changed anything, since you've just defined a local variable. But, in fact, you've broken a! Now, a prints oops rather than qux.

Bringing this back out of the realm of pseudo-languages, this is exactly how MUMPS behaves, albeit with different syntax.

Modern ("modern") versions of MUMPS include the so-called NEW statement, which allows you to prevent variables from leaking from a callee to a caller. So in the first example above, if we had done NEW y = "tetanus" in foo(), then print(y) in bar() would print nothing (in MUMPS, all names point to the empty string unless explicitly set to something else). But there is nothing that can prevent variables from leaking from a caller to a callee: if we have function p() { NEW x = 3; q(); print(x); }, for all we know, q() could mutate x, despite not explicitly receiving x as a parameter. This is still a bad situation to be in, but not as bad as it probably used to be.

With these dangers in mind, how can we safely refactor code in MUMPS or any other language with dynamic scoping?

There are some obvious good practices for making refactoring easier, like never using variables in a function other than those you initialize (NEW) yourself or are passed as an explicit parameter, and explicitly documenting any parameters that are implicitly passed from a function's callers. But in a decades-old, ~108-LOC codebase, these are luxuries one often does not have.

And, of course, essentially all good practices for refactoring in languages with lexical scope are also applicable in languages with dynamic scope - write tests, and so forth. The question, then, is this: how do we mitigate the risks specifically associated with the increased fragility of dynamically-scoped code when refactoring?

(Note that while How do you navigate and refactor code written in a dynamic language? has a similar title to this question, it is wholly unrelated.)


问:
Licensing for artistic work used inside GPLv3 licensed software
I'm a volunteer for a non-profit organization and am helping them develop a free open source Android application that will be licensed under GPLv3.

We are going to use the logo and some other graphics files from the organization and are wanting to use licensing of this artistic work to protect ourselves from anyone doing damage to the reputation of the organization.

What license would you suggest us using for our artistic work? Thinking outside of the box, is there another approach that would be better for us? Any thoughts more in general about what we can do to protect the organization?

答:
For copyright purposes, the code of an application and the resources (images, sounds, etc.) used by the application are considered to be separate works. This means that they can have completely separate license terms.

For your Android app, you can license the code under GPLv3 and the logos under a non-free license that disallows inappropriate use.

However, writing up a copyright license that allows only certain uses of a protected work is very hard to get right, even for a specialized lawyer. Another path, and possibly an easier one, to protect the image of the organisation is to register the logo (and possibly other graphics) as a trademark for the organisation.

Under trademark law, you can put more restrictions on how the logo gets used and it is completely separated from the copyright on the logo/artwork.


问:
How can I get an anonymous user to submit bugs on a private GitHub project?
Our company has a private GitHub repository for the project I'm working on.  After a full summer of work, it looks like we'll be launching this week (wheee!).  However, I want to include a "submit a bug" link in the program that leads to a form somewhere where the user can fill out a form that becomes an issue for us on GitHub.  Googling around hasn't found any solution (or someone who has the same problem).

Is this possible (through some API, perhaps?) or will I have to manually enter the bugs my users report?

答:
Someone on reddit created an open source Project called Gitreports where you can sign up and it will give you a unique URL you can give to your clients and they can submit bugs even to private repos without ever seeing code.

If this seems shady to you, you can host it yourself


问:
C: How does struct node * next work?
In C, for creating linked list we write:

```<code>struct Node{
int data;
struct Node* next;
};
</code>```

So, my understanding is "struct Node* next" is a pointer variable of "Node" datatype.
But how does it point to the next node in a linked list?

答:
Your code is just a small piece of a linked list.

The idea is that your list consists of n occurrences of the struct you called "Node".
You need a pointer to the FIRST of them, this pointer tells you the memory location of this first struct (you usually request the space for this manually with malloc). The structure of this memory block is defined by your struct "Node". It tells you that first there are some bytes for the int (sizeof int tells you how mutch) and then there are some bytes for a address (this is your pointer "next").
On the last Item of your linked list u usually use null as value for next, this way you can check if your active item is the last.
To add a Item to your list u have to malloc the memory for it and change the next pointer of the last item to the memory location malloc gave out. (And dont forget to set the next pointer of the item you just created to null.)

This way a linked list works. Hope this helps a little bit!

Title: C: How does struct node * next work?


答:
This is part of a type definition.  It in and of itself doesn't point to anything, for the same reason that you can't put a real couch and TV inside of a living room drawn on a set of blueprints for a house.  It simply specifies "this is what's supposed to go here."

The way it points to the next node in a linked list is that when someone actually creates the nodes, they assign a value to the field described by that definition, which is a pointer that contains the address of another Node.

Title: C: How does struct node * next work?

Body:
In C, for creating linked list we write:

```<code>struct Node{
int data;
struct Node* next;
};
</code>```

So, my understanding is "struct Node* next" is a pointer variable of "Node" datatype.
But how does it point to the next node in a linked list?


问:
CRUD API: How do you specify which fields to update?
Let's say you have some kind of data structure, which is persisted in some kind of database. For simplicity, let's call this data structure Person. You are now tasked to design a CRUD API, which allows other applications to create, read, update and delete Persons. For simplicity, let's assume that this API is accessed via some kind of web service.

For the C, R and D parts of CRUD, the design is simple. I'll use C#-like functional notation - the implementation could be SOAP, REST/JSON, or something else:

```<code>class Person {
    string Name;
    DateTime? DateOfBirth;
    ...
}

Identifier CreatePerson(Person);
Person GetPerson(Identifier);
void DeletePerson(Identifier);
</code>```

What about update? The natural thing to do would be

```<code>void UpdatePerson(Identifier, Person);
</code>```

but how would you specify which fields of Person to update?

Solutions that I could come up with:

You could always require a complete Person to be passed, i.e. the client would do something like this to update the date of birth:

```<code>p = GetPerson(id);
p.DateOfBirth = ...;
UpdatePerson(id, p);
</code>```

However, that would require some sort of transactional consistency or locking between the Get and the Update; otherwise, you could overwrite some other change done in parallel by some other client. This would make the API much more complicated. In addition, it's error prone, since the following pseudo-code (assuming a client language with JSON support)

```<code>UpdatePerson(id, { "DateOfBirth": "2015-01-01" });
</code>```

-- which looks correct -- would not only change DateOfBirth but also reset all other fields to null.

You could ignore all fields that are null. However, how would you then make a difference between not changing DateOfBirth and deliberately changing it to null?

Change the signature to void UpdatePerson(Identifier, Person, ListOfFieldNamesToUpdate).

Change the signature to void UpdatePerson(Identifier, ListOfFieldValuePairs).

Use some feature of the transmission protocol: For example, you could ignore all fields not contained in the JSON representation of the Person. However, that usually requires parsing the JSON yourself and not being able to use the built-in features of your library (e.g. WCF).

None of the solutions seems really elegant to me. Surely, this is a common problem, so what is the best-practice solution used by everybody?

答:
If you don't have tracking of changes as requirement on this object (e.g. "User John changed name and birth date"), simplest would be to override whole object in DB with one you receive from consumer. This approach would involve slightly more data being send through wire, but you are avoiding read before update.

If you have activity tracking requirement. Your world is much more complicated and you will need to design how to store information about CRUD actions and how to intercept them. That is the world you don't want to dive into if you don't have such requirement.

As per overriding values by separate transactions, I would suggest to do research around optimistic and pessimistic locking. They mitigate this common scenario:

Object is read by user1

Object is read by user2

Object written by user1

Object written by user2 and overwritten changes by user1

Each user has different transaction, therefore standard SQL with this. Most common is optimistic locking (also mentioned by @SJuan76 in comment about versions). Your version your record in DB and during write you first take a look into DB if versions match. If versions don't match, you know somebody updated the object in the meantime, and you need to response with error message to consumer about this situation. Yes, you have to show this situation to user.

Notice that you need to read actual record from DB before writing it (for optimistic locking version comparison), so implementing delta logic (write only changed values) may not require additional read query before write.

Putting in delta logic highly depends on contract with consumer, but notice that easiest for consumer is to construct full payload instead of delta also.


问:
How can I go about testing this javascript?
I'm working on a project that has me responsible for testing out some software that scrapes a web-page representing an input form, and generates a mobile friendly version of that page. This is particularly useful for form data, since not all websites have mobile-enabled browsers, and the aim of this project is to ultimately take these mobile-unfriendly pages, do some parsing on them, and then create a mobile-friendly version of said web-pages.

The code responsible for generating these mobile-friendly documents is more or less in javascript, which is the most untested portion of our code base. I want to find a way to test this code, and an idea came up amongst the team to see if there is some way to "record" a user's interaction with a web-site to disk such that locally, on the file system, there will be a series of N web-pages, each linking to one another on the file system. This way, we can generate test data rather easily for our project. There are several types of forms that we have to handle, such as forms that span across different web-pages, forms that have some javascript to hide aways certain fields, etc...

I'm not at all a web-developer; I'm more of a backend engineer. I think the greater goal we have is to find a way to test javascript that depends on the existence of specific types of forms; this latest requirement I have sort of grew out of that. Getting to the point, I have a couple of questions:

1) Is the creation and maintenance of this tool even a good idea? It would help create test data trivially assuming this was a browser plugin, but something about it seems kinda off to me.

2) What is the best way to do what I need to do, which is to find a way to test out some parser-javascript?

答:
Try creating an HTML file, and adding your javascript between the "script" tags.
See Below:</p>

```<code><!DOCTYPE>
            <HTML>
            <HEAD><H1>Hello!</H1></HEAD>
            <TITLE>My Website</TITLE>
            <BODY>
               <H5><I>My Junk</I></H5>
               <img src="1430639373_website.png"/>
               <p>I'm a programmer that programs in C, Python, and a little HTML, and I am learning Java programming.</p>
               <p>I'm a musician</p>
               <p>I'm a <i>Christian</i> first and foremost!</p>
               <p><a href="https://www.google.com/">My Email Address Provider</a></p>
               <P>I'm an American<P>

            </BODY>
            <SCRIPT>
               document.write("Welcome new user!\n");
               var name=prompt("What is your name?");
               document.write("\nWelcome ",name);
            </SCRIPT>

            </HTML>
</code>```

Body:
Try creating an HTML file, and adding your javascript between the "script" tags.
See Below:

<!DOCTYPE>
            <HTML>
            <HEAD><H1>Hello!</H1></HEAD>
            <TITLE>My Website</TITLE>
            <BODY>
               <H5><I>My Junk</I></H5>
               <img src="1430639373_website.png"/>
               <p>I'm a programmer that programs in C, Python, and a little HTML, and I am learning Java programming.</p>
               <p>I'm a musician</p>
               <p>I'm a <i>Christian</i> first and foremost!</p>
               <p><a href="https://www.google.com/">My Email Address Provider</a></p>
               <P>I'm an American<P>

            </BODY>
            <SCRIPT>
               document.write("Welcome new user!\n");
               var name=prompt("What is your name?");
               document.write("\nWelcome ",name);
            </SCRIPT>

            </HTML>


问:
What approach in DataMapper Pattern is better for multiple or joined tables?
Normally, a Data Mapper maps data of one particular table. (Theoretically it should be communicating between Storage and a Domain Object, but its not possible in my case, so I am directly communicating with tables.)

Table1Mappper > Table1

But if that table requires data to be joined from another table, then you are expanding the scope of your Data Mapper which was only suppose to mapping from one table.

Table1Mapper > Table1 :inner-join: Table2

Wouldn't it be better if Table2 had its own mapper Table2Mapper to maps its data?

If you think Yes, then if you want to show a list of records from Table1Mapper and then later use Table2Mapper to get those data that were supposed to be joined, You are going to running a query in a loop, which is not good either.

What are you insights on this way?

Another way is to change your mapper to handle sub tables?

```<code>class Table1Mapper {
    public main_table = 'table1';
    public sub_table1 = 'table2';
}
</code>```

Which I think is fine, but only until the scope of the entire mapper is dealing one particular entity in the application. For example post and post_author. But if the scope is different like post and gallery, the above will not give a ideal data mapper. To illustrate this

```<code>class PostMapper {
     public table_name = 'tbl_post';
     public gallery_table_name = 'tbl_gallery';
}
</code>```

Is not correct is it? But however you would want to grab the galleries of one post in one query though, because adding an overhead of query in a loop is not a good solution performance.

What do you think is the right way to solve this in DataMapper Pattern / or any other pattern if it has better way of handling such cases?

答:
By Data Mapper you mean one described by Martin Fowler, right? It is one of Data Source Architectural Patterns patterns. Others are:

Table Data Gateway

Row Data Gateway

Active Record

Data Mapper differs from other patterns with regard to relationship between objects and tables. Both Data Gateway patterns and Active Record pattern assume almost one to one mapping from tables to objects.

Let's take a look at an example:

```<code>table BANK_ACCOUNT
   ID

table BANK_ACCOUNT_BALANCE
   ID
   BANK_ACCOUNT_ID
   BALANCE_AMOUNT
   DATE
</code>```

Domain objects are then:

```<code>class BankAccount {
    long id;
}

class BankAccountBalance {
    long id;
    long bankAccountId;
    Decimal balanceAmount;
    Date date;
}
</code>```

As you see one to one mapping between classes and tables. There are also two different Table/Row Data Gateways or Active Records - one for each table.

In contrast, Data Mapper allows for indirection:

A layer of Mappers (473) that moves data between objects and a database while keeping them independent of each other and the mapper itself.

So when you are using Data Mapper your objects can differ from database tables. You are free to introduce aggregation, joins with other tables, perform arithmetical operations, introduce inheritance hierarchies. So answering your question - it is perfectly fine to join two tables in Data Mapper as long as the result object is valid domain object.

In our example we could have:

```<code>class BankAccount {
    long id;
    Decimal latestBalance;
    Date latestBalanceDate;
}
</code>```

as domain object returned by single Data Mapper based on JOIN and aggregation.

Therefore, Data Mapper is perfect for representing non-trivial domain model. If your domain model is rather simple you might consider using Active Record pattern or Data Gateways.

Need for JOINs Data Mapper might sometimes (but not must) indicate that domain class is too complex. Please check Single Responsibility Principle, Interface Segregation Principle.

In Domain-Driven Design domain classes (i.e. returned by Data Mapper) take form of entities or value objects. DDD book pretty well describes what should an entity comprise of. You might want to check this out.

Additionally DDD defines Aggregates (pretty well described here). They are often loaded together. Joining two tables might suggest that there are two entities in single aggregate.

Body:
By Data Mapper you mean one described by Martin Fowler, right? It is one of Data Source Architectural Patterns patterns. Others are:

Table Data Gateway

Row Data Gateway

Active Record

Data Mapper differs from other patterns with regard to relationship between objects and tables. Both Data Gateway patterns and Active Record pattern assume almost one to one mapping from tables to objects.

Let's take a look at an example:

table BANK_ACCOUNT
   ID

table BANK_ACCOUNT_BALANCE
   ID
   BANK_ACCOUNT_ID
   BALANCE_AMOUNT
   DATE

Domain objects are then:

class BankAccount {
    long id;
}

class BankAccountBalance {
    long id;
    long bankAccountId;
    Decimal balanceAmount;
    Date date;
}

As you see one to one mapping between classes and tables. There are also two different Table/Row Data Gateways or Active Records - one for each table.

In contrast, Data Mapper allows for indirection:

A layer of Mappers (473) that moves data between objects and a database while keeping them independent of each other and the mapper itself.

So when you are using Data Mapper your objects can differ from database tables. You are free to introduce aggregation, joins with other tables, perform arithmetical operations, introduce inheritance hierarchies. So answering your question - it is perfectly fine to join two tables in Data Mapper as long as the result object is valid domain object.

In our example we could have:

class BankAccount {
    long id;
    Decimal latestBalance;
    Date latestBalanceDate;
}

as domain object returned by single Data Mapper based on JOIN and aggregation.

Therefore, Data Mapper is perfect for representing non-trivial domain model. If your domain model is rather simple you might consider using Active Record pattern or Data Gateways.

Need for JOINs Data Mapper might sometimes (but not must) indicate that domain class is too complex. Please check Single Responsibility Principle, Interface Segregation Principle.

In Domain-Driven Design domain classes (i.e. returned by Data Mapper) take form of entities or value objects. DDD book pretty well describes what should an entity comprise of. You might want to check this out.

Additionally DDD defines Aggregates (pretty well described here). They are often loaded together. Joining two tables might suggest that there are two entities in single aggregate.


答:
Whether or not to re-invent the wheel is a cost/benefit thing. Costs are fairly obvious...

It takes a lot of time to do the reinventing.

It takes even more time to document what you have invented.

You cannot hire people who already understand what you have invented.

It is all too easy to reinvent something badly, causing ongoing costs for the problems caused by the bad design.

New code means new bugs. Old code has usually had most bugs removed already, and may have subtle workarounds to issues you're not aware of and therefore cannot work around in the new design.

The last is important - there's a blog post somewhere warning about the tendency to "throw the old code away and start from scratch" on the basis that a lot of the old cruft you don't understand is actually essential bugfixes. There's a cautionary tale about Netscape, IIRC.

The advantages can be...

The ability to add features that existing libraries don't have. For example, I have containers that "maintain" their iterator/cursor instances. Insertions and deletions don't invalidate iterators. An iterator pointing into a vector will continue to point to the same item (not the same index) irrespective of inserts and deletes earlier in the vector. You simply cannot do that with standard C++ containers.

A more specialised design targeting your particular requirements and respecting your priorities (but beware the tendency toward the inner-platform effect).

Complete control - some third party cannot decide to redesign the API in a way that means you have to rewrite half your application.

Complete understanding - you have designed it that way, so you hopefully fully understand how and why you did so.

EDIT You can learn the lessons from other libraries without being caught in the same traps by being selective about how you imitate them.

One thing - using a third-party library can count as reinventing the wheel. If you already have your own ancient, well used, well tested library, think carefully before discarding it to use a third-party library instead. It may well be a good idea in the long run - but there can be a huge amount of work and a lot of nasty surprises (from subtle semantic differences between the libraries) before you get there. For example, consider the effect of me switching from my own containers to standard library ones. A naive translation of calling code wouldn't allow for the fact that the standard library containers don't maintain their iterators. Cases where I save an iterator for later as a "bookmark" couldn't be implemented using a simple translation at all - I'd need some non-trivial alternative means of indicating bookmark positions.

Title: Is reinventing the wheel really all that bad?

Body:
Its common knowledge in programming that reinventing the wheel is bad or evil.

But why is that?

I am not suggesting that it's good. I believe it to be wrong. However, I once read an article that said, if someone is doing something wrong (programming wise) explain to them why its wrong, if you can't, then maybe you should be asking yourself if it is really wrong.

That leads me to this question:

If I see someone is clearly reinventing the wheel by building their own method of something that is already built into the language/framework. First, for arguments sake, lets assume that their method is just as efficient as the built in method. Also the developer, aware of the built in method, prefers his own method.

Why should he use the built in one over his own?


问:
MEAN stack -- express?
I've been a rails developer for a bit now, and I've started to get into the MEAN stack through a tutorial.

I kinda understand Angular and Node and the purposes they both serve, but I'm not sure I get express yet. Does rails do all of these things in the background?

My understanding:

Angular is does most of your views, routing, etc.
Node is your webserver.

Am I not getting those either?

答:
I am not familiar with Rails, but I believe it uses server side HTML templating (injecting variables into HTML code). Angular uses client side templating. So there is paradigm shift which is probably confusing you.

Angular is best suited for so called Single Page Applications, which does all the routing and templating on client without need for full refresh of the site. Your back-end is just CRUD layer (most commonly REST) which is called via AJAX from client.

If you are used to Rails Rapid development, look into Loopback framework. It's framework for creating REST APIs on stereoids. It is using Express under the hood and is created by company StrongLoop, which also maintains Express project itself now.

Title: MEAN stack -- express?


答: We have a PHP API at work. For updates if a field isn't sent in the JSON object it gets set to NULL. Then it passes everything to the stored procedure. The stored procedure attempts to update every field with field = IFNULL(input, field). So if just 1 field is in the JSON object only that field is updated. To explicitly empty a set field we have to have field = '', the DB then updates the field with either empty string or the default value of that column.</p>

Title: CRUD API: How do you specify which fields to update?

Body:
Let's say you have some kind of data structure, which is persisted in some kind of database. For simplicity, let's call this data structure Person. You are now tasked to design a CRUD API, which allows other applications to create, read, update and delete Persons. For simplicity, let's assume that this API is accessed via some kind of web service.

For the C, R and D parts of CRUD, the design is simple. I'll use C#-like functional notation - the implementation could be SOAP, REST/JSON, or something else:

```<code>class Person {
    string Name;
    DateTime? DateOfBirth;
    ...
}

Identifier CreatePerson(Person);
Person GetPerson(Identifier);
void DeletePerson(Identifier);
</code>```

What about update? The natural thing to do would be

```<code>void UpdatePerson(Identifier, Person);
</code>```

but how would you specify which fields of Person to update?

Solutions that I could come up with:

You could always require a complete Person to be passed, i.e. the client would do something like this to update the date of birth:

```<code>p = GetPerson(id);
p.DateOfBirth = ...;
UpdatePerson(id, p);
</code>```

However, that would require some sort of transactional consistency or locking between the Get and the Update; otherwise, you could overwrite some other change done in parallel by some other client. This would make the API much more complicated. In addition, it's error prone, since the following pseudo-code (assuming a client language with JSON support)

```<code>UpdatePerson(id, { "DateOfBirth": "2015-01-01" });
</code>```

-- which looks correct -- would not only change DateOfBirth but also reset all other fields to null.

You could ignore all fields that are null. However, how would you then make a difference between not changing DateOfBirth and deliberately changing it to null?

Change the signature to void UpdatePerson(Identifier, Person, ListOfFieldNamesToUpdate).

Change the signature to void UpdatePerson(Identifier, ListOfFieldValuePairs).

Use some feature of the transmission protocol: For example, you could ignore all fields not contained in the JSON representation of the Person. However, that usually requires parsing the JSON yourself and not being able to use the built-in features of your library (e.g. WCF).

None of the solutions seems really elegant to me. Surely, this is a common problem, so what is the best-practice solution used by everybody?


问:
Why is mergesort O(log n)?
Mergesort is a divide and conquer algorithm and is O(log n) because the input is repeatedly halved. But shouldn't it be O(n) because even though the input is halved each loop, each input item needs to be iterated on to do the swapping in each halved array? This is essentially asymptotically O(n) in my mind. If possible please provide examples and explain how to count the operations correctly! I haven't coded anything up yet but I've been looking at algorithms online. I've also attached a gif of what wikipedia is using to visually show how mergesort works.

答:
It's O(n * log(n)), not O(log(n)). As you've accurately surmised, the entire input must be iterated through, and this must occur O(log(n)) times (the input can only be halved O(log(n)) times). n items iterated log(n) times gives O(n log(n)).

It's been proven that no comparison sort can operate faster than this. Only sorts that rely on a special property of the input such as radix sort can beat this complexity. The constant factors of mergesort are typically not that great though so algorithms with worse complexity can often take less time.

Title: Why is mergesort O(log n)?


问:
Why should I use "functional operations" instead of a for loop?
```<code>for (Canvas canvas : list) {
}
</code>```

NetBeans suggests me to use "functional operations":

```<code>list.stream().forEach((canvas) -> {
});
</code>```

But why is this preferred? If anything, it is harder to read and understand. You are calling stream(), then forEach() using a lambda expression with parameter canvas. I don't see how is that any nicer than the for loop in the first snippet.

Obviously I am speaking out of aesthetics only. Perhaps there is a technical advantage here that I am missing. What is it? Why should I use the second method instead?

答:
Streams provide much better abstraction for composition of different operations you want to do on top of collections or streams of data coming in. Especially when you need to map elements, filter and convert them.

Your example is not very practical. Consider the following code from Oracle's site.

```<code>List<Transaction> groceryTransactions = new Arraylist<>();
for(Transaction t: transactions){
    if(t.getType() == Transaction.GROCERY){
        groceryTransactions.add(t);
    }
}
Collections.sort(groceryTransactions, new Comparator(){
    public int compare(Transaction t1, Transaction t2){
        return t2.getValue().compareTo(t1.getValue());
    }
});
List<Integer> transactionIds = new ArrayList<>();
for(Transaction t: groceryTransactions){
    transactionsIds.add(t.getId());
}
</code>```

can be written using streams:

```<code>List<Integer> transactionsIds =
    transactions.stream()
                .filter(t -> t.getType() == Transaction.GROCERY)
                .sorted(comparing(Transaction::getValue).reversed())
                .map(Transaction::getId)
                .collect(toList());
</code>```

The second option is much more readable. So when you have nested loops or various loops doing partial processing, it's very good candidate for Streams/Lambda API usage.

Body:
Streams provide much better abstraction for composition of different operations you want to do on top of collections or streams of data coming in. Especially when you need to map elements, filter and convert them.

Your example is not very practical. Consider the following code from Oracle's site.

List<Transaction> groceryTransactions = new Arraylist<>();
for(Transaction t: transactions){
    if(t.getType() == Transaction.GROCERY){
        groceryTransactions.add(t);
    }
}
Collections.sort(groceryTransactions, new Comparator(){
    public int compare(Transaction t1, Transaction t2){
        return t2.getValue().compareTo(t1.getValue());
    }
});
List<Integer> transactionIds = new ArrayList<>();
for(Transaction t: groceryTransactions){
    transactionsIds.add(t.getId());
}

can be written using streams:

List<Integer> transactionsIds =
    transactions.stream()
                .filter(t -> t.getType() == Transaction.GROCERY)
                .sorted(comparing(Transaction::getValue).reversed())
                .map(Transaction::getId)
                .collect(toList());

The second option is much more readable. So when you have nested loops or various loops doing partial processing, it's very good candidate for Streams/Lambda API usage.


答: Another advantage of using the functional streaming API is, that it hides implementation details. It only describes what should be done, not how. This advantage becomes obvious when looking at the change that needs to be done, to change from single threaded to parallel code execution. Just change the .stream() to .parallelStream().

Title: Why should I use "functional operations" instead of a for loop?

Body:
```<code>for (Canvas canvas : list) {
}
</code>```

NetBeans suggests me to use "functional operations":

```<code>list.stream().forEach((canvas) -> {
});
</code>```

But why is this preferred? If anything, it is harder to read and understand. You are calling stream(), then forEach() using a lambda expression with parameter canvas. I don't see how is that any nicer than the for loop in the first snippet.

Obviously I am speaking out of aesthetics only. Perhaps there is a technical advantage here that I am missing. What is it? Why should I use the second method instead?


答:
Why Design when I can be Coding?

I offer a contrarian view to the answers I've read. From that perspective all the answers and frankly even the question itself focus on coding mechanics. But this is a design issue.

Should I create a class if my function is complex and has a lot of variables?

Yes, as it makes sense for your design. It may be a class unto itself or part of some other class or it's behavior may be distributed among classes.

Object Oriented Design is about Complexity

The point of OO is to successfully build and maintain large, complex systems by encapsulating the code in terms of the system itself. "Proper" design says everything is in some class.

OO design naturally manages complexity primarily via focused classes that adhere to the single responsibility principle. These class give structure and functionality throughout the breath and depth of the system, interact and integrate these dimensions.

Given that, it is often said that functions dangling about the system - the all too ubiquitous general utility class - is a code smell suggesting an insufficient design. I tend to agree.