答:
For Java, yes, it's nothing more than a better way of creating an anonymous inner class. This is because of the fundamental decision in java that every bit of byte code has to live within a specific class, which cannot be changed now after decades of legacy code to consider.

However, that is not what lambda expressions really are about. In formalisms where they are native concepts rather than a jump-on-the-bandwagon contortion, lambdas are fundamental building blocks; both their syntax and people's attitude towards them are very different. The example of an anonymous recursive function created purely out of lambdas in Structure and Interpretation of Computer Programs is capable of changing your entire conception of computation. (However, I'm pretty certain that way of learning to program is just to esoteric ever to become a mainstream success story.)

Title: Is a lambda expression something more than an anonymous inner class with a single method?

Body:
There is a new hype with the long awaited lambda expressions in Java 8; every 3 day another article appears with them about how cool they are.

As far as I have understood a lambda expression is nothing more than an anonymous inner class with a single method (at least at the byte-code level). Besides this it comes with another nice feature - type inference but I believe the equivalent of this can be achieved with generics on some level (of course not in such a neat way as with lambda expressions).

Knowing this, are lambda expressions going to bring something more than just a syntactic sugaring in Java? Can I create more powerful and flexible classes or other object-oriented constructs with lambda expressions that aren't possible to be built with current language features?


问:
How can we avoid having to build yet another CRM system from scratch
We are building an accounting web application. In our database, we store basic data about our customers, like phone number, their login informations, because these things are tied into our web application. Now we need a CRM system to do things like sending marketing mails to users who signed up, but never used the service, we also want a database of potential customers or partners, who we would like to contact some day etc. etc.

Such functionality is basic in any CRM system and I would hate to have to implement all these features ourselves. At the same time, I cannot see how we could utilize a CRM solution like SalesForce without having to store some data in two places and with all the complications that that would lead to. What should we do? Is there any CRM system that can be put upon our PostgreSQL database and just utilize the data we have and store what we do not have?

答:
Off the shelf tools exist to meet customer needs.

Building an off the shelf tool that does everything any customer might need is a kind of panacea that a lot of companies try to build.

The problem client companies like yours have is that no "all in one" system will ever do absolutely everything your company needs.

So extensibility and customisability are both important things for the "all in one" system.

IMHO, you will not find a system that does everything, and you will always have to compromise.

That may mean buying a second system, or building something else, and managing data between them.

ContentLicense: CC BY-SA 3.0


答:
Is there any CRM system that can be put upon our PostgreSQL database
  and just utilize the data we have and store what we do not have?

here's your problem - you want a CMS, but you don't want to use the functionality that CMS offers you, you want to bend it to your requirements. Here's a suggestion: why not look for a CMS that does the things you are building, and bend your design to its structures? Most CMSs come with way more functionality, and include things like customer details. You then move from building a CMS to modifying your existing system.

In the case where you cannot do this, the trick is to build a service-style component that presents your existing data to the CMS, so you replace the bit that would read from a customer phone number (say) from its DB, and replace that code with a call to your service that returns the phone number from your old DB. Good code will be structured in this way already so modifying it to read (and write) will be relatively trivial - if you're lucky you'll just need to change a DB connection and some SQL.

Open Source CMSes are ten a penny, you could try vtiger which is a salesforce clone, or investigate the options offered by more generic systems like drupal, joomla or plone. See which one could be altered the easiest.

Title: How can we avoid having to build yet another CRM system from scratch

Body:
We are building an accounting web application. In our database, we store basic data about our customers, like phone number, their login informations, because these things are tied into our web application. Now we need a CRM system to do things like sending marketing mails to users who signed up, but never used the service, we also want a database of potential customers or partners, who we would like to contact some day etc. etc.

Such functionality is basic in any CRM system and I would hate to have to implement all these features ourselves. At the same time, I cannot see how we could utilize a CRM solution like SalesForce without having to store some data in two places and with all the complications that that would lead to. What should we do? Is there any CRM system that can be put upon our PostgreSQL database and just utilize the data we have and store what we do not have?


问:
How to embed an article in the source code?
Sometimes, I notice typos in articles (blog posts) or books in source code that appears in the body of the article. It may be an indication that the code has been manually copied and pasted (e.g. missing braces ), or that something nasty happened to the text.

How may I write an article inside the source code of a project ? I'm targetting Wordpress; I'm basically looking for a parser that would recognize two kinds of region: article and source code, and that would format them to whatever I want (stackoverflow question, LaTeX code or Wordpress article)

答:
I think you could utilize doxygen for this purpose.

works for objective-c

does not support Wordpress directly, but HTML and LaTeX output. As far as I know you can import HTML into Wordpress by this plugin

cross-platform (works on MacOSX)

You might have to setup some kind of infrastructure around your program to get exactly the part of your program you want as the final article, but I guess this should not be too hard.

ContentLicense: CC BY-SA 4.0


问:
How to end my dependency on .NET?
I have been developing Windows GUI applications since many years and jumped into .NET in early 2005. .NET is a undoubtedly a remarkable platform and I am still using it, but with a variety of technologies out there, I don't want to remain dedicated to this camp. I want to learn new languages with which I can develop GUI applications.

I am learning Ruby and just installed Python. I read about WxRuby, a framework for developing Windows GUI app. in Ruby. I am searching for a similar framework for Python.

Apart from that I want to know which language is more suitable for a production-level GUI app. I doubt that Ruby is more focused on Web platform with it's glamor, Ruby on Rails.

I know that I may not get those rich .NET classes and that impressive Visual Studio IDE, but still I want to follow the road less traveled. I don't want to go with IronPython and IronRuby, however sometime later, I may dip hands to explore them.

答:
Check Qt.

it's arguably as rich as .NET, and the IDE (QtCreator) is simple yet pretty powerful.  Of course, it's better used on the native C++, but the Python binding is kept complete and up to date.

On top of it, it's really crossplatform, and that includes mobile platforms now too :-)

ContentLicense: CC BY-SA 2.5

Title: How to end my dependency on .NET?


问:
Why is String immutable in Java?
I couldn't understand the reason of it. I always use String class like other developers, but when I modify the value of it, new instance of String created.

What might be the reason of immutability for String class in Java?

I know there are some alternatives like StringBuffer or StringBuilder. It's just curiosity.

答:
Immutability means that constants held by classes that you don't own can't be modified. Classes that you don't own include those that are in the core of the implementation of Java, and strings that shouldn't be modified include things like security tokens, service addresses, etc. You really shouldn't be able to modify those sorts of things (and this applies doubly when operating in sandboxed mode).

If String wasn't immutable, every time you retrieved it from some context which didn't want the string's contents changed under its feet, you'd have to take a copy “just in case”. That gets very expensive.

Title: Why is String immutable in Java?


答:
The Java Virtual Machine performs several optimizations regarding string operations which couldn't be performed otherwise.  For example, if you had a string with value "Mississippi" and you assigned "Mississippi".substring(0, 4) to another string, as far as you know, a copy was made of the first four characters to make "Miss".  What you don't know is that both share the same original string "Mississippi" with one being the owner and the other being a reference of that string from position 0 to 4.  (The reference to the owner prevents the owner from being collected by the garbage collector when the owner goes out of scope)

This is trivial for a string as small as "Mississippi", but with larger strings and multiple operations, not having to copy the string is a big time saver!  If strings were mutable, then you could not do this, because modifying the original would affect the substring "copies" as well.

Also, as Donal mentions, the advantage would be greatly weighed down by its disadvantage.  Imagine that you write a program which depends on a library and you use a function which returns a string.  How could you be sure that that value will remain constant?  To ensure no such thing happens, you'd always have to produce a copy.

What if you have two threads sharing the same string?  You wouldn't want to be reading a string that is currently being rewritten by another thread, would you?  String would then therefore have to be thread safe, which being the common class that it is, would make virtually every Java program that much slower.  Otherwise, you'd have to make a copy for every thread which requires that string or you would have to put the code using that string in a synchronize block, both of which only slow down your program.

For all these reasons, that was one of the early decisions made for Java in order to differentiate itself from C++.

Title: Why is String immutable in Java?

Body:
I couldn't understand the reason of it. I always use String class like other developers, but when I modify the value of it, new instance of String created.

What might be the reason of immutability for String class in Java?

I know there are some alternatives like StringBuffer or StringBuilder. It's just curiosity.


答:
Reasons I can recall :

String Pool facility without making string immutable is not possible at all because in case of string pool one string object/literal e.g. "XYZ" will be referenced by many reference variables , so if any one of them changes the value others will be automatically gets affected .

String has been widely used as parameter for many java classes e.g. for opening network connection , for opening database connection, opening files . If String is not immutable, this would lead to serious security threat .

Immutability allows String to cache its hashcode.

Makes it thread-safe .

Title: Why is String immutable in Java?


问:
How can I say that programming language compiles to other languages?
How can I say in english, that programming language can be compiled to other programming languages?

The example can be Haxe. On the website the language is decribed as "Multiplatform":

Multiplatform:
  Haxe can be compiled to all popular programming platforms with its
  fast compiler – JavaScript, Flash, NekoVM, PHP, C++, C# and Java
  (soon)

but multiplatform can be misunderstood as hardware or software platforms (win, mac, linux).

So what is the most suitable word describing this ability?

