问:
how a pure functional programming language manage without assignment statements?
When reading the famous SICP, I found the authors seem rather reluctant to introduce the assignment statement to Scheme in Chapter 3. I read the text and kind of understand why they feel so.

As Scheme is the first functional programming language I ever know something about, I am kind of surprised that there are some functional programming languages (not Scheme of course) can do without assignments.

Let use the example the book offers,the bank account example. If there is no assignment statement, how can this be done?How to change the balance variable? I ask so because I know there are some so-called pure functional languages out there and according to the Turing complete theory, this must can be done too.

I learned C, Java, Python and use assignments a lot in every program I wrote. So it's really an eye-opening experience. I really hope someone can briefly explain how assignments are avoided in those functional programming languages and what profound impact (if any) it has on these languages.

The example mentioned above is here:

```<code>(define (make-withdraw balance)
    (lambda (amount)
        (if (>= balance amount)
            (begin (set! balance (- balance amount))
                balance)
            "Insufficient funds")))
</code>```

This changed the balance by set!. To me it looks a lot like a class method to change the class member balance.

As I said, I am not familiar with functional programming languages, so if I said something wrong about them, feel free to point out.

答:
"Multiple-assignment operators" is one example of a language feature which, generally speaking, has side effects, and is incompatible with some useful properties of functional languages (such as lazy-evaluation).

That, however, doesn't mean that assignment in general is incompatible with a pure functional programming style (see this discussion for example), nor does it mean that you can't construct syntax which allows actions that look like assignments in general, but are implemented without side effects. Creating that kind of syntax, and writing efficient programs in it, is time consuming and hard, though.

In your specific example, you're right - the set! operator is an assignment. It's not a side-effect free operator, and it's a place where Scheme breaks with a purely functional approach to programming.

Ultimately, any purely functional language is going to have to break with the purely functional approach sometime - the vast majority of useful programs do have side effects. The decision of where to do it is usually a matter of convenience, and language designers will try to give the programmer the highest flexibility in deciding where to break with a purely functional approach, as appropriate for their program and problem domain.


问:
Conceptual question regarding the portability of a software from desktop to mobile
I am planning to create a web solution for the desktop, I would be dividing my task into three steps

Design

Coding

Automated use case

I am wondering if in the future I have to port my web solution as mobile phone native application. How would I do that? Will I go back again to the design phase to redesign or will I just recode some of the already written stuff meant to be for the desktop?

答:
I don't think there is a "safe" way to design your web application to be easily converted to a native mobile application. You can look at solutions like Appcelerator's Titanium and PhoneGap that allow you to build native mobile applications through common web technologies (HTML, JS, CSS). Probably not exactly what you want, but you may get some valuable tips on how to structure your application to be a little bit easier to convert when the time comes.

As one of the comments mentions, the simplest thing you could do right now is approach your design in a way that cleanly separates the user interface from the interaction with the data. A common way to do that for web applications is to build a REST API and have your interface interact only with that. This way, when time comes to move to mobile, you only need to build a mobile interface that will interact with the already existing API to get access to your data, so half your work will already be done.

Hope that helps ;)

ContentLicense: CC BY-SA 3.0


问:
Is it a bad decision to release code that is not open source
I work for a company that owns several closed source software. One of our software is used to service clients and generate income so it has commercial value to us (and it pays my salary).

I've talked about open sourcing the code, but the option of open sourcing under something like the MIT or GPL or any other open source license that allows competitors to install it and offer it to our clients for cheaper has met clear resistance.

What about showing the code but not under an open source license?

The arguments I've been getting against this is that this move will confuse clients and developers and will get us more bad publicity than any good thing. The developer of PAINT.NET used to release his code and got a lot of flack when he started reminding competitors that the code is only for educational purposes and isn't really open source.

I've also been told that open sourcing for the sake of open sourcing doesn't make sense, bla bla bla, and that unless I have a plan for how that's going to bring more revenue, it's not for us. Well, honestly I don't have a plan, but I thought why not try. Of course I can't say if this will help us or hurt us. I don't want to take the responsibility for a move that might hurt a company that's doing well and get people laid off.

As I said, an open source license does not look like an option, so it's between closed source or showing the code but still under a normal copyright license. But as I said there's resistance to showing the code because of the worry that competitors will use our code to create their own.

Does anyone know of any facts that can help with this decision, whether in favor or against showing the code.

答: Its up to the employer's will whether to open-source their code. Even thought you have written that code its not your code. Its your employer's. You need abide by their terms and have good ethics. If open-sourcing the code reduces the revenue then don't open-source it. I'm not against open-source movement.</p>

OwnerDisplayName: samiii

ContentLicense: CC BY-SA 2.5


答:
If there is no assignment statement,how can this be done?How to change the balance variable?

You can't change variables without some sort of assignment operator.

I ask so because I know there are some so-called pure functional languages out there and according to the Turing complete theory,this must can be done too.

Not quite. If a language is Turing complete that means that it can calculate anything that the any other Turing complete language can calculate. It doesn't mean that it has to have every feature other languages have.

It's not a contradiction that a Turing complete programming language has no way of changing the value of a variable, as long as for every program that has mutable variables, you can write an equivalent program that does not have mutable variables (where "equivalent" means that it calculates the same thing). And in fact every program can be written that way.

Regarding your example: In a purely functional language you simply wouldn't be able to write a function that returns a different account balance each time it's called. But you'd still be able to rewrite every program, that uses such a function, in a different way.

Since you asked for an example, let's consider an imperative program that uses your make-withdraw function (in pseudo-code). This program allows the user to withdraw from an account, deposit to it or query the amount of money in the account:

```<code>account = make-withdraw(0)
ask for input until the user enters "quit"
    if the user entered "withdraw $x"
        account(x)
    if the user entered "deposit $x"
        account(-x)
    if the user entered "query"
        print("The balance of the account is " + account(0))
</code>```

Here's a way to write the same program without using mutable-variables (I won't bother with referentially transparent IO because the question wasn't about that):

```<code>function IO_loop(balance):
    ask for input
    if the user entered "withdraw $x"
        IO_loop(balance - x)
    if the user entered "deposit $x"
        IO_loop(balance + x)
    if the user entered "query"
        print("The balance of the account is " + balance)
        IO_loop(balance)
    if the user entered "quit"
        do nothing

 IO_loop(0)
</code>```

The same function could also be written without using recursion by using a fold over the user input (which would be more idiomatic than explicit recursion), but I don't know whether you're familiar with folds yet, so I wrote it in a way that doesn't use anything you don't know yet.

Title: how a pure functional programming language manage without assignment statements?

Body:
When reading the famous SICP, I found the authors seem rather reluctant to introduce the assignment statement to Scheme in Chapter 3. I read the text and kind of understand why they feel so.

As Scheme is the first functional programming language I ever know something about, I am kind of surprised that there are some functional programming languages (not Scheme of course) can do without assignments.

Let use the example the book offers,the bank account example. If there is no assignment statement, how can this be done?How to change the balance variable? I ask so because I know there are some so-called pure functional languages out there and according to the Turing complete theory, this must can be done too.

I learned C, Java, Python and use assignments a lot in every program I wrote. So it's really an eye-opening experience. I really hope someone can briefly explain how assignments are avoided in those functional programming languages and what profound impact (if any) it has on these languages.

The example mentioned above is here:

```<code>(define (make-withdraw balance)
    (lambda (amount)
        (if (>= balance amount)
            (begin (set! balance (- balance amount))
                balance)
            "Insufficient funds")))
</code>```

This changed the balance by set!. To me it looks a lot like a class method to change the class member balance.

As I said, I am not familiar with functional programming languages, so if I said something wrong about them, feel free to point out.

Body:
If there is no assignment statement,how can this be done?How to change the balance variable?

You can't change variables without some sort of assignment operator.

I ask so because I know there are some so-called pure functional languages out there and according to the Turing complete theory,this must can be done too.

Not quite. If a language is Turing complete that means that it can calculate anything that the any other Turing complete language can calculate. It doesn't mean that it has to have every feature other languages have.

It's not a contradiction that a Turing complete programming language has no way of changing the value of a variable, as long as for every program that has mutable variables, you can write an equivalent program that does not have mutable variables (where "equivalent" means that it calculates the same thing). And in fact every program can be written that way.

Regarding your example: In a purely functional language you simply wouldn't be able to write a function that returns a different account balance each time it's called. But you'd still be able to rewrite every program, that uses such a function, in a different way.

Since you asked for an example, let's consider an imperative program that uses your make-withdraw function (in pseudo-code). This program allows the user to withdraw from an account, deposit to it or query the amount of money in the account:

account = make-withdraw(0)
ask for input until the user enters "quit"
    if the user entered "withdraw $x"
        account(x)
    if the user entered "deposit $x"
        account(-x)
    if the user entered "query"
        print("The balance of the account is " + account(0))

Here's a way to write the same program without using mutable-variables (I won't bother with referentially transparent IO because the question wasn't about that):

