答:
As others have said, if you're testing a client you don't need to go as far as creating, deleting, etc. on the server. A lot of the time you don't even need to mock a server at all. You really only need to make sure you are making the right requests and correctly handling the responses, Whether it's written in Ruby, Python, PHP or anything else, at some point your client is probably going to use a method from an HTTP library to make a request and it's enough to mock that method, check how it's called, and return a test result.

Take a hypothetical Python client that uses urllib2 for making requests. You probably have some method in the client, let's call it get(), that has a call to urllib2.Request() in it. You only really need to mock the call to your own class's get().

```<code>@patch('your.Client.get')
def test_with_mock(self, your_mock):
    your_mock.return_value({'some': 'json'})
    test_obj = your.Client.get_object(5)
    your_mock.assert_called_with('/the/correct/endpoint/5')
</code>```

This very simplified example uses Python's Mock library to test a hypothetical your.Client class with a get_object() method that generates the correct url to get something from some API. To make the request the client calls its get() method with that url. Here, that method is mocked (your.Client.get is "patched" so that it is under the control of your_mock), and the test checks whether the right endpoint was requested.

The mocked method returns the configured JSON response (your_mock.return_value) which the client must handle and you would make further assertations to test that it handled the expected data in the expected way.

Body:
As others have said, if you're testing a client you don't need to go as far as creating, deleting, etc. on the server. A lot of the time you don't even need to mock a server at all. You really only need to make sure you are making the right requests and correctly handling the responses, Whether it's written in Ruby, Python, PHP or anything else, at some point your client is probably going to use a method from an HTTP library to make a request and it's enough to mock that method, check how it's called, and return a test result.

Take a hypothetical Python client that uses urllib2 for making requests. You probably have some method in the client, let's call it get(), that has a call to urllib2.Request() in it. You only really need to mock the call to your own class's get().

@patch('your.Client.get')
def test_with_mock(self, your_mock):
    your_mock.return_value({'some': 'json'})
    test_obj = your.Client.get_object(5)
    your_mock.assert_called_with('/the/correct/endpoint/5')

This very simplified example uses Python's Mock library to test a hypothetical your.Client class with a get_object() method that generates the correct url to get something from some API. To make the request the client calls its get() method with that url. Here, that method is mocked (your.Client.get is "patched" so that it is under the control of your_mock), and the test checks whether the right endpoint was requested.

The mocked method returns the configured JSON response (your_mock.return_value) which the client must handle and you would make further assertations to test that it handled the expected data in the expected way.


问:
Choosing DOCTYPE for an online eBook
I'm about to begin working on a project which involves creating an eBook-like website which will contain lots of large documents with text and images.

The site should have a rather minimalistic design, but it will include a UI with some scripting and animations to make browsing the large documents easier.

I've been thinking on this matter for a while now and I can't decide what markup to use for such a project.

Should it be HTML 4.0 strict? XHTML 1.0 strict? Perhaps HTML5?

It is a likely that people who are not especially internet-savvy will visit the site due to its content, and as such I think it's very plausible for some of the visitors to have relatively old browsers. Can XHTML or HTML5 hurt me in this regard?

Reading about various eBook formats (specifically EPUB), I learned that many of them use XHTML internally; does this mean that if I use XHTML (correctly) the site might also be packaged and delivered as an EPUB in the future? The strictness and cleanliness of XHTML/XML also appeals to me greatly.

Overall XHTML appeals to me the most, but I'm scared about the implication of its use. It has supposedly been discontinued by W3C in favor of HTML 5. However, I don't really see any advantages to using HTML5 over HTML 4 strict, as I won't be using any of it's features. I'm also worried about browser compatiablity of HTML5.

Should I just stick with good ol' HTML 4 strict?

答:
HTML 5

The advantages of HTML 5 are the ability to use new tags, more expressive and meaningful than
s, and to benefit from a few features added in HTML 5, like better support for forms (with validation of fields, etc.).

Note that you are not forced to use HTML 5 in order to use:

styles available in CSS 3, like gradients. You can use CSS 3 with older versions of HTML as well.

features related to JavaScript, like web sockets. In the same way, a website written in XHTML 1.1 would still be able to support web sockets.

XHTML

XHTML was published in 2000 to replace HTML by introducing stricter rules. The goal was to make it easier for smartphones and especially mobile phones to parse XHTML code with sparse hardware resources, given that an XML parser is easier to develop compared to an HTML parser (factor which can benefit both the usage on low-end hardware and the adoption of such parser in new programming languages and frameworks).

This attempt failed for a few reasons:

Today's iPhone is ways more powerful than a quite expensive desktop PC you were able to buy in 1999. Smartphones are now capable to parse HTML, including non-W3C-compliant HTML, fast enough.

Not everyone wrote valid XHTML code. In practice, most people just changed the headers, while keeping the legacy invalid, crappy HTML 4 full of  and

.

Severe issues caused by, on one side, the misunderstanding of the appropriate HTTP headers to use when sending XHTML, and on the other side, the terrible behavior of some well-known browser when it came to recognizing XHTML, made the adoption of XHTML difficult.

One of the advantages of XHTML compared to HTML 4 was the fact that a valid XHTML code was also a valid XML. This made it possible to somehow use XHTML as XML to extract data programmatically from the web page. This scenario is infrequent and I can't even find a good example where such thing would be used, instead of requesting/sending the raw model directly as JSON or XML.

This advantage doesn't exist any longer, since HTML 5 can be generated as a valid XML code¹.

Another minor advantage was to be able to use XML features, like namespaces. I don't recall any situation where namespaces in XHTML were particularly useful and where it would have been particularly difficult to find a workaround in HTML.

HTML 4

The advantage of HTML 4 is that you're sure that even very old browsers support it.

This advantage is very limited:

If we talk about perfect support of the standard, then Internet Explorer is out of the game: no matter what HTML version you chose, IE6 and IE7 will have their own understanding of the standard.

If we talk about the ability, for the browser, to actually understand and display the web page, any modern and no so modern browser will succeed displaying any low-quality (X)HTML, no matter its version.

Want a proof? The following code displays perfectly well, even if nobody have any idea about the version of (X)HTML actually used:

```<code><html>
    <h1>Hello World!</h1>
    <p>Guess, what is the HTML version used in this ugly code?
</html>
</code>```

Conclusion

In essence, you may use whatever you want. Given your specific requirements, i.e.:

Minimalistic design,

JavaScript support,

Support of legacy browsers,

Ability to use Epub later,

you may use whatever you want. In your case, you don't benefit from any of the versions in particular and any version will fit your needs. The choice would be dictated by:

your personal preferences,

and, eventually, reasons which are unrelated to the project. For example, if you lack HTML 5 keyword on your CV, this may be a reason to pick HTML 5.

Overall XHTML appeals to me the most, but I'm scared about the implication of its use. It has supposedly been discontinued by W3C in favor of HTML 5.

What do you mean by "discontinued"?

HTML 5 has currently a status of Candidate Recommendation, not a W3C Recommendation (REC).

XHTML 1.1 is a W3C Recommendation since 2001.

HTML 4.01 is a W3C Recommendation since 1999.

Both HTML 4 and XHTML 1.1 are perfectly valid choices from the point of view of the standards. Both HTML 4 and XHTML 1.1 are widely used by the web industry.

¹ “The other syntax that can be used for HTML5 is XML. This syntax is compatible with XHTML1 documents and implementations.” Source: W3C working draft HTML5 differences from HTML4.

ContentLicense: CC BY-SA 3.0

Title: Choosing DOCTYPE for an online eBook

Body:
HTML 5

The advantages of HTML 5 are the ability to use new tags, more expressive and meaningful than <div>s, and to benefit from a few features added in HTML 5, like better support for forms (with validation of fields, etc.).

Note that you are not forced to use HTML 5 in order to use:

styles available in CSS 3, like gradients. You can use CSS 3 with older versions of HTML as well.

features related to JavaScript, like web sockets. In the same way, a website written in XHTML 1.1 would still be able to support web sockets.

XHTML

XHTML was published in 2000 to replace HTML by introducing stricter rules. The goal was to make it easier for smartphones and especially mobile phones to parse XHTML code with sparse hardware resources, given that an XML parser is easier to develop compared to an HTML parser (factor which can benefit both the usage on low-end hardware and the adoption of such parser in new programming languages and frameworks).

This attempt failed for a few reasons:

Today's iPhone is ways more powerful than a quite expensive desktop PC you were able to buy in 1999. Smartphones are now capable to parse HTML, including non-W3C-compliant HTML, fast enough.

Not everyone wrote valid XHTML code. In practice, most people just changed the headers, while keeping the legacy invalid, crappy HTML 4 full of <center> and <p><div></p></div>.

Severe issues caused by, on one side, the misunderstanding of the appropriate HTTP headers to use when sending XHTML, and on the other side, the terrible behavior of some well-known browser when it came to recognizing XHTML, made the adoption of XHTML difficult.

One of the advantages of XHTML compared to HTML 4 was the fact that a valid XHTML code was also a valid XML. This made it possible to somehow use XHTML as XML to extract data programmatically from the web page. This scenario is infrequent and I can't even find a good example where such thing would be used, instead of requesting/sending the raw model directly as JSON or XML.

This advantage doesn't exist any longer, since HTML 5 can be generated as a valid XML code¹.

Another minor advantage was to be able to use XML features, like namespaces. I don't recall any situation where namespaces in XHTML were particularly useful and where it would have been particularly difficult to find a workaround in HTML.