答:
Maybe this is a question for https://english.stackexchange.com/ yet I would say that the process of compiling includes compiling to another high level language and is not only limited to compilers that compile towards native machine code.

As a word "Compile" is not specific to computer compilers at all and is quite general. "Compiling a table" or "compiling a list of names" comes to my mind, therefore it is broad enough for a lot of purposes (text processors like Latex compile as well, etc.). To be more specific about the target of the compiliation I would use to-source-compiler

Now for the specific example, I think that platform is an appropriate word to use. Since human languages are inherently ambigeous you have to use redundancy (examples, paraphrasing with other words, explaining) to get the point across if in doubt.

I would also read the "Haxe" statement in a way that includes standard libraries and similar things. I.e. in that case plattform would be a superset of "language" and you could separate it from that by calling it "software development platform" etc.


答: The usual term is "transcompilation" - not a common term, but the technically correct one. It's not just for trendy new scripting languages (CoffeeScript -> JavaScript) either; the first C++ compilers were in fact transcompilers to C.</p>

Title: How can I say that programming language compiles to other languages?

Body:
How can I say in english, that programming language can be compiled to other programming languages?

The example can be Haxe. On the website the language is decribed as "Multiplatform":

Multiplatform:
  Haxe can be compiled to all popular programming platforms with its
  fast compiler – JavaScript, Flash, NekoVM, PHP, C++, C# and Java
  (soon)

but multiplatform can be misunderstood as hardware or software platforms (win, mac, linux).

So what is the most suitable word describing this ability?


答:
First thing first: I don't know whether there is already a suitable word for this feature.

But maybe it could be called multilanguage? Or languageagnostic? Since it is more about the programming language, then the mention of 'language' in the name could make it more obvious than multiplatform.

Of course language is ambiguous as well, as it could be understood that the source code can be written in any real world language (for example because variables can be written in unicode).

On the other hand every seasoned programmer will probably recognize such a construct as different from localization or internationalization, so they might 'get' it more easily.

Just my 2 cents.


答:
Imagine a system where you accept some data, verify its correctness and then pass it on (to be stored in a DB, for example).

Assuming that data is a String and it has to be at least 5 characters long. Your method looks something like this:

```<code>public void handle(String input) {
  if (input.length() < 5) {
    throw new IllegalArgumentException();
  }
  storeInDatabase(input);
}
</code>```

Now we can agree, that when storeInDatabase is called here, the input will fit the requirement. But if String were mutable, then the caller could alter the input object (from another thread) right after it has been verified and before it's been stored in the database. This would require good timing and would probably not go well every time, but occasionally, he'd be able to get you to store invalid values in the database.

Immutable data types are a very simply solution to this (and a lot of related) problems: whenever you check some value, you can depend on the fact that the checked condition is still true later on.

Title: Why is String immutable in Java?

Body:
Imagine a system where you accept some data, verify its correctness and then pass it on (to be stored in a DB, for example).

Assuming that data is a String and it has to be at least 5 characters long. Your method looks something like this:

public void handle(String input) {
  if (input.length() < 5) {
    throw new IllegalArgumentException();
  }
  storeInDatabase(input);
}

Now we can agree, that when storeInDatabase is called here, the input will fit the requirement. But if String were mutable, then the caller could alter the input object (from another thread) right after it has been verified and before it's been stored in the database. This would require good timing and would probably not go well every time, but occasionally, he'd be able to get you to store invalid values in the database.

Immutable data types are a very simply solution to this (and a lot of related) problems: whenever you check some value, you can depend on the fact that the checked condition is still true later on.


问:
How can I deal with a team member who duplicates code?
One of our team member duplicates code. Code duplication causes confusion among my team members reading his code, it causes bugs down the line when the duplicated segment is fixed in one location and not the others and it bloats the size of his code-base.

I have discussed with him not to duplicate code. But he show excuses that it will delay our projects deadline if he refactors all the places where he made code duplication.

How better can I deal with him?

答:
You can explain that it would be more costly in delays to fix the same bug in 5 locations.

And then finding out that the fix was missed in location 6.

It also delays the team when they look at a piece of code, expecting it be be called from one location, but it never does, as it is duplicated elsewhere, where it is being called.

This is particularly problematic when certain versions of the duplication change slightly - it is then difficult to tell which one is the "right" one and why - this is one of the most difficult things to correct and is very time consuming.

You can also send them to  Why is “copy and paste” of code dangerous?


答:
they are expensive and keeping them immutable allows for such things as sub strings sharing the byte array of the main string. (speed boost also as do not need to make a new byte array and copy over)

security - would not want your package or class code to be re named

[removed old 3  looked at StringBuilder src - it does not share memory with string (until modified) I think that was in 1.3 or 1.4]

cache hashcode

for mutalble strings use SB (builder or buffer as needed)

Title: Why is String immutable in Java?


答:
Sorry gents, but the word for this is just "compiled". It means turning one type of code into another type of code. It makes no real difference if that code is English, C++, x86 machine code, ARM machine code, Java, bytecode, or back to English. We generally use it to mean the trip from programming language to machine code, but that's an aspect the word has gained over time. And hey, if enough people start using a word incorrectly, it DOES indeed gain that new meaning. But if you want a word for turning Haxe into C++, the word is "compiles".

Multiplatform: Haxe can be compiled into all popular programming languages with its fast compiler – JavaScript, Flash, NekoVM, PHP, C++, C# and Java (soon)

(Also, I'm ignoring Merriam-Webster, because they're stupid because they disagree with me... hmmmm)


问:
Implicit optimization versus explicit optimization
To explain what I mean, let me start with an example.

Consider a deque that supports O(logn) concatenation with another deque  and O(n) addition of n elements at one end. This dequeimplements a general seq interface (or type-class, or what have you) that allows iterating over a collection.

An explicit optimization approach would be, having a concat method (or function) for deque  objects and a separate pushSeq method for seq objects. Each method would be documented with the appropriate complexity.

An implicit optimization approach would be to have a single concat method that accepts a seq. An internal dynamic type test checks whether the supplied argument is actually a deque, and if so, calls an implementation method for concating deques. This is documented in the API.

Obviously you could have both of these. The point of implicit optimization is that you don't give the user explicit control over optimization. It just "happens", unless the user deliberately looks for it.

Right now I'm writing a library and I'm facing a very similar choice. I very much like the idea of a compact interface where things just "work". An implicit approach also gives me a lot more freedom. For example, maybe I can perform ten dynamic type tests to optimize the concat operation for different collections. Having ten different methods wouldn't make sense.

What's your take on this? Which approach is better, and why?

答:
Having a single method that can choose if/when to follow a pre-defined optimization is a better route to take. Just some advantages off the top of my head:

Easier to write unit tests

Will "Just Work" for anybody using it

Can update/change the code handling that section without requiring anyone relying on the code to change anything

Can add further optimizations or new types without affecting anything else

Less likely people will use it "wrong" and come complaining to you

Easier to learn how to use your library

Leads to better code reuse. What if an optimization actually works for 3 types, not just 1? You don't need to rewrite much, if anything, and the users don't need to worry about which one to use

All that said, and as has been said above, don't do too much premature optimization. Wait until you know there's a problem, which unit testing and getting users will help you find.


问:
Are square brackets and curly braces in Clojure still S-expressions?
I am trying to learn Lisp and looking at all the Lisps out there and their differences.

I see that in some implementations of Scheme, you can use square brackets interchangeably with round brackets for readability, so because they are treated the same, I assume they are still just S-expressions like everything else.

However, in Clojure I see that square brackets and curly braces are used to represent different data types like vectors and so on. Are these also still valid S-expressions, or must they be considered atoms? Doesn't this "break" the whole concept of S-expressions, thereby making Clojure an "impure" Lisp?

答:
Literal notation for vectors and maps (ie, square brackets and curly braces) are just read-time sugar, and anything you can represent with that notation can also be represented with S-expressions. As a result, there's no loss of power or homoiconicity, and indeed reader macros (which I understand are even more powerful) are available in a number of lisps.

Incidentally, note that Clojure now provides a mechanism for creating custom "tagged" literals, which, like other literals, are transformed to S-expressions before they are compiled and interpreted.


答:
First off, I'm going to assume that you've verified that optimisation is actually needed. Much has been said on the perils of premature optimisation, so I'll just say that if you haven't already, then check that this code actually needs optimising (ie. it's responsible for a significant portion of the program's execution time, or, for libraries, it's significantly slower than the things it's going to be used alongside).

Having made sure that this optimisation is necessary, there are a few issues to consider. The first thing is to consider who will use it:

Some users don't care about optimisation. Having multiple methods provides them with multiple options in a place where one option would be fine. You're making them think more than they might otherwise have to, which is to be avoided - a programmer's brain is their most important resource; you should not eat into it lightly.

Some users may be less skilled or less experienced - they might not know about optimisation, or might not understand the difference between the methods. Presenting them with several options will confuse them, and they might use the wrong one, or just give up and go find another library.

To generalise the previous two points, if it's up to the user to optimise, then there will be some users who don't. This means you're limiting the performance of your library in a lot of its applications. If you can make your code faster, you'll probably want to make it faster for everyone who uses it.

It's also worth considering how the code will be used:

Your different methods might end up having different names, depending on your language's restrictions on method naming and argument types. This means that users have to remember which method goes with which type. This is more complicated than just knowing that collections have a concat method.