function IO_loop(balance):
    ask for input
    if the user entered "withdraw $x"
        IO_loop(balance - x)
    if the user entered "deposit $x"
        IO_loop(balance + x)
    if the user entered "query"
        print("The balance of the account is " + balance)
        IO_loop(balance)
    if the user entered "quit"
        do nothing

 IO_loop(0)

The same function could also be written without using recursion by using a fold over the user input (which would be more idiomatic than explicit recursion), but I don't know whether you're familiar with folds yet, so I wrote it in a way that doesn't use anything you don't know yet.


答:
You're right that it looks a lot like a method on an object.  That's because that's essentially what it is.  The lambda function is a closure that pulls the external variable balance into its scope.  Having multiple closures that close over the same external variable(s) and having multiple methods on the same object are two different abstractions for doing the exact same thing, and either one can be implemented in terms of the other if you understand both paradigms.

The way pure functional languages handle state is by cheating.  For example, in Haskell if you want to read input from an external source, (which is nondeterministic, of course, and will not necessarily give the same result twice if you repeat it,) it uses a monad trick to say "we've got this other pretend variable that represents the state of the entire rest of the world, and we can't examine it directly, but reading input is a pure function that takes the state of the outside world and returns the deterministic input that that exact state will always render, plus the new state of the outside world."  (That's a simplified explanation, of course.  Reading up on the way it actually works will seriously break your brain.)

Or in the case of your bank account problem, instead of assigning a new value to the variable, it can return the new value as the function result, and then the caller has to deal with it in a functional style, generally by recreating any data that references that value with a new version containing the updated value.  (This is not as bulky an operation as it might sound if your data is set up with the right sort of tree structure.)


问:
How to convince teammates to use TDD
I am the only person on my team that use TDD. How do I make them to use it?

I am annoyed that when I pull, someone's code will break my tests and I am the one who has to fix them.

Will using github, fork and pull request solve this problem, so that they need to pass the test before the pull is accepted?

I am not the project manager and I can't seems to convince her to use it.

答:
If they resists TDD, it is ok. Many people (including myself) are having problems with writing unit tests first.

However, you should raise a question about having no unit tests at all, and the issue of unit tests breaking. Unit tests are a safety net that prevents lots of possible bugs, and allows code refactoring. Explain about higher code quality, and cleaner code.

I think the best would be to find a video that explains advantages of using TDD, and show it on a meeting.

If she refuses to listen, then you can try to go to someone above her, but that might not be very smart if your boss is so stubborn.

Title: How to convince teammates to use TDD


答:
It's really hard to convince people to change their habits, but here are some things you can try:

Talk to the other developers and explain to them why you think TDD is a good idea.

Convince them (or at least some of them) to try it for a limited time

Try to establish some minimum requirements for working well as a team. They don't necessarily have to do TDD, but they certainly shouldn't be checking in code that is failing unit tests. This is a separate issue than convincing them to use TDD, and is much more important to address.

Try to convince management to enforce a trial period for TDD. You will have to be ready to provide some evidence on why this is a good practice and how it will save the company time and money in the future.

If none of this works at all, you might want to consider working somewhere else. There are plenty of other companies that where your life would be considerably easier.

Title: How to convince teammates to use TDD

Body:
I am the only person on my team that use TDD. How do I make them to use it?

I am annoyed that when I pull, someone's code will break my tests and I am the one who has to fix them.

Will using github, fork and pull request solve this problem, so that they need to pass the test before the pull is accepted?

I am not the project manager and I can't seems to convince her to use it.


问:
What services exist for finding someone specific to then run your own peer to peer software with?
If you give people peer to peer software (such as a web sockets application if the peer to peer part gets implemented, but could be anything) the first step for some kinds of applications is to find a specific person and try to connect with them.  If neither of you has a URI (and knows what it is) you need a third party to handle finding each other and verifying your identities.  After that the third party isn't needed because you go peer to peer.

I could of course write that third party software and put it up on a website, but then I would have to write that third party software and put it up on a website (or a server that isn't a website if that's how I want to do it).

Does anyone offer this service?  Ideally as a website and of course ideally free.

答: irc has been known to be used as a "find a peer" mechanism. otherwise that is the entire purpose of a 'tracker' (in bittorrent parlance). ie to tell peers about other peers particularly interested in the same assets.  So if you have a web server handy, just grab a tracker install and use it. You don't have to code anything for it. your software could just spoof requesting a dummy asset just to find peers.</p>


问:
planning the same app for both OSX and iOS
I would like to ask which is the best strategy for creating an application that will be developed both on Mac and iPad, so to make minumum effort to port it from one platform to the other, starting from iPad, for example, but rather trying to make both at the same time. The application, in fact, would be an iPad-style one on the Mac too. How should I have to plan the project? Which are the main tricks to easily get the goal?</p>

答:
Design the model for reuse. There's very little that's platform-specific about a data model, and you should be able to use the entire model on both iOS and MacOS X. As much as possible, you'll want to include business logic in your model so that any given operation yields the same result on either platform.

Create a visual design that can be reused. Using the same aesthetic elements (color palette, textures, proportions, terminology) in the same ways in both applications will go a long way toward making the user feel that your program works the same way on both platforms.

Make the most of each platform. Forget about reusing user interface code or even reimplementing the same UI on both platforms. Users will want your app to feel the same on both platforms, but they won't want it to be the same. Take advantage of the larger screen, menu bar, and windows on MacOS X, and the touch interface on iOS. You can show lots of information at the same time on MacOS X; on iOS it's better to stick to one or two kinds of data at any moment.


问:
Why do programmers write closed source applications and then make them free?
As an entrepreneur/programmer who makes a good living from writing and selling software, I'm dumbfounded as to why developers write applications and then put them up on the Internet for free.  You've found yourself in one of the most lucrative fields in the world.  A business with 99% profit margin, where you have no physical product but can name your price; a business where you can ship a buggy product and the customer will still buy it.

Occasionally some of our software will get a free competitor, and I think, this guy is crazy.  He could be making a good living off of this but instead chose to make it free.

Do you not like giant piles of money?

Are you not confident that people would pay for it?

Are you afraid of having to support it?

It's bad for the business of programming because now customers expect to be able to find a free solution to every problem. (I see tweets like "is there any good FREE software for XYZ? or do I need to pay $20 for that".) It's also bad for customers because the free solutions eventually break (because of a new OS or what have you) and since it's free, the developer has no reason to fix it. Customers end up with free but stale software that no longer works and never gets updated. Customer cries. Developer still working day job cries in their cubicle. What gives?

PS: I'm not looking to start an open-source/software should be free kind of debate. I'm talking about when developers make a closed source application and make it free.

答:
If you produce closed source, paid software, it's likely that you had to pay for libraries and other gimmicks to develop your product. What you earn must be subtracted of the amount of money you spent in developing that product, not only the time. This leaves a very small net income.

If you use open source free products, you didn't spend any money to use them, but you are also obligated (by some licenses) to reuse the same license for your software. You paid "in code", rather than "in money". It's a different economy, but it gives products anyway.


答: On an existing project, you don't. It's the same as if you'd be making changes to the way curly brackets are placed in legacy code because you dislike the indentation style.</p>

Title: How to convince teammates to use TDD


问:
Why do different languages use different Code Line Delimiters?

Possible Duplicate:

  Why are statements in many programming languages terminated by semicolons?

I just found out that R Programming Language, which is somewhat belong to the C family (I'm not sure about this but it uses {} instead of begin end), uses a new line as a delimiter for a new line of code instead of the semi-colon ;.

Why is some programming language designed to use a new line instead of a symbol like semi-colon which I think will make the code more readable?

Phyton

```<code>total = item_one + \
        item_two + \
        item_three
</code>```

C

```<code>total = item_one +
        item_two +
        item_three;
</code>```

答:
The idea behind semantic whitespace in Python is that the program structure as seen by the interpreter should match the structure as seen by humans as closely as possible. Consider the following C program:

```<code>if ( foo )
    bar;
    baz;
</code>```

At first glance, you'll assume that bar and baz are both conditional; they aren't, however, due to misleading indentation. The C way of thinking is "make your whitespace match semantics". The Python way is more along the lines of thinking DRY: "whitespace already expresses program structure, just parse it".

Body:
The idea behind semantic whitespace in Python is that the program structure as seen by the interpreter should match the structure as seen by humans as closely as possible. Consider the following C program:

if ( foo )
    bar;
    baz;

At first glance, you'll assume that bar and baz are both conditional; they aren't, however, due to misleading indentation. The C way of thinking is "make your whitespace match semantics". The Python way is more along the lines of thinking DRY: "whitespace already expresses program structure, just parse it".


答: Any answer to this is going to be subjective.  There was a big discussion about why the semicolon was used to terminate statements in this question.  The bottom line is that any scheme can be made parseable and it is up to the language designer to choose their own statement termination scheme.  This choice will be influenced by the emotional baggage that they attach to each scheme.  Some people have a pathological loathing for semicolons or other explicit statement termination characters, while others see utility in having an explicit, visible termination character. </p>

Title: Why do different languages use different Code Line Delimiters?

Body:
Possible Duplicate:

  Why are statements in many programming languages terminated by semicolons?

I just found out that R Programming Language, which is somewhat belong to the C family (I'm not sure about this but it uses {} instead of begin end), uses a new line as a delimiter for a new line of code instead of the semi-colon ;.

Why is some programming language designed to use a new line instead of a symbol like semi-colon which I think will make the code more readable?

Phyton

```<code>total = item_one + \
        item_two + \
        item_three
</code>```

C

```<code>total = item_one +
        item_two +
        item_three;
</code>```


答:
The semicolon in C and languages that adopt its syntax is used to terminate statements. Put simply it's the symbol the compiler looks for to know where a statement ends, and by association where the next one begins.

It's mostly a quirk of the language, a convention. Whether it makes code more readable or not depends a lot on your personal preferences, I don't think there is a valid metric that can be applied objectively. Wikipedia has an extensive list of languages organized per their statement terminator, and some of the popular newline terminated / separated languages are:

Haskell,

BASIC,

Eiffel,

Fortran,

Visual Basic

and others.

You can find a very interesting discussion on whether semicolons or newlines should be used as statement separator/terminator here: http://www.cs.nmsu.edu/~jeffery/godiva/semi.html. Sum of the discussion is that Larry Wall really likes his semicolons ;)


答:
There are 2 slightly different issues here: getting people to do TDD and people breaking your tests.

I'm not sure about the first issue, personally I find it an artificial way of working and not suited to all types of development. I'm all for having a good suite of unit tests, but I usually find it more efficient to write the code first and then the tests, since while writing the code my ideas are always changing, and it's a waste of time writing tests too early (IMO).

On the second issue, set up the project so that unit tests are run on check-in, so that other developers don't have any choice but to know they've broken a test.

Title: How to convince teammates to use TDD


答:
I'd try try again to convince the manager. From what you've written, I don't think you could convince your teammates to do TDD behind her back.

You have to speak her language. Manager tend not to be impressed with technology, but they understand the business language:

tests will save time during development, because instead of manual testing (trying to reproduce bug locally, playing with the rails console...) you will be running tests automatically

test will save a lot of time during application maintenance, when you can easily detect bugs whenever you change something. Explain that tests require higher initial investment, but they'll pay for themselves in the long run (maintenance of good tests is usually quick and easy)

and what will you do with the extra time? create moar stuff and make them moar money :)

As for programmers, try this argument (it worked for me, way back): "You're testing code anyway, with or without TDD. Only you do it manually instead of automating it. Smart developers automate as many things as they can."

Title: How to convince teammates to use TDD


问:
Merging similar graphs based solely on the graph structure?
I am looking for (or attempting to design) a technique for matching nodes from very similar graphs based on the structure of the graph*.  In the examples below, the top graph has 5 nodes, and the bottom graph has 6 nodes.  I would like to match the nodes from the top graph to the nodes in the bottom graph, such that the "0" nodes match, and the "1" nodes match, etc.  This seems logically possible, because I can do it in my head for these simple examples.  Now I just need to express my intuition in code.  Are there any established algorithms or patterns I might consider?

(* When I say based on the structure of the graph, I mean the solution shouldn't depend on the node labels; the numeric labels on the nodes are only for demonstration.)

UPDATE:  It has been correctly pointed out that using the structure alone, most of these graphs can't be solved with 100% accuracy.  I've added some thoughts to each graph.

I'm also interested in the performance of any potential solutions.  How well will they scale?  Could I merge graphs with millions of nodes?

In more complex cases, I recognize that the best solution may be subject to interpretation.  Still, I'm hoping for a "good" way to merge complex graphs.

(These are directed graphs; the thicker portion of an edge represents the head.)

This graph is a cycle with 1 node "attached to the outside."  After attaching a second node to the outside it's not possible to determine whether the new node (node 5) is attached to node 1 or 3.  The 4 nodes composing the cycle can't be perfectly matched either.

Nodes 1 and 5 can be swapped in the bottom graph without changing the structure.  Thus, you can only guess with 50/50 accuracy which is the new node.

This graph has symmetry in 2 dimensions and can be mirrored without changing the structure.  Meaning you can swap several nodes without changing the structure.

This last graph is the only one for which you can identify the new node with 100% accuracy.

Thanks Kirk Broadhurst, for pointing this out.

答:
As others pointed out, a site like cstheory may be more helpful. From what I can understand of your problem this sounds pretty much exactly like the subgraph isomorphism problem:

```<code>Given two graphs G and H find a subgraph of H that is isomorphic to G.
</code>```

What you tried to express with "matching" 0 and 1, and so on, is referred to as isomorphism in a graph-theoretic setting. This is the typical mathematical concept of isomorphisms and general graph isomorphism is an interesting problem, for which it is yet unclear if it is NP-complete.

The good news is that this problem is well-known, well-researched and there exists a recursive algorithm that solves it (the paper is linked from the wp article).

The bad news is that the algorithm is exponential (except for some special cases, which seem to not apply to your problem), and in fact, the very problem itself is NP-complete. Yes, unfortunate as it my seem, for the graph isomorphism problem it is not known whether it is NP-complete, but the sub-graph isomorphism problem definitely is NP-complete.

Body:
As others pointed out, a site like cstheory may be more helpful. From what I can understand of your problem this sounds pretty much exactly like the subgraph isomorphism problem:

Given two graphs G and H find a subgraph of H that is isomorphic to G.

What you tried to express with "matching" 0 and 1, and so on, is referred to as isomorphism in a graph-theoretic setting. This is the typical mathematical concept of isomorphisms and general graph isomorphism is an interesting problem, for which it is yet unclear if it is NP-complete.

The good news is that this problem is well-known, well-researched and there exists a recursive algorithm that solves it (the paper is linked from the wp article).

The bad news is that the algorithm is exponential (except for some special cases, which seem to not apply to your problem), and in fact, the very problem itself is NP-complete. Yes, unfortunate as it my seem, for the graph isomorphism problem it is not known whether it is NP-complete, but the sub-graph isomorphism problem definitely is NP-complete.


问:
Solutions for software using many calls to a server
I am developing software that uses many calls to a server. On a client side it's a Silverlight application. Almost every time a user clicks on a button in it, it sends 1-5 WCF calls to a server. There can be up to dozen or so users at a time. The server is a database server that serves data to a client. I am an intermediate level developer and am thinking about caching some data and syncing my changes from time to time. Are there any official solutions or technologies for it, like, patterns and such?</p>

答:
you can use a cross-cutting concern library like, Enterprise library caching block : - http://msdn.microsoft.com/en-us/library/ff647280.aspx, which is highly configurable and useful.

and a better solution, but only if you are using ORM like Nhibernate for example, you have the option first and second level caching: - http://nhibernate.hibernatingrhinos.com/28/first-and-second-level-caching-in-nhibernate


问:
Difference between "String" and "string" in .NET and which is best?
In the .NET Framework, at least in the C# language, we have two "versions" of the string type:

"string"

"String"

It appears that they are interchangeable, but are they really?  If they are not interchangeable, is it generally better to use one instead of the other, and under what circumstances?

答:
string is a C# keyword which is simply an alias for the System.String

..but as it's a keyword, your syntax colouring editor/IDE will show it in keyword colour, same as int, double, if, else, etc. Stylistically, you may prefer to use the keyword rather than the System.String type (or just String after you've done using System;).

This is a niche point though, as although bool, char, int, double and string are all keyword aliases for system types, string is an odd-one-out as it is a reference type and the others are value types.


答:
As for your GUI, Microsoft Silverlight offer a functionality that allows you to do this. However, Silverlight has limitations in that it does not run on all devices. See MS SL Compatibility Tab on This Page. Alternatively, you may want to use some of the new tools such as Telerik Kendo UI that utilizes JavaScript on the GUI. As for the future, HTML-5 and JavaScript may be the winner platform so Kendo may be a safer choice (Other choices exist of course).

As for the back end, if you use the advice from @Roc Martí you should be OK.

When designing the interface, it is kind of difficult to ignore the differences between a 19-inch monitor and a mobile's monitor and its orientation change feature, so I guess some attention is required for the GUI, however, that totally depends on your application of course.

As for the steps you mentioned, I find that they are not in line with any of the  methodologies I am aware of. For example, there is no Planning or Analysis or Requirements determination. Also, there is no Deployment/Production activities listed. So, be careful.

Title: Conceptual question regarding the portability of a software from desktop to mobile

Body:
I am planning to create a web solution for the desktop, I would be dividing my task into three steps

Design

Coding

Automated use case

I am wondering if in the future I have to port my web solution as mobile phone native application. How would I do that? Will I go back again to the design phase to redesign or will I just recode some of the already written stuff meant to be for the desktop?


问:
Learn C++ before/at the same time as C#?
I'm currently learning C#, but wondering whether it is beneficial to learn some C++ before/at the same time as in order to understand the concepts a little better? I've got a C++ book and it does seem rather useful, especially explaining pointers and references.</p>

答:
No, it wouldn't help.

C# and C++ are quite different languages, they might have similar syntaxes but that's where their similarities stop. Now, if you were already familiar with C++, yes, that knowledge would be useful (but not required) while learning C++ or any other language, really.


问:
I just started a job with Scrum and something seems to be missing. I am new to Scrum
The code is a complete mess of a combination of classic ASP/ASP.NET. The scrum consist of us patching up the big mess or making additions to it. We are all too busy doing that to start a rewrite so I am wondering..

Where is the part in Scrum where the developers can have the power to say that enough is enough and demand that they are given time to start the big rewrite? We seem in an endless loop of just patching old code with 'Stories'.

So things are being run by the non-technical people who seem to have no desire to push for a rewrite because they don't understand how bad the codebase has gotten..

So who is in charge of making this big rewrite change happen? The developers? The Scrum Master?

The current strategy is just to find time and do it ourselves without the higher-ups involved since they are mostly to blame for the current mess we are in.. <- insert rant about non-technical people telling technical people what to do here ->.

答:
If you would really be doing Scrum, which I doubt, the Product Owner would be responsible for deciding about a rewrite. Most of the times a rewrite is not a good idea, btw, because it produces no new functionality, only introduces new bugs.

http://blog.objectmentor.com/articles/2009/01/09/the-big-redesign-in-the-sky

http://www.joelonsoftware.com/articles/fog0000000069.html

To expand on "rewrite is not a good idea":

It is almost always better to try a gradual improvement. Like Jarrod Robertson wrote in a comment, find a module that needs improvement become the expert for that module and write a story for the next sprint for improving that particular module. Explain to the product owner why that module needs work.


答:
Where I am and how we work this is what we would do:
Write a new story and hand it to the product owner, who will then decide how to prioritise it.
An example would be:
"As a Developer of Product X, I would like to re-write the code in this area so that future development is more efficient"
Acceptance criteria would then need to be along the lines of:
Re writing / refactoring x so that it is better in this way.

I don't know about the situation where you are but here if we wanted to re-start from scratch it would be a case of sitting down with the product owner and persuading them why and then writing a pile of stories to re-create existing functionality.

The other things we've done to try and deal with bad and / or legacy code have been to include tasks for reworking when tasking out the user stories.

Title: I just started a job with Scrum and something seems to be missing. I am new to Scrum

Body:
The code is a complete mess of a combination of classic ASP/ASP.NET. The scrum consist of us patching up the big mess or making additions to it. We are all too busy doing that to start a rewrite so I am wondering..

Where is the part in Scrum where the developers can have the power to say that enough is enough and demand that they are given time to start the big rewrite? We seem in an endless loop of just patching old code with 'Stories'.

So things are being run by the non-technical people who seem to have no desire to push for a rewrite because they don't understand how bad the codebase has gotten..

So who is in charge of making this big rewrite change happen? The developers? The Scrum Master?

The current strategy is just to find time and do it ourselves without the higher-ups involved since they are mostly to blame for the current mess we are in.. <- insert rant about non-technical people telling technical people what to do here ->.


答: Although learning both languages at the same time may confuse you because of what linguists call false friends, learning one after the other will be of benefit to you. The order in which you learn the two languages does not matter much, as long as you make an effort to master both in sufficient depth. The second language will give you an additional perspective that will prove very useful to your understanding of general programming concepts that are independent of your programming language.

Title: Learn C++ before/at the same time as C#?

Body: I'm currently learning C#, but wondering whether it is beneficial to learn some C++ before/at the same time as in order to understand the concepts a little better? I've got a C++ book and it does seem rather useful, especially explaining pointers and references.</p>


答:
Here is the official definition of the Scrum Development Team from the official Scrum Guide. I put emphasis on the parts that concerns you directly:

The Development Team consists of professionals who do the work of delivering a potentially  releasable Increment of “Done” product at the end of each Sprint. Only members of the  Development Team create the Increment. Development Teams are structured and empowered by the organization to organize and manage their own work. The resulting synergy optimizes the Development Team’s overall efficiency and effectiveness. Development Teams have the following characteristics:

They are self-organizing. No one (not even the Scrum Master) tells the Development Team how to turn Product Backlog into Increments of potentially releasable functionality;

Development Teams are cross-functional, with all of the skills as a team necessary to create a product Increment;

Scrum recognizes no titles for Development Team members other than Developer,
  regardless of the work being performed by the person; there are no exceptions to this rule;

Individual Development Team members may have specialized skills and areas of focus, but accountability belongs to the Development Team as a whole; and,

Development Teams do not contain sub-teams dedicated to particular domains like testing
  or business analysis.

The Development Team is therefore responsible of its own mess and should address it itself, without having to ask anyone outside the team.

Include a technical debt fixing time in each of your future estimation, and ensure that the quality of the software you deliver is top notch.

If you really have to do a complete rewrite, you must address the problem at the Scrum Restrospective. Product Owner may eventually cancel the project and start a new one. Product Owner is also the only one able to cancel a sprint.


答:
To me it's just a question of a personal traits.

Some people find that learning two or three foreign languages at a time more effective than then they concentrate on one. As you can expect most of the people will find this approach not so effective..

So I recommend give it a try, learn both at the same time. If you find youself confused, then switch to one.


问:
How to pass around a debug flag variable?
I need to generate debug output in a java appliation that cannot be debugged by placing break points and traces. I've thus far been placing the debug flag as a static variable in one of the classes and then accessing it from all other classes. But this I suspect will eventually cause massive issues later on. What's the best way to do this?</p>

答:
Consider using a logging framework like log4j. Log4j is very flexible and extendible. This is clearly the best option.

If you cannot use such a framework, you have to tell all parts of your program generating debug output, whether this is a debug run or not. This can be done in two ways. Either using static access to some variable/singleton or passing the information to the relevant parts. Both solutions have advantages and disadvantages.

In general the static/singleton pattern is considered harmful because it introduces a global variable and therefore global state which can make testing difficult. However, as long as you are only generating output which does not interfere with any other part of your program you should be fine.

The other approach is to pass the information via a constructor for example. This approach does not hide the dependency of the object on the information and is preferable in theory. However, now you have to pass this information to all classes possibly generating debug output. If you got lots of these classes and/or they are buried deep in the system, you will have to do a lot of boilerplate coding. Dependency injection frameworks (e.g. Guice) are designed to help you with this kind of boilerplate code. If you already use DI this is probably the best way. But if this feels like using a sledge hammer to crack a nut, you should consider using the static access (which is btw what log4j does).


答: If all you do in response to a flag is producing debug output, then using a logging framework is a better choice: you can set different log levels to individual classes using a centrally located configuration, and control the way the logging information is delivered to you (file, console, database, etc.)</p>

Title: How to pass around a debug flag variable?

Body: I need to generate debug output in a java appliation that cannot be debugged by placing break points and traces. I've thus far been placing the debug flag as a static variable in one of the classes and then accessing it from all other classes. But this I suspect will eventually cause massive issues later on. What's the best way to do this?</p>


答:
Disclaimer: I work in both languages (and a few more) on a daily basis.

When I was studying CompSci at University (studying  Comp Sci & Games Development), the curriculum they used taught us C# in the first year (to get the basics of CompSci and Software Development), we moved onto C++ in the second year (so that we could study, what you are calling "the concepts" and some hardcore Comp Sci ) and in the third year we moved onto C and Assembly (so that we could see the difference that speed and efficiency make to the design and the amount of work you have to put in).

I'd already studied a little Assembly and C in my college days (I'm from the UK, so I'd have been 18 at the time. I studied Electronics and Telecommunications, if you're wondering). So by the time I got to Uni I already had an understanding of why certain aspects of C# where designed the way that they are (admittedly, this was back in '04 and the language has changed quite a bit since then).

Oh, by the way, I also studied Japanese at Uni, too

I can't imagine what it would be like studying them both at the same time. I suppose it depends on how far down the rabbit hole you want to go, but I'd steer clear of C++ for now as you might end up trying to learn too much all at once. Some people can do this, but most people can't - I'm not trying to offend anyone, but that's the way it is.

I had a friend at Uni (who was new to software development) who decided, during the first few weeks, that he wanted to write his own operating system and that C# wasn't going to cut it. So, off he went to the library to read up about C++ and C. To be fair, he studied really hard, and learned a lot about the C family. Except that he failed all of his assignments (on account of programming them all in a C++/C# hybrid) and never got anywhere with his operating system (on account of being a 1st year student with grandiose ideas). He ended up dropping out, after taking the first year twice more.

I suppose the point I'm trying to make is: It's great that you seem to have the enthusiasm to learn and progress ("...wondering whether it is beneficial to learn some C++ before/at the same time...") and that will serve you well in the working world (from my experience, anyway. As employers tend to prefer developers who are willing to learn). But you need to be careful not to confuse yourself by learning too many things all at once.

It's great to have more than a single tool on your belt, but the ability to know and understand (and that's the key point) why these tools differ and when you use them is more important and useful.

