答:
Different implementations of sets spring to my mind. One of the most naive is implementing it over a vector, which means remove as well as contains and therefore also add all take O(N).

An alternative is to implement it over some general purpose hash, which maps input hashes to input values. Such a set implementation performs with O(1) for add, contains and remove.

If we assume N is about 10 or so, then the first implementation is probably faster. All it has to do to find an element is to compare 10 values to one.

The other implementation will have to start all sorts of clever transformations, which can be a lot more expensive, than making 10 comparisons. With all the overhead, you might even have cache misses and then it really doesn't matter how fast your solution is in theory.

This doesn't mean, that the worst implementation you can think of will outperform a decent one, if N is small enough. It simply means for sufficiently small N, that a naive implementation, with low footprint and overhead can actually require less instructions and cause less cache misses than an implementation that puts scaleability first, and will therefore be faster.

You can't really know how fast anything is in a real world scenario, until you put it into one and simply measure it. Often results are surprising (at least to me).


问:
Why the scorn for COBOL?
When people mention COBOL, it's usually either met with a snort or groan. I don't know much about COBOL, but I've seen some programs written in it. I can see that it's wordy, and to uninitiated eyes such as mine, unintelligible. But, really, aren't all programming languages complete gibberish to a lay person?

I understand that it works, works well, and is still in widespread use in the industries it was designed for. Aren't those the hallmarks of a good language? What's so bad about COBOL?

答:
Two features.

The ALTER statement is pure evil.  While rarely used in more modern COBOL applications, it was heavily used in the "olden days" because it was more efficient than the equivalent "IF-GOTO" structure.  When computers only had 32K of RAM, each instruction mattered.  It modified a GOTO statement to have a different destination.

This made some code opaque because the code itself was stateful.

The REDEFINES clause in a data structure (like the union in C) is a perpetual problem.  The term "free union" -- i.e., overlayed data structures without a discriminator -- is a way to summarize the problem.  Two REDEFINES aliases cannot be trivially distinguished by the data; only extensive reading of program logic could determine the meaning of the two alternate interpretations of the bytes.

This made many data structures opaque because the data cannot be understood without the code.

The readability of the English-like syntax was defeated by these two constructs.