Hiding the optimisations away makes your library more useable - the user doesn't need to make any type checks themselves, or use different methods in different places. They can forget about performance and focus on functionality, using concat everywhere and knowing that the optimisations will be handled for them.

In general, I'd definitely advise making the optimisations implicit, tucked "under the hood". In most cases, a user should be required to understand as little as possible about the internal workings of your code in order to use it. They'll need to know what it does, but the details of how it does it shouldn't affect them.

The main argument I'd make in favour of letting the user access the internal methods is that they may be able to select the correct method themselves without needing the type checks you're making, simply by knowing from the structure of the logic what type the object will be at that point. If you want to leave this possibility open, then one approach I've seen work quite well is to have a layered namespace structure. This depends on what your language allows, and the nature of the methods in question (might not work with your situation) but in general, it works something like this:

A standard namespace, MyLibrary, which contains all the top-level functions with their checks and implicit optimisations. The majority of your users will just use this, and leave your code to optimise things.

A deeper namespace, MyLibrary.Core or something like that, which exposes some more of the internal methods. The standard namespace is mostly a wrapper to hide this deeper namespace from users who are happy to let your code handle the optimisations. Users who really want to squeeze a little extra performance can use this namespace to give them access to the internal methods, so they can handle the optimisation themselves.

Title: Implicit optimization versus explicit optimization

Body:
To explain what I mean, let me start with an example.

Consider a deque that supports O(logn) concatenation with another deque  and O(n) addition of n elements at one end. This dequeimplements a general seq interface (or type-class, or what have you) that allows iterating over a collection.

An explicit optimization approach would be, having a concat method (or function) for deque  objects and a separate pushSeq method for seq objects. Each method would be documented with the appropriate complexity.

An implicit optimization approach would be to have a single concat method that accepts a seq. An internal dynamic type test checks whether the supplied argument is actually a deque, and if so, calls an implementation method for concating deques. This is documented in the API.

Obviously you could have both of these. The point of implicit optimization is that you don't give the user explicit control over optimization. It just "happens", unless the user deliberately looks for it.

Right now I'm writing a library and I'm facing a very similar choice. I very much like the idea of a compact interface where things just "work". An implicit approach also gives me a lot more freedom. For example, maybe I can perform ten dynamic type tests to optimize the concat operation for different collections. Having ten different methods wouldn't make sense.

What's your take on this? Which approach is better, and why?


问:
Is Haskell/Clojure actually unsuited for dynamic systems such as particle simulation?
I've been told in previous questions that functional programming languages are unsuited for dynamic systems such as a physics engine, mainly because it's costly to mutate objects. How realistic is this statement, and why?</p>

答:
I can't speak for Clojure, but I can say Haskell has a lot of very highly tuned IO packages available that will allow all the mutation you could want.

Here's an answer to a question I wrote where someone details the 3 most common ones and regards their performance: https://stackoverflow.com/questions/15439966/when-why-use-an-mvar-over-a-tvar/15440286#15440286

You can also see here a simple graph showing performance metrics of a haskell web server called Warp, which is a highly IO intensive application.

There is a lot of confusion about this regarding Haskell, the truth is it has fantastic IO facilities with many packages on hackage for using IO in a great many different ways, many of which have been highly tuned. The reason people presume this isn't the case is because Haskell goes to great lengths to separate IO from everything else, but that has no effect on the performance characteristics.

Now to speak about performance characteristics however, the reason people recognize it as having poor performance is due to the lazy evaluation causing it to behave in ways that aren't always intuitive. This is however something you have to worry about considerably less when you start working in an IO context doing destructive updates such as in a system you are referring to. Further people tend to find that when they are having performance troubles, the built in facilities to instrument and identify where resources are going help a great deal.

Another monad worth looking at for a system like you describe would be the ST monad which is specifically for destructive updates done by very small IO calls giving it great performance.

Sorry I really can't speak to Clojure, hopefully someone else can give details there.


问:
Security in Authentication in single page apps
What's the most secure method of performing authentication in a single paged apps? I'm not talking about any specific client-side or server-side frameworks, but just general guidelines or best practices. All the communications are transfered primarily through sockJS.

Also, OAuth is out of the question.

答:
I think here are two starting points.

Web services/REST services on the same server as your single web app.

It's not uncommon to do so nor it is necessarily bad, and also clearly the easiest way. Whatever authentication you choose (basic, digest, form, etc.) the API and the app are going to share the same user sessions on the server. Which means several things:

The API can easily detect whether the user is logged or not, and obtain its permissions, roles or whatever you need to know if the user is allowed to perform a given action.

You can deploy both the API and the app at the same time.

Scaling the app is simple, just deploy both the API and the app to another instance. Load balancing is also easier.

Monitoring the app is simple.

On the negative side, if you want another app to use this API you'll have to either store this new app on the same server, or negotiate the user login yourself (for example, transmitting the credentials to the server). It may be even more complicated if your new app is NOT a web app.

Another point: even if it's a single web app, you will most likely load images or other resources. If the API usage is high it may impact the loading time of your app (which is generally a "big" HTML file) and other client resources. One of the way to prevent this is to use CDN for your JavaScript files, CSS stylesheets and pictures.

I think this approach is perfectly suited for quickly launching simple websites and/or for API that will not need to be accessed by other services. And even if you start with that approach (we know everything is possible when it comes to programming, right?) you can still at one point switch to the split API/app model.

Web services/REST services on one server and the app on another.

The best practice today for authenticating users to a SPA linked to an "external" API, or an API stored on a different instance of the server is to imitate OAuth in its principles. The key is to use ... keys, or tokens obtained from your main server. The basic flow should be:

Authenticate on the main server (where the app is hosted)

If the authentication is successful, create a token and send it in the HTTP response, for example in a cookie.

Whenever you need to access your API, send the token. It may be sent in a custom HTTP request header for example.

The API receives the request and checks :

If the requested resource needs a token, otherwise it's ok (example: returning information available to guests, unauthenticated users)

If the token is there, check if it's still acceptable. Deciding how and when the token expires is up to you, there are various ways to design the token expiration strategy.

Return the response data (optionally, with an updated token)

This approach allows you to:

Dissociate the API from the apps that are going to use it AND from the user system in itself. Granted, you have to somehow interpret the token, but you don't need to know how and where the user data is stored. If you want a new web app or client/server app to access this API, all you need is a proper token.

Deploy separately. For example, updating or fixing your API will not cause the single app server to go down.

Monitor usage of your API only.

To conclude, apply the KISS and YAGNI principles before deciding. And remember you can always go from one model to another.


问:
Who is responsible for fixing failed SQL code reviews?
As a DBA, most SQL is submitted to my team for review.  We do not have a SQL developer, so the code is frequently very, very inefficient.

Our current process is:

SQL is submitted for review right before it goes to beta

Issues are pointed out but frequently not resolved because the application has already been written around it, and is scheduled to be deployed to beta the same week

If the DBA team identifies an issue, the developer response is "show me how to fix it, then"

It should be noted that the DBA team has no requirements around any code, no context and no idea what 1000s of lines of a stored procedure is supposed to be doing.

Is this a typical scenario?  Who is responsible for fixing the code?  Does your DBA typically re-write the stored procdedure for you?

答:
There is constant confusion about this and it's caused by the fact that there are two different types of DBA: DataBase Architect and DataBase Administrator.

Many developers work with a database Architect who will design the database structures and write stored procedures. Database Administrators however often live on IT teams doing backups, knowing nothing of coding or engineering practices.

It sounds like your devs expect you to be the Architect, where you are an Administrator. I think you need to fix this expectation with them and then you won't have these problems. Also, if you are just an administrator who doesn't understand the code or engineering that went into designing the structures and writing the stored procedures, it's entirely likely the developers do not take your critiques of their work seriously. If you have suggestions or issues with the engineering work, it may be best if you can get a database Architect with more engineering know-how to champion those to the developers for you.

Also, I have to question why you are reviewing the SQL the developers write if you aren't an engineer familiar with reading complex stored procedures. It sounds like management may be trying to get their IT department to do what their engineering department does, and not understanding that they are completely different skillsets. You may wish to raise this with management.


问:
What is it called when you're developing a web application where every url has its own php file
What is it called when you aren't using an MVC framework and each URL has it's own file associated with it.  I want to say it's model 0 or class 0 but I haven't been able to find anything useful via Google. :-)</p>

答: It's called the Model 1 architecture in Java . Perhaps I have heard PHP developers referring to it as Monolithic architecture .</p>


答:
This review is happening way too late in the process. These reviews should happen as a dev finishes a piece of work, not before the actual release.

There must be a common pattern that you are seeing eg. incorrect indexes, using cursors etc. Maybe you should put together a crib sheet of what you will reject, and what you would replace it by.

For what it's worth, it sounds like the devs are putting way too much business logic in the database.

Title: Who is responsible for fixing failed SQL code reviews?

Body:
As a DBA, most SQL is submitted to my team for review.  We do not have a SQL developer, so the code is frequently very, very inefficient.

Our current process is:

SQL is submitted for review right before it goes to beta

Issues are pointed out but frequently not resolved because the application has already been written around it, and is scheduled to be deployed to beta the same week

If the DBA team identifies an issue, the developer response is "show me how to fix it, then"