For instance: I can knock up a basic server/client program in minutes using C# and .NET and it will make use of all the memory management and auto closing of ports and sockets provided by .NET but it won't be very efficient.

I could do the same thing in C++ and it would be efficient, but it would take, considerably, longer to create and would involve writing a LOT of custom code. There would be no memory management provided for me, and no auto closing of ports and sockets. But it would be really fast and efficient.

Sorry for the long answer. I hope it helps.


问:
The rule of 5 - to use it or not?
The rule of 3 (the rule of 5 in the new c++ standard) states :

If you need to explicitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them.

But, on the other hand, the Martin's "Clean Code" advises to remove all empty constructors and destructors (page 293, G12:Clutter) :

Of what use is a default constructor with no implementation? All it serves to do is clutter up the code with meaningless artifacts.

So, how to handle these two opposite opinions? Should empty constructors/destructors really be implemented?

Next example demonstrates exactly what I mean :

```<code>#include <iostream>
#include <memory>

struct A
{
    A( const int value ) : v( new int( value ) ) {}
    ~A(){}
    A( const A & other ) : v( new int( *other.v ) ) {}
    A& operator=( const A & other )
    {
        v.reset( new int( *other.v ) );
        return *this;
    }

    std::auto_ptr< int > v;
};
int main()
{
    const A a( 55 );
    std::cout<< "a value = " << *a.v << std::endl;
    A b(a);
    std::cout<< "b value = " << *b.v << std::endl;
    const A c(11);
    std::cout<< "c value = " << *c.v << std::endl;
    b = c;
    std::cout<< "b new value = " << *b.v << std::endl;
}
</code>```

