答:
You can make this more efficient by developing a specialised data structure. Let X' be a pair (D,S) where D is a dictionary and S is a set.  It corresponds to the dictionary X of your example by the following substitutions:

there is no keys bound to 0 in D

if a key is bound in D then X' behaves as if it were X and that binding were also in X

if a key is not bound in D but in S then X' behaves as if it were X and that key were bound to 0 in X.

You can define the lookup and update operations as.

```<code> lookup(key):
   if key is bound in D then D[key] elseif key is in S then 0 else Not_found

 update(U):
   set D to U
   add all keys bound in U to S
</code>```

If U is quite small, this will improve the performance: if your dictionary X is implemented with a hashtable and grows very large, you have many hash collisions and lookup time behaves as O(N).  With X' key lookup is O(size(U)) + O(log N) which becomes O(log N) if the size of U is bounded.

Title: Efficient solution for dictionary updates

Body:
Let's start with the problem:

There is a large dictionary X that contains {key, value} pairs, i.e.:

```<code>X = [{100, 10}, {101, 0}, {103, 0}, {106, 2}, {110, 1}]
</code>```

Every t seconds, X has to be updated with values from sub dictionary U and 0 set to each value for a key that is not present in new updated U, but was in the previous update.

The most important requirements is, that an update has to be performed in such a way, that the minimum number of update operations of each {key, value} pair in dictionary X have been performed, ie.

X updated by U where

```<code>U = [{100, 10}, {102, 5}, {103, 0}, {105, 1}, {110, 0}]
</code>```

would become:

```<code>X = [{100, 10}, {101, 0}, {102, 5}, {103, 0}, {105, 1}, {106, 2}, {110, 0}]
</code>```

but only following pairs have been updated/added in X:

```<code>{102, 5}
{105, 1}
{110, 0}
</code>```

To make things a bit more interesting, there are few constraints:

it is very costly to iterate over dictionary X. Assume X is very large.

it is very costly to make an update to {key, value} pair so the task is to minimize this cost.

So that was the problem stated. Here is my solution:

First idea I had was to save the dictionary U after updating X.
On the next update I take each key from Uprev and set it to 0 in X.

```<code>foreach (var pair in Uprev)
{
    X[pair.Key] = 0;
}
</code>```

After this has been done, I would do a loop to set new values for keys present in new dictionary U:

```<code>foreach (var pair in U)
{
    if (X.ContainsKey(pair.Key))
       X[pair.Key] = pair.Value;
    else
       X.Add(pair.Key, pair.Value);
}
</code>```

So ... the question: is there a better solution for the problem I described above? Is it possible to better manage the updates?
Any ideas are welcome, so feel free to post anything that comes to mind.

Thank you for contribution

Body:
You can make this more efficient by developing a specialised data structure. Let X' be a pair (D,S) where D is a dictionary and S is a set.  It corresponds to the dictionary X of your example by the following substitutions:

there is no keys bound to 0 in D

if a key is bound in D then X' behaves as if it were X and that binding were also in X

if a key is not bound in D but in S then X' behaves as if it were X and that key were bound to 0 in X.

You can define the lookup and update operations as.

 lookup(key):
   if key is bound in D then D[key] elseif key is in S then 0 else Not_found

 update(U):
   set D to U
   add all keys bound in U to S

If U is quite small, this will improve the performance: if your dictionary X is implemented with a hashtable and grows very large, you have many hash collisions and lookup time behaves as O(N).  With X' key lookup is O(size(U)) + O(log N) which becomes O(log N) if the size of U is bounded.


问:
shall a vector2 extends a vector3 or is it the opposite?
Perhaps the question might be tied to a theoritical or mathematical forum, but since it is for programming purpose, i ask here first:

In a computer vision context, i write a couple of interfaces intended to be the "read-only" part of vectors. So i define "IVector2R" and "IVector3R" that only contain getters. The question is:
does IVector2R extends IVector3R (and the "y getter" always returns 0), or is it the opposite: IVector3R extends IVector2R?

I would like a conception as close as possible to the mathematic/sets theory...

Thank you for your attention

答:
I would like a conception as close as possible to the mathematic/sets theory…

When you work with vector coordinates, it means that you work in some vector space where you chose a base.  Asking if there is a natural relation between 2-dimensional vectors and 3-dimensional vectors is the same thing as as asking if there is a natural relation between a 2-dimensional vector space equipped with a base and a 3-dimensional vector space equipped with a base. In general, there is not.

However, it seems you are working with a euclidean space with a basis (e1, e2, e3) so that the vector of coordinates (X,Y,Z) is Xe1 + Ye2 + Ze3. If you assume that your 2-dimensional space has the basis (e1,e2) then you have two natural maps between 2-dimensional vectors and 3-dimensional vectors:

```<code>- The projection (X,Y,Z) -> (X,Y)
- The embedding (X,Y) -> (X,Y,0)
</code>```

Therefore, from a mathematical point of view, there is no natural way to express a relation between 2-dimensional vectors and 3-dimensional vectors that you could express through inheritance. There is however two natural transformations that you could implement as regular functions.

ContentLicense: CC BY-SA 3.0

Body:
I would like a conception as close as possible to the mathematic/sets theory…

When you work with vector coordinates, it means that you work in some vector space where you chose a base.  Asking if there is a natural relation between 2-dimensional vectors and 3-dimensional vectors is the same thing as as asking if there is a natural relation between a 2-dimensional vector space equipped with a base and a 3-dimensional vector space equipped with a base. In general, there is not.

However, it seems you are working with a euclidean space with a basis (e1, e2, e3) so that the vector of coordinates (X,Y,Z) is Xe1 + Ye2 + Ze3. If you assume that your 2-dimensional space has the basis (e1,e2) then you have two natural maps between 2-dimensional vectors and 3-dimensional vectors:

- The projection (X,Y,Z) -> (X,Y)
- The embedding (X,Y) -> (X,Y,0)

Therefore, from a mathematical point of view, there is no natural way to express a relation between 2-dimensional vectors and 3-dimensional vectors that you could express through inheritance. There is however two natural transformations that you could implement as regular functions.


问:
Is it normal to write all logs into a single file?
Our teamlead said that many files much worse than a single, despite of we are working on a big project.

He argued that our customers could more easily send logs to us if there will be just a single file.

To understand our log-file he wants to develope our own log-analyzer which will analyze a single log-file separating it to many

答: Putting on my sysadmin hat, the best practice is that the developers put plenty of logging calls in their apps and then expose the logging level and destination configuration for me -- logging to file might work in one scenario but I might really want to send stuff to SNMP in another or to email in another. Please don't make my decisions for me.</p>


答:
Please define what methods or operations Vector2R and Vector3R have in common and the use case where you'd want to treat them the same without needing to know which is which.  Those would be reasons to come up with a common interface.  Failing that, there is no useful answer to your question.

I'm presuming matrix multiplication is your use case?  "Vector" and "Array" are loaded terms in some languages.  In Java they are the same, but in Scala, Vector=shallow tree.  In JavaScript, Array=Map/Dictionary.  Even in math and physics, "Vector" can mean many things.

Otherwise, "Favor Composition Over Inheritance."  But I'll give you some background information.

Most languages have multidimensional arrays built in:

Java

Scala

Clojure

Haskell

Matrix Multiplication can be done in most languages as well:

Clojure's core.matrix

Scala/Haskell

Many other languages - this may be what you were looking for - not sure...

So most languages side-step your issues or provide no support for abstracting over n dimensions where n can change.  This is why your use case is critical for designing a meaningful abstraction for treating arrays of different dimensions as the same.

Title: shall a vector2 extends a vector3 or is it the opposite?

Body:
Perhaps the question might be tied to a theoritical or mathematical forum, but since it is for programming purpose, i ask here first:

In a computer vision context, i write a couple of interfaces intended to be the "read-only" part of vectors. So i define "IVector2R" and "IVector3R" that only contain getters. The question is:
does IVector2R extends IVector3R (and the "y getter" always returns 0), or is it the opposite: IVector3R extends IVector2R?

I would like a conception as close as possible to the mathematic/sets theory...

Thank you for your attention


问:
What's the most readable way of echoing from PHP?
Should I use

```<code><?php
    if(!$user->is_logged_in()){
        echo '<p id="login">Click here to log in</p>';
    }
?>
</code>```

or

```<code><?php
    if(!$user->is_logged_in()){
?>
    <p id="login">Click here to login.</p>
<?php
    }
?>
</code>```

? Why?

The first one will not have the HTML tags coloured so is less readable in code editors, but with the second one, it seems like it would be bad to take up three lines just to add a curly brace.

Which should I be using?