It should be noted that the DBA team has no requirements around any code, no context and no idea what 1000s of lines of a stored procedure is supposed to be doing.

Is this a typical scenario?  Who is responsible for fixing the code?  Does your DBA typically re-write the stored procdedure for you?


问:
Bridging the gap between computer science research and software engineering
Do you believe there is a gap between computer science research and software engineering problems?  For example, do software engineers ever have to worry about "factoring and graph isomorphism" or some complex computer science problems if they have to....say build a shopping cart website?  Probably not.

And if there is a disconnect between computer science and the engineers that build applications?  Is that the way that engineering and science should exist?  Will engineers dive through years and years of research papers to solve a particular problem that they have?

Edit-1: After thinking about it, general science probably has the same problem.  I am sure there are top chemists working at companies like McDonald's and Taco Bell that are tasked with making a better, easier to manufacture burger.

答:
Academic Computer Scientists are very good with the following:

Analysis of algorithms

Knowledge of Standard Data Structures.

Automata theory

All of above are useful things for software engineering. In fact it would be indispensable to have at least one computer scientist in a software engineering team.

However, the way computer science is taught, and ABET accreditation rules exacerbate the problem (if it can be called a problem). The computer scientists do not have much knowledge of following key software engineering areas.

RAM footfprint of a software and impact it may have on software performance.

Maintainabilty engineering of software. They have no appreciation of the fact that 80% of software jobs are in maintaining software, which is the biggest component of software cost.

How to work close to the hardware. This is required when you view entire system as a combination of hardware and software and you optimize the system to see as to how to optimize both for best functionality.

Inventing new, fast, and reliable software testing, implementation, and maintenance procedures.

Software documentation, client training and related documentation.

System security engineering.

I can go on and on but I think I have made my point.

Software engineering today is a discipline of its own which borrows from computer science, but is driving the technology and human life today. You really need an Engineer's brain to excel in it. All computer scientists are not cut out to be great software engineers. Of course reverse will not be true either.


答: Generally, when a DBA has a problem with a query it's because it is slow. In that regard, it is up to the programmer to fix the query, because they actually know what the query is supposed to be doing, are part of the normal application development workflow, and will likely be responsible for changes in the future; however, it is very likely that the DBA will have to assist in the optimization process. Very few programmers I know can reliably look at a query and a query plan and figure out how to remove the bottlenecks.


问:
MIT licence copyright notice for derived works
We're thinking of using some open-source MIT-licensed software in one of our web projects (a  jQuery datetime plugin).

The first line of the MIT licence is:

Copyright (c) [year] [copyright holders]