Compiles fine using g++ 4.6.1 with :

```<code>g++ -std=c++0x -Wall -Wextra -pedantic example.cpp
</code>```

The destructor for struct A is empty, and not really needed. So, should it be there, or should it be removed?

答:
For a start the rule says "probably", so it doesn't always apply.

The second point I see here is that if you have to declare one of the three, that's because it's doing something special like allocating memory. In this case, the others wouldn't be empty since they would have to handle the same task (such as copying the content of dynamically allocated memory in the copy constructor or freeing such memory).

So as a conclusion, you shouldn't declare empty constructors or destructors, but it's very likely that if one is needed, the others are needed too.

As for your example:  In such a case, you can leave the destructor out.  It does nothing, obviously.  Usage of smart pointers is a perfect example of where and why the rule of 3 doesn't hold.

It's just a guide for where to take a second look over your code in case you may have forgotten to implement important functionality you might otherwise have missed.

Title: The rule of 5 - to use it or not?


答:
Here your potential (*) equivalent to the default one constructor/assignment/destructor has a purpose: document the fact you have though about the issue and determined that the default behavior was correct. BTW, in C++11, things have not stabilized enough to know if =default can serve that purpose.

(There is another potential purpose: provide an out of line definition instead of the default inline one, better to document explicitly if you have any reason to do so).