[I've been warned by moderators that short answers are dismissive of your important and interesting question.  If you find this dismissive, you could ask for details.  Or flag it so that the moderators can delete it.]

ContentLicense: CC BY-SA 3.0

Title: Why the scorn for COBOL?


答:
Having spent most of today writing some COBOL I think I can give some current input.

First the BAD stuff:-

No function calls.
Modern COBOL has some built in functions but its a serious engineering job to write your own.

No type checking on subroutine calls.
You can pass (or not pass) anything on a subroutine call, the called subroutine will blithely assume it has the correct parameters, and, there is no way to detect missing or invalid parameters.

No libraries.
None zero zilch. No standard libraries, no widely used easily available libraries. You end up coding commomplace tasks by hand over and over again.

Everything is implemented as a keyword.
Because the language authors don't have the concept of a library every new feature ends up being implemented with new keywords e.g. PARSE and RENDER for XML support.

The misunderstood, i.e. those criticisms commonly leveled against the dear old language which are invalid or irrelevant.

Verbosity.
So you type a few extra characters! Its not a serious issue.
In many  cases COBOL is less verbose than say Java.

"COBOL FILES"
You see this term bandied around a lot. There is no such thing its just that COBOL can handle just about any file format and just about any file organization.

No multi-threading.
In the environments where COBOL thrives, multi-threading is usually left to application containers like CICS or IMS which are good at it, rather, than programmers who tend to be bad at it.

And the good stuff - some aspects of COBOL are superior to other languages:-

Data structures.
COBOL has a concise and flexible syntax for defining complex data structures and odd data types.

Decimal Arithmetic.
It has native support for decimal arithmetic i.e. arithmetic as understood by accountants, with proper rounding etc.

Moving with the Times.
Some aspects of COBOL are surprisingly modern. Built in XML support, support for OO programing, the ability to use Java classes etc.

Integration with DB2,CICS etc.
This only applies to IBM's mainframe COBOL (but that is by far the largest chunk of COBOL still running) but the integration with DB2, CICS and other mainframe environments make it easier to code up things like data base backed web services than in any other environment.

Screen handling.
The standard screen handling as implemented on AS/400 and MicroFocus Cobol is excellent.

Performance.
For many years COBOL compilers have been producing very high performance executables. Only native C and native Assembler beat COBOL on an IBM mainframe.

So all in all its doing quite well for something that was put together by a committee in the 1950s. If an existing application is implemented in COBOL and does the job there is no reason to re-write it. However unless there is a really good reason I don't see any justification for new projects to use COBOL.

Title: Why the scorn for COBOL?

Body:
When people mention COBOL, it's usually either met with a snort or groan. I don't know much about COBOL, but I've seen some programs written in it. I can see that it's wordy, and to uninitiated eyes such as mine, unintelligible. But, really, aren't all programming languages complete gibberish to a lay person?

I understand that it works, works well, and is still in widespread use in the industries it was designed for. Aren't those the hallmarks of a good language? What's so bad about COBOL?


问:
Do real-world algorithms that greatly outperform in the class below exist?
Last night I was discussing with another programmer that even though something may be O(1), an operation which is O(n) may outperform it if there are is a large constant in the O(1) algorithm. He disagreed, so I've brought it here.

Are there examples of algorithms which greatly outperform those in the class below it? For example, O(n) being faster than O(1) or O(n2) being faster than O(n).

Mathematically this can be demonstrated for a function with an asymptotic upper bounds, when you disregard constant factors, but do such algorithms exist in the wild? And where would I find examples of them? What types of situations are they used for?

答:
The unification algorithm used in practice is exponential in the worst case, for some pathological inputs.

There is a polynomial unification algorithm, but it is too slow in practice.


问:
Have objects delivered in terms of code reuse?
I have often heard it said that objects have not delivered in terms of code reuse. Do you agree? If you believe that they haven't, why not?</p>

答:
Objects have no more ability to deliver code reuse than a stairclimber or other fitness equipment can deliver weight loss. Developers have to be motivated to use tools properly.

Once software teams place a higher value on reusing tested code than they do on keeping all the details in their head, you'll see far more fine-grained objects and methods and hence more code reuse.

ContentLicense: CC BY-SA 2.5


答:
An O(1) algorithm:

```<code>def constant_time_algorithm
  one_million = 1000 * 1000
  sleep(one_million) # seconds
end
</code>```

An O(n) algorithm:

```<code>def linear_time_algorithm(n)
  sleep(n) # seconds
end
</code>```

Clearly, for any value of n where n < one_million, the O(n) algorithm given in the example will be faster than the O(1) algorithm.

While this example is a bit facetious, it is equivalent in spirit to the following example:

```<code>def constant_time_algorithm
  do_a_truckload_of_work_that_takes_forever_and_a_day
end

def linear_time_algorithm(n)
  i = 0
  while i < n
    i += 1
    do_a_minute_amount_of_work_that_takes_nanoseconds
  end
end
</code>```

You must know the constants and coefficients in your O expression, and you must know the expected range of n, in order to determine a priori which algorithm will end up being faster.

Otherwise, you must benchmark the two algorithms with values of n in the expected range in order to determine a posteriori which algorithm ended up being faster.

Title: Do real-world algorithms that greatly outperform in the class below exist?

Body:
Last night I was discussing with another programmer that even though something may be O(1), an operation which is O(n) may outperform it if there are is a large constant in the O(1) algorithm. He disagreed, so I've brought it here.

Are there examples of algorithms which greatly outperform those in the class below it? For example, O(n) being faster than O(1) or O(n2) being faster than O(n).

Mathematically this can be demonstrated for a function with an asymptotic upper bounds, when you disregard constant factors, but do such algorithms exist in the wild? And where would I find examples of them? What types of situations are they used for?

Body:
An O(1) algorithm:

def constant_time_algorithm
  one_million = 1000 * 1000
  sleep(one_million) # seconds
end

An O(n) algorithm:

def linear_time_algorithm(n)
  sleep(n) # seconds
end

Clearly, for any value of n where n < one_million, the O(n) algorithm given in the example will be faster than the O(1) algorithm.

While this example is a bit facetious, it is equivalent in spirit to the following example:

def constant_time_algorithm
  do_a_truckload_of_work_that_takes_forever_and_a_day
end

def linear_time_algorithm(n)
  i = 0
  while i < n
    i += 1
    do_a_minute_amount_of_work_that_takes_nanoseconds
  end
end

You must know the constants and coefficients in your O expression, and you must know the expected range of n, in order to determine a priori which algorithm will end up being faster.

Otherwise, you must benchmark the two algorithms with values of n in the expected range in order to determine a posteriori which algorithm ended up being faster.


问:
Windows Phone 7 app development - Is it worth it?
I've written a Windows Phone 7 application to display the Ordnance Survey maps that are loved so much in the UK (I am amazed that no-one else has done this yet). However I was about to shell out the £65 to pay for the app hub and get my app to the marketplace when I started investigating how you actually get paid for the apps that people buy. Apparently if you are not a US developer then you have to start sending over forms e.g. W8BEN form? and even after this the IRS takes another 30% (after MS have taken their 30% share). It also mentions VAT so maybe there is more money taken off after this as well???

Has anyone from outside the US actually got all the paperwork sorted so they got paid? Did you get tax taken off as well? What percentage of the sales do you actually end up with? Is it all worth it?

I don't expect to make much from the app but I would like to think I could recoup my £65 and have enough to buy a couple of beers as well.

答:
Well after thinking this over I've gone and registered on app hub and handed over my money anyway. The app (OS Maps) is priced at 99p so after all the deductions I will pocket approx 30 pence for each download. I'll need at least approx 220 downloads before I earn any beer money. It's not a bad app and fills a niche but who knows how many downloads I'm likely to get.

Just a couple of comments on the whole Income Tax/VAT thing:

In the UK we don't pay VAT unless our wonderful business turns over more than 73k. If any app makes that much money I'll happily pay the VAT!

In the UK the income tax rate is generally 20%, so less than the 30% that the IRS want. Also, you would only pay income tax after any expenses, and the £65 for the app hub registration would definately be a legitimate expense so we are being short-changed by the way that MS are handling App store payments.


问:
Is there a practical guide to Team Software Process?
I have seen the Carnegie Mellon site covering TSP.  I am looking for a practical, non-academic guide to application of TSP in the real world.  I would really like to know, how does TSP reduce bugs?</p>

答:
If you aren't familiar with the Personal Software Process (PSP), I'd start with Watts Humphrey's book PSP: A Self-Improvement Guide for Software Engineers. This book is geared for practitioners looking to apply the PSP in their job. It also begins to introduce the Team Software Process (TSP) in the later chapters. A very brief, high level introduction to the PSP can also be found in Introduction to the Personal Software Process, also by Watts Humphrey. Although I don't own them, the canonical books on the Team Software Process are Introduction to the Team Software Process (a high level overview to get started), TSP: Leading a Development Team, and TSP: Coaching Development Teams. Since you've mentioned the TSP website, you've probably already seen the Team Software Process Technical Report along with other reports published by the Software Engineering Institute about the TSP.

The PSP, and by extension, the TSP, reduce defects by introducing a repeatable, quantatively measured process. The TSP calls for a team (or teams) of PSP-trained engineers working together on a larger project. In order to understand how the TSP reduces defects, you need to first employ the PSP to reduce defects on an individual level by gaining insight and making adjustments to the individual process.

At PSP0, you begin making measurements to help understand how you current build software - size, time, number of defects, and so on. The act of simply recording data and analyzing it can provide insights into which life cycle phases are most problematic for the individual, either by individual data elements or some combination of them.

PSP1 doesn't add any quality aspects, but does improve estimation. There might be a quality improvement here since you have a greater understanding of how you use your time and can allocate and utilize time more efficiently. Even though you don't use this data until PSP2, you start tracking it now to have a historical record to start with. Being able to know if you need to spend more time on a particular aspect of the product life cycle or if time is being wasted might help you improve process quality, if not also product quality.

In PSP2, you add reviews in order to prevent and remove defects. You also add process improvement - utilizing your measurements and estimations, as well as recording where defects happen. By taking your time, size, defect, and estimation data, as well as defect injection data newly added, you can answer more questions. Relationships form between program size and defect rates, time spent in reviews versus defect rates, and so on. Using this allows you to act (as an example, if you're spending a long time in reviews, yet many defects are escaping to the next phase, there's a problem with how you conduct reviews).

The Team Software Process takes a team of engineers all utilizing PSP, scales it up, and adds management-level tasks to coordinate their interactions and explore measurements and metrics relevant to a team of software developers rather than just at an individual level. The ability to identify relevant measurements and metrics and then apply them to identify weaknesses in the process is the whole point of both the TSP and PSP.


问:
Required technical knowledge for developing high-level to high-level language translators
I have seen a tool (Shed Skin) to translate one high-level language to another high-level language. Apart from knowing those languages what are the other areas of technical knowledge required to develop this kind of translators? </p>

答:
You are developing a compiler here (a program that translates from one language into another), so I'd consider a firm background in compiler theory both crucial and sufficient to do the job.

Any further knowledge depends on the scope of the job. Compiling Java to C++ would, for example, be mostly trivial when you have a garbage collector implementation at hand. Haskell to C seems to be a much more complicated matter, judging from the slow progress of the ghc.


问:
Why was Rails written in Ruby?
I know PHP and Ruby.

Using a PHP Rails clone (not out of choice), called Symfony, (which is apparently the best PHP framework), I notice that it's a clone of Rails. I think Symfony is stupid and that (SensioLabs is a clever business) because Rails already exists.

Apart from open-source projects gaining money, I don't understand why people are making Rails clones in PHP, when Rails already exists. Why not use Rails? Surely DHH coded Rails with Ruby for a reason.

Using Symfony, I notice that something doesn't quite feel right but I don't know what it is. I learnt Rails through a crap Sitepoint ebook and forgot it, so now I'm learning it through the PragProg ebook and I love that ebook. I don't fully know Rails, but I understand how it works (thanks to Symfony). I would love finish getting through the whole ebook so I can make 2 Rails apps. I remember Rails being more fun than Symfony using the Sitepoint ebook that I couldn't finish, and that had nothing to do with Ruby's pretty syntax.

Why is Rails coded in Ruby?

What is it about PHP Rails clones, that don't feel right?

What is it that Rails is doing, that Rails clones aren't doing?

答:
Why not use rails?

I'll offer some perspective as a user of both. I hobby program in Ruby/Rails and I use PHP exclusively at work. (Note: I do not dismiss Ruby/Rails as a hobbyist environment, this is just how I choose to use it.)

Many people treat Ruby/Rails as the holy grail of website development because of the popularity bandwagon and because its 'different.' In many ways it certainly is but not enough to dismiss PHP as something ancient.

Symfony doesn't feel like Rails because PHP does lack some of the syntactic sugar that rails provides.  PHP is improving in this regard and 5.3's addition of closures has made a difference in how many of us write code.

Don't get me wrong, I love Ruby and I love Rails. But when you don't want to deal with complex or expensive website hosting or worry about performance or being 'bleeding edge', PHP is still extremely relevant today and it's frameworks are also very good.

Redbean offers great ORM functionality with PHP. So does Doctrine, Idiorm/Paris, and Propel.

Symfony2 and CakePHP offer a bloated web development framework similar in spirit to Rails.

CodeIgniter offers a full framework solution without the bloat.

Slim offers a sinatra-like framework.

Your insinuation that PHP rails clones don't 'feel right' is misguided I think, because they aren't clones and they aren't going to be the same as Rails. Learn to bask in the simplicity and familiarity of a PHP solution.

Title: Why was Rails written in Ruby?


答: Heh, I went to college in the early 80s, and people were scornful of COBOL even back then.  I think the biggest problem is its verbosity -- a simple "Hello, world!" in COBOL is probably over fifty lines, 95% of which are required boilerplate.  It's just not a very elegant or attractive language.  It was also designed to handle yesterday's problems, and doesn't really lend itself to development paradigms developed after about 1970.  It's a pretty good report generation language — as long as your reports are endless columns of numbers with headers and footers.  If you want to stick in a graph or a logo somewhere, forget it.  I think it's still the fastest language for "data processing"-type tasks (take a fixed-format file with 5M ATM transactions and do a simple balance adjustment for each one), but how many developers do those kinds of things any more?  And lots of systems use XML or JSON nowadays, I'd hate to think about trying to parse anything like that with COBOL (actually, I'd hate to think about parsing in general in COBOL!)</p>

Title: Why the scorn for COBOL?


问:
source code file system layout for 2 very similar projects (with git)
we're working on "two" android apps that are very similar; in fact, they're the same apps with different graphics and color schemes, slightly different configuration and one or two unique activities that are not in the other project - but the functionality is 95% the same.

the plan was to work on one app until it is as complete as possible and then change the images and the other /res(ource) files.

of course it's not that easy; we're still working on the shared code, and patching the same code in different projects (or repositories) is - in my opinion - out of the question.

we're all using git and eclipse.

is there the "definitive guide" about handling such a situation?

my thoughts about it:

three repositories

rep1 for the unique files of application1, rep2 for the unique files of application2, and rep3 for the shared files.

if there is a way to push files in one folder (the project folder) to different repositories ... i mean, cloning rep1 automatically pulls the files from rep1 AND rep3, and pushing automatically pushes files back into to the right rep?

my teammates are suspicious; no one of us knows git very well and we're afraid of spending too much time repairing our dcvs mistakes.

2 repositories

if the first option isn't possible, our plan was to have 2 repositories. rep1 for the complete app1 and rep2 only for the rep2-specific files. a build script would replace the files from app1 with those of app2. imo this is an "accidental overwrite" minefield, and i don't like it. but as long as we don't have a better solution, this is the way to go.

eclipse

maybe there is some kind of eclipse-specific hack that would make this painless?

(edit) branching!?

i don't have any experience with branching. but this be a possible solution?

note: these are android projects; android demands a specific file layout. e.g. the name and structure of the "res" folder is pretty much fixed. this means that there are directories which contain files both app-dependent and shared files. i don't know if git can handle this.

答:
we solved the problem - it's actually trivial, and we had the answer for months, only we didn't recognize it as such:

2 android projects

1 android project as a library

3 directories, all in the same git rep. so easy.

edit: actually, i've been a bit overenthusiastic with this answer. there are still unsolved problems with resource sharing (libraries taking resources from host projects? afaik not possible). we have devised two workarounds for that problem, but neither one is very satisfying.

late edit:

libraries actually do inherit their parents resources. so, if there is a resource string/foo = "bar" in the library project, and a resource string/foo = "boo" in the client project, then if you use string/foo in the client project the value is boo. this is a working solution, even though i have the feeling that sometimes there could be unintended namespace collisions.


答:
Regex libraries are usually implemented to do backtracking which has worst case exponential time rather than DFA generation which has a complexity of O(nm).

Naive backtracking can be a better performer when the input stays on the fast path or fails without the need to backtrack excessively.

(Although this decision isn't just performance based, it's also to allow back references.)


问:
Is it wrong to take code you have produced at work and re-use it for personal projects?
Throughout my various workplaces I always wrote code which made me think "this would be really useful in other situations". Indeed, I intentionally write code, even if it takes me longer  write, which I know will help me in the future (e.g. custom SubString() functions).  A good candidate for these snippets are various 'Helper' classes.

These snippets I'm sure can probably be found elsewhere online but the point is, I wrote them, and I will use them again later in other jobs or for personal projects.  Currently I don't maintain a personal code library, but the question is, is it wrong to take code you have produced at work and re-use it (a) for personal projects, and (b) in other jobs?

答:
Depending on your terms of employment, it might be. Consult with your supervisor, human resources department, legal department, and/or ethics department to determine what is owned by your company and what is owned by you, as well as what the process is for requesting to obtain rights to use or ownership of things that you produce at work.

Nearly every place that I have worked, things that go into projects are owned by the company, but I've sought and obtained permission to bring things out for personal projects on a case-by-case basis, which usually required explaining what I want to do with it and how it wouldn't be detrimental to the organization to let it go.


答:
It depends on your employment contract. These days, the most probable answer is (a) yes, this is wrong and (b) yes, this is really wrong. Almost all contracts offered to developers today have provisions saying that any code you write while employed by the company (whether during office hours or not) is theirs and you automatically transfer your copyright to them. Unless you specifically negotiated against this, this presumably applies to you.

However, as always:

Don't believe us! Consult a lawyer before doing something potentially perilous.

Title: Is it wrong to take code you have produced at work and re-use it for personal projects?

Body:
Throughout my various workplaces I always wrote code which made me think "this would be really useful in other situations". Indeed, I intentionally write code, even if it takes me longer  write, which I know will help me in the future (e.g. custom SubString() functions).  A good candidate for these snippets are various 'Helper' classes.

These snippets I'm sure can probably be found elsewhere online but the point is, I wrote them, and I will use them again later in other jobs or for personal projects.  Currently I don't maintain a personal code library, but the question is, is it wrong to take code you have produced at work and re-use it (a) for personal projects, and (b) in other jobs?


答:
I've had the same thoughts as well in the past. Unfortunately, I think anything you write directly for your job would technically be held under copyright by your employer. You would need to ask for permission to reuse that code in other non-company related work.

On the other hand, if you wrote code in your spare time for one of your own projects you could protect your code with some sort of copyright and then offer to give that code to your employer for use.

Either way there needs to be clear communication on the issue.

Of course, IANAL.


答:
You might want to check out this article. As it turns out, Microsoft has greatly simplified the formal steps WP7 developers need to take to get Marketplace revenues paid out.

This is a quote from MS:

One issue we’ve heard loud and clear from you is the time and energy
  required to provide tax information such as ITIN. I’m happy to share
  today that we’ve simplified payout and taxes by eliminating the need
  to provide an ITIN on your W-8 to take advantage of a reduced
  withholding rate. That’s MORE money, with less paperwork.

In addition, as far as I know, you don't have to pay taxes to the IRS in addition to UK taxes.

Title: Windows Phone 7 app development - Is it worth it?

Body:
I've written a Windows Phone 7 application to display the Ordnance Survey maps that are loved so much in the UK (I am amazed that no-one else has done this yet). However I was about to shell out the £65 to pay for the app hub and get my app to the marketplace when I started investigating how you actually get paid for the apps that people buy. Apparently if you are not a US developer then you have to start sending over forms e.g. W8BEN form? and even after this the IRS takes another 30% (after MS have taken their 30% share). It also mentions VAT so maybe there is more money taken off after this as well???

Has anyone from outside the US actually got all the paperwork sorted so they got paid? Did you get tax taken off as well? What percentage of the sales do you actually end up with? Is it all worth it?

I don't expect to make much from the app but I would like to think I could recoup my £65 and have enough to buy a couple of beers as well.


答:
You question is very similar in vane to this one "Open Source - Is it legal to recreate/open source a program you previously created for another company?"

I would say you are on shaky legal grounds as the companies you worked for probably own the code you wrote for them.  It would be better to code the routines from scratch, but even then there could be questions if you still had copies of the other code around.

[I'm not a lawyer, so don't expect my advise to help you in a court of law.]


答:
Just rewrite the code as and when you need it. It completely avoids the issue for the sake of a few minutes of coding.

Chances are in the interim you will have learned more and will write something better. Rewriting code also generally makes it more elegant.


答:
I would say that those generic little method/function are best not kept between projects.  Most of the time, you can use Boost or whatever your language provides to do this.  Most of the time, those are better written than yours. </p>

<p>What is a good idea is to have a set of unit tests for those and use those to test your code kata. </p>

Body:
I would say that those generic little method/function are best not kept between projects.  Most of the time, you can use Boost or whatever your language provides to do this.  Most of the time, those are better written than yours.

What is a good idea is to have a set of unit tests for those and use those to test your code kata.


答:
I've always solved this problem by having a personal project where I put all my crazy ideas and generic stuff, and then license it under the BSD license, which allows people to re-use, alter, rebrand, close it and charge money for it. That way, I retain the copyright but can re-use the code as I please for this and that employer, so that I retain the copyright to the original, but the employer retains the copyright to the re-used instance. I figure that if they had a problem with that, then they'd simply have to pay me to rewrite it on work time which makes no sense from their point of view. Furthermore, companies use BSD code all the time, since the idea behind BSD is to allow people and companies to do with it pretty much whatever they want, including rebranding and selling it.

Then of course, if additions are made to the code at the work place, I can't re-use it elsewhere without rewriting it on my own time... which is fine because generic stuff tends to be relatively small, unless it's an idea that warrants considerable free-time effort anyway.

Writing it on your own time and licensing the code under a BSD-style license should allow you to maintain a library for yourself which you can use pretty much anywhere you want.

Now, as for contracts that claim to suck up all your personal projects' copyright... this probably differs radically between jurisdictions, but in at least some western jurisdictions it's my understanding that a contract can't do that. The contract can say that it does, but it wouldn't be enforced in a court of law because copyright has to be explicitly transferred, as opposed to "all your base are belong to us"-kinda deal which would never be upheld (in the jurisdiction where I'm from anyway). There are a number of restrictions on what can be upheld in a court of law via contract, which is why you'll usually (and hopefully) see a clause saying something to the effect that if one part of the contract doesn't work legally, the rest of the contract still holds.

But as always, consult a lawyer before you interpret this as accurate legal advice. I've never been taken to court on this so I know none of these things as lawyer-proof facts. :)


问:
The cost of running a Windows App Server
I want to know what is the cost of running a Windows Application Server.

I know the cost of running a Linux server with Java based Application Server is probably zero.

What is the cost of running a windows based server on which all Apps are written in C#? I assume is is just the license cost of a copy of Windows Server.

Is this true? Are there any other hidden cost for hosting with WIndows?

I think with Cloud based hosting, these license costs can be avoided then.

答:
This is what I remember from training about MS licensing. It is probably not be 100% correct but I believe it is close:

In case of MS Software it is more complicated than it looks like. MS Windows Server license doesn't have to be enough. MS as many other companies also uses client access licenses (CAL) = you must pay for every client accessing to your server.

When dealing with CALs you can have multiple options:

Per user CAL - each authenticated user must have his own CAL

Per device CAL - each connecting device must have its own CAL

External connector - usually for Internet where you don't pay for every authenticated user but simply buy (some very expensive) license for everyone. External connector should not be needed for anonymous users.

Special cases

Per processor licenses don't require CALs for end users (for example SQL server)

Special server types don't require CALs (for example Windows Web Server 2008)

More about CALs. CALs are most commonly purchased in some Volume licensing plans because it reduces their price a lot.

Some example how it can be:

You join a company where you will use your desktop machine running Windows 7 Enterprise + Office 2010. You will also use MS Exchange and MS Sharepoint. You need:

License for Windows 7 Enterprise

License for Office 2010

CAL License for Windows Server because both MS Exchange and MS Sharepoint are running on Windows Server (one CAL user call per product can be used to connect to every instance of the product => the price of CAL is same if you need to connect to single Windows Server or to 100 Windows Servers within company).

CAL License for Exchange

CAL License for Sharepoint

SQL server used for Sharepoint must use per processor licensing or you will also need CAL to SQL server

Price of CALs differs per server version so CALs for Enterprise versions are much more expensive than CALs for Standard versions.

Another example:

You want to run Windows Server hosting your business application which internally connects to MS CRM and MS SQL. The application requires user to authenticate. You need:

Windows Server license for App Server, CRM and SQL

CRM license

Per processor SQL license

External connector for Windows Server Enterprise

External connector for CRM because you exposing information from CRM to external users

So as you can see the licensing costs can be very different per application and requirements. The important is that these costs should bother you only if you host the application on the servers where you are responsible for licenses. In shared hosting / VS hosting / or cloud it should not be the case because you pay for hosting plan which should already offer you SW with correct licensing.

Edit: There is also possibility that hosting companies have different licensing options.


问:
Are these signs of a bad developer?
I used to blame changing specifications from clients for code rot, not realising that business models do change and it's my job to develop in an adaptable way. I now see that as a sign of a bad developer (I've changed!).

But now I see other 'whinges' in myself. A few times recently I've found myself saying 'it's like trying to fit a square peg in a round hole', and also I find myself blaming client indecision for a project not progressing.

Are there signs I should look out for where I should change my attitude? Is the client always right, or am I sometimes justified in getting frustrated?

答:
When you're interacting with a client, you're not programming; you're learning and teaching.

Keep the clients informed and educate them about the process. Change is going to happen. Let them know you will try to implement them, but it will cost more. Let them decide.

Don't get into technical detail even when the question they ask is technical in nature. You're tempted because you'll feel a little defensive and will want to take on a challenge/get your geek-on. Don't do it; they don't care about the details and will stop listening after 45 seconds.

If you didn't tell them ahead of time don't expect them to know about industry standards and best practices or any other excuse for doing what you do. I hate it when I don't see a fee until the very end only to have the salesperson tell me it's standard in the industry. I should not be expected to know that. My response is, "Is making me feel like a dumb-ass a standard too?"

When you're with a client, pay more attention to them than anyone or anything else in the room. Domesticated dogs are geniuses at this; especially if you have food.

Title: Are these signs of a bad developer?


答:
I'm sure this is a legal matter depending on where you live/work and what was agreed upon/your contract.

If I learn something on my own, in my own time, all expenses paid by me (computer, internet access, software, etc.), wouldn't they want me to utilize it in my job? You find a regex for a personal project and decide to email it to your work account because you could probably use it. It would be a little silly to spend company time pretending to search for it on the internet again. Of course we strive to improve our craft, this is what is expected of programmers, blah, blah, blah, but what if it was in an area outside of programming or even IT? I can hold back if they want to play this game.

The company can try to keep a tight grip on the code I produce. It's just a poor foundation to build a relationship.  If they care that much about a few lines of code, I can't imagine the extent they will go to dominate my time; which is worth a lot more.


问:
How to link classes in different packages (on different pages)?
Extending the answer to this question, I have broken down a large system into a few classes per package.

Each package is now shown in a different page for readability, but now how do I show the relationship of two classes in separate packages (separate printed pages)?

An example for clarification:

E has an association with A but are in separate packages (which means they are on different pages)

答: An option would be to show a subset of Package2 on the diagram for Package1. In this case, you would show Package2 and ClassE, but not at full detail. Don't include any private or protected members, and consider not even showing public members for ClassE on the diagram for Package1. Depending on how they are structured, include a note or reference to the Package2 diagram for easy access via a link or a document ID reference.</p>


问:
Are there any non-blocking web servers for Java?
I was studying about the infrastructure being used by Facebook, as I was developing a website based on social interaction for a university project.

Facebook is using Tornado Web Server as its scalable, non-blocking web server, but it's written for Python. I'm trying to find something similar for Java: what should I be looking at? What are your experiences in non-blocking web servers for Java?

答: There has been some activity around building a web server on top of Apache Mina, but I'm not sure how far along it is.  The webpage is currently pretty light on details.</p>

OwnerDisplayName: Pinnacle


答:
Often the more advanced algorithms assume a certain amount of (expensive) setup. If you only need to run it once, you might be better off with the brute-force method.

For example: binary search and hash table lookup are both much faster per lookup then a linear search, but they require you to sort the list or build the hash table, respectively.

The sort will cost you N log(N) and the hash table will cost at least N. Now if you are going to be doing hundreds or thousands of lookups, that is still an amortized savings. But if you only need to do one or two lookups, it might just make sense to just do the linear search and save the startup cost.


问:
What is the greatest design flaw you have faced in any programming language?
All programming languages are having their design flaws simply because not a single language can be perfect, just as with most (all?) other things. That aside, which design fault in a programming language has annoyed you the most through your history as a programmer?

Note that if a language is "bad" just because it isn't designed for a specific thing isn't a design flaw, but a feature of design, so don't list such annoyances of languages. If a language is illsuited for what it is designed for, that is of course a flaw in the design. Implementation specific things and under the hood things do not count either.

答:
In C, and inherited by C++, Java, and C#:

You cannot parse the language without building a symbol table. Because code like this:

```<code>Foo Bar();
</code>```

could be declaring a variable Bar of type Foo and calling the default constructor, or could be declaring a function Bar that returns a Foo and takes no arguments. (In C++, anyway. The others have similar flaws.)

This means you can't parse these languages without building a symbol table, making analysis tools much harder to write.

(Javascript and Go manage to avoid this problem.)

Body:
In C, and inherited by C++, Java, and C#:

You cannot parse the language without building a symbol table. Because code like this:

Foo Bar();

could be declaring a variable Bar of type Foo and calling the default constructor, or could be declaring a function Bar that returns a Foo and takes no arguments. (In C++, anyway. The others have similar flaws.)

This means you can't parse these languages without building a symbol table, making analysis tools much harder to write.

(Javascript and Go manage to avoid this problem.)


问:
Does a mobile app need to poll external data sources or can it receive data in other ways?
I'm beginning the design stages of a mobile application. I'm looking for knowledge about common practices for user notifications. I understand that the SDK for the device will expose methods which will allow me to notify a user how and when I need it to. What I'm not sure about is how my application gets notified from a external data source. Is it common practice to poll a web service for data periodically? Or is it more likely that my application will have the facility to receive data at any time?

For example:
I have a website which asks users to fill out a contact form. I would like my mobile app to display a notification when one of these forms gets filled out. Should my app be polling my data server for updated records or should my site be notifying my app somehow of a new record?

Any opinions or advice are welcomed. Thanks.

答:
Almost always you would have the mobile poll the server for new data.

The 'new data?' request can be a very small message and so reduces the power/data cost on the mobile  device, it handles the mobile being of/off/blocked/busy better and it scales to a large number of devices better than having to maintain an open connection to each device to push new data.


答:
This will most likely depend on whether your target platform/device support server push. Not all of them do.

Also it is worth keeping in mind that even in some cases when it's supported, end user may have an option to turn it off.

Given above, I'd consider "push-only" application only when I am certain that it is established as a major feature at target platform. I mean if say, I know that 9 of 10 applications will fail without push I wouldn't mind designing mine so that it would also fail in such a case.

For a less "push-friendly" target though I'd rather think about giving my application an opportunity to fall back to polling in cases when push is't available for some reason.

Title: Does a mobile app need to poll external data sources or can it receive data in other ways?

Body:
I'm beginning the design stages of a mobile application. I'm looking for knowledge about common practices for user notifications. I understand that the SDK for the device will expose methods which will allow me to notify a user how and when I need it to. What I'm not sure about is how my application gets notified from a external data source. Is it common practice to poll a web service for data periodically? Or is it more likely that my application will have the facility to receive data at any time?

For example:
I have a website which asks users to fill out a contact form. I would like my mobile app to display a notification when one of these forms gets filled out. Should my app be polling my data server for updated records or should my site be notifying my app somehow of a new record?

Any opinions or advice are welcomed. Thanks.


答: Coldfusion's nested CFLoop behavior.</p>

Title: What is the greatest design flaw you have faced in any programming language?

Body:
All programming languages are having their design flaws simply because not a single language can be perfect, just as with most (all?) other things. That aside, which design fault in a programming language has annoyed you the most through your history as a programmer?

Note that if a language is "bad" just because it isn't designed for a specific thing isn't a design flaw, but a feature of design, so don't list such annoyances of languages. If a language is illsuited for what it is designed for, that is of course a flaw in the design. Implementation specific things and under the hood things do not count either.

Body: Coldfusion's nested CFLoop behavior.


问:
How do I package a J2SE app for sale to a market of buying customers?
Currently, I enjoy my Java 101 class.  I have some ideas for apps that I'd like to make and with time and work I think the process of developing an application from the ground up will work out fine.  When I get my Java app(s) up and running - will it be easy to find a place where I can offer them for sale?

In the Enterprise labor marketplace, I see ads for developers with expertise with J2EE, WebSphere, Hibernate, Spring, etc.  As a Java newbie, I'm aware that I can forget about ever qualifying for those jobs.

An alternative for me might be to make something that I can build a micro-business with.  Is there a straightforward way of doing that?

答: Marketing costs money.  Most people will have to spend a ton in order to get going.  There's those "hey I made an app and some guy found it and talked about it and now I'm rich" stories, but those are by FAR the exception.  Don't believe those podcasts/bloggers/talking heads that say it's easy.  Even if you get the app perfect, there's a tremendous amount of luck that goes into success.  Odds are that if you make the best app you can, work hard, market hard, you may be able to scrape by with a decent living.  :-)</p>


答: The m4 macro language lacks a loop construct. Instead, the documentation recommends that you create your own using recursion. That kept me from bothering with the language, pretty much for ever.</p>


答:
Probably not the greatest design flaw but a flaw nonetheless in my opinion...

The keyword final in the context of variables is Java.

I wish there was a non-final / mutable / rassignable keyword instead to indicate that the reference to a variable can be changed.

Good practices suggest that you should use the keyword final liberally in all cases especially when you are writing multi-threaded applications.

I follow this advice and use the final keyword whenever I can. It is very rare that I need a variable to be non-final. This makes my source code a lot more cluttered and forces me to type more than I really should have to.


问:
Why does Garbage Collection only sweep the heap?
Basically, I've learned so far that garbage collection erases forever any data structure that is not currently being pointed to. But this only checks the heap for such conditions.

Why doesn't it also check the data section (globals, constants, etc etc) or the stack as well? What is it about the heap that it's the only thing that we want to be garbage collected?

答:
The most obvious answer, and perhaps not the fullest, is that the heap is the location of instance data.  By instance data, we mean the data representing the instances of classes, aka objects, that are created at run time.  This data is inherently dynamic and the number of these objects, and thus the amount of memory they take up, is known only at runtime.  There HAS to be some sore of recovery of this memory or long running programs would consume all of there memory over time.

The memory being consumed by class defintions, constants, and other static data structures is inherently unlikely to increase unchecked.  Since there's only a single class definition in memory per an unknown number of run time instances of that class, it makes sense that this type of structure is not a threat to memory usage.


答:
Ukkonen's algorithm for building suffix tries is O(n log n).  It has the advantage of being "on-line" - that is, you can incrementally append more text.

Recently, other more complex algorithms have claimed to be faster in practice, largely because their memory access has higher locality, thus improving processor cache utilization and avoiding CPU pipeline stalls.  See, e.g., this survey, which claims that 70-80% of processing time is spent waiting for memory, and this paper describing the "wotd" algorithm.

Suffix tries are important in genetics (for matching gene sequences) and, somewhat less importantly, in the implementation of Scrabble dictionaries.


答:
Yes, for suitably small N.  There will always be a N, above which you will always have the ordering O(1) < O(lg N) < O(N) < O(N log N) < O(N^c) < O(c^N) (where O(1) < O(lg N) means that at an O(1) algorithm will take fewer operations when N is suitably large and c is a some fixed constant that is greater than 1).

Say a particular O(1) algorithm takes exactly f(N) = 10^100 (a googol) operations and an O(N) algorithm takes exactly g(N) = 2 N + 5 operations.  The O(N) algorithm will give greater performance until you N is roughly a googol (actually when N > (10^100 - 5)/2), so if you only expected N to be in the range of 1000 to a billion you would suffer a major penalty using the O(1) algorithm.

Or for a realistic comparison, say you are multiplying n-digit numbers together.  The Karatsuba algorithm is at most 3 n^(lg 3) operations (that is roughly O(n^1.585) ) while the Schönhage–Strassen algorithm is O(N log N log log N) which is a faster order, but to quote wikipedia:

In practice the Schönhage–Strassen algorithm starts to outperform
  older methods such as Karatsuba and Toom–Cook multiplication for
  numbers beyond 2^2^15 to 2^2^17 (10,000 to 40,000 decimal
  digits).[4][5][6]

So if you are multiplying 500 digit numbers together, it doesn't make sense to use the algorithm that's "faster" by big O arguments.

EDIT: You can find determine f(N) compared g(N), by taking the limit N->infinity of f(N)/g(N).  If the limit is 0 then f(N) < g(N), if the limit is infinity then f(N) > g(N), and if the limit is some other constant then f(N) ~ g(N) in terms of big O notation.


问:
When following SRP, how should I deal with validating and saving entities?
I've been reading Clean Code and various online articles about SOLID lately, and the more I read about it, the more I feel like I don't know anything.

Let's say I'm building a web application using ASP.NET MVC 3. Let's say I have a UsersController with a Create action like this:

```<code>public class UsersController : Controller
{
    public ActionResult Create(CreateUserViewModel viewModel)
    {

    }
}
</code>```

In that action method I want to save a user to the database if the data that was entered is valid.

Now, according to the Single Responsibility Principle an object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility. Since validation and saving to the database are two separate responsibilities, I guess I should create to separate class to handle them like this:

```<code>public class UsersController : Controller
{
    private ICreateUserValidator validator;
    private IUserService service;

    public UsersController(ICreateUserValidator validator, IUserService service)
    {
        this.validator = validator;
        this.service= service;
    }

    public ActionResult Create(CreateUserViewModel viewModel)
    {
        ValidationResult result = validator.IsValid(viewModel);

        if (result.IsValid)
        {
            service.CreateUser(viewModel);
            return RedirectToAction("Index");
        }
        else
        {
            foreach (var errorMessage in result.ErrorMessages)
            {
                ModelState.AddModelError(String.Empty, errorMessage);
            }
            return View(viewModel);
        }
    }
}
</code>```

That makes some sense to me, but I'm not at all sure that this is the right way to handle things like this. It is for example entirely possible to pass an invalid instance of CreateUserViewModel to the IUserService class. I know I could use the built in DataAnnotations, but what when they aren't enough? Image that my ICreateUserValidator checks the database to see if there already is another user with the same name...

Another option is to let the IUserService take care of the validation like this:

```<code>public class UserService : IUserService
{
    private ICreateUserValidator validator;

    public UserService(ICreateUserValidator validator)
    {
        this.validator = validator;
    }

    public ValidationResult CreateUser(CreateUserViewModel viewModel)
    {
        var result = validator.IsValid(viewModel);

        if (result.IsValid)
        {
            // Save the user
        }

        return result;
    }
}
</code>```

But I feel I'm violating the Single Responsibility Principle here.

How should I deal with something like this?

答:
It seems to me that the first example is "closer" to true SRP; it's the responsibility of the Controller in your case to know how to wire things up and how to pass along the ViewModel.

Wouldn't it make more sense to have the whole IsValid/ValidationMessages be part of the ViewModel itself?  I haven't dabbled with MVVM, but it seems like the old Model-View-Presenter pattern, where it was okay for the Presenter to handle things like that because it was directly related to presentation.  If your ViewModel can check itself for validity, there's no chance to pass an invalid one to the UserService's Create method.


答:
The size of those is predictable (constant except for the stack, and the stack is typically limited to a few MB) and typically very small (at least compared to the hundreds of MB large applications may allocate).

Dynamically allocated objects typically have a small time frame in which they are reachable. After that, there is no way they can be referenced ever again. Contrast that with entries in the data section, global variables, and such: Frequently, there's a piece of code that references them directly (think const char *foo() { return "foo"; }). Normally, code doesn't change, so the reference is there to stay and another reference will be created each time the function is invoked (which could be at any time as far as the computer knows - unless you solve the halting problem, that is). Thus you couldn't free most of that memory anyway, as it would always be reachable.

In many garbage-collected language, everything that belong to the program being ran is heap-allocated. In Python, there simply isn't any data section and no stack-allocated values (there are the references that local variables are, and there's the call stack, but neither is a value in the same sense as an int in C). Every object is on the heap.

Title: Why does Garbage Collection only sweep the heap?

Body:
Basically, I've learned so far that garbage collection erases forever any data structure that is not currently being pointed to. But this only checks the heap for such conditions.

Why doesn't it also check the data section (globals, constants, etc etc) or the stack as well? What is it about the heap that it's the only thing that we want to be garbage collected?


答:
I have had some success (not total success) at getting my employers to agree to release under an open source license some of my code written while I worked for them.  Mostly code I wrote on my own time, but sometimes not.  It's all code not specific to any industry.

I started the whole thing going by writing some libraries while I was unemployed, then releasing them under the MIT license.  Then during the hiring process at later jobs I would mention it, and say that I would use my that code to help them, if it could, but would they mind if added things I wrote while working for them, but only things that were not specific to their business and only with their approval.

Results have varied, but I have been able to build up my library over time.  And there have been cases where having the library has sped up development time for my employers.


答:
I'm surprised that the most heavily voted answer here is "yes". As a developer, the answer has always been an "absolutely not", except in circumstances where the code is either:

A previous composed library which I have developed independently of the current and all previous projects, or

A library which has been made available for this purpose, e.g., open source stuff.

Somebody paid you to write the code. Barring a different understanding and agreement, which is fine, it's not right for someone else to reap the DIRECT benefits of it.

Now - the word DIRECT. If you reach the end of a project and you learned something interesting and created something useful with it that isn't directly tied up with the intellectual property of the client, take some time and create yourself a library for it. Even better - START AN OPEN SOURCE PROJECT WITH IT, so that everyone ends up wealthier for it. I think it's absolutely 100% ethically pure as the driven snow, and indeed, I've done it myself.

In the short term, reusing code you've been paid to write for someone else will cause you legal headaches. In the long run, it will cause you character headaches.


答:
The garbage collector does scan the stack -- to see what things in the heap are currently being used (pointed to) by things on the stack.

It makes no sense for the garbage collector to consider collecting stack memory because the stack is not managed that way:  Everything on the stack is considered to be "in use."  And memory used by the stack is automatically reclaimed when you return from method calls.  Memory management of stack space is so simple, cheap and easy that you wouldn't want garbage collection to be involved.

(There are systems, such as smalltalk, where stack frames are first-class objects stored in the heap and garbage collected like all other objects.  But that's not the popular approach these days.  Java's JVM and Microsoft's CLR use the hardware stack and contiguous memory.)


答: It's worth bearing in mind the reason why we have garbage collection:  because sometimes it's difficult to know when to deallocate memory.  You really only have this problem with the heap.  Data allocated on the stack will be deallocated eventually, so there isn't really any need to do garbage collection there.  Things in the data section are generally assumed to be allocated for the program's lifetime.</p>


问:
What are the most important points of interface between a web developer and IT?
Some background:

My current job has be as the sole web developer for our company.  I have been given responsibility for a number of external websites, as well as our internal intranet site.

The external sites are currently hosted externally, and either created/maintained with a CMS, or custom designed by the external host.  I will be migrating the websites to our own internal server, and redesigning them using whatever tools I deem necessary (php, jquery, MySQL, etc.).

The intranet is hosted internally, but also needs a complete redesign.

Our IT is currently going through some reorganization, and historically has little experience with web technology.  I want to plan coordination with them, help develop proper infrastructure, and identify the primary channels of communication between us.

My question is: what are the main points of coordination that normally exist between development and IT, focusing on web-based development?  Given a (relatively) blank slate, what would be the ideal division of responsibilities, and primary points of direct collaboration?

I know some aspects of my particular situation may be atypical (i.e. I'll be responsible for setting up the PHP environments, source control repositories, database administration, etc.), but I'd like answers to focus more on the typical configurations, as that will be more useful to others.

答:
Have IT manage the web servers that will host your web applications as well as the database servers storing the related data. You do the rest (i.e. concentrate on writing and maintaining the web applications).

For communication, I would use a ticketing system to track any issues that come up with the web applications and associated infrastructure. Assign any server-specific issues to IT. Assign other issues to yourself or IT as you see fit. It's important to have a record of issues in general, especially if you are managing several web applications at once.

Develop a process, put it in writing and make sure everyone follows it. Coordination means participation, so involve the IT department in the development of a process you can all agree on.


问:
When do 'static functions' come into use?
OK, I've learned what a static function is, but I still don't see why they are more useful than private member functions. This might be kind of a newb-ish question here, but why not just replace all private member functions with static functions instead?</p>

答:
Assuming that you're using OOP, use static functions when they don't depend on any class members. They can still be private, but this way they are optimized as they don't depend on any instance of the related object.

Other than the above, I find static functions useful when you don't want to create an instance of an object just to execute one public function on it. This is mainly the case for helper classes that contain public functions to do some repetitive and general work, but don't need to maintain any state between calls.


答:
Because they don't require an instance and can be public. Say you need a function to get the greatest common denominator (GCD; very useful for fraction classes; and yes this is just a simple example). There is no point in creating a class of objects whose sole purpose is that you can have a this pointer you neither need nor use in gcd. So you use a static method for it, ideally on the class which actually uses the GCD (e.g. in the fraction class).

Of coures if there are only static methods, you're doing OOP wrong and should either switch to actually doing OOP or using a language more appropriate to your paradigm.

Title: When do 'static functions' come into use?

Body: OK, I've learned what a static function is, but I still don't see why they are more useful than private member functions. This might be kind of a newb-ish question here, but why not just replace all private member functions with static functions instead?</p>


答:
IT: Manages hardware and the Operating Systems. For example, servers, drives, backups, patches, windows users, network security, etc

Web Developer: Manages website content, and web hosting setup. For example, creating / maintaining webpages, creating/managing databases, IIS/Apache/Other setup, source/version control, etc

Title: What are the most important points of interface between a web developer and IT?

Body:
Some background:

My current job has be as the sole web developer for our company.  I have been given responsibility for a number of external websites, as well as our internal intranet site.

The external sites are currently hosted externally, and either created/maintained with a CMS, or custom designed by the external host.  I will be migrating the websites to our own internal server, and redesigning them using whatever tools I deem necessary (php, jquery, MySQL, etc.).

The intranet is hosted internally, but also needs a complete redesign.

Our IT is currently going through some reorganization, and historically has little experience with web technology.  I want to plan coordination with them, help develop proper infrastructure, and identify the primary channels of communication between us.

My question is: what are the main points of coordination that normally exist between development and IT, focusing on web-based development?  Given a (relatively) blank slate, what would be the ideal division of responsibilities, and primary points of direct collaboration?

I know some aspects of my particular situation may be atypical (i.e. I'll be responsible for setting up the PHP environments, source control repositories, database administration, etc.), but I'd like answers to focus more on the typical configurations, as that will be more useful to others.


答:
I use them as helper functions to common tasks, examples being:

Converting degrees into radians (and vice-versa);

Hashing a string;

Converting from a enum to something else (in this project I'm working, they act as a hash table);

Most of my files that group static functions have the suffix Helper, meaning that it's what they do, help me get somewhere faster.


问:
Do real-world algorithms that greatly outperform in the class below exist?
Last night I was discussing with another programmer that even though something may be O(1), an operation which is O(n) may outperform it if there are is a large constant in the O(1) algorithm. He disagreed, so I've brought it here.

Are there examples of algorithms which greatly outperform those in the class below it? For example, O(n) being faster than O(1) or O(n2) being faster than O(n).

Mathematically this can be demonstrated for a function with an asymptotic upper bounds, when you disregard constant factors, but do such algorithms exist in the wild? And where would I find examples of them? What types of situations are they used for?

答:
There's always the fastest and shortest algorithm for any well-defined problem. It's only purely theoretically the (asymptotically) fastest algorithm though.

Given any description of a problem P and an instance for that problem I, it enumerates all possible algorithms A and proofs Pr, checking for each such pair whether Pr is a valid proof that A is the asymptotically fastest algorithm for P. If it finds such a proof, it then executes A on I.

Searching for this problem-proof pair has complexity O(1) (for a fixed problem P), so you always use the asymptotically fastest algorithm for the problem. However, since this constant is so unspeakably enormous in nearly all cases, this method is completely useless in practice.


答: Many languages/frameworks use naive pattern matching to match strings instead of KMP. We look for string like Tom, New York rather than ababaabababababaababababababab.</p>


答:
Trying for a more simplified explanation than the above (pretty good ones).

An object is code + data normally.  A static method is used when you only have the "code" portion to deal with (there is no data/state being maintained (except static data members)).

ContentLicense: CC BY-SA 4.0


问:
PHP: brackets or no brackets with if/for/while/...?
Both these syntaxes are correct and equivalent:

With brackets:

```<code>foreach ($listOfThings as $thing) {
  echo $thing;
}
</code>```

Without brackets:

```<code>foreach ($listOfThings as $thing):
  echo $thing;
endforeach;
</code>```

Two questions come up in mind:

Is there any real difference between them or are they totally identical (performence, for example)?

Is it better always to use the same one or to use both, depending of some context (for example: to recognize easely the code concerning the framework).

I suspect all that to be a matter of taste and company standards, but I'm not sure of that.

答:
I appear to be in the minority here, but i prefer endforeach, endif etc over braces.  They clearly specify which statement they're intended to close, unlike braces (which just close the closest still-open block).

```<code><? if (someCondition): ?>
    imagine a bunch of code here
    <? foreach ($rows as $row): ?>
       imagine a bunch more code here
    <? endforeach ?>    (without this, PHP complains about "unexpected T_ENDIF")
    and a bunch more here
<? endif ?>

<? if (someCondition) { ?>
    imagine a bunch of code here
    <? foreach ($rows as $row) { ?>
        imagine a bunch more code here
    <? } ?>             (without this, PHP complains about "unexpected $end")
    and a bunch more here
<? } ?>
</code>```

In the first example, the error is pretty much confined to the if block (and whatever is inside of it), and PHP chokes on it sooner (and thus, closer to the real error).  In the second, PHP gets all the way to the end of the script before realizing the braces don't match up.  That's potentially a whole lot more code to look for a missing brace in.

The people preferring braces are all like "well, if you indent your code properly, braces are just as readable".  The thing is, though, there are a couple of issues:

Not everyone is as religious about code formatting as you.  Particularly that new guy that's fixing your code while you're on vacation.

Braces are not "just as readable".  Period.  I don't care how much you like C, C#, Java, or whatever other language taught you that braces were a good thing.  The fact is, there are far better syntaxes for control structures -- and PHP actually includes one.

Braces are punctuation.  A single char of punctuation.  Often surrounded by other punctuation, at that.  They're easy to miss.  It seems to me like the brain actually tries to filter out punctuation half the time.

I don't know about your editor, but mine highlights keywords.  They stand out, and are longer, and are thus easier to spot.  It highlights braces as well, and even attempts to highlight the matching brace...but no matter how brightly you color your braces, they're not going to stand out as well as a whole highlighted word.

Braces just say "close something".  They don't say what to close.  They simply can't convey that info on their own.  They rely on you to always (ALWAYS!) indent "properly", and savagely beat any programmer that doesn't (or uses spaces instead of tabs, or tabs instead of spaces, or whatever your pet coding style is).  That, or you end up adding comments like // end if.  And if you ever find yourself adding comments like that...why in the hell would you avoid a keyword that does the exact same thing, but can actually be verified by the interpreter?

Body:
I appear to be in the minority here, but i prefer endforeach, endif etc over braces.  They clearly specify which statement they're intended to close, unlike braces (which just close the closest still-open block).

<? if (someCondition): ?>
    imagine a bunch of code here
    <? foreach ($rows as $row): ?>
       imagine a bunch more code here
    <? endforeach ?>    (without this, PHP complains about "unexpected T_ENDIF")
    and a bunch more here
<? endif ?>

<? if (someCondition) { ?>
    imagine a bunch of code here
    <? foreach ($rows as $row) { ?>
        imagine a bunch more code here
    <? } ?>             (without this, PHP complains about "unexpected $end")
    and a bunch more here
<? } ?>

In the first example, the error is pretty much confined to the if block (and whatever is inside of it), and PHP chokes on it sooner (and thus, closer to the real error).  In the second, PHP gets all the way to the end of the script before realizing the braces don't match up.  That's potentially a whole lot more code to look for a missing brace in.

The people preferring braces are all like "well, if you indent your code properly, braces are just as readable".  The thing is, though, there are a couple of issues:

Not everyone is as religious about code formatting as you.  Particularly that new guy that's fixing your code while you're on vacation.

Braces are not "just as readable".  Period.  I don't care how much you like C, C#, Java, or whatever other language taught you that braces were a good thing.  The fact is, there are far better syntaxes for control structures -- and PHP actually includes one.

Braces are punctuation.  A single char of punctuation.  Often surrounded by other punctuation, at that.  They're easy to miss.  It seems to me like the brain actually tries to filter out punctuation half the time.

I don't know about your editor, but mine highlights keywords.  They stand out, and are longer, and are thus easier to spot.  It highlights braces as well, and even attempts to highlight the matching brace...but no matter how brightly you color your braces, they're not going to stand out as well as a whole highlighted word.

Braces just say "close something".  They don't say what to close.  They simply can't convey that info on their own.  They rely on you to always (ALWAYS!) indent "properly", and savagely beat any programmer that doesn't (or uses spaces instead of tabs, or tabs instead of spaces, or whatever your pet coding style is).  That, or you end up adding comments like // end if.  And if you ever find yourself adding comments like that...why in the hell would you avoid a keyword that does the exact same thing, but can actually be verified by the interpreter?


答:
I use static methods in both C++ and C# for Utility classes, classes that don't have any instance data, just one way to bundle a collection of useful, related methods.</p>

```<code>int count1 = DBUtil::GetCountOfSlackerEmployees();
int count2 = DBUtil::GetCountOfEmployedSlackers();
</code>```

Body:
I use static methods in both C++ and C# for Utility classes, classes that don't have any instance data, just one way to bundle a collection of useful, related methods.

int count1 = DBUtil::GetCountOfSlackerEmployees();
int count2 = DBUtil::GetCountOfEmployedSlackers();


问:
Can I make more money freelancing in Android, or Web development?
Is freelancing in Android development or Web development the better choice to achieve a ~300$ income\month? It is too hard for me to do both.

I'm currently studying CS in college and this is my second year. Financially, I'm 100% depending on my parents and this is really uncomfortable for me. My goal is to make at least 300$ a month with freelancing in programming. The problem is, I don't know where to start. I have a solid background in Java and have a basic knowledge of C, PHP, Javascript, Ruby, Prolog, CSS, HTML. I think my options are to go do Web development or Android development. I've already tried both of them (made a basic app for Android and a simple blog). It's kinda hard for me to do the both at the same time. Ultimately my question is, which one should I continue to work with to achieve the desired income\month? I really love doing both of them so I'm asking you guys to give me some helpful advice. Thank you for your time.

EDIT: Sorry for being off topic but I didn't knew where to ask. There are many experts on this site so it seemed logical to ask it here. Feel free to delete this post and sorry for braking the rules.

答:
My suggestion, as always, is oDesk.com. There you can find a lot of jobs, they pay fast, they are reliable and you can manage your time as you want. The only thing you need is: programming skills and English.

300 per month doing Android Development? You must be kidding. I earn that in two days... and trust me, I am really newbie to Android.


答:
As to what a static method is:

Static methods neither require an instance of the class nor can they
  implicitly access the data (or this, self, Me, etc.) of such an
  instance.[1]

Examples of when are static methods useful:

Global/helper methods

Getting query results from a Data Model class (calling a SP)

Just use them where appropriate only.

If you find yourself copying the same methods in multiple objects
consider making the method static so you can follow DRY.

Use static methods if you don't need an instance of an object (you're not doing work on and object's instance variables)

If a lot of your data is outside of objects and they are being worked on via static methods then your code is not object oriented and may become difficult to maintain.


答:
Assuming you are speaking of C++ (you didn't say) and you have the terms right (i.e. do not mean member functions/methods):

Even a private member function still has to be declared in the header, which means it actually becomes part of the API and ABI of the class, even though the user can't actually call it. If you add, modify or delete private member function, you are forcing recompilation of all dependent classes (the header has changed, make can't know better) and when you do so in a library, you have to consider compatibility for the application using it.

On the other hand file-scoped static functions don't get a public symbol, so you can add, modify or delete them as you like and nothing beyond the one compilation unit will ever be affected.


答: Typically you need a static main to act as an entry point for your program. That could be kind of important.</p>


答:
Static and private are in fact orthogonal: a method can be static, or private, or none, or both.

Static vs. non-static (a.k.a. 'instance methods') indicates whether the method operates on the class itself (static) or on one particular instance (non-static). Depending on the language, you can call a static method through an instance, but you can never access the instance through a static method (which also implies that you cannot call any non-static methods from inside a static method, simply because you have no this object). Use static methods to implement behavior that is conceptually linked to the class, but does not 'bind' to one particular instance. Another scenario where you might want to use static methods is when you have a function that operates on two instances of a class, and neither operand deserves a privileged status - for example, assuming you have a class Vector, and you want to implement addition; your addition method could be called as a.Add(b), but Vector.Add(a, b) probably makes more sense.

Private vs. public are about visibility of the method. Private methods can only be accessed from within the class's own scope, while public methods are accessible from anywhere. The most important use for this is encapsulation: by making only those methods and properties public that are absolutely needed by the rest of the code to communicate with your class, you limit the points at which outside code can introduce problems, and you prevent problems inside your class from bleeding into the rest of the project.

So, rule of thumb:

make all member functions private, except those that need to be called from outside the class

make all methods instance methods, unless they make sense even when no instance of the class exists


答:
As a number of other responders have said, the stack is part of the root set, so it is scanned for references but not "collected", per se.

I just want to respond to some of the comments that imply that garbage on the stack doesn't matter; it does, because it may cause more garbage on the heap to be considered reachable. Conscientious VM and compiler writers either null out or otherwise exclude dead parts of the stack from scanning. IIRC, some VMs have tables mapping PC ranges to stack-slot-liveness bitmaps and others just null out the slots. I don't know what technique is currently preferred.

One term used to describe this particular consideration is safe-for-space.


问:
Why the scorn for COBOL?
When people mention COBOL, it's usually either met with a snort or groan. I don't know much about COBOL, but I've seen some programs written in it. I can see that it's wordy, and to uninitiated eyes such as mine, unintelligible. But, really, aren't all programming languages complete gibberish to a lay person?

I understand that it works, works well, and is still in widespread use in the industries it was designed for. Aren't those the hallmarks of a good language? What's so bad about COBOL?

答:
People dislike COBOL because it has limited application. It was designed for business, finance, and administrative systems for
companies and governments.

What do all of these have in common? Data. Lots and lots of data.

Guess who was designed to crunch data and have lots of files for breakfast? Can you say COmmon Business-Oriented Language?

50 years ago COBOL was the best thing for large organizations with lots of data to manage. Today there are better ways to manage a large volume of data
so COBOL is no longer relevant. Or is it?

Let's consider governments. What data does a government need to track? People ids, birth certificates, medical records, taxes (oh... yes... taxes) etc etc. And they must hold these infos indefinitely, today and 50 years ago also.

People also mnetioned banks in some of the answers and indeed banks are heavy user of COBOL. Why? because unlike other types of companies banks usually have a history. Some exist for hundreds of years (like this one for example).

That means that some data from 50 years must still be here with us, today, the 7th October, 2011. Now we have SQL Server and C# or Oracle and Java, but 50 years ago there was COBOL and files.

As time passed the data for govs and banks grew larger and larger and it was more and more expensive to migrate the systems. Which means they must remain in COBOL and be constanlty maintained and evolved as business evolves. Some banks are slowly migrating while other just stick a nice Web2.0 interface in front of the mainframe (c# and Java are the mostly used). Can you say legacy code? (COBOL goes hand in hand with (extreme) legacy code, some that was touched by plenty of people over decades of existence - another thing we programmers don't like :D).

And now you have a niche of activity. COBOL now has limited application and your experience is affected.

And people who get into COBOL eventually discover that you do the same thing over and over and over again, year after year after year and by the time they wake up they are no longer competitive on the market because people now want PHP, Java, C#, REST, jQuery and only banks look for COBOL people.

At this point the demand is lower than the supply and those who don't make the cut must move to something else. And they must start as juniors since COBOL does really cripple the mind (believe it of not Copy-Paste is the main style of development in COBOL and accounts for large its large productivity) and now they curse the day they picked up COBOL and don't lose any occasion to tell their horror stories about it :). But you could tell those stories about any old fart language that is no longer in demand these days but you are the unfortunate person stuck with it. O well...

P.S. and COBOL is bad for all the other reasons mentioned by the others :)

P.S.2. In 1997, the Gartner Group reported that 80% of the world's business ran on COBOL with over 200 billion lines of
code in existence and with an estimated 5 billion lines of new code annually. Really? And how did day measure that? Did they go do every company in the word and ask them how many lines of COBOL do they have or what?

Title: Why the scorn for COBOL?


答:
A static function (and there's different meanings for that term in different languages), doesn't require any state that is retained between calls. If it is conceptually closely tied to what an class does, make it a class function (as in on a class not an object), or if not, make it a global (or module-level, whatever) function. It doesn't belong on an object if it has no need of the object's state. </p>

<p>If you're passing state to it all the time, its not really a stateless function, you're just making a stateful function with stateless syntax. In that case, it probably belongs on the calling object, or maybe a refactoring to better align the state and behavior is indicated. </p>

Body:
A static function (and there's different meanings for that term in different languages), doesn't require any state that is retained between calls. If it is conceptually closely tied to what an class does, make it a class function (as in on a class not an object), or if not, make it a global (or module-level, whatever) function. It doesn't belong on an object if it has no need of the object's state.

If you're passing state to it all the time, its not really a stateless function, you're just making a stateful function with stateless syntax. In that case, it probably belongs on the calling object, or maybe a refactoring to better align the state and behavior is indicated.


答:
The easiest way to do that would be create a SaaS and then go from there. It will allow you to learn JEE and is an easier model for making money. However, the downside to that I'm not sure of any host that hosts JEE for cheap (aka something a student would be able to consistently afford) and like Brian Knoblauch said, it isn't free to market it. Let's say you do find an idea you can execute and start doing it. Well then you'll have to get bogged down in the details of running the site (such as payment processing, legal compliances, etc) which can take a chunk of your income as well.

My opinion, learn for the sake of learning and become good friends with GitHub. That plan won't cost you a dime!

Title: How do I package a J2SE app for sale to a market of buying customers?

Body:
Currently, I enjoy my Java 101 class.  I have some ideas for apps that I'd like to make and with time and work I think the process of developing an application from the ground up will work out fine.  When I get my Java app(s) up and running - will it be easy to find a place where I can offer them for sale?

In the Enterprise labor marketplace, I see ads for developers with expertise with J2EE, WebSphere, Hibernate, Spring, etc.  As a Java newbie, I'm aware that I can forget about ever qualifying for those jobs.

An alternative for me might be to make something that I can build a micro-business with.  Is there a straightforward way of doing that?


答:
Turn your question around. The real motivating question is under what circumstances can we avoid the costs of garbage collection?

Well, first off, what are the costs of garbage collection? There are two main costs. First, you have to determine what is alive; that requires potentially a lot of work. Second, you have to compact the holes that are formed when you free something that was allocated between two things that are still alive. Those holes are wasteful. But compacting them is expensive too.

How can we avoid these costs?

Clearly if you can find a storage usage pattern in which you never allocate something long-lived, then allocate something short-lived, then allocate something long-lived, you can eliminate the cost of holes. If you can guarantee that for some subset of your storage, every subsequent allocation is shorter-lived than the previous one in that storage then there will never be any holes in that storage.

But if we've solved the hole problem then we've solved the garbage collection problem too. Do you have something in that storage that is still alive?  Yes. Was everything allocated before it longer-lived? Yes -- that assumption is how we eliminated the possibility of holes. Therefore all you need to do is say "is the most recent allocation alive?" and you know that everything is alive in that storage.

Do we have a set of storage allocations where we know that every subsequent allocation is shorter-lived than the previous allocation? Yes! Activation frames of methods are always destroyed in the opposite order that they were created because they are always shorter-lived than the activation which created them.

Therefore we can store activation frames on the stack and know that they never need to be collected. If there is any frame on the stack, the entire set of frames below it is longer-lived, so they don't need to be collected. And they will be destroyed in the opposite order that they were created. The cost of garbage collection is thus eliminated for activation frames.

That's why we have the temporary pool on the stack in the first place: because it is an easy way of implementing method activation without incurring a memory management penalty.

(Of course the cost of garbage collecting the memory referred to by references on the activation frames is still there.)

Now consider a control flow system in which activation frames are not destroyed in a predictable order. What happens if a short-lived activation can give rise to a long-lived activation? As you might imagine, in this world you can no longer use the stack to optimize away the need to collect activations. The set of activations can contain holes again.

C# 2.0 has this feature in the form of yield return. A method that does a yield return is going to be reactivated at a later time -- the next time that MoveNext is called -- and when that happens is not predictable. Therefore the information that would normally be on the stack for the activation frame of the iterator block is instead stored on the heap, where it is garbage collected when the enumerator is collected.

Similarly, the "async/await" feature coming in the next versions of C# and VB will allow you to create methods whose activations "yield" and "resume" at well-defined points during the action of the method. Since the activation frames are no longer created and destroyed in a predictable manner, all the information that used to be stored in the stack will have to be stored in the heap.

It is just an accident of history that we happened to decide for a few decades that languages with activation frames that are created and destroyed in a strictly ordered manner were fashionable. Since modern languages increasingly lack this property, expect to see more and more languages that reify continuations onto the garbage-collected heap, rather than the stack.


答:
"why not just replace all private member functions with static functions instead?"

... because a private member can access instance data whilst only allowing it to happen from calls made inside other member functions. The static function can be private, but its not going to be able to alter or refer to an instance of the class unless the instance is passed in as a parameter.


问:
Should the build drive your tags or should the tags drive the build?
Our current method of creating a product release is to tag all of our component repositories with the next appropriate version and then modify a master build script with these new version numbers for each component.  The master build script will then be run and it will perform a SCM checkout of each component, then modify the AssemblyInfo.cs file so that the compiled .exe (or .dll) has the correct version number, and then compile the component.  All of these components are then coalesced into a product release which is "versioned" with a pure marketing decided number.

So our process falls under the "tags drive the build" description, but I am not certain that is the best method.  Specifically, where I see this failing us is if we were to integrate our release build into the CI process, it seems like it would be backwards.

Not just that, but where in a typical release-management process does the decision for the new component version numbers come in? Someone has to decide when component A goes from 2.1.4 to 3.0.0 and if library B should change from 6.3.2 to 6.3.3 or 6.4.0.  Where are these version numbers stored and at what stage are they decided?  Currently, we make these decisions at the "last moment" and they are stored in the master build script.  The master build script itself is versioned and is tagged with the "marketing" version number.

答:
Semantic Versioning can help you with identifying when to bump the version and what to bump it to.

A few key points:

Backward-incompatible changes get a major-version bump (3.2.9 -> 4.0.0).

Backward-compatible feature additions/changes get a minor-version bump (3.2.9 -> 3.3.0).

Backward-compatible non-API-altering bug-fixes get a patch-level version bump (3.2.9 -> 3.2.10).


问:
Which programming methodology would be a good fit for us?
Unfortunately, somebody has taught our upper management the word "Agile" and now they want us to move towards it. I have a peripheral understanding of agile (in principle) but have never used it in practice. From what I know, it will not be a good fit for our organization. Right now, things are pretty grungey. Here's how it is;

We're a very small team - two developers, one DBA, one designer. The company I work for makes a disproportionately large amount of money relative to its size, and nearly 95% of that is pure online sales.

From a development perspective, we are subjected to many desk invasions during a typical day (we're tech support as well as dev), work can regularly just fall out of the sky at a moments notice if a sales team member promises something to someone. We do undertake larger projects too, and they're a nightmare with the constant interruptions. Some of us are starting to tear our hair out! Project plans are drawn up by non technical managers in excel spreadsheets, where they try and break the task down into bite-sized sentences that they can understand and put a date beside each one. These dates are always hideously unrealistic and often missed, and our meetings (which we have around weekly) are regularly filled with awkward moments with people asking "why hasn't this been done yet".

I am pretty sure Agile isn't the one for us. Now, given that (and i have tried) this company will not change its ways, and only the dev team is willing to change, is there a development methodology that we could adopt which is a good fit for just saving us some sanity?

答:
First I'd suggest gathering some data.  Sit down at a quiet time and figure out what the status quo really is- how things get done.  If management is hell-bent on implementing something they can call agile, then figure out something that would work for your team, draw up a document, slap "Agile" on the name and you're good to go.  Keep in mind that the only thing they really know about agile is the word, and some vague association with quickness for its usual definition in English.  So what I'm advocating is that your team gets out in front of the issue, finds a flavor that works for you, and then presents that to your management as the Agile(tm) way.  Otherwise some PHB is going to pick up a book and try to fit the square peg into the round hole and no one will be happy.

If you go with a "pure" form of agile it may be tough with your team having to fulfill the support role as well.  Let's face it, your boss may find it difficult to accept members of your team responding to the help-desk requests by saying "let me create a backlog item, I'll get to that in (time to end of sprint) weeks."

The biggest hurdle is the money one.  If everything is green gravy, it is much harder to say something is wrong and needs to change.

Best of luck.


问:
How can I translate ML code to F#?
Recently I found a book, Purely Functional Data Structures and all the examples in this book are given in ML with Haskell versions in its appendix. But I only know one programming language with the functional paradigm: F#. And after a bit of research, I found out that F# is (or was) the .NET port of CAML, which is derived from ML. I've heard it mentioned that CAML is just a dialect of ML.

Given that, is it possible to translate ML to F# without a lot of knowledge of ML? What are the key differences from the languages? Or is my best bet to just learn ML instead?

答:
You are a bit off on what you think F# is. F# isn't a .Net port of ML anymore than C# is a .Net port of Java. F# takes a lot from OCaml (you can actually compile most OCaml code using the F# compiler).

F# also takes a more imperative approach than OCaml because of the fact it needs to in order to use the .Net framework.

Based on this SO post here are more things that F# doesn't support that OCaml does:

functors

OCaml-style objects

polymorphic variants

the camlp4 preprocessor

Title: How can I translate ML code to F#?


问:
Is the agile approach too much of a convenient excuse for cowboys
I believe that an agile approach is best for projects where the requirements are fuzzy and a lot of interaction is required to help shape the end user's ideas.

However... In my professional work, I keep ending up at companies where an "agile" approach is used as an excuse as to why no effort was put into an up front design; when the requirements are well understood.

I can't help but thinking that if the agile approach wasn't around, I'd be sitting here with a nice high-level specification and not having to revisit the same screen and functionality every second day when something else crops up or so and so hadn't thought of that.

Are the benefits of agile methodologies really enough to outweigh the excuse for being lame it gives to cowboy technical leads?

Update: Ironically I'm now a certified Scrum Master. One of the papers presented on the Scrum course observed that the best development process was one where there was a single expert or guru making the design decisions, however that has obvious weaknesses. Scrum shifts the responsibility for producing quality software to the "Team" which means a sub-standard team can get away with churning out spaghetti which I guess is no different to other Agile and non-Agile development processes.

答:
The reason while agile is putting very little emphasize on up-front design/specifications is not just because requirements may change. The deeper reason is that even when requirements are stable, specs tend to be:

incorrect - fail to capture the requirements.

inconsistent - riddled with contradictions because they contain enough information to make it impossible to the writer/reader to catch them.

detached - they do not incorporate valuable feedback from a running (although degenerated) system.