HTML 4

The advantage of HTML 4 is that you're sure that even very old browsers support it.

This advantage is very limited:

If we talk about perfect support of the standard, then Internet Explorer is out of the game: no matter what HTML version you chose, IE6 and IE7 will have their own understanding of the standard.

If we talk about the ability, for the browser, to actually understand and display the web page, any modern and no so modern browser will succeed displaying any low-quality (X)HTML, no matter its version.

Want a proof? The following code displays perfectly well, even if nobody have any idea about the version of (X)HTML actually used:

<html>
    <h1>Hello World!</h1>
    <p>Guess, what is the HTML version used in this ugly code?
</html>

Conclusion

In essence, you may use whatever you want. Given your specific requirements, i.e.:

Minimalistic design,

JavaScript support,

Support of legacy browsers,

Ability to use Epub later,

you may use whatever you want. In your case, you don't benefit from any of the versions in particular and any version will fit your needs. The choice would be dictated by:

your personal preferences,

and, eventually, reasons which are unrelated to the project. For example, if you lack HTML 5 keyword on your CV, this may be a reason to pick HTML 5.

Overall XHTML appeals to me the most, but I'm scared about the implication of its use. It has supposedly been discontinued by W3C in favor of HTML 5.

What do you mean by "discontinued"?

HTML 5 has currently a status of Candidate Recommendation, not a W3C Recommendation (REC).

XHTML 1.1 is a W3C Recommendation since 2001.

HTML 4.01 is a W3C Recommendation since 1999.

Both HTML 4 and XHTML 1.1 are perfectly valid choices from the point of view of the standards. Both HTML 4 and XHTML 1.1 are widely used by the web industry.

¹ “The other syntax that can be used for HTML5 is XML. This syntax is compatible with XHTML1 documents and implementations.” Source: W3C working draft HTML5 differences from HTML4.