(*) Potential because I don't remember a real life case where the rule of three didn't apply, if I had to do something in one, I had to do something in the others.

Edit after your addition of an example. your example using auto_ptr is interesting. You are using a smart pointer, but not one which is up to the job. I'd rather write one which is -- especially if the situation occurs often -- than doing what you did. (If I'm not mistaken, neither the standard nor boost provide one).

Title: The rule of 5 - to use it or not?

Body:
The rule of 3 (the rule of 5 in the new c++ standard) states :

If you need to explicitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them.

But, on the other hand, the Martin's "Clean Code" advises to remove all empty constructors and destructors (page 293, G12:Clutter) :

Of what use is a default constructor with no implementation? All it serves to do is clutter up the code with meaningless artifacts.

So, how to handle these two opposite opinions? Should empty constructors/destructors really be implemented?

Next example demonstrates exactly what I mean :

```<code>#include <iostream>
#include <memory>

struct A
{
    A( const int value ) : v( new int( value ) ) {}
    ~A(){}
    A( const A & other ) : v( new int( *other.v ) ) {}
    A& operator=( const A & other )
    {
        v.reset( new int( *other.v ) );
        return *this;
    }

    std::auto_ptr< int > v;
};
int main()
{
    const A a( 55 );
    std::cout<< "a value = " << *a.v << std::endl;
    A b(a);
    std::cout<< "b value = " << *b.v << std::endl;
    const A c(11);
    std::cout<< "c value = " << *c.v << std::endl;
    b = c;
    std::cout<< "b new value = " << *b.v << std::endl;
}
</code>```

Compiles fine using g++ 4.6.1 with :

```<code>g++ -std=c++0x -Wall -Wextra -pedantic example.cpp
</code>```

The destructor for struct A is empty, and not really needed. So, should it be there, or should it be removed?


问:
How to improve designer and developer work flow?
I work in a small startup with two front end developers and one designer. Currently the process starts with the designer sending a png file with the whole page design and assets if needed. My task as front end developer is to convert it to a HTML/CSS page. My work flow currently looks like this:

Lay out the distinct parts using html elements.

Style each element very roughly (floats, minimal fonts and padding) so I can modify it using inspection.

Using Chrome Developer Tools (inspect) add/change css attributes while updating the css file.

Refresh the page after X amount of changes

Use Pixel Perfect to refine the design more.

Sit with the designer to make last adjustments.

Inferring the paddings, margins, font sizes using trial and error takes a lot of time and I feel the process could become more efficient but not sure how to improve it.

Using PSD files is not an option since buying Photoshop for each developer is currently not considered. Design guide is also not available since design is still evolving and new features are introduced.

Ideas for improving the process above and sharing how the process looks like in your company will be great.

答:
Few things you can do to minimize your workflow

use livereload.com  : auto refresh your web page on save, update your css change without refresh and script compile for sass, less, coffee ....

start with a framework, so you don't need to worry about floats, positiong, sizes... i just wrote my 3rd framework http://devric.co.cc/lab/jelly/_presentation/

or you can use something like http://foundation.zurb.com, their one is professional.

but the reason for my framework is that i broke it down into really small pieces, smaller than foundations. which it can be easily managed and replaced between each project.
you just got to manage your config.css and do a minify at the end to compress it down to one css file ( i use juicer merge app.css, which takes 3second to compress something like 23 files. )

for example, you should sit down with the designer and unify the grid sizes with them, if pixel perfect is needed, this way they will design within your grid size to steamline your workflow.

For pixel perfect just take a screenshot of your site in 80% transparency overlay on top of psd, you can use gimp to compare psd file, or just save as jpg, and compare screenshot with the


答:
Why can't your design team deliver things in the correct medium? You are building a website not a photo gallery exhibit. We make our use HTML and CSS and get them working directly in the project with the developers.

In the cases where this is impractical, we require a style guide from the designers showing things like fonts, font sizes, margins, padding and such. If the whitespace is important to them they can at least tell you how big it is.

Title: How to improve designer and developer work flow?

Body:
I work in a small startup with two front end developers and one designer. Currently the process starts with the designer sending a png file with the whole page design and assets if needed. My task as front end developer is to convert it to a HTML/CSS page. My work flow currently looks like this:

Lay out the distinct parts using html elements.

Style each element very roughly (floats, minimal fonts and padding) so I can modify it using inspection.

Using Chrome Developer Tools (inspect) add/change css attributes while updating the css file.

Refresh the page after X amount of changes

Use Pixel Perfect to refine the design more.

Sit with the designer to make last adjustments.

Inferring the paddings, margins, font sizes using trial and error takes a lot of time and I feel the process could become more efficient but not sure how to improve it.

Using PSD files is not an option since buying Photoshop for each developer is currently not considered. Design guide is also not available since design is still evolving and new features are introduced.

Ideas for improving the process above and sharing how the process looks like in your company will be great.


答:
When I wanted to encourage the use of Test Driven Development I ran a Cyber-Dojo. With this sort of exercise, the emphasis is not on the code itself, but on the process of writing the code.

We spent an afternoon, in pairs, repeating the same kata, but under different conditions. We started with all groups doing one exercise at the same time. This provided a baseline.

We then discussed some of the basic principles of TDD, had everyone change partners and repeat the same kata. We repeated the same kata to de-emphasise the generation of code and instead concentrate people on the process of naming test cases and the Red/Green cycle.

Then we repeated the kata again, but roughly every 10 minutes one person in each group would move to another group, simulating the rather fluid team environments we often find ourselves in these days.

In the final iteration, we had both partners change every 10 minutes or so into different groups.  This helped to demonstrate that with TDD, even the handover from one team to a completely different one needn't necessarily be too painful, since the project should only every be one Red/Green cycle from working.

The interesting thing was, there were few people who had done any TDD before the session, but what TDD knowledge there was rapidly spread until by the final iteration through the kata, most people were thinking in a TDD way or could at least appreciate why it might be beneficial.

People generally said that the afternoon was both fun and informative and we are now looking at other ways to use Cyber-Dojo at my workplace.

Cyber-Dojo, written by Jon Jagger, works incredibly well for this sort of exercise. It is a web based integrated environment for doing deliberate practice of TDD and learning about team dynamics. It has lots of kata's selected specifically to help people concentrate on the process of TDD and not the problem. It also supports a range of languages, from Python and Ruby to Java and C++.