If we include the plugin as-is (without making any changes), I understand we need to include the licence with only the original author (though the actual copyright notice at the top of the js file doesn't specify a year):

Copyright (c) 2013 Keith Wood

If we make changes to the plugin, what does the copyright notice become?

Copyright (c) 2013 Keith Wood, 2013 [My name/Company name]

Do you need to include all previous authors or is there another way of handling such a notice?

答:
The license for that plugin doesn't say "Copyright (c) 2013 Keith Wood."  It says:

Copyright 2013 jQuery Foundation and other contributors

I would imagine you could simply leave it just like that.  If you want to include your company name, you could simply say:

Copyright 2013 jQuery Foundation, [My name/Company name] and other contributors.

The MIT license simply states that existing copyrights must be preserved.  In other words, don't remove someone else's copyright notice.  This, of course, doesn't preclude you from adding "portions copyrighted by [me]" to the copyright header.


答:
You can only make changes in the context of what information and skills you have. Since you don't have the requirements, you have to assume the outcomes of the existing code are correct. Any changes you make for performance should not change the results. This is easy to test.

You may be able to make changes to improve the code without changing the code itself. Queries can be analyzed to see if an index would improve the performance. Other database settings or hardware changes can be made as well.

To a certain extent, your review process is almost asking the DBAs for a rubber-stamp of approval. If you want to do more than this, you need to request the requirements, get involved in development, and request your approval be made earlier in the development process.


答:
DBA as Architect:

If the DBA team is rejecting code, then yes the DBA team should be giving the reason why they are rejecting the code.

If the DBA team is rejecting code because it is inefficient, the DBA team should probably re-write the code to be efficient, and return it to developers. Developers need to validate that the code you re-wrote still passes their tests.

If the DBA team is rejecting code because it incorrectly implements requirements, then the DBA team should actually be writing the code themselves. If they know the requirements, then it makes far more sense to have SQL experts writing SQL code to some API agreed to by the DBA team and developer team.

DBA as Administrator:

The DBA team should not be tasked with code review. Such a team would likely not have the skills to effectively review code, and are rather just a "rubber stamp" approval that feels good to management but doesn't actually improve the process.


答:
Both Haskell and Clojure allow actual mutability, so that's a non-issue to start with.

Beyond that, if your "mutable" data consists of intermediate values being updated incrementally as part of some larger computation, you may not even need mutability to be efficient! For example, there's ongoing research in Haskell regarding a technique called stream fusion, where the compiler fuses processing loops, data producers, and data consumers to eliminate intermediate data structures entirely.

The main issue with Haskell here is laziness--in a number-crunching program where you have a lot of input data and a lot of output data and all of it is important, laziness does you very few favors but still imposes some overhead. That's not to say you can't write programs like that in Haskell (people do, in fact) but it's not playing to the language's strengths and you need to have a better understanding of the evaluation model to get the performance you want.

That said, heavy number-crunching doesn't play to the strengths of the JVM, either. That sort of program is why FORTRAN is still around.

Title: Is Haskell/Clojure actually unsuited for dynamic systems such as particle simulation?

Body: I've been told in previous questions that functional programming languages are unsuited for dynamic systems such as a physics engine, mainly because it's costly to mutate objects. How realistic is this statement, and why?</p>


问:
Is reverse debugging possible?
I know there are some products for reverse debugging.

I am wondering that does reverse debugging mean going to one step back or starting over again up to one step back?

I've found an explanation here.

答:
does reverse debugging mean going to one step back or starting over again up to one step back?

According to the link you posted, "reverse debugging" means being able to undo instructions in the debugger. So you'd have something like a 'step back' command that tells the debugger to reverse the effect of the last instruction executed. It doesn't mean re-running the program to get back to the previous instruction.

Title: Is reverse debugging possible?


问:
Should website frontends be rendered in client-side or server-side?
I've been talking to a colleague that comes from AS3 to the HTML world. He has created a small website (there are apparently no dynamic contents) following the no-flash rules for his very first time, and as if you own a hammer you tend to hammer everything, he decided to create a framework in JavaScript, so he could do all "the AS3 way", with frames, pure X-Y coordinates animation and so, to animate contents. The page would be fully loaded at first, load the vast amount of JS at first and then the page would be accessible without changing url.

Views would turn into class methods (where the class represents a section, and the method stands for a view) which append text to a variable that is then added to a div. He defends this situation with many reasons:

Websites with a high amount of users do this to prevent server overloading.

It is easier to create new sections.

It is easier to translate, as translations, texts and almost everything is loaded from a JSON.

You can expand more sections directly from a JSON file.

Everything is smooth, as you don't move to another page.

Now, here comes the PHP-loyal developer, which defends the opposite side. I say that views should be split into smaller files but contained in .php or even .html files, with the business logic in a controller and the view logic in these files. This releases the client, as it can disable JavaScript and still show the content without a matter. Of course your server needs to make calculations, but it's just rendering files. Some benefits could be:

You don't need to load the whole website at first. Webpages loaded faster.

Your urls are always clean and (in case you did so) friendly, without plugins and working seamlessly in old browsers, as you move to another page.

Views are kept in independent files, so it is easier to work with them in a team.

Views are regular html files, instead of calls to methods appending strings, so editing them is just natural.

You still need PHP (or any other language) to load data from a server (NodeJS not considered here)

And, of course, here comes the real question. Should views be rendered on client or server side?

答:
RobertHarvey is totally right: it depends. It could be a good solution but it is a terrible solution also for some projects.

In you question you state:

He has created a small website (there are apparently no dynamic contents)

Based on that he chose the wrong solution. Now you also note that there are animations. So maybe, if those are exceptional, it might be a good solution. Let's state those animation could also be made with normal solutions.

Whether it is good or right is then simple: If it should work like a normal website, so with a good ranking in search engines, good accessibility and all other standard webdevelopers take care of it is just wrong. You build a website with a goal. If that is: Have normal people visit it to subscribe/buy/view etc. it won't meet that goal.

His arguments:

Websites with a high amount of users do this to prevent server overloading.

Yes, but this is a small website right? http://c2.com/cgi/wiki?PrematureOptimization

It is easier to create new sections.

Likely he is unaware of other solutions. No problem, it's his first one. This is something where training / reading could do a lot.

It is easier to translate, as translations, texts and almost everything is loaded from a JSON.

Same here, localisation is something much more complex than just translating some pieces of text anyway. Education is here also the key.

You can expand more sections directly from a JSON file.

Might be correct, seems simple to do. If a user has to do it then it directly becomes more difficult. With a database for example it might be possible to create a form for that.

Everything is smooth, as you don't move to another page.

This is true but not undoable with other solutions. Loading pieces of content with ajax (with changing the browser history) might solve this well. https://developer.mozilla.org/en/docs/DOM/Manipulating_the_browser_history

To take this into a broader level: It is nonsense to build a dedicated framework if it is just a simple site. Use the basics or an existing system for it. On the other side, it's a nice learning experience. We all tried to build a CMS once right? ;) His arguments are not strong, if he want to work more in this area more knowledge would be advisable.


答: Strings should have been a primitive data type in Java.  If they had been, then strings would default to being mutable and the final keyword would generate immutable strings. Mutable string are useful and so there are multiple hacks for mutable strings in the stringbuffer, stringbuilder, and charsequence classes.</p>

Title: Why is String immutable in Java?


问:
Opinions on distribution of software via virtual appliance
I've created a distribution of my open source application framework in a working virtual appliance.  It includes everything to get started with the tutorial.  The distribution is Fedora 14 running Tomcat 5.5 and Oracle 10g Express Edition, plus my framework.  It is completely preconfigured and boots into a working running copy.

Would this be something you might try?

What assurances might you need to get you to try it?

Edit: The VM is just over a 2Gb download.  Alternatively it is also available via 23Mb download for the source and a PDF detailing how to configure the Tomcat and Oracle dependencies.

答:
Microsoft has had success distributing demo software using appliances, and did this with the beta of Visual Studio 2010.  I think they use appliances pretty often for betas of operating systems also.

How big is the download?  Could you explain more about what the framework is?


问:
caching on multiple servers
Because we need to keep response times low, we get tons of requests, and we need to basically process ALMOST the same data (which I'll refer to as X) each request (the inputs are different though, so we can't cache responses), we are using a technique where we grab a new copy of X every 90 seconds from the database and store it locally in memory as a python list of dictionaries, on our application servers (we are using uwsgi).

The kink in the machine: There are temporary analytics that we need to keep track of in those 90 seconds to adjust our data each iteration, and each iteration is dependent on what we calculate from the last iteration.

The trouble with this is, we have multiple application servers that are storing the same data, X, in memory and each of those servers need to refresh X at the same time to keep calculations consistent for the next interval.  I've tried some techniques, like broadcasting a message after each calculation to reload each server's X, but it hasn't been as effective as I would hope, and it just makes things more complicated.

I should say, the reason we haven't used memcached or something similar is because we don't want to sacrifice any speed if we can.  Maybe I am ignorant on how fast we can retrieve and load the list into python objects from memcached.

I understand my explanation isn't the greatest, and will answer any questions to give a better picture of the situation.

Edit:
we are at about 5000 request/second, the size of the data we process is about 2MB at the moment but will continue to grow, so we'd like to avoid sending it over the wire for each request.

答:
Your question is interesting, thought to give a quick answer but it is more complicated.

You have a set of data (please supply size and amount of requests indication!). It should be equal at all machines at a given moment. That is interesting because it makes distributed systems less use-full. You get to a more transaction based system where you can really trust the data.

You state it is a requirement (and so important).

First thing to ensure yourself of is: Do I really need to distribute this data? If you use a central storage you don't have all the synchronisation and replication issues at all. So if there is no problem you don't have to fix it. (In this case hardware might be a much cheaper solution).

And I assume based on your story that there is no reason. Why? Because it is possible for you to get every 90 seconds "all" data. You could even do that on a broadcast. So your central storage seems to be able to deliver that instant.

Though you have multiple servers so it seems needed. Now they store the data, do calculations on it, reset itself to the new data and start servicing again. That means the expectation is that the response delay will increase significantly when you ask the data from you central storage instead of your local Python dictionary.

Sounds reasonable. Did you measure this? Are you really sure that's not possible? Really really sure?

Ok, let's say it is impossible: The you need to have a distributed system which guarantees that the data will be there always when you start with a new session. I personally think you should forget about that 90 sec. period anyway. So, in that case you get into realtime, near-realtime, solutions. This is possible but I think you make it yourself very hard.

Generally all no-sql solutions which are distributed weakened the guarantees for syncing data. So find yourself an easier way out or create the almost real-time cluster. Those are your best bets.

Title: caching on multiple servers


答:
Concurrency

Java was defined from the start with considerations of concurrency. As often been mentioned shared mutables are problematic. One thing can change another behind the back of another thread without that thread being aware of it.

There are a host of multithreaded C++ bugs that have croped up because of a shared string - where one module thought it was safe to change when another module in the code had saved a pointer to it and expected it to stay the same.

The 'solution' to this is that every class makes a defensive copy of the mutable objects that are passed to it. For mutable strings, this is O(n) to make the copy.  For immutable strings, making a copy is O(1) because it isn't a copy, its the same object that can't change.

In a multithreaded environment, immutable objects can always be safely shared between each other.  This leads to an overall reduction in memory usage and improves memory caching.

Security

Many times strings are passed around as arguments to constructors - network connections and protocals are the two that most easily come to mind.  Being able to change this at an undetermined time later in the execution can lead to security issues (the function thought it was connecting to one machine, but was diverted to another, but everything in the object looks like it connected to the first... its even the same string).

Java lets one use reflection - and the parameters for this are strings.  The danger of one passing a string that can get modified through the way to another method that reflects.  This is very bad.

Keys to the Hash

The hash table is one of the most used data structures.  The keys to the data structure are very often strings.  Having immutable strings means that (as above) the hash table does not need to make a copy of the hash key each time.  If strings were mutable, and the hash table didn't make this, it would be possible for something to change the hash key at a distance.

The way the Object in java works, is that everything has a hash key (accessed via the hashCode() method). Having an immutable string means that the hashCode can be cached.  Considering how often Strings are used as keys to a hash, this provides a significant performance boost (rather than having to recalculate the hash code each time).

Substrings

By having the String be immutable, the underlying character array that backs the data structure is also immutable.  This allows for certain optimizations on the substring method the be done (they aren't necessarily done - it also introduces the possibility of some memory leaks too).

If you do:

```<code>String foo = "smiles";
String bar = foo.substring(1,5);
</code>```

The value of bar is 'mile'.  However, both foo and bar can be backed by the same character array, reducing the instantiation of more character arrays or copying it - just using different start and end points within the string.

```
foo |    | (0, 6)
    v    v
    smiles
     ^  ^
bar  |  |  (1, 5)
```

Now, the downside of that (the memory leak) is that if one had a 1k long string and took the substring of the first and second character, it would also be backed by the 1k long character array.  This array would remain in memory even if the original string that had a value of the entire character array was garbage collected.

One can see this in String from JDK 6b14 (the following code is from a GPL v2 source and used as an example)

```<code>   public String(char value[], int offset, int count) {
       if (offset < 0) {
           throw new StringIndexOutOfBoundsException(offset);
       }
       if (count < 0) {
           throw new StringIndexOutOfBoundsException(count);
       }
       // Note: offset or count might be near -1>>>1.
       if (offset > value.length - count) {
           throw new StringIndexOutOfBoundsException(offset + count);
       }
       this.offset = 0;
       this.count = count;
       this.value = Arrays.copyOfRange(value, offset, offset+count);
   }

   // Package private constructor which shares value array for speed.
   String(int offset, int count, char value[]) {
       this.value = value;
       this.offset = offset;
       this.count = count;
   }

   public String substring(int beginIndex, int endIndex) {
       if (beginIndex < 0) {
           throw new StringIndexOutOfBoundsException(beginIndex);
       }
       if (endIndex > count) {
           throw new StringIndexOutOfBoundsException(endIndex);
       }
       if (beginIndex > endIndex) {
           throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
       }
       return ((beginIndex == 0) && (endIndex == count)) ? this :
           new String(offset + beginIndex, endIndex - beginIndex, value);
   }
</code>```

Note how the substring uses the package level String constructor that doesn't involve any copying of the array and would be much faster (at the expense of possibly keeping around some large arrays - though not duplicating large arrays either).

Do note that the above code is for Java 1.6.  The way the substring constructor is implemented was changed with Java 1.7 as documented in Changes to String internal representation made in Java 1.7.0_06
 - the issue bing that memory leak that I mentioned above.  Java likely wasn't seen as being a language with lots of String manipulation and so the performance boost for a substring was a good thing.  Now, with huge XML documents stored in strings that are never collected, this becomes an issue... and thus the change to the String not using the same underlying array with a substring, so that the larger character array may be collected more quickly.

Don't abuse the Stack

One could pass the value of the string around instead of the reference to the immutable string to avoid issues with mutability.  However, with large strings, passing this on the stack would be... abusive to the system (putting entire xml documents as strings on the stack and then taking them off or continuing to pass them along...).

The possibility of deduplication

Granted, this wasn't an initial motivation for why Strings should be immutable, but when one is looking at the rational of why immutable Strings are a good thing, this is certainly something to consider.

Anyone who has worked with Strings a bit knows that they can suck memory. This is especially true when you're doing things like pulling data from databases that sticks around for awhile. Many times with these stings, they are the same string over and over again (once for each row).

Many large-scale Java applications are currently bottlenecked on memory. Measurements have shown that roughly 25% of the Java heap live data set in these types of applications is consumed by String objects. Further, roughly half of those String objects are duplicates, where duplicates means string1.equals(string2) is true. Having duplicate String objects on the heap is, essentially, just a waste of memory. ...

With Java 8 update 20, JEP 192 (motivation quoted above) is being implemented to address this. Without getting into the details of how string deduplication works, it is essential that the Strings themselves are immutable. You can't deduplicate StringBuilders because they can change and you don't want someone changing something from under you. Immutable Strings (related to that String pool) means that you can go through and if you find two strings that are the same, you can point one string reference to the other and let the garbage collector consume the newly unused one.

Other languages

Objective C (which predates Java) has NSString and NSMutableString.

C# and .NET made the same design choices of the default string being an immutable.

Lua strings are also immutable.

Python as well.

Historically, Lisp, Scheme, Smalltalk all intern the string and thus have it be immutable. More modern dynamic languages often use strings in some way that requires that they be immutable (it may not be a String, but it is immutable).

Conclusion

These design considerations have been made again and again in a multitude of languages.  It is the general consensus that immutable strings, for all of their awkwardness, are better than the alternatives and lead to better code (fewer bugs) and faster executables overall.

Title: Why is String immutable in Java?

Body:
Concurrency

Java was defined from the start with considerations of concurrency. As often been mentioned shared mutables are problematic. One thing can change another behind the back of another thread without that thread being aware of it.

There are a host of multithreaded C++ bugs that have croped up because of a shared string - where one module thought it was safe to change when another module in the code had saved a pointer to it and expected it to stay the same.

The 'solution' to this is that every class makes a defensive copy of the mutable objects that are passed to it. For mutable strings, this is O(n) to make the copy.  For immutable strings, making a copy is O(1) because it isn't a copy, its the same object that can't change.

In a multithreaded environment, immutable objects can always be safely shared between each other.  This leads to an overall reduction in memory usage and improves memory caching.

Security

Many times strings are passed around as arguments to constructors - network connections and protocals are the two that most easily come to mind.  Being able to change this at an undetermined time later in the execution can lead to security issues (the function thought it was connecting to one machine, but was diverted to another, but everything in the object looks like it connected to the first... its even the same string).

Java lets one use reflection - and the parameters for this are strings.  The danger of one passing a string that can get modified through the way to another method that reflects.  This is very bad.

Keys to the Hash

The hash table is one of the most used data structures.  The keys to the data structure are very often strings.  Having immutable strings means that (as above) the hash table does not need to make a copy of the hash key each time.  If strings were mutable, and the hash table didn't make this, it would be possible for something to change the hash key at a distance.

The way the Object in java works, is that everything has a hash key (accessed via the hashCode() method). Having an immutable string means that the hashCode can be cached.  Considering how often Strings are used as keys to a hash, this provides a significant performance boost (rather than having to recalculate the hash code each time).

Substrings

By having the String be immutable, the underlying character array that backs the data structure is also immutable.  This allows for certain optimizations on the substring method the be done (they aren't necessarily done - it also introduces the possibility of some memory leaks too).

If you do:

String foo = "smiles";
String bar = foo.substring(1,5);

The value of bar is 'mile'.  However, both foo and bar can be backed by the same character array, reducing the instantiation of more character arrays or copying it - just using different start and end points within the string.

foo |    | (0, 6)
    v    v
    smiles
     ^  ^
bar  |  |  (1, 5)

Now, the downside of that (the memory leak) is that if one had a 1k long string and took the substring of the first and second character, it would also be backed by the 1k long character array.  This array would remain in memory even if the original string that had a value of the entire character array was garbage collected.

One can see this in String from JDK 6b14 (the following code is from a GPL v2 source and used as an example)

   public String(char value[], int offset, int count) {
       if (offset < 0) {
           throw new StringIndexOutOfBoundsException(offset);
       }
       if (count < 0) {
           throw new StringIndexOutOfBoundsException(count);
       }
       // Note: offset or count might be near -1>>>1.
       if (offset > value.length - count) {
           throw new StringIndexOutOfBoundsException(offset + count);
       }
       this.offset = 0;
       this.count = count;
       this.value = Arrays.copyOfRange(value, offset, offset+count);
   }

   // Package private constructor which shares value array for speed.
   String(int offset, int count, char value[]) {
       this.value = value;
       this.offset = offset;
       this.count = count;
   }

   public String substring(int beginIndex, int endIndex) {
       if (beginIndex < 0) {
           throw new StringIndexOutOfBoundsException(beginIndex);
       }
       if (endIndex > count) {
           throw new StringIndexOutOfBoundsException(endIndex);
       }
       if (beginIndex > endIndex) {
           throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
       }
       return ((beginIndex == 0) && (endIndex == count)) ? this :
           new String(offset + beginIndex, endIndex - beginIndex, value);
   }

Note how the substring uses the package level String constructor that doesn't involve any copying of the array and would be much faster (at the expense of possibly keeping around some large arrays - though not duplicating large arrays either).

Do note that the above code is for Java 1.6.  The way the substring constructor is implemented was changed with Java 1.7 as documented in Changes to String internal representation made in Java 1.7.0_06
 - the issue bing that memory leak that I mentioned above.  Java likely wasn't seen as being a language with lots of String manipulation and so the performance boost for a substring was a good thing.  Now, with huge XML documents stored in strings that are never collected, this becomes an issue... and thus the change to the String not using the same underlying array with a substring, so that the larger character array may be collected more quickly.

Don't abuse the Stack

One could pass the value of the string around instead of the reference to the immutable string to avoid issues with mutability.  However, with large strings, passing this on the stack would be... abusive to the system (putting entire xml documents as strings on the stack and then taking them off or continuing to pass them along...).

The possibility of deduplication

Granted, this wasn't an initial motivation for why Strings should be immutable, but when one is looking at the rational of why immutable Strings are a good thing, this is certainly something to consider.

Anyone who has worked with Strings a bit knows that they can suck memory. This is especially true when you're doing things like pulling data from databases that sticks around for awhile. Many times with these stings, they are the same string over and over again (once for each row).

Many large-scale Java applications are currently bottlenecked on memory. Measurements have shown that roughly 25% of the Java heap live data set in these types of applications is consumed by String objects. Further, roughly half of those String objects are duplicates, where duplicates means string1.equals(string2) is true. Having duplicate String objects on the heap is, essentially, just a waste of memory. ...

With Java 8 update 20, JEP 192 (motivation quoted above) is being implemented to address this. Without getting into the details of how string deduplication works, it is essential that the Strings themselves are immutable. You can't deduplicate StringBuilders because they can change and you don't want someone changing something from under you. Immutable Strings (related to that String pool) means that you can go through and if you find two strings that are the same, you can point one string reference to the other and let the garbage collector consume the newly unused one.

Other languages

Objective C (which predates Java) has NSString and NSMutableString.

C# and .NET made the same design choices of the default string being an immutable.

Lua strings are also immutable.

Python as well.

Historically, Lisp, Scheme, Smalltalk all intern the string and thus have it be immutable. More modern dynamic languages often use strings in some way that requires that they be immutable (it may not be a String, but it is immutable).

Conclusion

These design considerations have been made again and again in a multitude of languages.  It is the general consensus that immutable strings, for all of their awkwardness, are better than the alternatives and lead to better code (fewer bugs) and faster executables overall.


问:
Will B-Trees and Other Data Structures Become Obsolete With The Advent of Solid State Drives?
Many (perhaps most?) database applications today use B-Trees and variations to store data, because this data structure optimizes the read, write and seek operations on a hard disk (and these operations in turn play an important role in the overall efficiency of the databases).

Should Solid State Drives (SSDs) completely outplace traditional hard disks (HDDs), though, could we say that B-Trees and variations will become obsolete, giving room for data structures that are more efficient operating on direct access memory? If so, what will those structures be? (e.g., hash tables, AVL trees)

答:
A priori, yes, most database engines will have to be rewritten since the B-Tree will no longer be the most efficient data structure to store data, given that locality is all important in a hard drive where the disk moves slowly and data is fetched in blocks, meaning that any change to the data needs to:

Move the head to the right location on disk (~10ms).

Wait for the disk to rotate (at 10k rpm, that means 167 rotations per second, but on average we only wait for half a rotation, so ~3ms).

Read the block (~3ms).

Modify in RAM. (~10ns)

Move the head to the right location on disk again (~10ms again).

Wait for the disk to rotate again (~3ms again).

Write the block (~3ms).

That's 10+3+3+10+3+3 = 34 ms

On average, doing the same on an SSD is only 1ms, regardless of the position on the disk.

And since a hashtable is far faster, we could think a hashtable would be a better replacement.

The only problem is that hashtables are not order preserving and therefore it is not possible to find next and previous like  Van Emde Boas does.

See:

http://en.wikipedia.org/wiki/Van_Emde_Boas_tree

http://bryanpendleton.blogspot.com/2009/06/cache-oblivious-data-structures.html

Why find next and previous is important? Imagine getting all elements larger than x and smaller than z, you need to use indexes with find previous and find next.

Well, the only problem is that we haven't found hashtables with order preserving abilities. Maybe the size of the bucket in the B-tree will be important but that gets resolved with cache oblivious algorithms.

So I would say this is an open ended problem.


问:
Is There Any Benefit to Learning Machine Code?
I mostly work in Python and Ruby, but I recently decided to learn some C so I have a better feel for how a computer actually works.

I've been wondering whether it is possible to take this even a step further. Does anyone learn machine code (whatever C is compiled into) anymore? Would I benefit from taking some time to learn it?

答:
Probably not.

There is an argument that knowing machine code will help you understand what the machine is doing in more detail. But so would knowing how the transistors work and nobody suggests you need to know semiconductor physics to be a good programmer!

Having some idea what the code is doing and what operations, such as copying memory or accessing a disk, are expensive is useful - but you can know these without being fluent in assembler. There was also an argument that assembler helps you debug a stack dump - but modern compilers can produce some very odd optomised code which is almost impossible to understand/.

If you want to understand assembler for the pure joy of it - then there are a number of synthetic assemblers, or at least more modern CPU designs which are cleaner than x86


问:
Where can I get free public raw data?
In web development, a mashup is a web page or application that uses and combines data, presentation or functionality from two or more sources to create new services.

There are many sources for getting data (raw information). Governments are good examples.

However many of those cost and have complicated licensing.
For instance SMHI in Sweden sells temperature data meanwhile our neighbor country Norway gives it away for free.

One would say what kind of application are you building and what data do you need?  I would say give me some interesting data and I will do a good mashup of it. I could just plot it on Google maps for instance.

So the question is: Where can I get free data?

Note: I'm not interested in data mining using a webcrawler!

Please share your sources with me.

答:
Calgary Public Data Catalogue has some stuff from the city of Calgary, Alberta, Canada that is freely available.

Open Data and Internet Democracy Tools workshop was an event held in Calgary last Saturday about using this data, just as something to disclose.

Title: Where can I get free public raw data?


答:
I learned it, but that was back in the days when Real Programmers Wore Mountain Boots.

Learning assembly will give you a wonderful appreciation for memory management, pointers, buffer overflows, caffeine, and the value of extreme patience.

My personal opinion is that it's worth writing a small test program or two, but not much more than that.

It takes a tremendous amount of effort to code features that are almost trivial to do in modern environments. (e.g., text to speech)

Title: Is There Any Benefit to Learning Machine Code?

Body:
I mostly work in Python and Ruby, but I recently decided to learn some C so I have a better feel for how a computer actually works.

I've been wondering whether it is possible to take this even a step further. Does anyone learn machine code (whatever C is compiled into) anymore? Would I benefit from taking some time to learn it?


问:
Is a lambda expression something more than an anonymous inner class with a single method?
There is a new hype with the long awaited lambda expressions in Java 8; every 3 day another article appears with them about how cool they are.

As far as I have understood a lambda expression is nothing more than an anonymous inner class with a single method (at least at the byte-code level). Besides this it comes with another nice feature - type inference but I believe the equivalent of this can be achieved with generics on some level (of course not in such a neat way as with lambda expressions).

Knowing this, are lambda expressions going to bring something more than just a syntactic sugaring in Java? Can I create more powerful and flexible classes or other object-oriented constructs with lambda expressions that aren't possible to be built with current language features?

答: Yes, it is just a syntactic sugar, in the sense that anywhere you write a lambda, you can re-write that expression as an anonymous inner class expression with one method, where the class implements the functional interface inferred for the lambda's context, and it would be exactly equivalent semantically. And you can do this by simply replacing the lambda expression with the anonymous class expression, without changing any other expression or line of code.


问:
What is LPCTSTR?
what is LPCTSTR and LPCTSTR-like (for instance HDC) and what it does stand for?

答:
There's no need to ever use any of the types relating to TCHAR.

Those types, all structure types that use them, and all related functions are mapped at compile time to an ANSI or UNICODE version (based on your project's configuration). ANSI versions typically have an A appended to the end of the name, and unicode versions append a W. You can use these explicitly if you prefer. MSDN will note this when necessary, for example it lists a MessageBoxIndirectA and MessageBoxIndirectW function here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms645511(v=vs.85).aspx

Unless you are targeting Windows 9x, which lacked implementations of many unicode functions, there's no need to use the ANSI versions. If you are targeting Windows 9x, you can use TCHAR to build an ansi and unicode binary from the same codebase, as long as your code makes no assumptions about whether TCHAR is a char or wchar.

If you don't care about Windows 9x, I recommend configuring your project as unicode and treating TCHAR as identical to WCHAR. You can explicitly use the W functions and types if you prefer, but as long as you don't plan to run your project on Windows 9x, it doesn't really matter.

Title: What is LPCTSTR?


问:
How can I say that programming language compiles to other languages?
How can I say in english, that programming language can be compiled to other programming languages?

The example can be Haxe. On the website the language is decribed as "Multiplatform":

Multiplatform:
  Haxe can be compiled to all popular programming platforms with its
  fast compiler – JavaScript, Flash, NekoVM, PHP, C++, C# and Java
  (soon)

but multiplatform can be misunderstood as hardware or software platforms (win, mac, linux).

So what is the most suitable word describing this ability?

答:
I would say that compiler by definition translate into different programming language (at least this is definition I know - program that transforms one language into another). For example most C compilers produce assembly as output. Assembly compilers takes this output and transforms it into the binary code which is also a language (sure - probably no one writes writes in it during past 40 years or more but technically it is language) - which can be taken and recompiled to say micro-ops by processors (or there are certain operations done by linker on object files). Similarly the javap compiles into bytecode. Usually at the end of such chain there is interpreter which executes the final code (be it CPU, GPU or executed program). There is 'no such thing' as machine code as modern x86 recompiles the programs into internal operations (micro-ops) and I'm perfectly capable of treating ARM machine code as interpreted language on x86 or other way round (in some cases even recompile from one form to another).

Haxe is source-to-source compiler as it does not transforms the higher-level language into lower level one as the previous examples. It doesn't seem to address directly your problem of multi-platform ambiguity but unfortunately I don't think there is practical way of differentiation between those two things - the APIs are kind of languages which can be in general interpreted, recompiled etc.


问:
Should I Do Calculations in T-SQL or Program?
I am creating a stored procedure that is logging some data. The data ultimately needs to end up in 2 tables. The incoming data is coming from a JSON string containing 15 parameters, and the data is then logged to the database using the stored procedure I'm writing. I would like to send the data into 1 stored procedure and INSERT it into both tables.

The first table is a raw data logging table. It will be used for debug and troubleshooting.

The second table will be used for report generation. This table requires some simple mathematical calculations to be done on incoming data. For example:

DECLARE @Table2Fld3 DECIMAL = @IncomingFld9 - @IncomingFld4;

I'll have about 8 of these calculations to do to compute the values for table 2, then I'll do an INSERT to save the data.

So my question is, is it a good practice to do these calculations in the T-SQL? Or would it be better for me to create 2 separate stored procedures and do the calculations in my code?

One trade-off I see is that if I do it all in the code then I have to create 2 database connections.

EDIT

I should elaborate on the "2 database connections" comment. The application in question is a windows service that establishes multi-threaded server/client communication. The logging system is asynchronous to the server/client communication. Using that existing system, in order for me to target multiple stored procedures, it would require 2 calls to the logger which would spin up 2 connections to the database.

答:
I prefer to keep as much of the logic outside the database as possible. So that if the way calculations are done gets changes, I only need to update the code in the program and not mess around with the stored procedures.

I'm not sure how complex these calculations are, but if they do become a bottleneck you can always move them somewhere else.


答: You can say that a compiler has languages X, Y, and Z as translation targets, or design a language with those targets in mind.


问:
How can I justify a technology over another? (Java over .NET)
We are working in a Java/.NET company and my team and I are planning a project for a client.

One of the requirements is that the project has to be done in .NET

I've asked about this requirement, and the client said that it doesn't matter, and that if I have a good reason we can use other technology. But, I have to justify the decision.

As a Project Manager / Analyst I'm interested in making the project in Java because:

The team knows java much better, regarding the language and frameworks

I don't know anything about .NET technology (and maybe we could make bad decisions thinking in a Java way to do things)

There are other people in company that have more skills in .NET but they have other projects with more priority.

For experience, I'm sure that if we use Java, the project will have much more quality. But this arguments could be weak from the client perspective.

How can I justify making the project in Java?

EDIT: I'm not asking if one technology is better than other. "It's not a technology war" question.

答: I am surprised no one has mentioned the cost. .net is going to cost client more for maintaining and buying the framework while Java is Free and platform independent. How much you argue - at the end JVM ships free with every OS and CLR does not. </p>


问:
Class table inheritance... To 'type' or not to 'type'
I currently have a database that uses Class table inheritance model. Three different tables inherit from this table. The child tables have all a FK to the parent table and the fields are properly indexed.

We hare currently having some issues at the application level because it is difficult to figure out what child table we are referencing from the parent. In addition to this, a query where we organize by type seems costly.

One developer argues that we should just join with all 3 tables to figure out what child the parent record corresponds to, and as long as the tables have the proper index queries shouldn't be costly.

In the other hand we could avoid a lot of confusion and problems if we add a discriminator field in the parent table, that way we would know without having to do any joins the 'type' of record we are dealing with. Also grouping by type would be much simpler.

Should we add a type in the parent table?

What would be the disadvantages?

Is it really not costly to join with multiple tables (as long as they
are properly indexed) compared to having a discriminator field?

Other thoughts?

We are currently using an implementation of active record for PHP, and it doesn't support Class Table Inheritance.

答:
I see these advantages of using a type in the base table:

You'll know exactly which other tables to read.

You'll know directly which concrete class to instantiate when hydrating.

You know what type of data you have just by looking at the parent table row.

And this disadvantage:

If you retrieve the instance via the application, you'll have to issue two queries: one to retrieve the base table data, and another to retrieve the children data given the found type. (This can be alleviated by using a stored procedure that encapsulates that logic.)

On the other hand, I don't think that a three-table join should be a problem, but remember that they need to be outer joins if you're not using a discriminator type in the parent table. You simply don't know what type of data you're looking at. But, as usual, profile accordingly.


问:
How does dependency inversion principle work in languages without interfaces?
In C#/Java, the dependency inversion principle is often demonstrated by high-level classes that depends on an interface/abstraction (that it owns). Low-level classes will implement the interface, thus inverting the dependency.

I wonder, how is it applied in object-oriented languages with no interface? For example, I'm not an expert in Ruby, but it seems that in this language you can't define interfaces like in Java/.NET

答:
Even though you don't have explicit interfaces in dynamic languages, the dependency inversion principle can be followed by writing the client code against an abstract representation of the dependency, which the concrete "implementers" will adhere to via duck typing.

In a sense, that's the default in a dynamic language, and it could be argued that the dependency inversion principle is followed without any conscious effort. But, in practice it's worthwhile to consider the abstract representation of your concrete classes, to gain more insight into the domain, and to decouple from any implementation details that don't capture the essence of the abstraction.


问:
What does it mean to perform an operation "In Place" for Interpreted Languages?
Programming question:

Reverse words in a string (words are separated by one or more spaces).
  Now do it in-place.

What does "in-place" mean in the above context for an interpreted language like PHP or JavaScript?

答:
It depends on how low-level the language you're working with is, but assuming something like C it means "do not take the string apart and put it back together in a different part of memory, modify the part of memory the string is already in".

I.e. not:

```<code>1. foo bar baz
2. foo bar baz -> baz
3. foo bar baz -> baz bar
4. foo bar baz -> baz bar foo
</code>```

but:

```<code>1. foo bar baz
2. baz foo bar
3. baz bar foo
</code>```

(Or however exactly your algorithm will work.)

Body:
It depends on how low-level the language you're working with is, but assuming something like C it means "do not take the string apart and put it back together in a different part of memory, modify the part of memory the string is already in".

I.e. not:

1. foo bar baz
2. foo bar baz -> baz
3. foo bar baz -> baz bar
4. foo bar baz -> baz bar foo

but:

1. foo bar baz
2. baz foo bar
3. baz bar foo

(Or however exactly your algorithm will work.)


问:
Design patterns: Extract instance types into different buckets
I have the following type hierarchy:

```<code>interface I:
    ----+class B implements I
    ----+class C implements I
    ----+class D implements I
</code>```

I have another class Consumer1 that supports types C and D but not B (in its various methods) and a class Consumer2 that supports type B. I have total control over Consumer1 and Consumer2 so I can choose how to implement them. Now, at runtime I expect my callers to give me a collection of Is and I will decide internally whether to route them to Consumer1 or Consumer2.

Now, a very bad non-OOP way is to do an if instanceof check all over the place and mess things up. One alternative is to register a supporting class Map<Class<?>, Class<?>> that shall contain {{B,Consumer2}, {C,Consumer1}, {D,Consumer1}}. This is as bad as the previous one because I shall have to cast objects after figuring out whether to send them to Consumer1 or Consumer2.

A second alternative is to apply a Visitor pattern which would solve this rather neatly but prevent my interface from being extended further (unless I modify the visitor). Is there a neater alternative?

答:
Consider the acyclic visitor pattern. It allows extensions to the hierarchy without necessarily impacting all the visitors (only the ones that need to visit all objects, which don't seem to be present in your design).

Alternatively, I think it's not a problem to have the type checks in the consumer themselves, since they'll be concerned with checking only the types that they work with (not that different from the acyclic visitors). Then you could either dispatch the Is to all consumers and only the ones that really care about the runtime type will do anything with them, or you could do it in a chain of responsibility style, as already suggested in the comments by John Cartwright.


答:
It normally means to perform the operation without using any additional memory. In terms of space complexity, the auxiliary space complexity would be O(1).

In practice, depending on implementation, temporary variables may be allowed. In this case the output should use same location in memory as the input.

Title: What does it mean to perform an operation "In Place" for Interpreted Languages?

Body:
Programming question:

Reverse words in a string (words are separated by one or more spaces).
  Now do it in-place.

What does "in-place" mean in the above context for an interpreted language like PHP or JavaScript?


答:
In this context, it refers to modifying the original variable, as opposed to using further memory.  This means that, as opposed to running through the original string and copying each character to a new string variable, you need to swap pieces of the original as you are viewing it.

Wikipedia actually has an entire article on the topic, citing the topic's relevance and usefulness relating to minimizing memory usage.


问:
Are animations and other eye candies considered non-functional requirements?
I've seen many lists on the internet that includes many 'ities' (maintainability, scalability, portability, etc), but I'm not sure if animations, screen transitions, and similar features are functional or non functional requirements.</p>

答:
Animations can be an extremely important part of the user interface. They communicate or hint at things a user can do, guide the user through the application or help build up a well defined mental model of the application inside the user's head. Consider the classic iPod interface, where screens slid from side to side to signify the navigation through a hierarchy.

Nothing communicated this better than an animation, which helped build a mental model of the navigation tree which greatly improved usability. Imagine the same interface without animations, where screens would simply change without transition; it'd be much harder to understand intuitively. Since I'd consider a good UI to be pretty essential to an application (depending on the kind of application obviously), animations are not just "eye candy", they're part of usability.

If you just throw animations on top of a general GUI with no clear purpose, they're pretty superfluous of course.

Having said this, usability is typically considered a non-functional requirement.


问:
Proper name for a project supports 2 different release
Is there a technical name for a software project where the current and prior stable releases are both maintained?</p>

答:
The general terminology for releases (see Release Management Done Right) are:

Active - describes a release that's currently in development (unreleased)

Latest - the "highest" release available

Previous - anything other than the Latest Release

So, 4.0 is the latest, while 3.0 and 3.1 are previous. Most software has a linear release pattern (this is significantly easier to maintain obviously): 3.0 first, then 3.1, then 4.0.

The non-linear pattern you describe (3.0 first, then 4.0, then 3.1) is called  Previous Release Support. In this case, 4.0 remains the Latest release, even though 3.1 shipped after as a fix for 3.0 users.

Microsoft follows this pattern (Windows XP, a previous release is continually supported), whereas Apple (I believe), does not - you always have to upgrade to latest.


答:
I prefer to keep plenty (not all, but plenty) of the logic in the database for just a ton of reasons (and without getting into the whole "who needs stored procedures nowadays" argument).

Do this in your stored procedure.

These look like simple computations.  Also use a transaction in your sproc to manage the writes to both tables, unless it is okay if your database becomes inconsistent (sometimes the write might succeed in one table, but not the other).  And don't listen to the guys who try to tell you that "real programmers write their own rollback code," because that's just silly.  :-) The only reliable rollback code is the rollback code inside the database engine itself, and it's easy to use.

If you do these calculations in your imperative code outside the database and use two stored procedures to write the data, you still have to consider utilizing a database transaction unless it is okay for your database to become inconsistent.  So now (if you do this outside the database) all of a sudden you're up to at least 4 round-trip calls to the database instead of 1:

Begin TX

Write table 1

Write table 2

Commit TX

If the writes are small, it is entirely possible that you'll have more overhead in the network round trips than in the actual work done by the database.  Even though you can use the same connection to call both stored procedures (must, if you use a transaction), you still have to make multiple, separate calls to the database server across the network.

Finally, if the logic of the calculations changes, and you're doing those calculations in your code outside the database, then you have to change that code, recompile it and redeploy the updated program.  But if you have those calculations in your stored procedure, you can rebuild that one stored procedure without having to redeploy (re-install?) your entire application.

All of these points are exacerbated if we're talking about a thick client desktop app--which you did not specify--because that means you have to re-install the updated app on every workstation, and while you have it installed on some workstations but not on others, you have different workstations doing different things to your database.  Also, depending on your source control and build practices, you could be looking at a major operation to go back in time and branch your repository to make some changes in your data access layer, not to mention the potential work involved in merging the changes in the branch forward into the DAL in your main source line.

Do this in the stored procedure, because that is honestly the right place to do it.

Title: Should I Do Calculations in T-SQL or Program?

Body:
I am creating a stored procedure that is logging some data. The data ultimately needs to end up in 2 tables. The incoming data is coming from a JSON string containing 15 parameters, and the data is then logged to the database using the stored procedure I'm writing. I would like to send the data into 1 stored procedure and INSERT it into both tables.

The first table is a raw data logging table. It will be used for debug and troubleshooting.

The second table will be used for report generation. This table requires some simple mathematical calculations to be done on incoming data. For example:

DECLARE @Table2Fld3 DECIMAL = @IncomingFld9 - @IncomingFld4;

I'll have about 8 of these calculations to do to compute the values for table 2, then I'll do an INSERT to save the data.

So my question is, is it a good practice to do these calculations in the T-SQL? Or would it be better for me to create 2 separate stored procedures and do the calculations in my code?

One trade-off I see is that if I do it all in the code then I have to create 2 database connections.

EDIT

I should elaborate on the "2 database connections" comment. The application in question is a windows service that establishes multi-threaded server/client communication. The logging system is asynchronous to the server/client communication. Using that existing system, in order for me to target multiple stored procedures, it would require 2 calls to the logger which would spin up 2 connections to the database.