问:
Read K&R before learning low latency C++?
I have never really done a large amount of C programming but am in the middle of teaching myself low latency C++. Would it do more harm than good to read the K&R C programming book? I am a bit worried I will be reading about C conventions which may no longer hold in C++ (especially with C's fondness of global variables).</p>

答: When doing deterministic or low latency coding on very limited hardware, sometimes those "corrupt/bad/non-PC" coding practices can be beneficial, or even necessary to meet the real-time requirements and/or consume the least nano-watts of system energy.  For instance, hand placing global variables in the minimum number of 1st level data cache lines or small local scratch memory bank, etc.  C is useful in this manner as a sort of near-macro-assembly langauge for RISC (and PDP-11) processors.  Maybe a book on assembly coding and machine language for your choosen processor would be useful as well.  It's all part of having a big toolbox.  Just make sure not to use the right special tool in the wrong place.</p>


问:
better way to define an exception thrown by a method in Java?
I know how to define exceptions and all, but I'm not sure if the way I'm doing it is the most intuitive and readable by another users.

I have a very simple method I've written that I want to throw an exception, because it's easier then manually checking return values; the method is private and there is no way need to define a public Exception type.  None of the existing Java exceptions fit the error exactly, so I'm trying to figure out what type of exception I want to throw here?

I don't want to just throw a RuntimeException, I only want to catch my specific exception I throw, all other Exceptions should propagate up. I figured I would define a little inner class for my exception.  However, i don't really need to overwrite anything in the RuntimeException class, I just want to catch and and print it's message.  So now I have a line that says something like

```<code>private class MissingPropertyException extends RuntimeException{};
</code>```

This does nothing but allow me to catch only the exception I'm intentionally throwing while ignoring the rest.  Is this good syntax?  it feels odd to define a inner class without implementing anything within it.  Is there a way to do this elegantly without creating an empty inner class?

答:
I'm going to assume that there are situations where it is reasonable to throw exceptions.

I'm also going to assume that this is a situation where it is reasonable to use exceptions.  (The fact that this is "internal" to your code does not alter this.  And you cannot reasonably infer that exceptions are in appropriate based on the proposed exception name ... @Jarrod Roberson note!)

So the question is whether it is reasonable to declare a private exception class.  To that I would say "Yes", assuming that there is no existing exception class that is suitable.

The only riders I would make is that if there is any chance that the exception might "leak", then:

you should declare a constructor so that the exception has a reason String, and

you should declare it as public ... so that any javadoc for the exception appears in the published API documentation.


问:
What recent studies point to the possible improvement a programmer can make as a result of personal character traits?
In Chapter 33, Personal Character of Code Complete (Second ed.) McConnell cites some studies such as those listed below in support of the assertion that 10-1 improvement is possible from efforts in improving our programming as a result of personal determination to improve.

Sackman, Erikson, and Grant 1968;

Curtis 1981; Mills 1983;

DeMarco and Lister 1985;

Curtis et al. 1986;

Card 1987;

Valett and McGarry 1989

As you can see from the list above, these studies are quite dated.  Have more recent studies been conducted that studied potential for improvement in programming efficacy? How do the findings compare to McConnell's research? What have these studies revealed about the progress modern methods and tools had in our ability to program?

答:
I would try to explain how it is I can be a programming genius in spite of having none the traits listed in this 1998 study but I hear a video game calling and I'm sick and tired of explaining myself to you people!

Laziness, Impatience, Hubris: Personality Traits of a Great Programmer by John E. Bentley

Not every one can be a great computer programmer. Many don’t really have the desire, some lack a higher-level technical aptitude, and still others don’t have the personality needed to be great. Wait, you say. What’s personality got to do with it? Well, most programmers don’t have a colleague who isn’t intelligent enough to do the work, but most do know someone who isn’t exactly temperamentally suited to the job. To help explain the impact of personality on success as a programmer, this paper will present some of the traits that can be indicators of professional success or failure in the field. For one, a sense of humor is important because the computer “doth make fools of us all”...

Also, complete coincidence, (I found it after my comment above), Myers Briggs ratings. Not much on tools unfortunately and more of a paper than a study but lots of references within to more recent stuff.


问:
Where can I turn to if I can't fix a bug?
I am looking for resources to turn to when I don't have the answer for something. I lead a team of software developers. We have been rolling out new software releases on a monthly basis.

When there is a bug that my team cannot fix, it lands on me. Most of the time I can resolve the issue, but there are times when I get stuck.

Unfortunately, I'm the top of the line at our company. There is nobody I can ask for help or assistance in figuring something out.

Do you happen to have any recommendations or guidance for situations like this?

答: My personal last resort is to start commenting things out in what appears to be the affected area until the bug stops happening to narrow down.</p>


问:
Testing a REST client against a REST Server. How to do fixtures?
When writing unit tests, it's common to use fixtures: little testable data, so we can say:
1. Get all clients should include Willy Wonka.
2. Delete client 3, and now get clients should not include Willy Wonka anymore.

That's fine for unit tests.  Use setup/teardown to re-load the fixtures or rollback the transaction.  So testing creates, updates, and deletes are done inside a transaction.  The new temporary data lasts just for the length of that test, then is reset.

But what about when we've separated the REST server from the REST client?

We want to make sure our REST client is not just reading correctly, but creating, updating, and deleting correctly.

I haven't been able to find any examples or suggestions for how to do this against a remote test REST server.

Assuming I've got a test REST server serving only fixtures.  The whole stateless nature of HTTP means it'd be hard to send a "BEGIN TRANSACTION" and "ROLLBACK TRANSACTION" or "RELOAD FIXTURES" type of message, right?

I can't be the first to want to do this, so I have a feeling I need a different way of thinking about this.

Any suggestions?

答:
Monkey Patch

At my work we do ATDD by using an exiting xUnit framework and monkey patching network calls between the client and server.  In the same process space we load the client, monkey patch the network call to the top of the REST server stack code.  All calls are then issued from the client like they would normally be, and the server code gets the requests exactly as they would normally appear.

Benefits

no having to synchronize with server startup (because there is no server)

leverage classic unit setup and teardown method to manage things like fixtures

ability to use mocks/stubs and other monkey patches for more fine grained control of the test

can be written using a xUnit framwork

Tradeoffs

doesn't expose multi-process interactions/issues (locking, resource starvation, etc)

doesn't expose multi-server issues (data serialization, clustering style)

doesn't expose network issues because that is simulated (access, timeout errors, etc)


问:
Looking to build a 2 java applications. should it be web-based application or standalone application?
The first application (web-based) will be located at site1 and once the information is processed, it will be sent to the second application(web-based) located at site2. Application2 needs to be able to do the same thing as application1. Because of this, there has to be a way to share the database to keep data in sync. I wanted to go web-based for these two applications, but the issue arises, what if the internet is down? If application1 goes down due to a blackout or lost of internet, application2 should still be able to do what it needs to. I was thinking the database/server will be on Amazon EC2.

Even if I go with a standalone application for site1 and site2, it still needs some sort of internet connection to talk to a shared database/server right, possiblity through tcp connection? Because of this, I dont see why it shouldn't just be a web-based applicatin then. This the disagreement I'm having with my team.

I want to know the pros and cons of making these two application either being a stand-alone or web-based.

答:
Unless you're running some kind of proxy server which can fail, the internet going down is pretty much going to mean a network partition.  Since HTTP is over TCP, "internet is down" probably means you aren't able to establish TCP connections between the two nodes.  I would favor web-based because port 80 and 443 are generally open through firewalls, whereas oddball ports can be a problem in some environments.

Either way you will probably need to handle a partition by figuring out how to represent your changes (i.e. each message is a serialized method invocation to be executed on the destination node).  When you detect a partition (because you can't establish a network connection) you queue up messages.  The tricky part is detecting the partition has been cured and you can now flush your backlog of message to the destination.

However, and this is where CAP comes in, once you have a network partition you have to choose between availability and consistency.  http://en.wikipedia.org/wiki/CAP_theorem .  That, IMHO, is a larger, thornier problem than the transport layer.


问:
Can I start with a passing unit test?
Uncle Bob's rules for TDD are specified here.

You are not allowed to write any production code unless it is to
make a failing unit test pass.

You are not allowed to write any more
of a unit test than is sufficient to fail; and compilation failures
are failures.

You are not allowed to write any more production code
than is sufficient to pass the one failing unit test.

But, is it ok to write a bunch of tests that pass as soon as the test compiles?  For example, a test that asserts null and the default impl of a method I'm testing returns null.  Am I doing something wrong by doing this?  Should I skip to the first test that will fail or is it ok to write tests that automatically pass first?

答:
It depends.

If you are writing software to solve a business problem or produce a useful tool, then yes, you are allowed to write a test that passes automatically.

If, on the other hand, you are writing software in order to perform a religious observance at the First Denominational Church of TDD, then no, you are not allowed to do that. And you should probably take a moment of self-flagellation for even asking the question.

Title: Can I start with a passing unit test?


问:
Re-writing a large web application - alternatives to LAMP
We have a very large, 10 year old LAMP (Linux, Apache, MySQL, PHP) web application that is out of control and poorly written due to a large number of patches and possible hundreds of programmers.

If we were to do a re-write, what are alternatives to the LAMP stack?  One of the reasons behind LAMP was that it's easy to develop and cheap.  Now the company can afford to spend more time/effort/money on a new system.  I thought about Java or C++ with Oracle?  Is there a common 'Enterprise' stack companies use?

Many thanks.

答:
First of all, any use of C++ for web development is so incredibly niche as to not even be worth considering. If you're asking "what language should we use?", then I can guarantee you 100% that the answer is not "C++". That out of the way, as others have said, there are options:

I would say that far and away the two most common choices for enterprise-y web applications are Java (and one of its frameworks) and C#/.NET (probably ASP.NET MVC for a greenfield development, ASP.NET Web Forms for anything that's been in production a while). I find the decision between those two is often largely driven by preferred server OS. Java for Unix, .NET for Windows. You can do Java on Windows but it often makes you sad. You can allegedly run .NET on Unix using Mono but I would recommend against betting your business on it.

Others have mentioned Python and Ruby. My personal experience with these two is little and none. My understanding is that there are quality frameworks for both. My understanding is further that they are not particularly commonly seen at the enterprise end of the spectrum.

Those who have dismissed PHP out of hand have already been accused of bias. I'm biased as well - I dismiss PHP out of hand, and I think you should too. You've already built one absolutely typical PHP trainwreck, don't go out and build another.

Having said all of that, you describe "a very large web application". You mention "possibly hundreds" of programmers having dipped their oars into it over 10 years. I'm going to assume that you have quite a few programmers working there. And I'm further going to assume (possibly inaccurately) that this large PHP application is the main or only thing they are working on, and that therefore, many or most of these programmers do not have any significant large-scale experience with anything other than PHP.

They are not going to built a good "second system" in any other platform.

If you're going to do this thing, you need it to be started off by experienced developers who live and breathe the platform you choose to use. I said above that my personal experience with Python and Ruby is little and none. I could easily learn them and I'm confident I could write good code with them. But if I tried to use a large-scale system as a learning experience, I'm positive I would produce a trainwreck which didn't take 10 years to look as bad as the system you're hoping to replace.

Ultimately, if your company can afford to spend the time, effort and money on a second system (and rewriting a 10-year-old system will be a lot of time, effort and money), you're going to need to spend a fair chunk of that hiring people who have extensive current experience in the platform you select.


答:
Rod Johnson author of Expert One-On-One J2EE Design and Development mentioned runtime exceptions are often a better alternative to checked exceptions(Obviously many things depends on your business logic and team members).

But Rather

```private class MissingPropertyException extends RuntimeException{};```

you can use/design something close to NestedRuntimeException

Title: better way to define an exception thrown by a method in Java?

Body:
I know how to define exceptions and all, but I'm not sure if the way I'm doing it is the most intuitive and readable by another users.

I have a very simple method I've written that I want to throw an exception, because it's easier then manually checking return values; the method is private and there is no way need to define a public Exception type.  None of the existing Java exceptions fit the error exactly, so I'm trying to figure out what type of exception I want to throw here?

I don't want to just throw a RuntimeException, I only want to catch my specific exception I throw, all other Exceptions should propagate up. I figured I would define a little inner class for my exception.  However, i don't really need to overwrite anything in the RuntimeException class, I just want to catch and and print it's message.  So now I have a line that says something like

```<code>private class MissingPropertyException extends RuntimeException{};
</code>```

This does nothing but allow me to catch only the exception I'm intentionally throwing while ignoring the rest.  Is this good syntax?  it feels odd to define a inner class without implementing anything within it.  Is there a way to do this elegantly without creating an empty inner class?

Body:
Rod Johnson author of Expert One-On-One J2EE Design and Development mentioned runtime exceptions are often a better alternative to checked exceptions(Obviously many things depends on your business logic and team members).

But Rather

private class MissingPropertyException extends RuntimeException{};

you can use/design something close to NestedRuntimeException


问:
How to handle User Story at end of sprint if users want changes?
We just adopted Scrum and completed our first sprint (yeah!)

At the Sprint Review, we demoed a User Story for feature X. This feature X worked exactly how described in the User Story from initial business analysis and details we worked out during product backlog grooming and sprint planning.  However, after the user saw feature X in action they wanted some tweaks (not shocking, purpose of the demo and feedback loop).

My question is:

(a) Do we consider the original user story done and create a new user story to handle the new requirements in a future sprint?

(b) Do we consider the original user story unfinished, roll into backlog with more detailed requirements that will turn into more tasks in the next sprint?

If (b), in sprint planning do we re-estimate the story point weight of the story now knowing that 90% of the work is complete?  So if it was originally 5 pts it might now be 2 pts?

答:
It boils down to your "Definition of Done". Is your story Done according to that list?

My opinion though is to consider the original story done and you should create a brand new one for the next sprint.

But more importantly: Learn from this and find a way to avoid it happening again. Retrospective meeting might be a good place to bring it up. I bet more user feedback might have something to do with it :)

Btw, congratz on your first sprint!


问:
Is garbage collection needed for implementing safe closures?
I recently attended an online course on programming languages in which, among other concepts, closures were presented. I write down two examples inspired by this course to give some context before asking my question.

The first example is an SML function that produces a list of the numbers from 1 to x, where x is the parameter of the function:

```<code>fun countup_from1 (x: int) =
    let
        fun count (from: int) =
            if from = x
            then from :: []
            else from :: count (from + 1)
    in
        count 1
    end
</code>```

In the SML REPL:

```<code>val countup_from1 = fn : int -> int list
- countup_from1 5;
val it = [1,2,3,4,5] : int list
</code>```

The countup_from1 function uses the helper closure count that captures and uses the variable x from its context.

In the second example, when I invoke a function create_multiplier t, I get back a function (actually, a closure) that multiplies its argument by t:

```<code>fun create_multiplier t = fn x => x * t
</code>```

In the SML REPL:

```<code>- fun create_multiplier t = fn x => x * t;
val create_multiplier = fn : int -> int -> int
- val m = create_multiplier 10;
val m = fn : int -> int
- m 4;
val it = 40 : int
- m 2;
val it = 20 : int
</code>```

So variable m is bound to the closure returned by the function call and now I can use it at will.

Now, for the closure to work properly throughout its lifetime, we need to extend the lifetime of the captured variable t (in the example it is an integer but it could be a value of any type). As far as I know, in SML this is made possible by garbage collection: the closure keeps a reference to the captured value which is later disposed of by the garbage collector when
the closure is destroyed.

My question: in general, is garbage collection the only possible mechanism to
ensure that closures are safe (callable during their whole lifetime)?

Or what are other mechanisms that could ensure the validity of closures without garbage collection: Copy the captured values and store it inside the closure? Restrict the lifetime of the closure itself so that it cannot be invoked after its captured variables have expired?

What are the most popular approaches?

EDIT

I do not think the example above can be explained / implemented by copying the captured variable(s) into the closure. In general, the captured variables can
be of any type, e.g. they can be bound to a very large (immutable) list.
So, in the implementation it would be very inefficient to copy these
values.

For the sake of completeness, here is another example using references
(and side effects):

```<code>(* Returns a closure containing a counter that is initialized
   to 0 and is incremented by 1 each time the closure is invoked. *)
fun create_counter () =
    let
        (* Create a reference to an integer: allocate the integer
           and let the variable c point to it. *)
        val c = ref 0
    in
        fn () => (c := !c + 1; !c)
    end

(* Create a closure that contains c and increments the value
   referenced by it it each time it is called. *)
val m = create_counter ();
</code>```

In the SML REPL:

```<code>val create_counter = fn : unit -> unit -> int
val m = fn : unit -> int
- m ();
val it = 1 : int
- m ();
val it = 2 : int
- m ();
val it = 3 : int
</code>```

So, variables can also be captured by reference and are still alive after
the function call that created them (create_counter ()) has completed.

答:
Garbage collection is not needed for safe closures, when capturing variables by value. One prominent example is C++. C++ has no standard garbage collection. Lambdas in C++11 are closures (they capture local variables from the surrounding scope). Each variable captured by a lambda can be specified to be captured by value or by reference. If it is captured by reference, then you can say that it is not safe. However, if a variable is captured by value, then it is safe, because the captured copy and the original variable are separate and have independent lifetimes.

In the SML example you gave, it is simple to explain: variables are captured by value. There is no need to "extend the lifetime" of any variable because you can just copy its value into the closure. This is possible because, in ML, variables cannot be assigned to. So there is no difference between one copy and many independent copies. Although SML has garbage collection, it is not related to the capturing of variables by closures.

Garbage collection is also not needed for safe closures when capturing variables by reference (kind of). One example is the Apple Blocks extension to the C, C++, Objective-C, and Objective-C++ languages. There is no standard garbage collection in C and C++. Blocks capture variables by value by default. However, if a local variable is declared with __block, then blocks capture them seemingly "by reference", and they are safe -- they can be used even after the scope that the block was defined in. What happens here is that __block variables are actually a special structure underneath, and when blocks are copied (blocks must be copied in order to use them outside the scope in the first place), they "move" the structure for the __block variable into the heap, and the block manages its memory, I believe through reference counting.


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答:
Troubleshooting and Debugging Skills

They hardly spend any time on this topic in any of the programming courses I took, and in my experience it is one of the biggest determinants of how productive a programmer is. Like it or not, you spend a lot more time in the maintenance phase of your app than the new development phase.

I've worked with soooooo many programmers who debug by randomly changing things with no strategy for finding the problem whatsoever. I've had this conversation dozens of times.

Other Programmer: I think we should try  to see if it fixes it.

Me: Okay, assuming that does fix it. What does that tell you about where the source of the problem is?

Other Programmer: I don't know, but we have to try something.

ContentLicense: CC BY-SA 2.5


问:
Barter vs. Cash for a Retailer's eCommerce Site
I am putting together a proposal for a local store with both a brick-n-mortar and web presence. It's an upscale shop that also happens to be one of my wife's favorites. I am considering offering the option of barter for part of the payment. I have two questions in this regard:

What would be a reasonable “exchange rate” for such a transaction? That is, in lieu of $1000 cash money, I should ask for about how much in store credit?

In your own experience, has using barter introduced any complications into the client relationship? Are there particular pitfalls to be concerned about?

答:
If I could get a Nikon D7000 and a fast prime lens for doing a relatively simple project in my spare time, I'd definitely go for it. I've done a lot of bartering in the past and I've always been pleased with the result.

What you have to do is be very clear on what you will deliver for the agreed trade. In my example, they would be happy adding products to their store while I am out happily shooting around with my new camera. Support is something they would have to pay for in cash, because it involves an indeterminate amount of time on my end. Bug fixes would be prompt and free, of course.

I've bartered for:

Hardware (memory, monitors, drives, etc ..) in exchange for a shopping cart

Office space in exchange for a cabling job

Graphics in exchange for writing a custom PHP extension

Just be clear that you will be providing top notch goods and services in exchange for top notch goods and services. In the case of the office, I required that the lease be in writing, and offered the other party a written warranty on the cabling job.

If your wife gets something from the store, and it breaks under warranty, they should be receptive to replacing it for her, even if it means additional cost for them.

If what you receive is (to you) equal or grater in value than what you provide, why not?


问:
Is it a good idea to create multiple heads with Mercurial?
I just made a commit that I want to reverse, but I want to keep the bad commit in history. So, I hg update to the previous (good) commit. Then I keep working.

This leaves me with a new head: the abandoned bad commit.

Is this bad practice? What's the best way to keep bad commits in history while not using them?

答:
If you don't want the branch you don't have to have it, use hg revert.

using revert will still keep the bad commit in history, it will create a new commit that undoes the changes from the bad commit.


问:
How can I get git to clone untracked files
I'm new to git.

I'm using a development platform called automation studio.
This development tool creates all sorts of files and directories which it needs to maintain runtime and IO information for the target processor. These informations are specific for each project.
Therefore these file should not be under version control because they are provided and maintainded by the platform. Otherwise one cannot run the automation studio without these files.

I put the names of these files and directories in an .gitignore file.
Then I cloned myrepository to a bare repository on a server.
Then I cloned back to mynewrepository on my local machine.
Unfortunatedly in mynewrepository all files and directories listed in .gitignore were missing. Therefore the automation studio platform failed to work.

How can I exclude these files and the content of these directories from versioning but keep the them all in the repository in order to clone back a fully working project for automation studio?

答:
Sometimes there comes situations where you want to add configuration to version control but they change depending on where you've cloned the project. How to "semi-ignore" these files depends totally on how you want it to work. So here are some strategies for it:

Strategy No. 1: Commit ALL THE THINGS

You should try to commit everything and see later on what you don't need. Sometimes this is the best solution. It is more common for us to assume that we don't need them in version control until we realize that we do.

You can also follow it up with temporarily assuming files as unchanged in git. The command you can use to do this with is git update-index:

```<code>git update-index --assume-unchanged [file ...]
</code>```

If you have trouble doing this with directories, read this SO question on assuming directories with untracked files.

Strategy No. 2: If a tool sets up the project, use it to generate the configuration and then clone on top of that

You can do what you've done now, ignore the configuration in git and when you want to clone the project you do that on top of a new project that is created by the tool. Or write your own tool (a batch script) to set up the project for you.

Strategy No. 3: Check in "default" configuration shared between projects

You could try to figure out which configuration is the bare minimum that you need and have that committed to the repository.

If you want configuration defaults, you could copy (or zip) all the configuration files to a seperate directory and then have that committed. When you clone, you can then unzip all those files to the correct spot to get things going.

You can batch this installation process to make it easier for you to get going. So that you only need to run it once when you clone the project.

Bonus Strategy: Check in a "readme" text file that details a process of how to get started

Checking in a text file that details how you go about to set up the project is a useful thing to do. You may need this later on to remind yourself how you've set up the project.

Body:
Sometimes there comes situations where you want to add configuration to version control but they change depending on where you've cloned the project. How to "semi-ignore" these files depends totally on how you want it to work. So here are some strategies for it:

Strategy No. 1: Commit ALL THE THINGS

You should try to commit everything and see later on what you don't need. Sometimes this is the best solution. It is more common for us to assume that we don't need them in version control until we realize that we do.

You can also follow it up with temporarily assuming files as unchanged in git. The command you can use to do this with is git update-index:

git update-index --assume-unchanged [file ...]

If you have trouble doing this with directories, read this SO question on assuming directories with untracked files.

Strategy No. 2: If a tool sets up the project, use it to generate the configuration and then clone on top of that

You can do what you've done now, ignore the configuration in git and when you want to clone the project you do that on top of a new project that is created by the tool. Or write your own tool (a batch script) to set up the project for you.

Strategy No. 3: Check in "default" configuration shared between projects

You could try to figure out which configuration is the bare minimum that you need and have that committed to the repository.

If you want configuration defaults, you could copy (or zip) all the configuration files to a seperate directory and then have that committed. When you clone, you can then unzip all those files to the correct spot to get things going.

You can batch this installation process to make it easier for you to get going. So that you only need to run it once when you clone the project.

Bonus Strategy: Check in a "readme" text file that details a process of how to get started

Checking in a text file that details how you go about to set up the project is a useful thing to do. You may need this later on to remind yourself how you've set up the project.


答:
Others have lectured on proper exception usage, so instead of repeating that, I'd suggest an alternative in form of something called an Optional:

```<code>Optional<String> optionalProperty = myMethod();
if (optionalProperty.isPresent())
   // do something with it
else
   // property did not exist
</code>```

This approach forces the calling code to take an action in case the return value is missing. This is analogous to using throws MissingPropertyException which also forces the caller to handle it, but I think using Optional is more explicit.

Body:
Others have lectured on proper exception usage, so instead of repeating that, I'd suggest an alternative in form of something called an Optional:

Optional<String> optionalProperty = myMethod();
if (optionalProperty.isPresent())
   // do something with it
else
   // property did not exist

This approach forces the calling code to take an action in case the return value is missing. This is analogous to using throws MissingPropertyException which also forces the caller to handle it, but I think using Optional is more explicit.


答:
What you describe is an integration test scenario. These are usually a bit awkward to setup and tear down. It makes them slow to run and quite often brittle.

The approach with fixtures is just as awkward and clumsy, but it is the default way some frameworks go about it, e.g. Rails, and it is already supported. They need the abstract test case or something similar to prepare the database with fixtures. (Beware of unusual naming of test categories in Rails, the unit tests with DB fixtures are strictly speaking also integration tests.)

The way I would go about your scenario is to accept to have test-specific control over the API application state or its database. You can either have additional endpoints for setup and teardown, which are only present in the test environment. Or alternatively, you talk to the database (or whatever you're using) behind the back of your application / API.

If you feel this is too much (in the sense of undue) effort, then consider that the approach with fixtures for databases does just that: using additional, test-specific means to manipulate the database or application state.

I don't the think this discussion has to do with stateless nature of HTTP, though. HTTP is stateless, but the application is definitely not, in the majority of cases. It sounds a bit like you where looking for REST strictness. You could just as well have all resources be fully creatable, readable and deletable. In that case you could just do all setup and teardown through regular API means. This is often not done in practice, though, because you don't want to include certain operations from a business understanding of your application, at least not outside of the test environment.

Title: Testing a REST client against a REST Server. How to do fixtures?

Body:
When writing unit tests, it's common to use fixtures: little testable data, so we can say:
1. Get all clients should include Willy Wonka.
2. Delete client 3, and now get clients should not include Willy Wonka anymore.

That's fine for unit tests.  Use setup/teardown to re-load the fixtures or rollback the transaction.  So testing creates, updates, and deletes are done inside a transaction.  The new temporary data lasts just for the length of that test, then is reset.

But what about when we've separated the REST server from the REST client?

We want to make sure our REST client is not just reading correctly, but creating, updating, and deleting correctly.

I haven't been able to find any examples or suggestions for how to do this against a remote test REST server.

Assuming I've got a test REST server serving only fixtures.  The whole stateless nature of HTTP means it'd be hard to send a "BEGIN TRANSACTION" and "ROLLBACK TRANSACTION" or "RELOAD FIXTURES" type of message, right?

I can't be the first to want to do this, so I have a feeling I need a different way of thinking about this.

Any suggestions?


答:
The Rust programming language is interesting on this aspect.

Rust is a system language,  with an optional GC, and was designed with closures from the beginning.

As the other variables, rust closures come in various flavors. Stack closures, the most common ones, are for one-shot usage. They live on the stack and can reference anything. Owned closures take ownership of the captured variables. I think they live on the so called "exchange heap", which is a global heap. Their lifespan depends on who owns them. Managed closures live on the task-local heap, and are tracked by the task's GC. I'm not sure about their capturing limitations, though.

Title: Is garbage collection needed for implementing safe closures?

Body:
I recently attended an online course on programming languages in which, among other concepts, closures were presented. I write down two examples inspired by this course to give some context before asking my question.

The first example is an SML function that produces a list of the numbers from 1 to x, where x is the parameter of the function:

```<code>fun countup_from1 (x: int) =
    let
        fun count (from: int) =
            if from = x
            then from :: []
            else from :: count (from + 1)
    in
        count 1
    end
</code>```

In the SML REPL:

```<code>val countup_from1 = fn : int -> int list
- countup_from1 5;
val it = [1,2,3,4,5] : int list
</code>```

The countup_from1 function uses the helper closure count that captures and uses the variable x from its context.

In the second example, when I invoke a function create_multiplier t, I get back a function (actually, a closure) that multiplies its argument by t:

```<code>fun create_multiplier t = fn x => x * t
</code>```

In the SML REPL:

```<code>- fun create_multiplier t = fn x => x * t;
val create_multiplier = fn : int -> int -> int
- val m = create_multiplier 10;
val m = fn : int -> int
- m 4;
val it = 40 : int
- m 2;
val it = 20 : int
</code>```

So variable m is bound to the closure returned by the function call and now I can use it at will.

Now, for the closure to work properly throughout its lifetime, we need to extend the lifetime of the captured variable t (in the example it is an integer but it could be a value of any type). As far as I know, in SML this is made possible by garbage collection: the closure keeps a reference to the captured value which is later disposed of by the garbage collector when
the closure is destroyed.

My question: in general, is garbage collection the only possible mechanism to
ensure that closures are safe (callable during their whole lifetime)?

Or what are other mechanisms that could ensure the validity of closures without garbage collection: Copy the captured values and store it inside the closure? Restrict the lifetime of the closure itself so that it cannot be invoked after its captured variables have expired?

What are the most popular approaches?

EDIT

I do not think the example above can be explained / implemented by copying the captured variable(s) into the closure. In general, the captured variables can
be of any type, e.g. they can be bound to a very large (immutable) list.
So, in the implementation it would be very inefficient to copy these
values.

For the sake of completeness, here is another example using references
(and side effects):

```<code>(* Returns a closure containing a counter that is initialized
   to 0 and is incremented by 1 each time the closure is invoked. *)
fun create_counter () =
    let
        (* Create a reference to an integer: allocate the integer
           and let the variable c point to it. *)
        val c = ref 0
    in
        fn () => (c := !c + 1; !c)
    end

(* Create a closure that contains c and increments the value
   referenced by it it each time it is called. *)
val m = create_counter ();
</code>```

In the SML REPL:

```<code>val create_counter = fn : unit -> unit -> int
val m = fn : unit -> int
- m ();
val it = 1 : int
- m ();
val it = 2 : int
- m ();
val it = 3 : int
</code>```

So, variables can also be captured by reference and are still alive after
the function call that created them (create_counter ()) has completed.


问:
Continuous Integration Feedback Cycle
How long should the Continuous Integration process take (i.e. compiling classes and running unit tests + integration test)?

On my current project it takes about 30 minutes, is that OK?
What's the ideal length of build time?

Integration tests take most of that time, if the 30 min is too long what can be done here?

What's the impact of having the build complete in 30 min?

答:
Separate your unit-tests or otherwise quick tests from slower integration tests. Try to keep the 'commit' tests under 10 minutes (not much more time then it takes to grab a cup of coffee).

Split unit-tests from anything that requires an installed system to test against. Run those at a second test stage.

There really is no hard number, if you have a large system, keeping it all under 10 minutes can be hard. Just try keeping it as short as possible.

Title: Continuous Integration Feedback Cycle


答:
Coming up with new ideas after being presented new finished work is part of a normal iterative development. Most important is if the story brings what you 'knew' when you started the sprint. New insights are for new stories.

Keeping stories open or rejecting stories is for when you got things wrong or missed things you had discussed.

So definitely option A.

Title: How to handle User Story at end of sprint if users want changes?

Body:
We just adopted Scrum and completed our first sprint (yeah!)

At the Sprint Review, we demoed a User Story for feature X. This feature X worked exactly how described in the User Story from initial business analysis and details we worked out during product backlog grooming and sprint planning.  However, after the user saw feature X in action they wanted some tweaks (not shocking, purpose of the demo and feedback loop).

My question is:

(a) Do we consider the original user story done and create a new user story to handle the new requirements in a future sprint?

(b) Do we consider the original user story unfinished, roll into backlog with more detailed requirements that will turn into more tasks in the next sprint?

If (b), in sprint planning do we re-estimate the story point weight of the story now knowing that 90% of the work is complete?  So if it was originally 5 pts it might now be 2 pts?


答:
It is fine to create an 'empty' exception subclass. Just see it as a classification.

I would stick to YAGNI though and always look for code that would actually filter on the exception type you create.


答: This cannot possibly work. Git cannot clone any files that it doesn't even know exist. That doesn't even have anything to do with Git, that's just basic common sense.</p>

Title: How can I get git to clone untracked files

Body:
I'm new to git.

I'm using a development platform called automation studio.
This development tool creates all sorts of files and directories which it needs to maintain runtime and IO information for the target processor. These informations are specific for each project.
Therefore these file should not be under version control because they are provided and maintainded by the platform. Otherwise one cannot run the automation studio without these files.

I put the names of these files and directories in an .gitignore file.
Then I cloned myrepository to a bare repository on a server.
Then I cloned back to mynewrepository on my local machine.
Unfortunatedly in mynewrepository all files and directories listed in .gitignore were missing. Therefore the automation studio platform failed to work.

How can I exclude these files and the content of these directories from versioning but keep the them all in the repository in order to clone back a fully working project for automation studio?


答:
I would definitely vote for having a new story.  Unless your Definition of Done includes that the client accepts it, regardless of the acceptance criteria, you are looking at new requirements and I would want to track and prioritize the new changes separately from the original story.

For example, they may want to tweak Story A that you just finished, so you create Story X.  However, you don't want to tackle Story X if the client would rather move on and get a new feature with Story B first, and deal with their tweaks later if there is time.

Having separate work items allows for this separation of prioritization.


答:
A lot of it depends on large the changes are and how high a priority the tweaks are.
Will the client accept the feature as is knowing it will be changing next sprint? Will they not accept the feature as is?

The answer to those questions will drive what you do next, A or B.

As for the estimation, I would be careful about losing your original estimation. If you lose the original estimate, you will have a hard time figuring out your actual velocity for any sprint where you have to change the estimate.

If you use a tool like JIRA that allows you to link tasks together, I would log a new task with the tweaks requested, link it to the other ticket and put it into this sprints backlog (assuming you are working on it as part of this sprint).

Otherwise you could put a note on the original ticket with the combined story point value.

I have to commend you for your attitude about change. If you aren't able to accept it and figure out how to make your process flow with it, you will always be having retros about how you can plan more in order to ensure you don't miss anything again. I find that you will always miss something and the better approach is getting the feature in the clients hands early and often and then doing exactly what you are suggesting you do, Iterate.


答:
According to Joel Spolsky - the single worst strategic mistake that any software company can make: They decided to rewrite the code from scratch.

You say:

poorly written due to a large number of patches and possible hundreds of programmers

That is not the reason. Joel explains all in the following article http://www.joelonsoftware.com/articles/fog0000000069.html

Read it and then think about how you can make what you have better.

Title: Re-writing a large web application - alternatives to LAMP

Body:
We have a very large, 10 year old LAMP (Linux, Apache, MySQL, PHP) web application that is out of control and poorly written due to a large number of patches and possible hundreds of programmers.

If we were to do a re-write, what are alternatives to the LAMP stack?  One of the reasons behind LAMP was that it's easy to develop and cheap.  Now the company can afford to spend more time/effort/money on a new system.  I thought about Java or C++ with Oracle?  Is there a common 'Enterprise' stack companies use?

Many thanks.


答: If you want to keep track of the mistake in the history you want to use backout. The backout command will create a new commit that cancel the previous one. You can even document why original commit is a mistake.</p>

Title: Is it a good idea to create multiple heads with Mercurial?

Body:
I just made a commit that I want to reverse, but I want to keep the bad commit in history. So, I hg update to the previous (good) commit. Then I keep working.

This leaves me with a new head: the abandoned bad commit.

Is this bad practice? What's the best way to keep bad commits in history while not using them?


答:
Note that the so-called "HTML5 doctype" doesn't have the number 5 anywhere in it. It will put ALL browsers into strict mode going back to at least IE6 but I can't remember if that's true  back to IE4 or not. So using that one covers virtually all the bases including XHTML5.

The HTML5 doctype is forward compatible, as well as backwards compatible, so you might as well use that one.

The only time you should use the XHTML doctype is when you are serving the page as XHTML which most people do not. Just using XHTML syntax does not make a page XHTML compliant. It MUST be served as application/xml+xhtml and I doubt that you are. Serving XHTML as text/html, which most people do, is called "tag soup" and requires the browser to fix-up the XHTML elements to conform, ie, the browser has to figure out what you really meant.

For a comprehensive and excellent read: http://hsivonen.iki.fi/doctype/

Title: Choosing DOCTYPE for an online eBook

Body:
I'm about to begin working on a project which involves creating an eBook-like website which will contain lots of large documents with text and images.

The site should have a rather minimalistic design, but it will include a UI with some scripting and animations to make browsing the large documents easier.

I've been thinking on this matter for a while now and I can't decide what markup to use for such a project.

Should it be HTML 4.0 strict? XHTML 1.0 strict? Perhaps HTML5?

It is a likely that people who are not especially internet-savvy will visit the site due to its content, and as such I think it's very plausible for some of the visitors to have relatively old browsers. Can XHTML or HTML5 hurt me in this regard?

Reading about various eBook formats (specifically EPUB), I learned that many of them use XHTML internally; does this mean that if I use XHTML (correctly) the site might also be packaged and delivered as an EPUB in the future? The strictness and cleanliness of XHTML/XML also appeals to me greatly.

Overall XHTML appeals to me the most, but I'm scared about the implication of its use. It has supposedly been discontinued by W3C in favor of HTML 5. However, I don't really see any advantages to using HTML5 over HTML 4 strict, as I won't be using any of it's features. I'm also worried about browser compatiablity of HTML5.

Should I just stick with good ol' HTML 4 strict?


答:
Unfortunately beginning with a GC make you a victim of the XY syndrom:

closures require than the variables they closed over live as long as the closure does (for safety reasons)

using the GC we can extend the lifetime of those variables long enough

XY syndrom: are there other mechanisms to extend the lifetime ?

Note, however, than the idea of extending the lifetime of a variable is not necessary for a closure; it's just brought over by the GC; the original safety statement is just the closed over variables should live as long as the closure (and even that is shaky, we could say they should live until after the last invocation of the closure).

There are, essentially, two approaches that I can see (and they could potentially be combined):

Extend the lifetime of closed over variables (like a GC does, for example)

Restrict the lifetime of the closure

The latter is just a symmetrical approach. It's not often used, but if, like Rust, you have a region-aware type system, then it's certainly possible.


答:
Yep, you have a problem - but the solution is not to rewrite!

Now, solutions for actually fixing your problem in a constructive way.. you need to start shearing off layers of the old system and replacing them, that's clear, and that means that you need to maintain compatibility with what you already have. So that sounds like web services (which you can write in any language you like, C++ even).

So, identify which parts of the system can be replaced with a totally independent web service, and start to reduce the complexity of the main system. Then, once its been cut down to a more manageable size you can start to refactor (sorry for using that clichéd word) the codebase to get rid of any irrelevant cruft and replace it with something a little more well-designed. Hopefully you'll be able to see how more modification, maybe replacing larger parts of the main system with better-written code would then help more.

And once you've done that, chances are you'll have a maintainable, extensible system that is a solution.

The trick is:
1. independant components, well designed to a specification and documented as to how to use them and what they do.
2. rework some of the existing code so it still works exactly the same way, but better. This means you'll have to document what its supposed to do.
3. Document it some more - I don't say this because of liking documentation, but because it sounds like there was a general lack of rigour in how the system has been worked on in the past. Hack some code in, hack in some more and you end up with a mess. Force documentation and specifications and you'll have a much better chance of keeping things in line.


问:
Twitter in app browser + user agent string
Recently (I believe some weeks ago) with the latest update of the Twitter app for iOS, all links found inside tweets are opened in Twitter's build-in browser. My question is how to find Twitter's browser agent so I can display custom messages.

For example:
If browser is Twitter's in-app browser then display a custom message via HTML+PHP. It seems that there is no known agent available.
Any help would be appreciate.

答:
Two obvious means for discovering a user agent come to mind.  The first is checking your server logs.  The user agent is typically logged by default, and you can add it if it's not.

The second method is to put http://whatsmyuseragent.com in a tweet and visit it from an iOS device to see what it says.


问:
Do I need to learn python first to understand the part 2 of the book Test Driven development?
It seems like Python is used as a coding language for part 2 of Kent Beck's book Test Driven Development. I have read the first part of that book and started appreciating the value of TDD . First part was easy to understand as the examples were in Java and that is the only language that I have worked on. How should I prepare myself to go about reading the second part of the book? What value will it provide? I do not plan to write a testing framework myself. Can I skip this entirely and go to the third section?</p>

答: No, it is not mandatory to know the language used in books to get the ideas behind that. If you're interested anyways, feel free to learn it. But it's not that important. The concepts matter.


问:
Read K&R before learning low latency C++?
I have never really done a large amount of C programming but am in the middle of teaching myself low latency C++. Would it do more harm than good to read the K&R C programming book? I am a bit worried I will be reading about C conventions which may no longer hold in C++ (especially with C's fondness of global variables).</p>

答:
K&R is a good read regardless, if only because C is the grandmother of C++, Java, C#, S/R, ...
You'll get a good sense that computers execute instructions, not abstractions.
That poor little chip has to cycle away doing what you asked it to do, and the less you ask it to do, the sooner it will finish.

C++ is a terrific language but - it strongly tempts you do do things that take you far away from your goal of minimum latency.
It tempts you to build massive class hierarchies, with lots of new-ing and delete-ing, notifications galore, and falling in love with container classes.
The idea of doing these things in healthy moderation is usually absent.

The result is, without realizing it, you can build in sources of slowness taking you orders of magnitude away from optimality.
You might have the greatest big-O algorithms, but the constant factors can be killers.
However, you can get back to optimality if you know how and you're willing to take a meat-axe to the code.
You can stay in C++ and have nice classes, without wasting any cycles.
Here's an example.


问:
Are there any practical uses of allowing recursive inclusion of a file?
I am currently implementing NASM-like preprocessor for my assembler, and I am wondering what is the correct way of handling recursively included files. From what I see, there are two ways to deal with it without hanging the preprocessor or even the OS:

Set maximum include depth.

Disallow including a file recursively (not to be confused with disallowing including a file twice).

Also, as far as I can see, the second approach does essentially the same job, but produces nicer error messages. Compare output of Clang, when compiling file containing #include "main.cpp" only:

```<code>In file included from main.cpp:1:
[ repeated many times ]
In file included from main.cpp:1:
main.cpp:1:10: error: #include nested too deeply
#include "main.cpp"
</code>```

with this (current way of handling this in my preprocessor; input is similar to above, does %include "1.mov.asm" at line 6):

```<code>In file /home/griwes/projects/reaverasm/tests/1.mov.asm in line 6:
Error: file `/home/griwes/projects/reaverasm/tests/1.mov.asm` included recursively.
</code>```

The approach disallowing recursive inclusion produces - IMHO - more readable output.

The question is: is there any preprocessor technique that would be killed by disallowing recursive inclusion? This question is language-agnostic, so feel free to give examples from any languages.

答:
I think you're conflating two different things:

Whether to allow recursive inclusion

The error output

I have seen multiple real-world examples where recursive inclusion was desired, but it was usually to work around limitations in the preprocessor. I feel it is wrong to disallow any recursion but a limit of 10 times is reasonable IMO.


问:
What API is required for code completion/syntax highlighting/similar IDE features?
I've been developing a little language in my own time, and I've got a fairly bare-bones prototype that implements some of the most basic features. Now I'm looking at scaling up, and I don't want to make a nasty architectural mistake where I have to massively refactor everything to support these features. So I'd like to know about the key API features required. Right now, I have

The lexer can operate on any input buffer using iterators, the tokens are available for inspection before passing to the parser, and I also provide a hook for comments.

The parser can operate on any token stream (not hard coded to my lexer at all), and the AST construction can be swapped out. I also annotated my AST with location information. Also, the AST is readily available for inspection prior to analysis.

Finally, many of the analysis features are lazily evaluated, so it's easy to get their semantic representation from the AST. But I'm not sure what features those semantic representations need to be readily available for such efforts.

Any suggestions as to what is necessary in this regard?

答:
For examples of what functionality can be offered, see Using Clang as a Library. Clang's AST matching uses C++ templates and macros, which makes it look fairy different compiler examples in ML or Haskell. Consider this example that "will capture all for statements that define a new variable initialized to zero."

```<code>StatementMatcher LoopMatcher =
  forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
    hasInitializer(integerLiteral(equals(0)))))))).bind("forLoop");
</code>```

Body:
For examples of what functionality can be offered, see Using Clang as a Library. Clang's AST matching uses C++ templates and macros, which makes it look fairy different compiler examples in ML or Haskell. Consider this example that "will capture all for statements that define a new variable initialized to zero."

StatementMatcher LoopMatcher =
  forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
    hasInitializer(integerLiteral(equals(0)))))))).bind("forLoop");