答:
Why use endif instead of {}?
Most of the IDE mark appropriate starting brace { when the ending one is selected and oposite, which is not the case with endif sintax.
Similar as with HTML starting and ending tags, when starting one is selected, the ending one is marked.

Say You have 1000 lines of HTML+php code, if condition starts on line 100 and ends on line 500, its good to have markers where it starts and where it ends, isnt so?

Body:
Should I use

```<code><?php
    if(!$user->is_logged_in()){
        echo '<p id="login">Click <a href="login">here</a> to log in</p>';
    }
?>
</code>```

or

```<code><?php
    if(!$user->is_logged_in()){
?>
    <p id="login">Click <a href="login">here</a> to login.</p>
<?php
    }
?>
</code>```

? Why?

The first one will not have the HTML tags coloured so is less readable in code editors, but with the second one, it seems like it would be bad to take up three lines just to add a curly brace.

Which should I be using?


问:
How to structure tests where one test is another test's setup?
I'm integration testing a system, by using only the public APIs. I have a test that looks something like this:

```<code>def testAllTheThings():
  email = create_random_email()
  password = create_random_password()

  ok = account_signup(email, password)
  assert ok
  url = wait_for_confirmation_email()
  assert url
  ok = account_verify(url)
  assert ok

  token = get_auth_token(email, password)
  a = do_A(token)
  assert a
  b = do_B(token, a)
  assert b
  c = do_C(token, b)

  # ...and so on...
</code>```

Basically, I'm attempting to test the entire "flow" of a single transaction. Each step in the flow depends on the previous step succeeding. Because I'm restricting myself to the external API, I can't just go poking values into the database.

So, either I have one really long test method that does `A; assert; B; assert; C; assert...", or I break it up into separate test methods, where each test method needs the results of the previous test before it can do its thing:

```<code>def testAccountSignup():
  # etc.
  return email, password

def testAuthToken():
  email, password = testAccountSignup()
  token = get_auth_token(email, password)
  assert token
  return token

def testA():
  token = testAuthToken()
  a = do_A(token)
  # etc.
</code>```

I think this smells. Is there a better way to write these tests?

答: Not much better, but you can at least separate setup code from asserting code. Write a separate method that tells the entire story step by step, and take a parameter controlling how many steps it should take. Then each test can say something like simulate 4 or simulate 10 and then assert whatever it tests.


答:
Well, I might not get the Python syntax right here by "air coding", but I guess you get the idea: you can implement a general function like this:

```<code>def asserted_call(create_random_email,*args):
    result=create_random_email(*args)
    assert result
    return result
</code>```

which will allow you to write your tests like this:

```<code>  asserted_call(account_signup, email, password)
  url = asserted_call(wait_for_confirmation_email)
  asserted_call(account_verify,url)
  token = asserted_call(get_auth_token,email, password)
  # ...
</code>```

Of course, it is debatable if the loss in readability of this approach is worth to use it, but it reduces the boilerplate code a little bit.

Title: How to structure tests where one test is another test's setup?

Body:
I'm integration testing a system, by using only the public APIs. I have a test that looks something like this:

```<code>def testAllTheThings():
  email = create_random_email()
  password = create_random_password()

  ok = account_signup(email, password)
  assert ok
  url = wait_for_confirmation_email()
  assert url
  ok = account_verify(url)
  assert ok

  token = get_auth_token(email, password)
  a = do_A(token)
  assert a
  b = do_B(token, a)
  assert b
  c = do_C(token, b)

  # ...and so on...
</code>```

Basically, I'm attempting to test the entire "flow" of a single transaction. Each step in the flow depends on the previous step succeeding. Because I'm restricting myself to the external API, I can't just go poking values into the database.

So, either I have one really long test method that does `A; assert; B; assert; C; assert...", or I break it up into separate test methods, where each test method needs the results of the previous test before it can do its thing:

```<code>def testAccountSignup():
  # etc.
  return email, password

def testAuthToken():
  email, password = testAccountSignup()
  token = get_auth_token(email, password)
  assert token
  return token

def testA():
  token = testAuthToken()
  a = do_A(token)
  # etc.
</code>```

I think this smells. Is there a better way to write these tests?

Body:
Well, I might not get the Python syntax right here by "air coding", but I guess you get the idea: you can implement a general function like this:

def asserted_call(create_random_email,*args):
    result=create_random_email(*args)
    assert result
    return result

which will allow you to write your tests like this:

  asserted_call(account_signup, email, password)
  url = asserted_call(wait_for_confirmation_email)
  asserted_call(account_verify,url)
  token = asserted_call(get_auth_token,email, password)
  # ...

Of course, it is debatable if the loss in readability of this approach is worth to use it, but it reduces the boilerplate code a little bit.

ContentLicense: CC BY-SA 4.0


问:
Limiting certain functionality to development environment only
I intuitively think that an application should be exactly the same in DEV, QA, and PROD environments. However, I have been asked to add a feature to an application that will only be available in DEV environment.

I have a server and database for each environment - dev, test, and production. I want to know if there would be any possible issues that could arise (and "best practice" for avoiding them) from having a feature of a large application only available on development server.

The tool modifies DEV database values and produces an output script that will be tested in QA and afterwards will be used to modify production data. The authentication that allows access to the feature will not be available in QA and PROD environments. I understand that this will work, but is this correct for Java EE standards?

The feature would:

Modify values in the development database then export a SQL script that has the current state of the development database.

The SQL script would then be run on testing database and if every function worked properly afterwards it would also be run on production database.

The code that would modify the testing and production databases is not available in either of those environments.

答:
While I agree that you want all three to be as close as reasonably possible, there are frequently situations where it is unreasonable to make them identical.

Whether this is one or not, I of course can't know -- but it doesn't sound like it. Nothing you've said, indicates that you can't create a seperate utility to make whatever changes are necessary and create your script.  Which is what I would suggest doing when you have a feature that is only used in dev (instead of the more common scenario of having a feature that needs to act slightly different in dev).


问:
Why doesn't Java 8 include immutable collections?
The Java team has done a ton of great work removing barriers to functional programming in Java 8.  In particular, the changes to the java.util Collections do a great job of chaining transformations into very fast streamed operations.  Considering how good a job they have done adding first class functions and functional methods on collections, why have they completely failed to provide immutable collections or even immutable collection interfaces?

Without changing any existing code, the Java team could at any time add immutable interfaces that are the same as the mutable ones, minus the setter methods and make the existing interfaces extend from them, like this:

```<code>                  ImmutableIterable
     ____________/       |
    /                    |
Iterable        ImmutableCollection
   |    _______/    /          \   \___________
   |   /           /            \              \
 Collection  ImmutableList  ImmutableSet  ImmutableMap  ...
    \  \  \_________|______________|__________   |
     \  \___________|____________  |          \  |
      \___________  |            \ |           \ |
                  List            Set           Map ...
</code>```

Sure, operations like List.add() and Map.put() currently return a boolean or previous value for the given key to indicate whether the operation succeeded or failed.  Immutable collections would have to treat such methods as factories and return a new collection containing the added element - which is incompatible with the current signature.  But that could be worked-around by using a different method name like ImmutableList.append() or .addAt() and ImmutableMap.putEntry().  The resulting verbosity would be more than outweighed by the benefits of working with immutable collections, and the type system would prevent errors of calling the wrong method.  Over time, the old methods could be deprecated.

Wins of immutable collections:

Simplicity — reasoning about code is simpler when the underlying data does not change.

Documentation — if a method takes an immutable collection interface, you know it isn't going to modify that collection.  If a method returns an immutable collection, you know you can't modify it.

Concurrency — immutable collections can be shared safely across threads.

As someone who has tasted languages which assume immutability, it is very hard to go back to the Wild West of rampant mutation.  Clojure's collections (sequence abstraction) already have everything that Java 8 collections provide, plus immutability (though maybe using extra memory and time due to synchronized linked-lists instead of streams).  Scala has both mutable and immutable collections with a full set of operations, and though those operations are eager, calling .iterator gives a lazy view (and there are other ways of lazily evaluating them).  I don't see how Java can continue to compete without immutable collections.

Can someone point me to the history or discussion about this? Surely it's public somewhere.

答:
Because immutable collections absolutely require sharing to be usable. Otherwise, every single operation drops a whole other list into the heap somewhere. Languages that are entirely immutable, like Haskell, generate astonishing amounts of garbage without aggressive optimizations and sharing. Having collection that's only usable with <50 elements is not worth putting in the standard library.

Further more, immutable collections often have fundamentally different implementations than their mutable counterparts. Consider for example ArrayList, an efficient immutable ArrayList wouldn't be an array at all! It should be implemented with a balanced tree with a large branching factor, Clojure uses 32 IIRC. Making mutable collections be "immutable" by just adding a functional update is a performance bug just as much as a memory leak is.

Furthermore, sharing isn't viable in Java. Java provides too many unrestricted hooks to mutability and reference equality to make sharing "just an optimization". It'd probably irk you a bit if you could modify an element in a list, and realize you just modified an element in the other 20 versions of that list you had.

This also rules out huge classes of very vital optimizations for efficient immutability, sharing, stream fusion, you name it, mutability breaks it. (That'd make a good slogan for FP evangelists)


答:
I'd separate the testing code from the setup code. Perhaps:

```<code># Setup
def accountSignup():
    email = create_random_email()
    password = create_random_password()

    ok = account_signup(email, password)
    url = wait_for_confirmation_email()
    verified = account_verify(url)
    return email, password, ok, url, verified

def authToken():
    email, password = accountSignup()[:2]
    token = get_auth_token(email, password)
    return token

def getA():
    token = authToken()
    a = do_A()
    return a

def getB():
    a = getA()
    b = do_B()
    return b

# Testing
def testAccountSignup():
    ok, url, verified = accountSignup()[2:]
    assert ok
    assert url
    assert verified

def testAuthToken():
    token = authToken()
    assert token

def testA():
    a = getA()
    assert a

def testB():
    b = getB()
    assert b
</code>```

Remember, all random information that is generated must be included in the assertion in case it fails, otherwise your test may not be reproducible. I might even record the random seed used. Also any time a random case does fail, add that specific input as a hard-coded test to prevent regression.

Body:
I'd separate the testing code from the setup code. Perhaps:

# Setup
def accountSignup():
    email = create_random_email()
    password = create_random_password()

    ok = account_signup(email, password)
    url = wait_for_confirmation_email()
    verified = account_verify(url)
    return email, password, ok, url, verified

def authToken():
    email, password = accountSignup()[:2]
    token = get_auth_token(email, password)
    return token

def getA():
    token = authToken()
    a = do_A()
    return a

def getB():
    a = getA()
    b = do_B()
    return b

# Testing
def testAccountSignup():
    ok, url, verified = accountSignup()[2:]
    assert ok
    assert url
    assert verified

def testAuthToken():
    token = authToken()
    assert token

def testA():
    a = getA()
    assert a

def testB():
    b = getB()
    assert b

Remember, all random information that is generated must be included in the assertion in case it fails, otherwise your test may not be reproducible. I might even record the random seed used. Also any time a random case does fail, add that specific input as a hard-coded test to prevent regression.


答:
If this test is intended to run frequently, your concerns would rather be focused on how to present test results in a way convenient to those expected to work with these results.

From this perspective, testAllTheThings raises a huge red flag. Imagine someone running this test every hour or even more frequently (against buggy codebase of course, otherwise there would be no point to re-run), and seeing every time all the same FAIL, without a clear indication of what stage failed.

Separate methods look much more appealing, because results of re-runs (assuming steady progress in fixing bugs in code) could look like:

```<code>    FAIL FAIL FAIL FAIL
    PASS FAIL FAIL FAIL -- 1st stage fixed
    PASS FAIL FAIL FAIL
    PASS PASS FAIL FAIL -- 2nd stage fixed
    ....
    PASS PASS PASS PASS -- we're done
</code>```

Side note, in one of my past projects, there were so many re-runs of dependent tests that users even began complaining about not willing to see repeated expected failures at later stage "triggered" by a failure at the earlier one. They said this garbage makes it harder to them to analyze test results "we know already that the rest will fail by test design, don't bother us repeating".

As a result, test developers were eventually forced to extend their framework with additional SKIP status and add a feature in test manager code to abort execution of dependent tests and an option to drop SKIPped test results from the report, so that it looked like:

```<code>    FAIL -- the rest is skipped
    PASS FAIL -- 1st stage fixed, abort after 2nd test
    PASS FAIL
    PASS PASS FAIL -- 2nd stage fixed, abort after 3rd test
    ....
    PASS PASS PASS PASS -- we're done
</code>```

Body:
If this test is intended to run frequently, your concerns would rather be focused on how to present test results in a way convenient to those expected to work with these results.

From this perspective, testAllTheThings raises a huge red flag. Imagine someone running this test every hour or even more frequently (against buggy codebase of course, otherwise there would be no point to re-run), and seeing every time all the same FAIL, without a clear indication of what stage failed.

Separate methods look much more appealing, because results of re-runs (assuming steady progress in fixing bugs in code) could look like:

    FAIL FAIL FAIL FAIL
    PASS FAIL FAIL FAIL -- 1st stage fixed
    PASS FAIL FAIL FAIL
    PASS PASS FAIL FAIL -- 2nd stage fixed
    ....
    PASS PASS PASS PASS -- we're done

Side note, in one of my past projects, there were so many re-runs of dependent tests that users even began complaining about not willing to see repeated expected failures at later stage "triggered" by a failure at the earlier one. They said this garbage makes it harder to them to analyze test results "we know already that the rest will fail by test design, don't bother us repeating".

As a result, test developers were eventually forced to extend their framework with additional SKIP status and add a feature in test manager code to abort execution of dependent tests and an option to drop SKIPped test results from the report, so that it looked like:

    FAIL -- the rest is skipped
    PASS FAIL -- 1st stage fixed, abort after 2nd test
    PASS FAIL
    PASS PASS FAIL -- 2nd stage fixed, abort after 3rd test
    ....
    PASS PASS PASS PASS -- we're done


答:
There is the best practice of "dev code never makes it into production".  There is also the best practice of "all builds are the same".  Unfortunately, these two can make for some difficult decisions and compromises between the two best practices.

If you have to compromise them, the all builds being the same is probably the better best practice.  In part because it means you can pull a production build into the dev environment, flip the appropriate switches and be able to investigate the internals with the dev tools available.

One example of this is how logging works.  LOG.debug("foo"); only runs in the environments where the debug configuration for logging has been enabled - which isn't production.

Within Java EE, one of the settings available is that of the server/vm settings.  With Java, you can use the -D option on the vm to set certain properties that can be queried at runtime with System.getProperty("propname");

With this approach, one could change the VM options to have -Djmoreno.debug which means its running in a dev enviroment.

This can also be put to good use when you have multiple machines in production that need properties (for example file paths)... and you want to only deploy one copy to both - change the option so that each vm knows its file path and then your code remains consistent between the two production deployments.

Its not so much a 'best practice' issue, but rather an inevitable design to avoid bad practices.

For the specific case of "here is functionality that only exists in dev" with a JEE environment - I would encourage looking into a dbfiddle.war file that gets bundled into the development .ear - it doesn't make its way into other .ear files.  This way the separation of development functionality from other functionality is clear and distinct - it can't accidentally leak into other environments with a misconfigured bit of code or server setting (misconfigured build - yes, but that is easier to check - just open up the .ear and look).

The other thing that (if this doesn't need to be bundled into the .ear) would be just write a stand alone application - don't even deploy it to the server. Just run it.  Ideally, any business logic that it needs is properly separated into a .jar that both the stand alone and the JEE code can use (rather than having it tightly coupled into the JEE code).

Title: Limiting certain functionality to development environment only

Body:
I intuitively think that an application should be exactly the same in DEV, QA, and PROD environments. However, I have been asked to add a feature to an application that will only be available in DEV environment.

I have a server and database for each environment - dev, test, and production. I want to know if there would be any possible issues that could arise (and "best practice" for avoiding them) from having a feature of a large application only available on development server.

The tool modifies DEV database values and produces an output script that will be tested in QA and afterwards will be used to modify production data. The authentication that allows access to the feature will not be available in QA and PROD environments. I understand that this will work, but is this correct for Java EE standards?

The feature would:

Modify values in the development database then export a SQL script that has the current state of the development database.

The SQL script would then be run on testing database and if every function worked properly afterwards it would also be run on production database.

The code that would modify the testing and production databases is not available in either of those environments.


问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
Instead of:

```<code>switch(myEnum) {
  case MyEnum.Val1: do1(); ...
  case MyEnum.Val2: do2(); ...
....
</code>```

Do it the Python, or now the C# way as well:

```<code>action = val2func[myEnum]
action()
</code>```

Scala has lots of new features.

Finally, languages such as Clojure can be extended to provide the extra functionality.

ContentLicense: CC BY-SA 2.5

Body:
Instead of:

switch(myEnum) {
  case MyEnum.Val1: do1(); ...
  case MyEnum.Val2: do2(); ...
....

Do it the Python, or now the C# way as well:

action = val2func[myEnum]
action()

Scala has lots of new features.

Finally, languages such as Clojure can be extended to provide the extra functionality.


问:
Where does Web Reference go in 3-layer app
I have a 3 layered application.

Presentation Layer (PL): ASP.NET MVC app

Business Logic Layer (BLL) project

Data Access Layer (DAL) project

I need to add a Web Reference to a service for a payment gateway. Where does it go? PL or BLL?

P.S.
Before using the Web service I need to retrieve some data from database and send that data to web service.

答: Since the actual operation isn't something the user needs to see then Presentation is out. What we have left is the Data Access and the Business layers. Since you aren't actually manipulating data from the payment gateway it's more of an external business process, which makes the Business layer the logical home for it.</p>


问:
Should more than one function be used when they do similar, but not identical things?
For example, if I wanted to generate some HTML based on some input. Which is the preferred way out of:

```<code><?php

function generate_html($type, $input){
    switch($type){
        case 'paragraph':
            //Generate and return the HTML code for a paragraph
            break;
        case 'ul':
            //Generate and return the HTML code for an unordered list
            break;
        default:
            error('Invalid type specified');
            break;
    }
}

generate_html('paragraph', 'This is a paragraph');
generate_html('ul', [
    'This is the first item in a list',
    'This is the second item in a list'
]);
</code>```

or:

```<code><?php

function generate_paragraph($input){
    //Generate and return HTML for a paragraph
}

function generate_ul($input){
    //Generate and return HTML for a list
}

generate_paragraph('This is a paragraph');
generate_ul([
    'This is the first item in a list',
    'This is the second item in a list'
]);
</code>```

I know about the idea of a function doing only one "thing", but I'm not sure how specific that "thing" should be. The first type could only be doing one thing (generating HTML), or it could be doing two things (generating lists, paragraphs). It depends how you look at it. What would be the preferred way of doing something like this?

答: I can find equal argument for both, except in one case. If the functions are similar enough, then usually a lot of the inner workings and plumbing is the same. So having multiple functions could mean code repetition. If that is the case then having one monolithic function that handles different types of output depending on an input argument could be the way to go.


答:
I would suggest to create seperate functions like

generate_paragraph

generate_ul

instead of one general purpose function

generate_html

Because in later case we are controlling the behavior of function by passing parameters. Based on different parameters, function will behave differently. This is high coupling (Code Complete by Steve McConnell), which is discouraged in OO programming.

Regarding duplicate code, we can wrap that in a common function, which can be used by other functions.

Title: Should more than one function be used when they do similar, but not identical things?

Body:
For example, if I wanted to generate some HTML based on some input. Which is the preferred way out of:

```<code><?php

function generate_html($type, $input){
    switch($type){
        case 'paragraph':
            //Generate and return the HTML code for a paragraph
            break;
        case 'ul':
            //Generate and return the HTML code for an unordered list
            break;
        default:
            error('Invalid type specified');
            break;
    }
}

generate_html('paragraph', 'This is a paragraph');
generate_html('ul', [
    'This is the first item in a list',
    'This is the second item in a list'
]);
</code>```

or:

```<code><?php

function generate_paragraph($input){
    //Generate and return HTML for a paragraph
}

function generate_ul($input){
    //Generate and return HTML for a list
}

generate_paragraph('This is a paragraph');
generate_ul([
    'This is the first item in a list',
    'This is the second item in a list'
]);
</code>```

I know about the idea of a function doing only one "thing", but I'm not sure how specific that "thing" should be. The first type could only be doing one thing (generating HTML), or it could be doing two things (generating lists, paragraphs). It depends how you look at it. What would be the preferred way of doing something like this?


问:
How to avoid unmaintainable code when using SQL in an MVC setting?
I want to present a list of products to the user. This list is paginated and can be sorted by the user by product ID or product name in ascending or descending order.

I am using an MVC setting, where I would like to query the database in the model.

How would I write functions that query the database? I can think of several options which all have their drawbacks:

Have one function for each possible combination of sort columns and sorting directions, each with a different query inside:

```<code>func GetProductsOrderByIdAsc() []*Product { … }
func GetProductsOrderByIdDesc() []*Product { … }
func GetProductsOrderByNameAsc() []*Product { … }
func GetProductsOrderByNameDesc() []*Product { … }
</code>```

This is obviously unmaintainable as it leads to lots of almost-identical SQL queries, aka “duplicate code.”

Concatenate strings of SQL:

```<code>func GetProducts(orderBy string, orderDirection string) []*Product {
    return db.query(`
          SELECT id, name, description
            FROM products
        ORDER BY ` + orderBy + ` ` + orderDirection + `
    `)
}
</code>```

This is inelegant, unreadable and unmaintainable as it quickly becomes a mess—imagine adding pagination and filtering. Parameter binding won’t work here as these are columns and not values.

Sort, filter and paginate in Go instead of in SQL. This would solve the code duplication problem but it can be a performance problem when having gazillions of records.

What is the usual concrete way of solving this problem? Ideally there would be no duplicate code, no ugly query synthesis and no major inefficiencies.

答:
I take option #2, almost, though my input is not SQL clauses but booleans and the like. The function then intelligently forms the query from those parameters. If you don't like that, have it accept an array containing values for all the options.

It doesn't have to be a mess. Code it properly and robustly and it'll look/run just fine.


答:
I don't have experience with Go, but since your question's title doesn't indicate that it's limited to Go, I will answer it in the general sense.

The best way to go about SQL in MVC is to use ORM for a model. Some queries may be slow using ORM, in which case they may be isolated in a separate function.

If you absolutely have to write the query yourself (lack of available ORM implementation, or queries which need tweaking for performance etc), I would go for having templates which expect parameters for substitution, similar to your #2, but using an existing robust template engine.

It is important to note, that query parameters for SQL should be always escaped to avoid SQL injection.

Title: How to avoid unmaintainable code when using SQL in an MVC setting?

Body:
I want to present a list of products to the user. This list is paginated and can be sorted by the user by product ID or product name in ascending or descending order.

I am using an MVC setting, where I would like to query the database in the model.

How would I write functions that query the database? I can think of several options which all have their drawbacks:

Have one function for each possible combination of sort columns and sorting directions, each with a different query inside:

```<code>func GetProductsOrderByIdAsc() []*Product { … }
func GetProductsOrderByIdDesc() []*Product { … }
func GetProductsOrderByNameAsc() []*Product { … }
func GetProductsOrderByNameDesc() []*Product { … }
</code>```

This is obviously unmaintainable as it leads to lots of almost-identical SQL queries, aka “duplicate code.”

Concatenate strings of SQL:

```<code>func GetProducts(orderBy string, orderDirection string) []*Product {
    return db.query(`
          SELECT id, name, description
            FROM products
        ORDER BY ` + orderBy + ` ` + orderDirection + `
    `)
}
</code>```

This is inelegant, unreadable and unmaintainable as it quickly becomes a mess—imagine adding pagination and filtering. Parameter binding won’t work here as these are columns and not values.

Sort, filter and paginate in Go instead of in SQL. This would solve the code duplication problem but it can be a performance problem when having gazillions of records.

What is the usual concrete way of solving this problem? Ideally there would be no duplicate code, no ugly query synthesis and no major inefficiencies.


问:
What can go wrong with composing a method name out of a string?
I have a piece of code that composes method name to call from a string parameter. I don't feel it's a good thing to do but I'm not sure what can go wrong with this.

Here is a simplified snippet of that code:

```<code>switchToFilter = function(filter){
    var filterMethod = 'switchTo' + filter;
    myObject[filterMethod]();
}
</code>```

答:
At run time, the worst thing that could probably happen is that the method doesn't exist, so you get some sort of run-time error saying ERROR: method: 'switchToFoo' could not be found in context blah blah blah...

I'm not really sure if this type of code could be vulnerable to injection attacks. Where does the value for filter come from?

A bigger problem might be that whatever development tools you're using won't be able to work with this. For example, if you want your IDE to search for all places where switchToFoo is called, it won't be possible to find the ones called by the snippet you show above. Or if you want to refactor switchToFoo to switchToFou, you have to change the method name, and then change the code that passes the value for filter. You will know all about this, but this sort of thing usually trips up developers who are new to the project.


答:
The biggest risk is trying to access something that doesn't exist within the array structure.  In the worst case, that will crash your application.  In the best case, there wouldn't be any perceived operation going on.

If you wrapped that logic with some guard checks to make sure you weren't accessing something that wasn't there, it would be a little bit more robust.  You could also consider adding logging for the errant requests that still manage to come in.  With log information, you could hunt the problems down after the fact.

Title: What can go wrong with composing a method name out of a string?

Body:
I have a piece of code that composes method name to call from a string parameter. I don't feel it's a good thing to do but I'm not sure what can go wrong with this.

Here is a simplified snippet of that code:

```<code>switchToFilter = function(filter){
    var filterMethod = 'switchTo' + filter;
    myObject[filterMethod]();
}
</code>```


答:
What can go wrong with composing a method name out of a string?

If myObject[filterMethod]() doesn't exist, you could crash your application.

If your application is part of the safety controls for nuclear missile fire control, you could be potentially disabling critical safety controls.

If other software for the controls doesn't account for this crash, you could allow anyone to fire ze missiles.

If someone is having a bad day, they could decide to try to launch the missiles and be surprised they launch.

If they launch the missiles, you could start a nuclear war.

If a nuclear war starts, you could end civilization as we know it.

FOR THE LOVE OF THE CHILDREN CHECK THINGS EXISTS BEFORE ACCESSING THEM!


答:
It's a form of reflection, which has its uses in dynamically-built applications (like a GUI builder for example) or plugins, but should be a matter of last resort outside those contexts.

In addition to the excellent reasons stated in other answers, it's a sign that your class hierarchy probably needs refactoring.  Doing so will most likely make it much easier to reason about all your code.  For one refactored example:

```<code>switchToFilter = function(filterName){
    var filter = filters[filterName];
    filter.switch();
}
</code>```

This allows you to use inheritance to avoid duplication in the switch functions, and most likely has a side effect of providing a convenient place to put other filter-specific behavior.

Body:
It's a form of reflection, which has its uses in dynamically-built applications (like a GUI builder for example) or plugins, but should be a matter of last resort outside those contexts.

In addition to the excellent reasons stated in other answers, it's a sign that your class hierarchy probably needs refactoring.  Doing so will most likely make it much easier to reason about all your code.  For one refactored example:

switchToFilter = function(filterName){
    var filter = filters[filterName];
    filter.switch();
}

This allows you to use inheritance to avoid duplication in the switch functions, and most likely has a side effect of providing a convenient place to put other filter-specific behavior.


问:
Reasoning behind the syntax of octal notation in Java?
Java has the following syntax for different bases:

```<code>int x1 = 0b0101; //binary
int x2 = 06;     //octal
int x3 = 0xff;   //hexadecimal
</code>```

Is there any reasoning on why it is 0 instead of something like 0o like what they do for binary and hexadecimal? Is there any documentation on why they went this route?

答:
Java syntax was designed to be close to that of C, see eg page 20 at How The JVM Spec Came To Be keynote from the JVM Languages Summit 2008 by James Gosling (20_Gosling_keynote.pdf):

C syntax to make developers comfortable

In turn, this is the way how octal constants are defined in C language:

If an integer constant begins with 0x or 0X, it is hexadecimal. If it begins with the digit 0, it is octal. Otherwise, it is assumed to be decimal...

Given above, it is natural that Java language designers decided to use same syntax as in C.

As pointed in this comment, StackOverflow's got a reasonable answer here:

All modern languages import this convention from C, which imported it from B, which imported it from BCPL.

Except BCPL used #1234 for octal and #x1234 for hexadecimal. B has departed from this convention because # was an unary operator in B (integer to floating point conversion), so #1234 could not be used, and # as a base indicator was replaced with 0.

The designers of B tried to make the syntax very compact. I guess this is the reason they did not use a two-character prefix.


问:
WCF and object-oriented programming
I am building a program which would have WCF support. I am using the MVC pattern. For each controller there is a WCF service class. e.g. I have CTRL.CTRLBooking, WCF.IWCFBooking and WCF.WCFBooking.

For each controller (total of 10) there is a WCF class and an endpoint.

Is this a good approach or should I keep all the methods I provide in one single class e.g. WCF.WCFService (considering their count would be no more than 25-30)?

答:
Have your cake and eat it too.

Group your methods into logical services, not necessarily by logical controllers.

The distinction being that a controller has a bias towards providing a set of services for an application.  So a controller is a broader container holding services or sets of services.

You can use partial classes in order to have separate files for smaller groupings of methods within a service.  At the extreme, you could even have one method per partial class file but I think that's a bit too far.  Look for natural groupings of methods and put those in a single file.

Try not to create monster service classes as individual methods tend to get buried within the volume of available methods.  The MS tools for manually testing a WCF service can get really cluttered in this case.  It also forces bigger service reference refreshes than you may like.

Title: WCF and object-oriented programming


问:
Why is Javascript faster than Jquery?
I was reading a thread and saw this post, which says that Javascript is faster than Jquery because it uses native code. But why is the use of native code faster? Is this always the case? What impediments does Jquery have in performance?</p>

答:
First of all, we have to get something straight:

Javascript and jQuery are not two completely different things: jQuery is a Javascript library.

jQuery:

jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML.

Javascript:

JavaScript (JS) is an interpreted computer programming language. As part of web browsers, implementations allow client-side scripts to interact with the user, control the browser, communicate asynchronously, and alter the document content that is displayed.

That said, the common trend among programming languages and libraries is that the library is always going to be slower because it is more code to run alongside your actual program.

For more information, check out this post. It's pretty similar to what you're asking.

Title: Why is Javascript faster than Jquery?


问:
Is functional programming actually used to create applications?

Possible Duplicate:

  What are some well known applications written in F#?

I see a lot of people talking about how cool functional programming is, how awesome Lisp and Haskell and F# are, etc, but what I don't see is them actually being used.  Just about every program on my computer is written in either something in the C family, Delphi, or Python.  I see tutorials talking about how easy it is to use functional languages to do complicated math problems, but no one talking about using them to do things most people actually care about using computers for, like business applications and games.

Does anyone have any examples of actual programs that people have heard of and are using, written in a functional language?  The only one I can think of off the top of my head is Abuse, from almost 15 years ago.  (Things like Emacs, where the core program is written in C with a functional language scripting layer on top, don't count.)

答:
It's used in the industry by the minority that understand how and have the opportunity to  use it. The majority of programmers won't understand recursion or things like first-class functions and that you can treat a function as a value and store it in a list. I'm not trying to sound elitist but the reality is the use of functional languages is limited because the vast majority of programmers can't get it. Sure lot's of people use Javascript but whether they use it in a functional way is another question.

Anyway here's a list of some organizations/people that use/used functional languages:

Paul Graham used Lisp to make a web store that got sold to Yahoo back in the day when Yahoo was king of the net.

Citrix use OCaml for the management tools for Xen.

The Halo team used F# internally

Fairly sure a lot of banks are using F# at the moment.

Ericsson use Erlang

But at the end of the day the language used makes little difference to the outcome of the project. The best programming language in the world won't save you from bad management implementing bad processes that have design and requirements proceeding for months and then expecting the 1000000 lines of documentation converted into working and tested code in 3 months.


答: Put your SQL in the DB and expose them to the model as stored procedures - you can do this directly, or you can wrap them in a more friendly service layer (eg using a web service) that gives you an API like you're calling a 3rd party web API. This means you have to think about what kind of data API you are exposing, rather than having all the DB available to use, it helps a lot to keep code separated and maintainable. IT also means you have a lot more security if (or when!) someone hacks your web server.</p>


答:
The link you posted is not that JavaScript is faster per se, but rather that calling the native DOM method is faster than calling a JavaScript abstraction that eventually calls the same DOM method.

For tasks that jQuery does well, such as gathering a list of DOM elements based on a class name, it would be difficult to write a "pure" JavaScript function that does the same task measurably faster.  (There are the occasional browser-specific optimization... but jQuery already includes several.)

Title: Why is Javascript faster than Jquery?

Body: I was reading a thread and saw this post, which says that Javascript is faster than Jquery because it uses native code. But why is the use of native code faster? Is this always the case? What impediments does Jquery have in performance?</p>


答:
When I first met PHP, I decided that I will never mix HTML and PHP code in the same file. It was 13 years ago, and it was a good decision. Okay, you will find some echo("$msg"), or if ($debug) echo("```"); print_r($result);, but that's all.

Use a templater, or you may even write a simple one, it's a good lession, even switching later to another one.

Did not ask, but here's another advice: use OOP. Finally, PHP supports the best OOP practices (was not available for long time), use it, design OOP, code OOP.

Title: What's the most readable way of echoing from PHP?

Body:
When I first met PHP, I decided that I will never mix HTML and PHP code in the same file. It was 13 years ago, and it was a good decision. Okay, you will find some echo("<b>$msg</b>"), or if ($debug) echo("<pre>"); print_r($result);, but that's all.

Use a templater, or you may even write a simple one, it's a good lession, even switching later to another one.

Did not ask, but here's another advice: use OOP. Finally, PHP supports the best OOP practices (was not available for long time), use it, design OOP, code OOP.


问:
Stacking keywords on top of each other - poor style?
I have always wondered about this, especially in C/Java style languages. For example, consider the first 3 lines of this C# code:

```<code>lock (serviceLock)
using (var client = new ServiceClient())
try
{
    // Do something
    client.DoSomething();
}

catch (System.ServiceModel.FaultException ex)
{
    // Handle error
    addLog(ex.ToString());
}
</code>```

This usage has always seemed somewhat questionable to me. However, the alternative is not very practical either (3+ levels deep of indentation for a service call). Apart from pure aesthetics, is there any practical reason to add or not to add the extra brackets in this case?

答:
The lock and using blocks are for programmer convenience, but are not required. If you find less indented code easier to read. You can write the same thing using the non-code-block version of the same C# features.

```<code>Monitor.Enter(serviceLock);
var client = new ServiceClient();
try
{
    client.DoSomething();
}
catch(FaultException ex)
{
    addLog(ex.ToString());
}
finally
{
    Monitor.Exit(serviceLock);
    client.Dispose();
}
</code>```

The above does the same thing, but there is no readability issue or confusion as to what it's doing.

The alternative approach is to use blocks and break everything into separate functions.

```<code>public function foo()
{
    lock(serviceLock)
    {
        fooService();
    }
}

private function fooService()
{
    using(ServiceClient client = new ServiceClient())
    {
        fooClientTry(client);
    }
}

private function fooClientTry(ServiceClient client)
{
    try
    {
        fooClient(client);
    }
    catch(System.ServiceModel.FaultException ex)
    {
        addLog(ex.ToString());
    }
}

private function fooClient(ServiceClient client)
{
    // work....
}
</code>```

I prefer the above approach. It looks like a lot more work/code but it's easier to maintain because each function performs a single task. When you get into multiple nested blocks this approach keeps everything only a few indentations.

Body:
The lock and using blocks are for programmer convenience, but are not required. If you find less indented code easier to read. You can write the same thing using the non-code-block version of the same C# features.

Monitor.Enter(serviceLock);
var client = new ServiceClient();
try
{
    client.DoSomething();
}
catch(FaultException ex)
{
    addLog(ex.ToString());
}
finally
{
    Monitor.Exit(serviceLock);
    client.Dispose();
}

The above does the same thing, but there is no readability issue or confusion as to what it's doing.

The alternative approach is to use blocks and break everything into separate functions.

public function foo()
{
    lock(serviceLock)
    {
        fooService();
    }
}

private function fooService()
{
    using(ServiceClient client = new ServiceClient())
    {
        fooClientTry(client);
    }
}

private function fooClientTry(ServiceClient client)
{
    try
    {
        fooClient(client);
    }
    catch(System.ServiceModel.FaultException ex)
    {
        addLog(ex.ToString());
    }
}

private function fooClient(ServiceClient client)
{
    // work....
}

I prefer the above approach. It looks like a lot more work/code but it's easier to maintain because each function performs a single task. When you get into multiple nested blocks this approach keeps everything only a few indentations.


答:
For a dissenting opinion, I rather like this practice with one significant change.

```<code>lock (serviceLock) using (var client = new ServiceClient()) try
{
    // Do something
    client.DoSomething();
}
catch (System.ServiceModel.FaultException ex)
{
    // Handle error
    addLog(ex.ToString());
}
</code>```

By not stacking, it forces the eye to read all the way across as one long statement. If the line is too long or does not read well, then you know you want to reorganize the logic.

I often do this with double for-loops and for-loops with try catch blocks.

```<code>for (int i = 0; i < x.Length; ++i) for (int j = 0; j < x[i].Length; ++j) try
{
    // each cell in a ragged matrix: x[i][j]
}
catch (/* … */)
{
    // exception in one cell allowing other cells to be processed.
}
</code>```

Above all else, clarity is the most important thing. If you are rigid with any style, you will end up with ugly and unreadable code in some cases. Be flexible in a way that allows you to highlight the logic. If you don't know if something is clear, then have your co-developers to look at it. Ask them what the code does without explaining it to them.

Title: Stacking keywords on top of each other - poor style?

Body:
I have always wondered about this, especially in C/Java style languages. For example, consider the first 3 lines of this C# code:

```<code>lock (serviceLock)
using (var client = new ServiceClient())
try
{
    // Do something
    client.DoSomething();
}

catch (System.ServiceModel.FaultException ex)
{
    // Handle error
    addLog(ex.ToString());
}
</code>```

This usage has always seemed somewhat questionable to me. However, the alternative is not very practical either (3+ levels deep of indentation for a service call). Apart from pure aesthetics, is there any practical reason to add or not to add the extra brackets in this case?

Body:
For a dissenting opinion, I rather like this practice with one significant change.

lock (serviceLock) using (var client = new ServiceClient()) try
{
    // Do something
    client.DoSomething();
}
catch (System.ServiceModel.FaultException ex)
{
    // Handle error
    addLog(ex.ToString());
}

By not stacking, it forces the eye to read all the way across as one long statement. If the line is too long or does not read well, then you know you want to reorganize the logic.

I often do this with double for-loops and for-loops with try catch blocks.

for (int i = 0; i < x.Length; ++i) for (int j = 0; j < x[i].Length; ++j) try
{
    // each cell in a ragged matrix: x[i][j]
}
catch (/* … */)
{
    // exception in one cell allowing other cells to be processed.
}

Above all else, clarity is the most important thing. If you are rigid with any style, you will end up with ugly and unreadable code in some cases. Be flexible in a way that allows you to highlight the logic. If you don't know if something is clear, then have your co-developers to look at it. Ask them what the code does without explaining it to them.


答:
Performance. Collections by their nature can be very large. Copying 1000 elements to a new structure with 1001 elements instead of inserting a single element is just plain horrible.

Concurrency. If you have several threads running they may want to get the current version of the collection and not the version that was passed 12 hours ago when the thread started.

Storage. With immutable objects in a multi threaded environment you can end up with dozens of copies of the "same" object at different points of its life cycle. Doesnt matter for a Calendar or Date object but when its a collection of 10,000 widgets this will kill you.

Title: Why doesn't Java 8 include immutable collections?

Body:
The Java team has done a ton of great work removing barriers to functional programming in Java 8.  In particular, the changes to the java.util Collections do a great job of chaining transformations into very fast streamed operations.  Considering how good a job they have done adding first class functions and functional methods on collections, why have they completely failed to provide immutable collections or even immutable collection interfaces?

Without changing any existing code, the Java team could at any time add immutable interfaces that are the same as the mutable ones, minus the setter methods and make the existing interfaces extend from them, like this:

```<code>                  ImmutableIterable
     ____________/       |
    /                    |
Iterable        ImmutableCollection
   |    _______/    /          \   \___________
   |   /           /            \              \
 Collection  ImmutableList  ImmutableSet  ImmutableMap  ...
    \  \  \_________|______________|__________   |
     \  \___________|____________  |          \  |
      \___________  |            \ |           \ |
                  List            Set           Map ...
</code>```

Sure, operations like List.add() and Map.put() currently return a boolean or previous value for the given key to indicate whether the operation succeeded or failed.  Immutable collections would have to treat such methods as factories and return a new collection containing the added element - which is incompatible with the current signature.  But that could be worked-around by using a different method name like ImmutableList.append() or .addAt() and ImmutableMap.putEntry().  The resulting verbosity would be more than outweighed by the benefits of working with immutable collections, and the type system would prevent errors of calling the wrong method.  Over time, the old methods could be deprecated.

Wins of immutable collections:

Simplicity — reasoning about code is simpler when the underlying data does not change.

Documentation — if a method takes an immutable collection interface, you know it isn't going to modify that collection.  If a method returns an immutable collection, you know you can't modify it.

Concurrency — immutable collections can be shared safely across threads.

As someone who has tasted languages which assume immutability, it is very hard to go back to the Wild West of rampant mutation.  Clojure's collections (sequence abstraction) already have everything that Java 8 collections provide, plus immutability (though maybe using extra memory and time due to synchronized linked-lists instead of streams).  Scala has both mutable and immutable collections with a full set of operations, and though those operations are eager, calling .iterator gives a lazy view (and there are other ways of lazily evaluating them).  I don't see how Java can continue to compete without immutable collections.

Can someone point me to the history or discussion about this? Surely it's public somewhere.


问:
Preventing a parser from turning into a (seemingly) god-sized object
So I have a program whose purpose is to take text files and parse them into a binary format that an embedded system understands.  However, the text format I've inherited that I need to parse is sufficiently complex enough that after refactoring the main parse routine I'm left with a class with more than 50 methods that almost all look something like parseChannel, parseWCommand, parseVCommand, parsePCommand, parseLoop, parseHex, parseInt, etc. etc. etc.

Needless to say, the class, from its declaration, looks huge and daunting.

However, the methods to interface with the class are extremely simple, just parse (compile the text, figure out its compiled size) and link (fix the pointers once the location in memory is known, return the finalized raw binary data).  Really, to the user the class has virtually no other reason for existence besides those two functions, but there's so much seemingly useless fluff in the class declaration that it's hard to even see what it's supposed to do. There's a similar situation going on with the rather massive number of data members that, again, are useless to everything but the class's internal methods that need them to talk to each other, though I don't know if that's as much of an issue.

I've considered making a separate class solely for parsing that's used within the parse method, but it seems strange to me to build an entirely separate class that's only used in a single method in a single class.  It seems a bit...superfluous, I guess?  And I don't even know if that's attacking the right problem.

I guess in the end, here's what I'm asking:

Is this seemingly-huge class actually a problem?  I don't think it's strictly a "god object", but it superficially looks like one.

If it is a problem, what are the best method(s) to fix it?

答:
I assume that the parser was written in a procedural style. If so, around 50 methods (= rules in your grammar) are to be expected for a small to medium-sized language. As there is no way to cut down on that, any criticism on the number of functions is void.

However, it is often the case that your grammar can be viewed as multiple largely unconnected subgrammars. For example in Markdown (the markup our posts here are using), the block-level grammar and the inline grammar are mostly separate. If your language has a similar distinction, writing various separate parsers that interface with each other would not only improve your design but also testability.

There is also a difference between parsing and lexing – some of your functions like parseInt don't necessarily belong into the parser level (but that very much depends).

If the only public methods of your parser object are parse and link, then there is no problem because the rest can be private, and implemented with whatever design you want. The link method however does probably not belong to a parser, and might have to be factored out into a seperate class – apply the Single Responsibility Principle as it makes sense.

A note on the term God Object: This term is used when

a class has too many responsibilities,

uses mutating global state instead of encapsulated state (aka. smaller objects) or function arguments, and

is written in a procedural, rather than object-oriented style.

The first two are real code smells that have to be adressed: The first is obvious, and the second is absolutely unecessary in a parser, which can be implemented just fine without mutating any state (assuming you are trying to build an AST). The third can be a valid criticism, but sometimes (e.g. with parsers), a procedural or functional solution is more elegant than an object-oriented one.


答:
I think you are stuck -- a big grammer needs a big parser.

You may be able to split the grammar into "sub grammers", e.g. one grammar for "object desrciptions" and another grammar for "action rules"; but this is only possible if your grammar can be broken down cleanly into separate "stanzas".

Title: Preventing a parser from turning into a (seemingly) god-sized object

Body:
So I have a program whose purpose is to take text files and parse them into a binary format that an embedded system understands.  However, the text format I've inherited that I need to parse is sufficiently complex enough that after refactoring the main parse routine I'm left with a class with more than 50 methods that almost all look something like parseChannel, parseWCommand, parseVCommand, parsePCommand, parseLoop, parseHex, parseInt, etc. etc. etc.

Needless to say, the class, from its declaration, looks huge and daunting.

However, the methods to interface with the class are extremely simple, just parse (compile the text, figure out its compiled size) and link (fix the pointers once the location in memory is known, return the finalized raw binary data).  Really, to the user the class has virtually no other reason for existence besides those two functions, but there's so much seemingly useless fluff in the class declaration that it's hard to even see what it's supposed to do. There's a similar situation going on with the rather massive number of data members that, again, are useless to everything but the class's internal methods that need them to talk to each other, though I don't know if that's as much of an issue.

I've considered making a separate class solely for parsing that's used within the parse method, but it seems strange to me to build an entirely separate class that's only used in a single method in a single class.  It seems a bit...superfluous, I guess?  And I don't even know if that's attacking the right problem.

I guess in the end, here's what I'm asking:

Is this seemingly-huge class actually a problem?  I don't think it's strictly a "god object", but it superficially looks like one.

If it is a problem, what are the best method(s) to fix it?


答:
Ditch the OOP

The member functions probably don’t need to be. You can have the Parser class provide a few primitive operations (accept character, backtrack, &c.) and implement the rest of the parser as free functions taking a Parser reference. They can live in the source file (under an anonymous namespace) thus keeping the header nice and minimal.

In this sense, Parser is really a minimal wrapper around a stream state.

Also, it helps to factor out combinators such as many, choice, and so on, to avoid writing error-prone and verbose manual loops.

Sketch

In Parse.h, your entire public API.

```<code>unique_ptr<const Program> parse(istream&);
</code>```

Your parser state can be entirely private to Parse.cpp.

```<code>struct Parser {

  Parser(istream& stream) : stream(stream) {}

  bool accept(const char expected) {
    char actual;
    if (!stream.get(actual)) return false;
    if (expected == actual) return true;
    stream.seekg(-1, ios::cur);
    return false;
  }

  template<class F, class O>
  bool accept_if(F predicate, O output) {
    char actual;
    if (!stream.get(actual)) return false;
    if (predicate(actual)) {
      *output++ = actual;
      return true;
    }
    return false;
  }

  void expect(const char expected) { if (!accept(expected)) throw ...; }

  void push_mark() { marks.push_back(stream.tellg()); }
  void pop_mark() { stream.seekg(marks.back()); drop_mark(); }
  void drop_mark() { marks.pop_back(); }

private:
  istream& stream;
  vector<istream::pos_type> marks;
};
</code>```

The public API implementation just forwards to the start production of a grammar with a new parser.

```<code>unique_ptr<const Program> parse(istream& stream) {
  return parse_program(Parser(stream));
}
</code>```

Output iterators are a fairly convenient way to produce multiple results.

```<code>template<class F, class O>
bool many_if(Parser& parser, F predicate, O output) {
  bool success;
  while (parser.accept_if(predicate, output)) success = true;
  return success;
}
</code>```

Pointers have the advantage of a conversion to bool.

```<code>unique_ptr<const Expression> number(Parser& parser) {
  string digits;
  auto append = back_inserter(digits);
  return many_if(isdigit, append) ? make_unique<Number>(digits) : nullptr;
}
</code>```

And so on. The real strengths of C++ to leverage when writing parsers are:

Generic programming

Iterators

Streams

Objects, not so much.

Body:
Ditch the OOP

The member functions probably don’t need to be. You can have the Parser class provide a few primitive operations (accept character, backtrack, &c.) and implement the rest of the parser as free functions taking a Parser reference. They can live in the source file (under an anonymous namespace) thus keeping the header nice and minimal.

In this sense, Parser is really a minimal wrapper around a stream state.

Also, it helps to factor out combinators such as many, choice, and so on, to avoid writing error-prone and verbose manual loops.

Sketch

In Parse.h, your entire public API.

unique_ptr<const Program> parse(istream&);

Your parser state can be entirely private to Parse.cpp.

struct Parser {

  Parser(istream& stream) : stream(stream) {}

  bool accept(const char expected) {
    char actual;
    if (!stream.get(actual)) return false;
    if (expected == actual) return true;
    stream.seekg(-1, ios::cur);
    return false;
  }

  template<class F, class O>
  bool accept_if(F predicate, O output) {
    char actual;
    if (!stream.get(actual)) return false;
    if (predicate(actual)) {
      *output++ = actual;
      return true;
    }
    return false;
  }

  void expect(const char expected) { if (!accept(expected)) throw ...; }

  void push_mark() { marks.push_back(stream.tellg()); }
  void pop_mark() { stream.seekg(marks.back()); drop_mark(); }
  void drop_mark() { marks.pop_back(); }

private:
  istream& stream;
  vector<istream::pos_type> marks;
};

The public API implementation just forwards to the start production of a grammar with a new parser.

unique_ptr<const Program> parse(istream& stream) {
  return parse_program(Parser(stream));
}

Output iterators are a fairly convenient way to produce multiple results.

template<class F, class O>
bool many_if(Parser& parser, F predicate, O output) {
  bool success;
  while (parser.accept_if(predicate, output)) success = true;
  return success;
}

Pointers have the advantage of a conversion to bool.

unique_ptr<const Expression> number(Parser& parser) {
  string digits;
  auto append = back_inserter(digits);
  return many_if(isdigit, append) ? make_unique<Number>(digits) : nullptr;
}

And so on. The real strengths of C++ to leverage when writing parsers are:

Generic programming

Iterators

Streams

Objects, not so much.


答: The rule is simple. Indentation needs to be consistent with scope. The lock is applying until the end of the catch block and needs to look like it. I'm not familiar with the using keyword in C# but from your code the same rule looks to apply.


问:
Confused about modifying the sprint backlog during a sprint
I've been reading a lot about scrum lately, and I've found what seem to me to be conflicting information about whether or not it's ok to change the sprint backlog during a sprint. The Wikipedia article on scrum says it's not ok, and various other articles say this as well.  Also my Software Development professor taught the same thing during an overview of scrum.

However, I read Scrum and XP from the Trenches and that describes a section for unplanned items on the taskboard. So then I looked up the Scrum Guide and it says that during the sprint "No changes are made that would affect the Sprint Goal" and in the discussion of the Sprint Goal "If the work turns out to be different than the
Development Team expected, then they collaborate with the Product Owner to negotiate the
scope of Sprint Backlog within the Sprint." It goes on to say in the discussion of the Sprint Backlog:

The Sprint Backlog is a plan with enough detail that changes in progress can be understood in
  the Daily Scrum. The Development Team modifies Sprint Backlog throughout the Sprint, and the
  Sprint Backlog emerges during the Sprint. This emergence occurs as the Development Team
  works through the plan and learns more about the work needed to achieve the Sprint Goal.

As new work is required, the Development Team adds it to the Sprint Backlog. As work is
  performed or completed, the estimated remaining work is updated. When elements of the plan
  are deemed unnecessary, they are removed. Only the Development Team can change its Sprint
  Backlog during a Sprint. The Sprint Backlog is a highly visible, real-time picture of the work that
  the Development Team plans to accomplish during the Sprint, and it belongs solely to the
  Development Team.

So at this point I'm altogether confused. Thinking about it, it makes more sense to me to take the second approach.  The individual, specific items in the backlog don't seem to me to be the most important thing, but rather the sprint goal, so not changing the sprint goal but being able to change the backlog makes sense. For instance if both the product owner and the team thought they were on the same page about a story, but as the sprint progressed they figured out there was a misunderstanding, it seems like it makes sense to change the tasks that make up that story accordingly.  Or if there was some story or task that was forgotten about, but is required to reach the sprint goal, I would think it would be best to add the story or task to the backlog during the sprint.

However, there are a lot of people who seem quite adamant that any change to the sprint backlog is not ok.  Am I misunderstanding that position somehow? Are those folks defining the sprint backlog differently somehow? My understanding of the sprint backlog is that it consists of both the stories and the tasks they're broken down into.

Anyway I would really appreciate input on this issue. I'm trying to figure out both what the idealistic scrum approach is to changing the sprint backlog during a sprint, and whether people who use scrum successfully for development allow changing the sprint backlog during a sprint.

答:
The confusion is due to ambiguous language.

The Sprint Backlog has two levels of detail. First, it is a list of Items (User Stories) that the Team has committed to deliver. Second, it is all the TASKS that the team intends to do in order to deliver each of those stories.

So when people talk about the Sprint Backlog, they should really be clear about what they mean. When you read the Scrum Guide you'll see that it states: The Sprint Backlog is the set of Product Backlog items selected for the Sprint, plus a plan for delivering the product Increment and realizing the Sprint Goal.

So it is BOTH the list of Product Backlog Items AND the Plan (Tasks) to deliver them.

Now, many teams like to add all the proposed tasks (plan) at the beginning of the Sprint so they can track a burndown chart based on hours left to do. Other teams let the tasks emerge as required. THIS is when it's OK to add to the 'Sprint Backlog', since the team has to do that in order to inspect and adapt in order to deliver the Items and meet the Sprint Goal.

Under certain circumstances, a team may be well-ahead of schedule and (having eliminated all other useful tasks that could improve the Team's capabilities) may decide to work with the Product Owner to select another story (should already have been prioritized and sized) from the Product Backlog... but only if they have the confidence that it will be completed within that Sprint and that it aligns with the Sprint Goal.

So, there we have it; YES... teams DO add Tasks to the Sprint Backlog plan as required. NO, they don't usually add to the list of Backlog Items that define the Scope of the Sprint.

I hope this clarifies the situation.


问:
History of vendor css prefix
When and how did this process of prefixing css with vendor specific prefix begin.

Which browser/org start this and why was this started. I searched the web but found no details on this.

答:
vendor prefixes have been around since pre css2. they are the standard method for implementing new features in a rendering engine, affixing the prefix implies that only this particular engine will render these particular properties/features/etc. vendor prefixes are rendering engine's extensions to the standard.

different implementations of the box model by ie and netscape are the root cause for all of this, as well as doctype switching. the browsers implemented standards differently and were forced with rolling back active features or dealing with what was already live.

microsoft has been doing it for awhile, as have wap css user agents, and -khtml; the explosion with css3 came about with the release of the iphone and all of its shiny. apple really set the tone in their aggressive -webkit css development.

i'm not sure who exactly, but somewhere shortly after, the idea was proposed to make them a standard per rendering engine...i remember eric meyer blogging about it and reading it on the w3c site.

upon implementation, it has turned out to be not optimal, if in the very least, because a certain percentage of developers are lazy and cannot be expected to prefix for any vendor besides -webkit. i'm being sarcastic, but that's pretty much dead on, minus the -webkit comment...the largest casualty from all of this was opera...opera mini/mobile on ios were pretty much ignored by the -webkit fan club, causing entirely too many sites to be "broken" or "ugly" when viewed using opera mini/mobile....so opera quit -o- and threw away presto for webkit.

Title: History of vendor css prefix


问:
Is TDD viable in collaborative open source projects
Let's say I wanted to start an open source project that I hope/expect to have many people submit patches and whatnot. Is it viable to take a strict TDD approach? Can/should I expect/trust collaborators to write quality tests whenever they submit a patch?

One thing I've been thinking about is writing test suites for individual bug reports and feature requests and requiring that all patches/pull requests make the tests pass, but at that point it seems like it would be better just to write the feature/bugfix myself.

As far as I can tell, most of the major open source projects that use TDD (or at least write tests) seem to be mostly written purely by an individual or team, where it's easy to enforce practices such as TDD.

答:
You can't really enforce a TDD (test first) approach on an open source project where patches can be submitted by the general public.

What you can enforce is that all patches must have a set of test cases for the fixes included in the patch and that those test cases, as well as all the existing test cases, must pass. You can enforce this by only giving commit rights to a few trusted developers who are known to use and agree to the policies of the project and by publicly stating that submissions/pull-requests will only be incorporated if they come with passing test cases (with sufficient coverage).

This doesn't ensure that the test is written first, but it does ensure that the test is written.


问:
Why do books say, "the compiler allocates space for variables in memory"?
Why do books say,  "the compiler allocates space  for variables in memory". Isn't it the executable which does that? I mean, for example, if I write the following program,

```<code>#include <iostream>
using namespace std;

int main()
{
   int foo;
   return 0;
}
</code>```

and compile it, and get an executable (let it be program.exe), now, if I run program.exe, this executable file will itself command to allocate some space for the variable foo. Won't  it ? Please explain why books keep on saying, "the compiler will do this...do that".

答:
Yes, you're right, in this case (declaring a variable in a function), the sentence of your book is probably incorrect: when you declare a variable in a function, it gets allocated on the stack upon entering the function. Anyway, a compiler should optimize the situation: if the function is non-recursive (main() is a good candidate for it), the it's OK to "allocate" it compile-time (on the BSS).

(If you are curious about where your variables reside, you can check it a dirty way (if you don't want to examine obj file structure, anyway, why not?), so you can declare some different kind of variables: constant, static, dynamic, malloc()-allocated etc., and display their addresses (use %X formatter in printf() for better readability). The variables reside on the stack will have very different memory addresses.)


答:
There's a similar situation going on with the rather massive number of data members that, again, are useless to everything but the class's internal methods that need them to talk to each other

I suspect that is the real issue. Having a class to be a container for a lot of private functions, for a program written in a non-OO style is not a problem for its own (as others have stated here) - as long as you have mostly pure functions, without any state or access to data members. Such functions can be still tested one by one, and when you change the behaviour of one function, the risk of breaking other functions is still very small.

But when these many functions depend also on many data members and communicate by them, then you are on the road to "spagetti code", because now you introduce dependencies where "everything depends on everything", and a change in one part of your parser may result in unwanted side effects on the other parts.

So my advice is: make your parser functions more functional. Make the communication more explicit - don't use "global variables" (your member variables are in fact global from the viewpoint of your parser), but explicit input and output parameters. This will most probably increase the maintainability and evolvability to a degree that you can still handle it when your parser gets more and more methods over the lifetime of your system.


问:
Should a structure be refactored into smaller structures?
In one of the projects (in C), I have the code that looks like this (the names are obfuscated specially for question to not give out details of the probject):

```<code>typedef struct Module_s {
    /* These fields are parsed by f1() */
    S1 *s11;
    S2 *s12;
    size_t n11;
    size_t n12;
    int i11;

    /* These fields are parsed by f2() */
    S2 *s21;
    S3 *s22;
    S4 *s23;
    char *c24;

    /* These fields are set by f3() and later */
    void *v31;
    bool b32;
    S5 s33[N];
    bool b34;
} Module_t;

{
    /* Read only header of file and
     * parse first 5 fields to determine how to load the rest. */
    Module_t *module = f1(input_file);

    /* Read the rest of file using information set by f1()
     * and determine how f3() should preprocess it. */
    f2(input_file, module);

    /* Preprocess the file using information provided by f1() and f2(). */
    f3(module);

    /* Process the file using the information provided by f2() and f3(). */
    f4(module);
}
</code>```

Then, the question is, is it a good move to separate the Module_t into 3 smaller chunks, which will contain corresponding fields, set by each function? Then each function will only accept and return a smaller part of Module_t, which is probably good, but may complicate further development as interconnections become more complex — and keeping all the dependent fields in one place looks simpler.

What I have in mind is this:

```<code>typedef struct SS1_s {
    /* These fields are parsed by f1() */
    S1 *s11;
    S2 *s12;
    size_t n11;
    size_t n12;
    int i11;
} SS1_t;

typedef struct SS2_s {
    /* These fields are parsed by f2() */
    S2 *s21;
    S3 *s22;
    S4 *s23;
    char *c24;
} SS2_t;

typedef struct SS3_s {
    /* These fields are set by f3() and later */
    void *v31;
    bool b32;
    S5 s33[N];
    bool b34;
} SS3_t;

typedef struct Module_s {
    SS1_t ss1;
    SS2_t ss2;
    SS3_t ss3;
} Module_t;

{
    /* Read only header of file and
     * parse first 5 fields to determine how to load the rest. */
    SS1_t *ss1 = f1(input_file);

    /* Read the rest of file using information set by f1()
     * and determine how f3() should preprocess it. */
    SS2_t *ss2 = f2(input_file, ss1);

    /* Preprocess the file using information provided by f1() and f2(). */
    SS3_t *ss3 = f3(ss1, ss2);

    /* Compose module and
     * process the file using the information provided by f2() and f3().
     * Store ss1 as well for future use. */
    Module_t module = f4(ss1, ss2, ss3);
}
</code>```

So, should I refactor the structure into smaller substructures?

答:
You're looking at this from a purely technical point of view, and that's the problem.

You're asking for a design decision for something that appears to be a domain model, and the design of the domain model should be based almost completely on domain knowledge (i.e. what you have obfuscated) rather than technical details of which part is parsed by which function.

If your "three smaller chunks" represent parts of the model that are conceptually coherent (for which a good criterium is whether you can give them a meaningful name), then yes, you should split it up that way. If not, then don't. The point of design is to make the code easier to understand, and a model is most easily understood when its structures closely reflect domain concepts.

Of course, there's a good chance that this is what you're already doing anyway and those chunks are processed by different functions exactly because they are conceptually separate. But your obfuscation makes it impossible to tell and thus impossible to answer the question.


答:
The only thing done at runtime will be bumping the stack poinbter by a certain amount. So the compiler decides beforehand:

how much stack space will be needed for the function.

At what offset from the stack pointer every individual variable will
be located.

This one can be called "allocation", but of course, during compile time it takles place only in the model the compiler has of the running program.

Title: Why do books say, "the compiler allocates space for variables in memory"?

Body:
Why do books say,  "the compiler allocates space  for variables in memory". Isn't it the executable which does that? I mean, for example, if I write the following program,

```<code>#include <iostream>
using namespace std;

int main()
{
   int foo;
   return 0;
}
</code>```

and compile it, and get an executable (let it be program.exe), now, if I run program.exe, this executable file will itself command to allocate some space for the variable foo. Won't  it ? Please explain why books keep on saying, "the compiler will do this...do that".


问:
Does Open Source lead to bad coding?
I have a thought that I tried asking at SO, but didnt seem like the appropriate place. I think that source sites like Google Code, GitHub, SourceForge... have played a major role in the history of programming. However, I found that there is another bad thing to these kind of sites and that is you may just "copy" code from almost anyone, not knowing if it is good(tested) source or not.

This line of thought has taken me to believe that source code websites tend to lead many developers (most likely unexperienced) to copy/paste massive amounts of code, which I find just wrong.

I really dont know how to focus the question well, but basic thought would be:

Is this ok? Is Open Source contributing to that or I'm just seeing ghosts...

Hope people get interested because I think this is an important theme.

答:
For each 100 programmers that just copies/pastes code without knowing what he's doing, there's almost one that doesn't.

Before Google Code et similia there were snippets all around the web that people copied/pasted, so I don't really see the problem as being relelated to this kind of sites.

Title: Does Open Source lead to bad coding?


问:
What is right choice of Data Access Layer for large application
I am using Singleton pattern for my application, I have used ADO.NET Entity framework as my Data Access Layer, after login to my application, it's taking 3 to 5 minutes to load the dashboard.

Is there a way to reduce the time? Or I have to look for some other methods instead of Entity framework?

答:
Entity Framework does have a warm up time but it's a couple of seconds. 3-5 minutes suggests something seriously wrong with your queries.

You should use something like Linqpad to see what SQL your LINQ to Entities is generating and work at optimizing it. Assuming of course you have done some troubleshooting and worked out that the DAL is your problem area.

If you are happy with the queries another area to look at if the data changes a lot is your indexes. Check your SQL Statistics are up to date and the fields being used for filtering are indexed.


问:
How to implement change and new tools in a small dev team?
I have been tasked with producing a plan for implementing a slight change to the work of our developers (there are eight of us working at this company). The change affects a small portion of our work, but introduces a new tool that the developers aren't familiar with, and a new "step".

Very schematically the change looks like this

Before change:

Write stuff

Do thing X

After change:

Write stuff

Use tool A

Use tool B to do thing X

What I have done so far is that I've written documentation for the use of tool A and tool B.

My question is what should you be keeping in mind when introducing new tools/changes in development to a small development team? How do you assure that the transmission to the new way of doing things is smooth? What type of educational resources should be available?

(The tools introduced are for version control of database schema [so it's only when we make changes the database schema that our development is affected], but I figured that was irrelevant to the topic)

答:
If you want to make sure your colleagues will follow the new process, you should take care about several things:

1) Create an easy to use Quickstart-type guide (I assume your documentation will suffice). Images and short but meaningful text should point everyone in the right direction.

2) Present the new workflow to your colleagues.

3) Point them towards the benefits of the new workflow. If there are no benefits - you might have a problem and a lot of work coming towrads you.

4) Make sure no one is circumventing the workflow. The more benefit the new process has, the easier this will be.


答:
Identify the problem this tool is suppose to solve. Sounds obvious, but you may not have a consensus on what the true problems are with your existing way of handling database changes. Does it take too long? Are mistakes made? Is it nearly impossible to roll-back? Poor documentation?

The team must be convinced this will solve those problems without a disproportionate amount of time and effort.

Make sure you have management support and that there are ways to track and have contingencies for not using the system properly and regularly. You can't just get by on the notion that they'll use it because we "told" them to.

Once you start the adoption and training process, keep your documentation up to date. I don't think you have to do some exhaustive data collection and study to see if this is working. If most of your devs can answer "yes" to the question, "Do you think this tool made managing our database easier?" It was probably successful. Perception is reality.

Title: How to implement change and new tools in a small dev team?

Body:
I have been tasked with producing a plan for implementing a slight change to the work of our developers (there are eight of us working at this company). The change affects a small portion of our work, but introduces a new tool that the developers aren't familiar with, and a new "step".

Very schematically the change looks like this

Before change:

Write stuff

Do thing X

After change:

Write stuff

Use tool A

Use tool B to do thing X

What I have done so far is that I've written documentation for the use of tool A and tool B.

My question is what should you be keeping in mind when introducing new tools/changes in development to a small development team? How do you assure that the transmission to the new way of doing things is smooth? What type of educational resources should be available?

(The tools introduced are for version control of database schema [so it's only when we make changes the database schema that our development is affected], but I figured that was irrelevant to the topic)


答:
Correlation doesn't imply causation. Developers copy/paste code they don't understand because they're bad developers. The availability of such code doesn't turn good developers bad.

If there were no open source projects, there would still be forum posts with code snippets or programming books with examples. So we're back to my first paragraph: bad developers will find a way to be bad at writing code. The blame for copying and pasting code lies with the developers who do it, not with the source code repositories.

Title: Does Open Source lead to bad coding?

Body:
I have a thought that I tried asking at SO, but didnt seem like the appropriate place. I think that source sites like Google Code, GitHub, SourceForge... have played a major role in the history of programming. However, I found that there is another bad thing to these kind of sites and that is you may just "copy" code from almost anyone, not knowing if it is good(tested) source or not.

This line of thought has taken me to believe that source code websites tend to lead many developers (most likely unexperienced) to copy/paste massive amounts of code, which I find just wrong.

I really dont know how to focus the question well, but basic thought would be:

Is this ok? Is Open Source contributing to that or I'm just seeing ghosts...

Hope people get interested because I think this is an important theme.


答:
I hate when someone introduces new tool in hope in fixing some problem without actually discussing this with the developers themselves. So before you start implementing such a tool or forcing developers to use it, make sure they are aware of problems the tool is trying to solve and even better, make them agree that the tool is best way to solve said problem.

There is nothing worse than management adding new tools into development process and developers having to follow it in such a way that kills half of their productivity and morale.