The best thing is, after doing a kata you can then go back and look at the red/green progression (or maybe not *8') of each of the groups participating. It's traffic lights are a great way to visualise how the TDD process works.

If you want your own CyberDojo server, the whole project can be found at github and there is even a Turnkey Linux appliance virtual machine linked from there, which means that assuming you already have VMware player or VirtualBox installed, you can be up and running within a few minutes of downloading the appliance!

Title: How to convince teammates to use TDD


问:
What are the design decisions involved in choosing how to expose a Java web application?
There are many ways to expose a Java web application to the consumer: application container (JBoss etc), servlet container (Tomcat etc), OSGi (Knopflerfish etc), self-executable WAR (Winstone etc) and so on. Are there any clear considerations where one approach should be favoured over another?

As an example, could a collection of self-executable WARs running as raw Unix processes outperform the same applications deployed within Tomcat taking into account administration and scalability concerns?

答:
I dont have a formalized view of considerations as such but can list some factors in making the decision:

Redeployment - Frequent redeployment causes problems in EARs with memory fragmentation so how often will we need to be releasing updates. Will these need an outage on the servers (if deployed on JBoss/Weblogic)?

Shared Resources - Access to shared resources such as JDBC etc if bundled in the same EAR. Will these cause contention and can I make changes to one without affecting the other? Usually all WARs will get affected by changes made at the EAR level.

Upgrades to servers - Deploying with Tomcat and so on requires a possible upgrade to the base web container to take advantage of new Java/server features when available. Example Tomcat 6 to 7.

Size - Downloadable size of installation package if distributing container along with application. How large should we keep it?

Control over configuration - Internal config within my app plus access to config.xml or server.xml on the underlying containers. Do we want clients to edit these? or do we bundle all these in with preferred settings?

Memory footprint - Full blown servers obviously need more Heap (Xmx) than a Winstone app

What is client already running - Existing servers in their data centre could be re-used if Weblogic or Tomcat infrastructure already in place (for example).

Cluster requirements - will an additional performance requirement require adding servers into a cluster? How good is JBoss clustering versus running on Tomcat and what is the impact on the application code in clustered environment w.r.t. caching etc ?


问:
Different callbacks for error or error as first argument?
We (and the JS SO chat room) had a talk with @rlemon some days ago about his Little-XHR library about error handling.

Basically, we wanted to decide which error handling pattern should be used:

```<code>xhr.get({
    // Some parameters, and then
    success: function(data) {},
    failure: function(data) {}
})
</code>```

Or:

```<code>xhr.get({
    // Some parameters, and then
    callback: function(err, data) {}
})
</code>```

One is more jQuery-like, while the other is more Node-like. Some say that the first pattern makes you think more about handling error. I think the opposite, since you may forget the other callback function, while the argument is always there on the second pattern.

Any opinion/advantage/drawback about both these patterns?

答:
Generally, I like to remember that explicit is always better than implicit.

Using this, I'd typically side with explicit success and failure functions - you know exactly what you're dealing with the moment you open that code up - success deals calls that finished successfully, while error deals with calls that had a problem.

The alternative, using a single method, will take longer to read when you go to modify that code. Besides, you'd likely end up with something like this;

```<code>xhr.get({
    callback: function(err, data) {
        if (err) {
            // handle that error somehow
        }
        else {
            // deal with success somehow
        }
    }
})
</code>```

And that kind of boilerplate gets boring, fast.

Not to mention, if you forget to add this boilerplate, and for example, you're only handling success, then a new developer entering the code base may not see see a problem with it. But having explicit error/success callbacks, they'd be able to see pretty quickly that you're missing an error callback and start working on a way to handle it, or at least figure out "well, this is only handling success - I must find a way to handle errors". It makes the code seem less magical.

Body:
Generally, I like to remember that explicit is always better than implicit.

Using this, I'd typically side with explicit success and failure functions - you know exactly what you're dealing with the moment you open that code up - success deals calls that finished successfully, while error deals with calls that had a problem.

The alternative, using a single method, will take longer to read when you go to modify that code. Besides, you'd likely end up with something like this;

xhr.get({
    callback: function(err, data) {
        if (err) {
            // handle that error somehow
        }
        else {
            // deal with success somehow
        }
    }
})

And that kind of boilerplate gets boring, fast.

Not to mention, if you forget to add this boilerplate, and for example, you're only handling success, then a new developer entering the code base may not see see a problem with it. But having explicit error/success callbacks, they'd be able to see pretty quickly that you're missing an error callback and start working on a way to handle it, or at least figure out "well, this is only handling success - I must find a way to handle errors". It makes the code seem less magical.


问:
Scrum: What if the Product Owner has tasks?
I have just started working with a team that has picked up some aspects of Scrum (two week timeboxing) but not others (the team does not currently agree to all estimates or to the number of points in a sprint, but I'll change this soon.)  The product owner is also a technical resource (scientist) with some development background.

Is it appropriate to have the product owner's tasks (which mostly involve research) mixed in with the team's tasks (some of which are research and some development).

答:
The Product Owner is responsible for maximizing the product's value and return on investment. It might seem simple but it's usually a full-time and very demanding role - arguably the most difficult one in Scrum. It involves a lot of high-level strategic work as well as lower-level tasks, from analyzing market opportunities and consulting the stakeholders and users of the product to make the right decisions, to keeping the product roadmap and backlog always polished, attending planning and review activities, making himself available for the team to answer their questions, etc.

If the PO is in charge of other tasks besides that, I'd only see them as marginal in most cases. So my answer would be yes, create tasks for the PO if you really have to and if they contribute directly to producing the sprint's software increment, but I don't see that happening often in your average Scrum project.

OwnerDisplayName: Lauren J


答:
Separate callbacks

If the xhr.get() call succeeds, then err is redundant. If the call fails. data is redundant. Rather than forcing client code to check the state of one or the other, don't pass both.

If it turns out that success could represent partial success, indicate that separately. Failure is usually the bail-out option.

I've worked with developers that only ever handle the success case and in many scenarios just implementing a success callback would suffice in this case. A multi-state callback would be catastrophic option for that style of programming as they'd assume success.

Title: Different callbacks for error or error as first argument?

Body:
We (and the JS SO chat room) had a talk with @rlemon some days ago about his Little-XHR library about error handling.

Basically, we wanted to decide which error handling pattern should be used:

```<code>xhr.get({
    // Some parameters, and then
    success: function(data) {},
    failure: function(data) {}
})
</code>```

Or:

```<code>xhr.get({
    // Some parameters, and then
    callback: function(err, data) {}
})
</code>```

One is more jQuery-like, while the other is more Node-like. Some say that the first pattern makes you think more about handling error. I think the opposite, since you may forget the other callback function, while the argument is always there on the second pattern.

Any opinion/advantage/drawback about both these patterns?


答:
On real projects with deadlines people want to focus on getting the work done with what they know. That's just human nature. And if you never learned TDD, you would be the same as her in this situation. I guarnatee it.

Why doesn't the garbage collection crowd love, learn, and live RAII? How could you champion automatic memory management but hold on to the old fashioned management for general resources like files, connections, etc? Because RAII is a technology they don't know, understand, and don't have time to use when they have a deadline that needs work done.

I bet you don't use RAII and aren't willing to learn and understand it for your current project. Same as your coworker who is not willing to learn and understand TDD.

Title: How to convince teammates to use TDD


答:
I'm going to be really blunt...

Are you in charge of the developers in this job?

Are you the project leader?

How much "stake" do the developers hold in the project?

What is your business justification for a rewrite?

What is it about the code base that makes it entirely useless and unrecoverable?

You've stated that you have just started a job, and yet you already appear to be a master of the situation there. Perhaps I have misunderstood the intent of your question, but I get the impression that you've entered a job where you see a number of problems, and you have jumped to the easiest conclusion in which the code is broken and the only way forward is a rewrite, but have you really considered the cost to your employer to do so?

With any existing code base - no matter how poor a state it is in - the owner will usually have a sizable investment in the product(s) the code represents.  There are both direct and indirect costs associated with the code base, and a rewrite is often the very last thing you want to do as a software developer, as you risk devaluing your code assets, and thus getting a lower return on all of your prior efforts.

Take the Window's operating system as an example. With each new version created, there has been a big chunk of code carried forward from the previous version.  Sometimes, entire libraries and APIs are dragged forward across several generations of OS.  Why?  Because the developers know that these elements work, have been tested, have been patched and fixed to prevent security and memory problems, and because they have cost a hell of a lot of money to get into that state. Nobody wants to throw away working code when it is making them money, even if the maintenance costs are relatively high, the cost to start from scratch will always be higher still, and in a company like Microsoft's case, they have billions in the bank which allow them to start from the beginning if they want to, but they don't because they want to maximize their return from their investment. Your employer is no different to Microsoft, except for the bit about having billions in cash to throw at a project.

So the code is a mess, and it sounds like there are communication and boundary issues between the various areas of the company.  What can you or your colleagues do about this?

One option is to simply continue on as the team has been, and hope for a miracle in the future. Probably not a good idea, and likely to only increase your frustration and stress.

A better option is to simply knuckle down and do your jobs, but as a part of this look for opportunities to add tests to support those areas of code that appear to be the most fragile, then refactor them until they become more stable.  You'll have an easier time making a compelling argument to improve the company's investment instead of arguing to simply throw it all away.

An even better option is to be organised as a team, and to ensure you get someone on side with enough seniority that they can make a good case to allow the team more flexibility to schedule time to improve the code base.  I don't care how busy a company is, or how rigid the schedule appears to be, there are always the occasional "lulls" in activity that can be used to squeeze in an improvement or two.  It's even better however if the improvements can be made while completing other tasks. If it were me, I'd be cozying up to a manager and introducing them to concepts in some of the canonical books that software developers read.  Clean Code is probably the one your team needs the most. Plant a few seeds about how to improve the code, and provide a few examples of what you mean. A good manager will see the value of adding incremental improvements to code, especially if you are able to describe the concept of Technical Debt. Help your team leader or manager to make a good business case for improving code, and they'll have a better motivation to act on it.

It's also not enough to say "the code is untidy". You need to encourage your colleagues to practice coding clean all of the time, and to use clean coding technique to encourage a little tidying up as you go. I have a little poster that I print out and hang from my office wall every time I take on a new job.  It says "Always strive to leave the code a little more beautiful than you found it". Right next to it I add another which says "Lilies don't need to be gilded". They both serve to remind me that I should always try to improve what I find, but avoid simply gold-plating one problem with another.  Massive rewrites are often the worst sort of "gold-plating", because they are often done for the wrong reasons. Sure an entirely new product version might be justifiable at some point, but rarely simply because the code base is a mess.


答:
Deciding on big rewrites is a business decision. You can try to influence business decisions by selling in your point of view to the people responsible for the business part of things.

However; the change in code quality from one iteration to the next is a developer decision.
If you allow the code quality to decline, you are adding technical debt in order to fulfill the product owner's expectations now.
What you can do is to start taking responsibility for the code you write and make sure it improves the code base, not the other way around. Now this means you will lose velocity, since you are continuously decreasing the amount of technical debt, and your product owner will surely be dissapointed. You can try to explain that in your eagerness to please, you've let the code quality degrade and you're now taking steps to correct this issue.

Now, I realize that it's a terrifying step to take, and it might feel tempting to delay it just one more sprint so you can get out feature X before an important deadline.
Unfortunately, it will just get more difficult the longer you wait.

By the way, this is not strictly a Scrum issue, nor am I suggesting a solution that is specific to Scrum. This is about developers taking ownership of the code.


答:
The developers are responsible for alerting the world on the code base's current state. This can happen during a daily scrum, a retrospective or just informally. It may seem obvious but if you don't express clearly what a mess it is and how much time you waste because of it, no one will ever notice. The Scrum Master will typically be responsible for passing the information on to the PO and the people in charge of the project and persuading them something needs to be done, and then facilitating the implementation of a solution by the team.

As a side note, a big bang rewrite is IMO not necessarily the right answer to this kind of problem. However fed up the devs are with the current code base, taking small measurable steps towards a cleaner architecture is often a better idea since you can see the progress, justify your work by regularly showing the PO the accomplishments and continue the flow of implementing new user stories in parallel as opposed to getting lost in an endless, resource-monopolizing makeover.


答:
I definitely suggest learning one after the other. You will most likely get confused between the two of them if you learn both at the same time, that's what happened to me when I learned Python and Ruby at the same time. It would be helpful though, to maybe learn a little bit of C as you go along with C#. For some good C++ resource recommendations, check out:

1

2

3


答:
I'm usually skeptical when people push for "big rewrites". There are some cases where it definitely makes sense but most of the time, that legacy code has value (in that it's already in production and being used for the purposes that inspired its creation). Performing a big rewrite is in many cases the opposite of agile. How long would it take to bring the new version of the application to a point where it can viably replace the existing application.

The approach I'd prefer is what Martin Fowler calls the strangling vine. Implement new functionality (including changes to existing functionality) using the new approach but use the existing application as a trellis which the new functionality can grow upon. This gives you the best of both worlds, you don't have to stop everything while the big rewrite is being brought up to snuff, but you get the benefit of writing new code that takes advantage of updated frameworks. It's definitely a more difficult approach than starting clean and might not be as sexy, but it provides more value to the business than dumping everything that's there because it's outdated.


问:
How to write functionally in a web framework
I love Rich Hickey, Clojure and Haskell and I get it when he talks about functions and the unreliability of side-effecting code.

However I work in an environment where nearly all the functions I write have to read from the database, write to the database, make HTTP requests, decrement a user's balance, modify a frontend HTML component based on a click action, return different results based on the URI or the POST body. We also use PHP for the frontend, which is littered with functions like parse_str(), which modifies an object in place. All of these are side-effecting to one degree or another.

Given these constraints and the side-effecting nature of the logic I'm coding, what can I do to make my code more reliable and function-able?

答:
I found what I think is a very interesting approach to your question in "Object-Oriented Modeling and Design", by  Rumbaugh et al. The edition I have is a bit
old (1991) but I think the concepts are still quite applicable. Also, I cite
from this book but I guess you can find similar concepts by other authors and
in more recent pubblications.

In Chapter 6, Functional Modeling, the authors explain that building a functional model is only one aspect of the analysis and design of an application. The other two models are the object model (the structure of your system, in terms of objects, their associations, and their operations / methods) and the dynamic model (systems states, events, state transitions).

The functional model "shows how output values in a computation are derived from input values" (page 123 in my 1991-edition). In other words, even though you have a lot of state (e.g. files, database) that you modify, and a lot of user input (events) that may guide your computation, you can identify the purely functional aspects in your application, with clear inputs, outputs, and data transformations, and no side effects (the side effect may consist in storing the result of a computation, but this is a separate step).

Further, on page 137, there is a section about the relation between functional, object, and dynamic models. I cite again: "The functional model shows what has to be done by a system. [cut] The object model shows the doers - the objects. The dynamic model shows the sequence in which the operations are performed."

So, these are just some rough ideas (you can do some reading on object-oriented design to have more details), but I think you can apply the following guidelines to the programming of a web application:

Try to identify data flows and transformations inside your application, with clear inputs (e.g. a database table) and clear output (e.g. a GUI table).

Clearly separate in your code the parts that (1) only read / query data (2) only write (save or update) data (3) only transform data.

All procedures that are in category (3) should

Either produce a completely new data object (the result) without changing the inputs or any other data in the environment;

or change an input data object and return it as the result (the input value is destroyed and a new output value is created; for efficiency reasons one common data object is used for both input and output), again without changing the remaining inputs or any other data in the environment.

So, IMO even if you are developing an application that has a lot of input / output with the user, other applications, and mass storage, you can still try to isolate its functional parts and implement them more cleanly.


问:
Why is it called a 'Here Document'?
(Let me know if this is the wrong SE for this)

Why is a Here Document (or Heredoc) called that? Wikipedia didn't have anything to say on that particular subject. I did find unix docs describing a "Here is document", is that the original form?

答:
Because it's all data from << HERE

all the way

down

to

right about

wait for it

HERE;

Title: Why is it called a 'Here Document'?


问:
Is it a bad decision to release code that is not open source
I work for a company that owns several closed source software. One of our software is used to service clients and generate income so it has commercial value to us (and it pays my salary).

I've talked about open sourcing the code, but the option of open sourcing under something like the MIT or GPL or any other open source license that allows competitors to install it and offer it to our clients for cheaper has met clear resistance.

What about showing the code but not under an open source license?

The arguments I've been getting against this is that this move will confuse clients and developers and will get us more bad publicity than any good thing. The developer of PAINT.NET used to release his code and got a lot of flack when he started reminding competitors that the code is only for educational purposes and isn't really open source.

I've also been told that open sourcing for the sake of open sourcing doesn't make sense, bla bla bla, and that unless I have a plan for how that's going to bring more revenue, it's not for us. Well, honestly I don't have a plan, but I thought why not try. Of course I can't say if this will help us or hurt us. I don't want to take the responsibility for a move that might hurt a company that's doing well and get people laid off.

As I said, an open source license does not look like an option, so it's between closed source or showing the code but still under a normal copyright license. But as I said there's resistance to showing the code because of the worry that competitors will use our code to create their own.

Does anyone know of any facts that can help with this decision, whether in favor or against showing the code.

答:
I have certainly seen some companies (with some classes of software) provide the source code to any paying customer, either for an extra licensing fee or as part and parcel of a normal installation. This, however, tends to be niche markets, with few established vendors and clients with demands that can more easily be met by letting them look at the source.

But, that would depend on what you're looking at making happen by allowing people to look at your source code. Unless you have a plan that's a bit more fleshed out than "let's try it and see what happens", I would probably have to argue against it.


问:
How to share problem solving knowledge in a multiteam group?
I've been working in multiteam groups for as long as I've been a web developer, and in my experience, a team can be a lonely soldier or several people; generally a company will have multiple teams working on different projects and once the project is out in the wild, any team can perform maintenance on it.

This is a simple example since I'm not talking only about project related knowledge, but "craft related" knowledge, but it should give you an idea of how I'm used to working:

Since we work on modularised teams, sometimes I feel like the teams are too tightly focused in their projects. I've seen cases where after an hour of discussion, the question was asked aloud and someone on a totally unrelated project suggested a much simpler solution.

The problem is difficult to solve because people tend not to be available all the time, and sometimes the person with the knowledge can't afford the time to go through a problem with the asker, but could do it themselves easily.

I've thought about software based solutions, something along the lines of SE, but I'd like to know other programmers opinions on the subject.

EDIT

I don't know if this is a problem that a wiki can solve, because I feel that wikis don't encourage the user to actually ask questions, but rather to write articles, and sometimes we don't know the knowledge we need before needing it.

答: We use RedMine, which integrates issue tracking, tickets, wiki and more into a nice project management web application. Though there are others of the kind of course.</p>


答:
I worked for a fast-growing startup company that went from under 100 to 500+ people in two and a half years, where the issue of knowledge sharing quickly became a problem. The company built a strategy that worked reasonably well, and included three key components:

Documentation

Standardization

Internal Training

Each team was responsible for releasing documentation along with the updates to their component. Release of the code without documentation was considered incomplete. The quality of the documentation was evaluated independently by the "target audience" (i.e. the other team inside the company that used the component). Errors or omissions in the documentation were entered in the bug tracking system, and treated as first-class defects.

There was also a requirement to mention documentation when answering e-mail questions about your component. If you could not locate a piece of documentation that answers the question, the policy expected you to write one, or modify an existing document to answer the question. This practice helped us keep our internal documentation at a respectable level of quality.

The company also created a coding standards committee, which met periodically, and published updates to company-wide coding standards. These standards paid a lot of attention to using the libraries built in the company, and laid out a framework for implementing new libraries in architecturally consistent ways.

Finally, each team was responsible for publishing a set of training course materials for the rest of the company. Team leads of the teams with wide internal exposure also ran internal training courses once or twice per quarter, so if you wanted to get trained on an internal component, you could learn it hands-on straight from the source.

Ultimately, knowledge sharing is a process issue, not a technical issue. Technology can definitely help, but the process remains the primary mean of addressing the problem.

"Selling" the process can be difficult, especially to stakeholders who will need to do more work. Fortunately, knowledge sharing has a significant benefit: it increases your mobility inside the company, which is especially good when the company is growing fast. This means that you can be promoted to a team lead on a much shorter notice, or move to a different project that happens to be of more interest to you.

Title: How to share problem solving knowledge in a multiteam group?

Body:
I've been working in multiteam groups for as long as I've been a web developer, and in my experience, a team can be a lonely soldier or several people; generally a company will have multiple teams working on different projects and once the project is out in the wild, any team can perform maintenance on it.

This is a simple example since I'm not talking only about project related knowledge, but "craft related" knowledge, but it should give you an idea of how I'm used to working:

Since we work on modularised teams, sometimes I feel like the teams are too tightly focused in their projects. I've seen cases where after an hour of discussion, the question was asked aloud and someone on a totally unrelated project suggested a much simpler solution.

The problem is difficult to solve because people tend not to be available all the time, and sometimes the person with the knowledge can't afford the time to go through a problem with the asker, but could do it themselves easily.

I've thought about software based solutions, something along the lines of SE, but I'd like to know other programmers opinions on the subject.

EDIT

I don't know if this is a problem that a wiki can solve, because I feel that wikis don't encourage the user to actually ask questions, but rather to write articles, and sometimes we don't know the knowledge we need before needing it.


答:
Some teleprinters* had a sequence of a dozen or two characters that could be programmed (mechanically) into the unit and was sent when the host sent an ENQ character or the operator pressed the HERE IS key on the keyboard.  A number of glass-tube terminals had the same feature.

A "here-is" document in shells and programming languages that support the same construct serves essentially the same purpose:  it's a canned sequence of characters that doesn't change unless the program does.

*These are also the origin of the term tty that appears in Unix.

Title: Why is it called a 'Here Document'?

Body:
(Let me know if this is the wrong SE for this)

Why is a Here Document (or Heredoc) called that? Wikipedia didn't have anything to say on that particular subject. I did find unix docs describing a "Here is document", is that the original form?


答:
The real important feature is style consistency so you can write code in the same style and you can make meta programming assumptions about how asynchronous situations are handled.

I personally prefer

(err, data) because it's a standard way of handling things. It allows for function composition.

For example after.map uses this pattern. So code like

```<code>after.map(["foo.js", "bar.js"], function (fileName, callback) {
    fs.readFile(fileName, function (err, file) {
        callback(err, file)
    })
}, function (err, files) {
    // handle files
})
</code>```

can be simplified to

```<code>after.map(["foo.js", "bar.js", fs.readFile, function (err, files) {
    // handle files
})
</code>```

Another advantage is that you can pass in a callback as a last parameter

```<code>asyncOperation(options, function (err, data) {
    // not nested inside an object literal
})
</code>```

The callback last approach is a nice API familiarity approach.

A further advantage is that you can easily forget to set the error handler in your object literal, or set it to some kind of default error handler.

When your using (err, data) it reminds you to think about how to efficiently handle this err every time.

Body:
The real important feature is style consistency so you can write code in the same style and you can make meta programming assumptions about how asynchronous situations are handled.

I personally prefer

(err, data) because it's a standard way of handling things. It allows for function composition.

For example after.map uses this pattern. So code like

after.map(["foo.js", "bar.js"], function (fileName, callback) {
    fs.readFile(fileName, function (err, file) {
        callback(err, file)
    })
}, function (err, files) {
    // handle files
})

can be simplified to

after.map(["foo.js", "bar.js", fs.readFile, function (err, files) {
    // handle files
})

Another advantage is that you can pass in a callback as a last parameter

asyncOperation(options, function (err, data) {
    // not nested inside an object literal
})

The callback last approach is a nice API familiarity approach.

A further advantage is that you can easily forget to set the error handler in your object literal, or set it to some kind of default error handler.

When your using (err, data) it reminds you to think about how to efficiently handle this err every time.


问:
How to convince teammates to use TDD
I am the only person on my team that use TDD. How do I make them to use it?

I am annoyed that when I pull, someone's code will break my tests and I am the one who has to fix them.

Will using github, fork and pull request solve this problem, so that they need to pass the test before the pull is accepted?

I am not the project manager and I can't seems to convince her to use it.

答:
Lots of good advice. And now, a bit more...

You must win hearts and minds (WHAM) one Luddite at a time. Forget about forcing it down their throats. Lots of object lessons over an indefinite (sorry about that) period of time. Eventually you will hit a critical mass, convince the "right" person(s).

Your constant and consistent enthusiasm & avocation for TDD is very important in a WHAM campaign.

You must turn the test-breaking and code changes into teachable moments, the lessons which matter for your co-coders. Make it personal. I.E. Do they care about a reputation for delivering above average clean code? Do they care about management ragging on them about code that is now late because integration testers gave them a reality check? Does Jack have a desire to modify some difficult code but is afraid of side effects?

Gather good examples of test-breaking as trapping coder-induced bugs. The coders will see changing tests as unnecessary work to irrelevant code; they must understand that the tests just covered their arses.

Find some code with global implications (some simple utility method), build some tests, then demonstrate that tests permit change w/out fear of earthquakes throughout the application. And I do mean to emphasize the emotional issue too!

Gather some simple time-to-clean-code examples (i.e. passed into production) and demonstrate that despite the extra effort for test coding, we got her done faster & with higher quality.

Warning: TDD is not a cure for and cannot overcome bad OO design and coding (but it definitely can expose it). Do not let the Luddites blame the testing code effort for their incompetence.

Title: How to convince teammates to use TDD


答:
There is really no contradiction here.  The rule of 3 talks about the destructor, the copy constructor and the copy assignment operator.  Uncle Bob talks about empty default constructors.

If you need a destructor, then your class probably contains pointers to dynamically allocated memory, and you probably want to have a copy ctor and an operator=() that do a deep copy.  This is completely orthogonal to whether or not you need a default constructor.

Note also that in C++ there are situations when you do need a default constructor, even if it is empty.  Let's say your class has a non-default constructor.  In that case, the compiler will not generate a default constructor for you.  That means that objects of this class cannot be stored in STL containers, because those containers expect the objects to be default-constructable.

On the other hand, if you are not planning to ever put the objects of your class into STL containers, an empty default constructor certainly is useless clutter.

Title: The rule of 5 - to use it or not?


答:
As programmers we sometimes erroneously look for technical solutions to what is fundamentally a people problem.  There are always going to be inefficiencies in a large group.  The best solution I'm aware of is the good old fashioned "grapevine."  I ask the person I feel is best suited to answer a particular question.  If he doesn't know the answer, he refers me to his "guru" on that topic, and so on.  I don't think I've ever had a chain longer than three people, and nearly always it's one or two.  If you have no idea who to ask, send out a group email.

The wiki comes in as a sort of FAQ.  When someone gets the same question multiple times, they write a wiki article so they can refer people to it.  Eventually people will start searching the wiki before they ask a question, and people will start writing wiki articles in anticipation of frequent questions.  In a large enough group, chances are good that someone else either has had the same question, or your question is specific enough to require one-on-one help anyway.