问:
How to deal with necessary workarounds in software?
Even with detailed specifications for exchanging data between computer programs, chances are that data generated by older versions of programs do not conform 100% to the specification, or that they use old obscure features which few people know how to implement them. As a result, companies have to keep a library of "odd specimens" for testing their software.

In good software design, these quirks can be confined into a small layer of libraries called "Abstraction Layer". However, most abstraction layers cut off too many functionalities (in order to prevent the higher level software from touching the unstable parts of the lower level software).

Sometimes it is not possible to completely hide away the unstable parts. What are the strategies for coping with such necessary workarounds?

((Please pardon my poor language skills.)

答: If data files, consider creating a translator module or separate program that will do the translation for you into the new format. Embed the knowledge of old -> new formats in that module and keep your current code clean.</p>


答: As for the first-line (unit) tests: According to Michael Feathers ("Working Effectively with Legacy Code"), more than a few seconds to compile and test your class locally is too long (causing you to start cheating away from the TDD method).</p>

Title: Continuous Integration Feedback Cycle

Body:
How long should the Continuous Integration process take (i.e. compiling classes and running unit tests + integration test)?

On my current project it takes about 30 minutes, is that OK?
What's the ideal length of build time?

Integration tests take most of that time, if the 30 min is too long what can be done here?

What's the impact of having the build complete in 30 min?


问:
Is there a way to use gcc as a library?
Anyone knows a solution that works something like this:

```<code>#include <stdio.h>
#include <gcc.h> /* This .h is what I'm looking for. */

int main (void) {
    /* variables declaration (...) */

    /* The following line is supposed to be equivalent to:
     *     $ gcc main.c -o main */
    results = gcc_compile_and_link("main.c", "main");

    /* Now I want to use the warnings and errors to do something.
     * For instance, I'll print them to the console: */
    printf("warnings:\n");
    for (i=0; i<results.warns_len; i++)
        printf("%s\n", results.warings[i].msg);
    printf("errors\n");
    for (i=0; i<results.errs_len; i++)
        printf("%s\n", results.errors[i].msg);

    /* free memory and finalize (...) */
    return 0;
}
</code>```

I know I can run the command "gcc main.c -o main" in a fork and parse the output... but I was looking for something more 'reliable' like the example above.

答:
It's not possible with gcc but you might find tcc (an embeddable C compiler) good enough for what you have in mind. The distribution comes with a libtcc library that allows to compile, link and run C code "on the fly".

Note that this only for C, your question is also tagged C++ but I've not seen any equivalent of tcc for C++.

Title: Is there a way to use gcc as a library?


答: I doubt there's anything better than forking gcc. You might consider clang, which is more designed for this kind of use.</p>

Title: Is there a way to use gcc as a library?

Body:
Anyone knows a solution that works something like this:

```<code>#include <stdio.h>
#include <gcc.h> /* This .h is what I'm looking for. */

int main (void) {
    /* variables declaration (...) */

    /* The following line is supposed to be equivalent to:
     *     $ gcc main.c -o main */
    results = gcc_compile_and_link("main.c", "main");

    /* Now I want to use the warnings and errors to do something.
     * For instance, I'll print them to the console: */
    printf("warnings:\n");
    for (i=0; i<results.warns_len; i++)
        printf("%s\n", results.warings[i].msg);
    printf("errors\n");
    for (i=0; i<results.errs_len; i++)
        printf("%s\n", results.errors[i].msg);

    /* free memory and finalize (...) */
    return 0;
}
</code>```

I know I can run the command "gcc main.c -o main" in a fork and parse the output... but I was looking for something more 'reliable' like the example above.


答: GCC was explicitly designed to resist being used as a tools base/library. You need to use Clang for this, or call GCC through commandline.</p>

Title: Is there a way to use gcc as a library?


问:
How is Sencha Touch performing on Android in practice?
I'm just about to start a project using Sencha Touch, and just done some minor testing on my HTC desire device. All tutorial videos at Vimeo seems to be using an iPhone emulator running on a Mac. Im not sure how fast this emulator is compared to a real iPhone device or even an real Android device, but from what i have experienced, it seems that my HTC desire is not performing that nicly as this emulator.

All animations (sliding, fading, etc) seems abit laggy. You can easily notice that the FPS is much less than on the Vimeo videos.

HTC desire is a relativly new and modern Android 2.2 phone, running with decent hardware, so im wondering if Sencha Touch is "ready" for the Android platform.

Anybody with practical experience with Android and Sencha Touch ?

答:
Sencha Touch + Phonegap Sucks on Android devices. Specially if you are targeting 2.2 onwards .
This combination works ok for G3/ Note category of android devices .
Forget Sencha Touch + Phonegap on Android if you want performance and UI like native.

Sencha Touch + Phonegap is only good for quickly hitting markets on thousands of devices without wishing eye poping & amazing performance.

IF your client is very specific about UI and Performance and insisting on Hybrid solution , just give him disclaimer and the paper signed by him that he wants Sencha Touch + Phonegap app.

I have burnt not only my fingers  but whole body with this deadly combo on Android.


问:
Shared QA responsibilities on an Agile team
For many years our IT development group subscribed to the waterfall software development methodology with segregated pods of programmers specializing in database development, logic layer and presentation layer development. Of course we also had a small quality assurance group which handled all testing responsibilities. Requirements, tasks and bugs were handed back and forth electronically, very little conversation took place, and the process ground painfully on.

In 2010 we made the monumental shift to Agile with Scrum and after some serious growing pains we've truly began to excel as a whole team. Communication is constant, people are growing and learning from each other every day, and our releases more stable and much more aligned with true business priorities.

One area we're still trying to grow in is in sharing software QA responsibilities amongst all development team members to get away from the toss-it-over-the-fence attitude that still seems to persist when it comes time to test a feature.

Does anyone have any advice as to how to grow a development team towards collective application quality ownership? We currently practice XP so we've begun to do more pair programming between developers and testers when creating unit and integration tests. But it still is challenging to get the whole team to proactively think about testing strategies for each sprint. Inevitably one or two "Write Test Cases" tasks are thrown into the sprint backlog with no forethought as to what will be tested and how it will best be achieved and organized so the entire team is aware of what testing has been completed, what's currently being tested, and what's left to test.

Sorry for the long-winded question, but any advice would be much appreciated.

答:
I think your question really has two aspects to it:

1) How does a traditional software QA/QE group fit into an Agile development environment?

In my experience, you're correct. Separating the testing team from the development team creates some issues. The "throw it over the fence" method doesn't work very well in Agile. What we've done is make the testing team just part of the Agile Team. If your quality team is more technical, maybe easing them into development is a possibility. Maybe one member of the quality team is interested in becoming the Scrum Master. Maybe some members of the quality team are looked at as specialized testing resources on the Team. I think it's important in any case that they are full-fledged Team members, though; they come to all of the standard Scrum meetings, help with estimation, contribute to the Retrospective, etc.

2) How is the testing responsibility spread throughout an Agile Team?

This has to do with your Team's Definition of Done. The testing effort for a Story should be part of the acceptance criteria. Testing (both automated and manual) should be parts of the tasks toward completion of the Story. That way, the dedicated testers can be assigned pieces of the Story that are an actual part of their completion. Of course, this means that development tasks need to be granular enough that there are testing tasks available throughout the Sprint. For testing resources, maybe the first couple of days of a Sprint is spent on maintaining automated tests, or grooming the bug database. We've decided that bugs found on a Story during the Sprint it's being developed in need to be fixed for the Story to be accepted. Bugs reported after the Story is accepted become part of the product backlog and are prioritized.

Hopefully this gives you one possible answer. As always with Agile, you'll find that what works for your Team will be unique in some respects.


问:
Is there a modern replacement for a mutation testing tool like Jester for Java?

“Why just think your tests are good when you can know for sure?
  Sometimes Jester tells me my tests are airtight, but sometimes the
  changes it finds come as a bolt out of the blue. Highly recommended.” - Kent Beck

But I see that there is not even a tag called "Jester" in stackoverflow. So what is the modern replacement for Jester,if any ? How can one be sure that unit tests written are rock solid other than finding statistics from code coverage from tools like Cobertura and Clover?

答:
As far as I'm aware mutation testing remains the best automated process for measuring the quality of your test suite. There are two good modern replacements for jester

http://pitest.org (I'm the author)

https://github.com/david-schuler/javalanche/

A detailed comparison between them, jester, and a couple of other systems is available here

http://pitest.org/java_mutation_testing_systems/

I think the main reason that jester never took off was that it was unworkably slow and scaled very badly.

PIT and javalanche both attempt to address this in a similar way. Instead of blindly running all the tests in a project against a mutation they first gather line coverage and run only those tests that can actually hit a mutation.

PIT also performs various other optimisations to speed things up and offers an option to re-use the results of previous analysis to greatly reduce the computational cost of subsequent runs.


问:
What is difference between publisher-subscriber and reactor patterns?
Publish-subscribe and Reactor patterns looking very similar to me. How they are different?

In both patterns a message is getting passed to subscribers indirectly (listeners in reactor pattern).

I feel observer pattern is very similar to two other patterns too.

What are key differences between those patterns?

答:
As I can see from the link, PubSub pattern is not an OOP pattern, but rather messaging pattern, which is a network architectural pattern.

Reactor pattern is something related to servers' request handling with single-threaded event loop. Again, the link shows some good examples like Node.js, Netty, Twisted, etc.

Finally, Observer is OOP design-pattern which describes a way of interaction between objects in OO-code.

So those three patterns are from different domains.


问:
What is the appeal of Systems Hungarian?
In a now deleted question titled "What naming guidelines do you follow?", the author says:

Also I prefer to code using hungarian notation from Charles Simonyi.

I've run in to several programmers who still prefer to use Hungarian, mostly of the Petzold/Systems Hungarian flavor.  Think dwLength = strlen(lpszName).

I've read Making Wrong Code Look Wrong, and I understand the rationale for Apps Hungarian, where domain-type information is included in the variable names.  But I don't understand the value in attatching the compiler type to the name.

Why do programmers still persist on using this style of notation?  Is it just inertia?  Are there any benefits that outweigh the decreased readability?  Do people just learn to ignore the decorators when reading the code, and if so, how do they continue to add value?

EDIT:
A lot of answers are explaining the history, or why it is no longer relevant, both of which are covered in the article I cited.

I'd really like to hear from anyone out there who still uses it.  Why do you use it?  Is it in your standard?  Would you use it if it wasn't required?  Would you use it on a new project?  What do you see as the advantages?

答:
I actually started using SH in new code I wrote this month.

My assignment involved rewriting some Perl code in JS so it could be moved to the client side of our web application. In Perl, SH is generally not required because of sigils ($string, @array, %hash).

In JavaScript, I found SH to be invaluable to track the types of data structures. For example,

```<code>var oRowData = aoTableData[iRow];
</code>```

This retrieves an object from an array of objects using an integer index. Adhering to this convention saved me quite some time looking up data types. Plus, you can overload succinct variable names (oRow vs. iRow).

tl;dr: SH can be great when you have complex code in a weakly typed language. But if your IDE can track types, prefer that.

ContentLicense: CC BY-SA 4.0

Body:
I actually started using SH in new code I wrote this month.

My assignment involved rewriting some Perl code in JS so it could be moved to the client side of our web application. In Perl, SH is generally not required because of sigils ($string, @array, %hash).

In JavaScript, I found SH to be invaluable to track the types of data structures. For example,

var oRowData = aoTableData[iRow];

This retrieves an object from an array of objects using an integer index. Adhering to this convention saved me quite some time looking up data types. Plus, you can overload succinct variable names (oRow vs. iRow).

tl;dr: SH can be great when you have complex code in a weakly typed language. But if your IDE can track types, prefer that.


问:
Connection between programming language and solutions
This is a rather philosphical / theoretical question.

I am interested in the question, how language (in this case programming languages) and thoughts (= solutions of problems) are connected.

I want to know, whether the programming language influences the solutions, I can come up with.

For example:

I program something in Haskell (functional) and in Java (OOP). Do the general solutions differ fundamentally or are they - aside from syntactic sugar - the same? Do I not just use different algorithms and a different software design, but do I fundamentally change my whole point of view, my concept and my view of the software, depending on the paradigm I am starting from?

(Note: "I" stands for a generic programmer)

I know, that this question is pretty hard to answer, but I find it very interesting, so I wanted to know, whether somebody has (and might share) a opinion about this.

答:
I think it's a good question, not easily answered.
All I can give you is my take on it.

There's something in your head - a problem and its solution.
The separation between those is not always clear, but they are stated in a mental language appropriate to the problem.
You can get a hint of what this language is by discussing the problem with another person.
That reveals a network of concepts in the form of words.

If a computer program is to be part of the solution, then the problem/solution needs to be communicated in keystrokes to the machine. To do this it is probably necessary to educate the machine about the problem domain, so you can tell it what you want.

When you define a datatype or write a procedure or otherwise define things in a computer language, you are augmenting that language with the concepts appropriate to your problem. You are turning it into a DSL (domain-specific-language in the lingo).
There is a lot of skill involved in this step, and different programmers have learned different ways to do this.

Now if you're asking about different programming paradigms like OOP, functional programming, logic programming, etc. etc., which of those shortens your path to creating the DSL that you want?
Again it depends on training.
(If all you have is a hammer, everything looks like a nail.)
I encourage people to have as diverse a set of mental tools as possible.

The extent to which you've created a DSL for your problem is a matter of degree.
In the ideal extreme, it should only be necessary to state your problem, where the solution is built into the DSL.
A measure of how well you've done this is to consider incremental changes to the problem and ask how much editing in the language is necessary to effect them without errors.
The ideal is 1:1. 1:5 is not too bad. I've seen 1:50 and that's not good.
The bigger that ratio is, the harder it is to get your idea across to the code, and the harder it is to avoid putting in bugs.

(I don't know if it would help to give you an idea what I mean to show how I tried to do this in the domain of dynamic user interfaces.)


答:
Without getting into the Sapir-Whorf Hypothesis, I will make the claim that the language, framework and tools (collectively, your programming ecosystem) profoundly influences and shapes the way you think, in terms of writing software.

It's not hard to see why this is true.  Consider a typical line-of-business application.  Traditionally, we would have written SQL statements to retrieve data out of a database and produce a report.  But then ORM's came along, and now we can retrieve data into collections of objects.  Eventually, someone pointed out "Well, why do we even need SQL at all," and the NoSQL movement was born.

How do these different paradigms affect the way programmers think?  Well, in SQL, if you want to relate two tables of information together, you perform a JOIN.  The NoSQL guy has to loop through his collections to find pairs that match.  The SQL guy thinks in terms of sets and joins.  The NoSQL guy thinks in terms of collections and loops.

In terms of the programming language itself, your programming experience (and the way you think) will be strongly influenced by:

what facilities the language offers,

at what level of conceptual abstraction the language is (i.e. is it low-level or high-level),

what paradigms the language offers (i.e. Functional, Imperative, Object-Oriented), and

what kind of assumptions the language designers make (e.g. many ways to do a thing vs. the One True Way).

Eric Raymond sums it up eloquently when he speaks of the benefits of learning Lisp:

Lisp is worth learning for the profound enlightenment experience you
will have when you finally get it; that experience will make you a
better programmer for the rest of your days, even if you never
actually use Lisp itself a lot.

For more about how language influences the way we think, see here:

http://scienceblogs.com/cognitivedaily/2005/05/13/does-our-language-affect-our-t/

Title: Connection between programming language and solutions

Body:
This is a rather philosphical / theoretical question.

I am interested in the question, how language (in this case programming languages) and thoughts (= solutions of problems) are connected.

I want to know, whether the programming language influences the solutions, I can come up with.

For example:

I program something in Haskell (functional) and in Java (OOP). Do the general solutions differ fundamentally or are they - aside from syntactic sugar - the same? Do I not just use different algorithms and a different software design, but do I fundamentally change my whole point of view, my concept and my view of the software, depending on the paradigm I am starting from?

(Note: "I" stands for a generic programmer)

I know, that this question is pretty hard to answer, but I find it very interesting, so I wanted to know, whether somebody has (and might share) a opinion about this.


问:
Maintain a web application once the only developer is gone
I have a terminal disease and there is a very high chance that I will no longer be in this world by the end of the year.

I have developed a web application that it is extensively used in my family’s business (a small hairdressing shop). No member of my family has neither programming nor system administration skills. I have neither close friends with those skills.

The business makes at most 10k in net profits per year. In fact, the business profits can only afford to pay the salaries of its 3 employees (father, mother and sister) and those are quite low and decreasing each year due to the financial crisis. In fact, I am not an employee of my family’s business, I work for a normal software development company. I developed the application during my free time in order to help them.

So far I do not care if another business also uses my application or even if the application itself loses my ownership. I just want that my family’s business can continue using it, which means system administration support if something goes wrong and development for new features/bugs.

I would like to ask you if you could give me the measures you think I could take in order to guarantee as much as possible the continuity of the application.

The technologies of the application are:

Platform: Tomcat (Java), MySQL and Linux

Frameworks: mainly JPA and ZK

答:
I appreciate this is a very sad situation for you and family, but it sounds like the problem is not entirely a technology one.

The business is barely viable. You've got to question whether they should bother to continue if they can only afford to do it with you working for free. It might be easier for them just to get other jobs.

The simplest solution is for your family to find someone who will continue to develop the site for free. The technology doesn't really matter. Perhaps you have a friend in your current workplace who might be able to continue after you've gone. Find this person and hand it over.

Without knowing what the site does its difficult to suggest or comment on technology choices.

There are a number of practices you can adopt to help other developers pick up your code.

Pick a coding standard that is widely adopted, for example, perhaps use Sun/Oracles. This will reduce the learning curve on your code base.

Ensure you have comprehensive test coverage. This will give a new developer confidence to make changes, while knowing they've not regressed anything.

Ensure that build and deploy are automated. You want to be able to get a clean checkout on any machine and only have to worry about actually making the code changes you care about.