答:
The concept you are describing is configuration management.  This is as it sounds, a way to identify, record, version/track, and report an environment.  It is often a task that is strongly related to version control and build management, but it is distinct enough that often requires a separate strategy, even if it uses some of the same concepts and same processing and storage mechanisms.

Configuration management besides helping keep a working environment under control also helps establish a record of the different working environments in which software is used (development as mentioned, plus testing/QA, deployment to routine customers, deployment to customers that require special consideration or special configuration or build properties, and so on).

As I said, often this is a task that coincides with source version control, and often configuration management data resides next to source in both documentation and the source repository.  It doesn't have to be, but often is as a matter of convenience.

Automation of some aspects of configuration management has largely improved in recent years.  Some answers and comments suggested scripts as a way to promote configuration management, and scripts are a good answer to help achieve reproducible results, but often times hand crafted scripts by themselves are inconsistent and incomplete.  One such way this has improved is through automatic provisioning.  Systems like puppet or chef help specify software components and systems for a particular user or machine or for a particular task profile and provide 'recipes' that allow a hands off approach to setting up a complete machine or environment.  It basically takes the concept of a software distribution repository and extends and generalizes it providing not only the packages of software needed for a system, but also configuration profiles particular to each package so that it is ready to use in the way that is appropriate to your situation.

Vagrant takes this in a slightly different direction and provides a way to quickly spin up virtual machines definitions, such that a VM can have its virtual software and hardware provisioned automatically, and can prove to be a convenient way to reproduce a particular representation of a hardware environment used by user of your software.

Each system (and variations) takes a bit to get set up, but has some clear value if you find the task of reloading and reconfiguring to be a common task.


问:
Loose Coupling in Object Oriented Design
I am trying to learn GRASP and I found this explained (here on page 3) about Low Coupling and I was very surprised when I found this:

Consider the method addTrack for an Album class, two possible methods are:

addTrack( Track t )

and

addTrack( int no, String title, double duration )

Which method reduces coupling?
  The second one does, since the class using the Album class does not have to know a Track class.
  In general, parameters to methods should use base types (int, char ...) and classes from the java.* packages.

I tend to diasgree with this; I believe addTrack(Track t) is better than addTrack(int no, String title, double duration) due to various reasons:

It is always better for a method to as fewer parameters as possible (according to Uncle Bob's Clean Code none or one preferably, 2 in some cases and 3 in special cases; more than 3 needs refactoring - these are of course recommendations not holly rules).

If addTrack is a method of an interface, and the requirements need that a Track should have more information (say year or genre) then the interface needs to be changed and so that the method should supports another parameter.

Encapsulation is broke; if addTrack is in an interface, then it should not know the internals of the Track.

It is actually more coupled in the second way, with many parameters. Suppose the no parameter needs to be changed from int to long because there are more than MAX_INT tracks (or for whatever reason); then both the Track and the method need to be changed while if the method would be addTrack(Track track) only the Track would be changed.

All the 4 arguments are actually connected with each other, and some of them are consequences from others.

Which approach is better?

答:
Both are correct

```<code>addTrack( Track t )
</code>```

is better (as you already argumented) while

```<code>addTrack( int no, String title, double duration )
</code>```

is less coupled because the code that uses addTrack does not need to know that there is a Track class. Track can be renamed for example without the need to update the calling code.

While you are talking about more readable/maintainable code the article is talking about coupling.
Less coupled code is not necessarily easier to implement and to understand.

ContentLicense: CC BY-SA 3.0

Body:
Both are correct

addTrack( Track t )

is better (as you already argumented) while

addTrack( int no, String title, double duration )

is less coupled because the code that uses addTrack does not need to know that there is a Track class. Track can be renamed for example without the need to update the calling code.

While you are talking about more readable/maintainable code the article is talking about coupling.
Less coupled code is not necessarily easier to implement and to understand.


答:
Low Coupling doesn't mean No Coupling. Something, somewhere, has to know about objects elsewhere in the codebase, and the more you reduce dependence on "custom" objects, the more reasons you give for code to change. What the author you cite is promoting with the second function is less coupled, but also less object-oriented, which is contrary to the entire idea of GRASP as being an object-oriented design methodology. The whole point is how to design the system as a collection of objects and their interactions; avoiding them is like teaching you how to drive a car by saying you should ride a bike instead.

Instead, the proper avenue is to reduce dependence on concrete objects, which is the theory of "loose coupling". The fewer definite concrete types a method has to have knowledge of, the better. Just by that statement, the first option is actually less coupled, because the second method taking the simpler types must know about all of those simpler types. Sure they're built-in, and the code inside the method may have to care, but the signature of the method and the method's callers most definitely do not. Changing one of these parameters relating to a conceptual audio track is going to require more changes when they're separate versus when they're contained in a Track object (which is the point of objects; encapsulation).

Going one step further, if Track were expected to be replaced with something that did the same job better, perhaps an interface defining the requisite functionality would be in order, an ITrack. That could allow for differing implementations such as "AnalogTrack", "CdTrack" and "Mp3Track" that provided additional information more specific to those formats, while still providing the basic data exposure of ITrack that conceptually represents a "track"; a finite sub-piece of audio. Track could similarly be an abstract base class, but this requires you to always want to use the implementation inherent in Track; reimplement it as BetterTrack and now you have to change out the expected parameters.

Thus the golden rule; programs and their code components will always have reasons to change. You can't write a program that will never require editing code you've already written in order to add something new or modify its behavior. Your goal, in any methodology (GRASP, SOLID, any other acronym or buzzword you can think of) is simply to identify the things that will have to change over time, and design the system so that those changes are as easy to make as possible (translated; touching as few lines of code and affecting as few other areas of the system beyond the scope of your intended change as possible). Case in point, what's most likely to change is that a Track will gain more data members that addTrack() may or may not care about, not that Track will be replaced with BetterTrack.

Title: Loose Coupling in Object Oriented Design

Body:
I am trying to learn GRASP and I found this explained (here on page 3) about Low Coupling and I was very surprised when I found this:

Consider the method addTrack for an Album class, two possible methods are:

addTrack( Track t )

and

addTrack( int no, String title, double duration )

Which method reduces coupling?
  The second one does, since the class using the Album class does not have to know a Track class.
  In general, parameters to methods should use base types (int, char ...) and classes from the java.* packages.

I tend to diasgree with this; I believe addTrack(Track t) is better than addTrack(int no, String title, double duration) due to various reasons:

It is always better for a method to as fewer parameters as possible (according to Uncle Bob's Clean Code none or one preferably, 2 in some cases and 3 in special cases; more than 3 needs refactoring - these are of course recommendations not holly rules).

If addTrack is a method of an interface, and the requirements need that a Track should have more information (say year or genre) then the interface needs to be changed and so that the method should supports another parameter.

Encapsulation is broke; if addTrack is in an interface, then it should not know the internals of the Track.

It is actually more coupled in the second way, with many parameters. Suppose the no parameter needs to be changed from int to long because there are more than MAX_INT tracks (or for whatever reason); then both the Track and the method need to be changed while if the method would be addTrack(Track track) only the Track would be changed.

All the 4 arguments are actually connected with each other, and some of them are consequences from others.

Which approach is better?


问:
Secure an Application/Software by expiration with Date?
I have been working on some software application and I update them every 6 months. Currently, the way I track the date is by extracting the date from the system when the user installs the application, encrypt it and store it in a file locally. Whenever the application is started, it checks if 6 months have passed, then it works or it doesn't, in which case it shows an error message telling the user to update.

If the user finds the encrypted date in the file they can simply replace it with one from a more recent install. I am wondering if there's a more secure way to do this?

答:
You could do something like @Uwe describes, but have the file contain an encrypted string. The string will contain, as part of its value, the install date (or expiration date) and ... other stuff.  What the other stuff is doesn't really matter unless you want other validations.

We do something similar but store the value in our app's database. Our encrypted string contains the app revision number, the "number of days from -base base- until license expires", and a few other things. On startup, we decrypt the string and calculate the number of days from -base date- until today. If the number is > than the encrypted value, they get a license warning. If the number is more than 30 days past warning date, they get a message and the app closes.

If the file (string) doesn't exist, the app doesn't start. If they dink the string and the decrypted value doesn't match the "mask" we use to parse it, the app doesn't start.

It's not foolproof for someone determined to beat it, but it serves our purpose of "secure enough".


答:
Well, your first three points are actually about other principles than coupling.  You always have to strike a balance between oft-conflicting design principles.

Your fourth point is about coupling, and I strongly agree with you.  Coupling is about the flow of data between modules.  The type of the container that data flows in is largely immaterial.  Passing a duration as a double instead of as a field of a Track doesn't obviate the need to pass it.  The modules still need to share the same amount of data, and still have the same amount of coupling.

He is also failing to consider all the coupling in the system as an aggregate.  While introducing a Track class admittedly adds another dependency between two individual modules, it can significantly reduce the coupling of the system, which is the important measure here.

For example, consider an "Add to Playlist" button and a Playlist object.  Introducing a Track object could be considered to increase coupling if you only consider those two objects.  You now have three interdependent classes instead of two.  However, that is not the entirety of your system.  You also need to import the track, play the track, display the track, etc.  Adding one more class to that mix is negligible.

Now consider needing to add support for playing tracks over the network instead of just locally.  You just need to create a NetworkTrack object that conforms to the same interface.  Without the Track object, you would have to create functions everywhere like:

```<code>addNetworkTrack(int no, string title, double duration, URL location)
</code>```

That effectively doubles your coupling, requiring even modules that don't care about the network-specific stuff to nevertheless still keep track of it, in order to be able to pass it on.

Your ripple effect test is a good one to determine your true amount of coupling.  What we are concerned with is limiting the places a change affects.

Body:
Well, your first three points are actually about other principles than coupling.  You always have to strike a balance between oft-conflicting design principles.

Your fourth point is about coupling, and I strongly agree with you.  Coupling is about the flow of data between modules.  The type of the container that data flows in is largely immaterial.  Passing a duration as a double instead of as a field of a Track doesn't obviate the need to pass it.  The modules still need to share the same amount of data, and still have the same amount of coupling.

He is also failing to consider all the coupling in the system as an aggregate.  While introducing a Track class admittedly adds another dependency between two individual modules, it can significantly reduce the coupling of the system, which is the important measure here.

For example, consider an "Add to Playlist" button and a Playlist object.  Introducing a Track object could be considered to increase coupling if you only consider those two objects.  You now have three interdependent classes instead of two.  However, that is not the entirety of your system.  You also need to import the track, play the track, display the track, etc.  Adding one more class to that mix is negligible.

Now consider needing to add support for playing tracks over the network instead of just locally.  You just need to create a NetworkTrack object that conforms to the same interface.  Without the Track object, you would have to create functions everywhere like:

addNetworkTrack(int no, string title, double duration, URL location)

That effectively doubles your coupling, requiring even modules that don't care about the network-specific stuff to nevertheless still keep track of it, in order to be able to pass it on.

Your ripple effect test is a good one to determine your true amount of coupling.  What we are concerned with is limiting the places a change affects.


问:
VPS versus Shared Hosting
Is there any compelling reason a programmer would host on a shared platform versus just having a VPS account somewhere?</p>

答:
A Shared platform frees you from responsibility for the OS.  not having to apply OS patches, not having to pay for software licences for the installed software, anti-virus, firewalls, backups are all your providers responsibility.

Now the flip side to this is that living on a shared server means your use of the server has to be compatible with the other hosted sites on that server.  You cannot be using major CPU cycles, large numbers of simultaneous users. etc.

You can go for a virtual private server, but I would be asking questions about what it was you were actually getting for your money. A virtual machine might believe it has 2 fast CPU's, lots of memory and plenty of I/O bandwidth to the disks, but if they are running 20 VM's on the one server, all of these resources are going to be compromised. insist on acceptable performance guarantees.

For that serious product, nothing beats dedicated servers.  Even if you run VMWare on it and host your own virtual server farm.  At least you know you have the hardware resourced available that you have paid for. you have the control you want.  You just need the expertise to manage the servers when they are in an Internet exposed position.

ContentLicense: CC BY-SA 2.5

Title: VPS versus Shared Hosting


问:
API design and versioning using EJB
I have an API that is EJB based (i.e. there are remote interfaces defined) that most of the clients use.  As the client base grows there are issues with updates to the API and forcing clients to have to update to the latest version and interface definition.

I would like to possibly look at having a couple versions of the API deployed at a time (i.e. have multiple EAR files deployed with different versions of the API) to support not forcing the clients to update as frequently.  I am not concerned about the actual deployment of this, but instead am looking for thoughts and experiences that others have on using EJB's as an API client.

How do you support updating versions, are clients required to update?

Does anyone run multiple versions in a production environment?  Are there pro's cons?

Any other experiences or thoughts on this approach, and having an EJB centric API?

答:
One way to do this is to add a Map<String, Object> addendum to all your EJB interfaces input and output before releasing it. For example:

Your interface:

```<code>interface UserService {
    GetUserResponse getUserResponse(GetUserRequest request);
    ...
}
</code>```

Your method parameter and return object:

```<code>class GetUserResponse {
     ...
     public Map<String, Object> addendum;
}

class GetUserRequest {
    ...
    public Map<String, Object> addendum;
}
</code>```

However, this is a double-edge sword.

While this will allow you to add to your implementation without changing the interface, it is very easily to fall into the trap of delaying the re-factoring of the interface.

Title: API design and versioning using EJB

Body:
One way to do this is to add a Map<String, Object> addendum to all your EJB interfaces input and output before releasing it. For example:

Your interface:

interface UserService {
    GetUserResponse getUserResponse(GetUserRequest request);
    ...
}

Your method parameter and return object:

class GetUserResponse {
     ...
     public Map<String, Object> addendum;
}

class GetUserRequest {
    ...
    public Map<String, Object> addendum;
}

However, this is a double-edge sword.

While this will allow you to add to your implementation without changing the interface, it is very easily to fall into the trap of delaying the re-factoring of the interface.


问:
what's a good approach to working with multiple databases?
I'm working on a project that has its own database call it InternalDb, but also it queries two other databases, call them ExternalDb1 and ExternalDb2.  Both ExternalDb1 and ExternalDb2 are actually required by a few other projects.  I'm wondering what the best approach for dealing with this is?

Currently, I've just created a project for each of these external databases and then generated Edmx and entities using the entity-framework approach.  My thought was that I could then include these projects in any of my solutions that require access to these databases.  Also, I don't have any separate business layers. I just have a solution like below:

```<code>Project.Domain
ExternalDb1Project.Domain
ExternalDb2Project.Domain
Project.Web
</code>```

So my Domain projects contain the data access as well as the POCOs generated by Entity Framework and any business logic.  But I'm not sure if this is a good approach.  For example if I want to do Validation in my Project.Domain on the entities in the InternalDb, it's fine.  But if I want to do Validation for entities from either of the ExternalDbs, then I wonder where it should go?  To be more specific, I retrieve Employees from ExternalDb1Project.Domain.  However, I want to make sure they are Active.  Where should this Validation go?

How to architect a project like this at a high level?  Also, I want to make sure that I use IoC for my data contexts so I can create Fakes when writing tests.  I wonder where the interfaces for these various data contexts would reside?

答:
if I want to do Validation for entities from either of the ExternalDbs, then I wonder where it should go. To be more specific, I retrieve Employees from ExternalDb1Project.Domain. However, I want to make sure they are Active. Where should this Validation go?

Depends on whether you need the same validation from any other project that accesses the same database and model. If so, you could just create an ExternalDb1Project.Domain.MetaData project to contain metadata and validation.

When not required ever by other projects, because "Active" means a totally different thing to your application than to another application accessing the same database, you could stick it under your project like Project.ExternalDb1Project.MetaData.


问:
Named output parameters vs return values
Which code is better:

```<code>// C++
void handle_message(...some input parameters..., bool& wasHandled)
void set_some_value(int newValue, int* oldValue = nullptr)

// C#
void handle_message(...some input parameters..., out bool wasHandled)
void set_some_value(int newValue, out int oldValue)
</code>```

or

```<code>bool handle_message(...some input parameters...) ///< Returns -1 if message was handled
                                                //(sorry, this documentation was broken a year ago and we're too busy to fix it)
int set_some_value(T newValue) // (well, it's obvious what this function returns, so I didn't write any documentation for it)
</code>```

The first one doesn't have any documentation, but it doesn't need it. It's a self-documenting code. Output value clearly says what it means, and it's really hard to make a change like this:

```<code>- void handle_message(Message msg, bool& wasHandled) {
-    wasHandled = false;
-    if (...) { wasHandled = true; ...
+ void handle_message(Message msg, int& wasHandled) {
+    wasHandled = -1;
+    if (...) { wasHandled = ...;
</code>```

When the code uses return values, it's easy to change them and leave the comments broken:

```<code>  /// Return true if message was handled
- bool handle_message(Message msg) {
+ int handle_message(Message msg) {
...
-     return true;
+     return -1;
</code>```

Most of compilers don't (and can't) check the documentation which is written in comments. Programmers also tend to ignore comments when they edit the code.

So the question is:

if a subroutine has a single output value,

should it be a procedure with well-named self-documenting output parameter,

or should it be a function which returns an unnamed value with a comment describing it?

答:
Your question is

If subroutine has single output value, should it be a procedure with well-named self-documenting output parameter, or should it be a function which returns an unnamed value and have a comment describing it?

and the answer to that is neither (or, perhaps, both).  If you only have a single output value, you should definitely be using functions, not void procedures.  But the function's name should make it trivial to see what the return value is, so it's not an "unnamed" value and it doesn't need a comment.

Your example is called handle_value(Message msg).  This is a bad function name, unless you don't care about the results (although see the last example below).  Compare it to C#'s default for handling events: void btnCreateTransfer_Click - the calling function doesn't care what happens inside this function, so we don't return anything, and the name just says that it does a "click" on "btnCreateTransfer".

Depending on what you want to get back out of your handle_value logic, there's a number of ways you can rename it.

If you just want to check that it is able to be handled (i.e. the message was valid), you can define it as bool is_valid_message(Message msg).  The result is clearly true if it is valid, and false if not.

C#: string.IsNullOrEmpty()

If you just want to know whether it was successfully handled, you can name it bool try_handling_message(Message msg), or bool handled_message(Message msg), or have a coding convention that any bool result from an unclear function is expressly success or failure.

C#: int.TryParse() - this has an out parameter for the value, but the function itself tells you whether it was successful.

If you need more details from your response, you can use int get_message_status(Message msg).  Obviously, you'd need some way to know what the int result meant.  It could have meaning on its own or it could be defined in a constant.

C#: Stream.Read() returns the number of bytes read.

Finally, you can return a custom type - either an enum or an actual class.  The enum works just like the int, except that it conveys meaning of its own so it gives you the most freedom of naming.  The class lets you encapsulate and return as much data as you need.

C#: DialogResult myform.ShowDialog() - ShowDialog() isn't very explicit about what it returns, but because it's a DialogResult value, you know exactly what it is returning.

MessageResult process_message(Message msg) - You process the message and get the result of doing so.  This can also be your original handle_message, but then it would be something like HandledMessageResult handle_message(Message msg).

Good code is self-documenting in that the functions, classes, and variables all explain what they are and what they do.  If you can name an out parameter clearly enough to know what's being returned, you can work that into the name of the function.  And if you can't name your out well and you can't name the function well, then you can still name the type of the return usefully. (see ShowDialog())


问:
Minimizing data sent over a webservice call on expensive connection
I am working on a system that has many remote laptops all connected to the internet through  cellular data connections.

The application will synchronize periodically to a central database. The problem is, due to factors outside our control, the cost to move data across the cellular networks are spectacularly expensive.

Currently the we are sending a compressed XML file across the wire where it is being processed and various things are done with (mainly stuffing it into a database).

My first couple of thoughts were to convert that XML doc to json, just prior to transmission and convert back to XML just after receipt  on the other end, and get some extra compression for free without changing much. Another thought was to test various other compression algorithms to determine the smallest one possible. Although, I am not entirely sure how much difference json vs xml would make once it is compressed.

I thought that their must be resources available that address this problem from an information theory perspective. Does anyone know of any such resources or suggestions on what direction to go in. This developed on the MS .net stack on windows for reference.

答:
The very best compression you get from leaving information out, because information that is not transmitted reduces down to 0 bytes.

As a first step, keep a record of when things were last changed and when the application last synchronized with the database. Then you have your first saving in all those records that didn't change since the last synchronization.

A second step to reduce the amount of data transmitted is to send only the differences during the synchronization, but that will require additional storage to keep a history of how things changed.

After you have minimised the amount of information that needs to be transmitted, then you can start to think about compression with gzip, bzip2, or some similar algorithm.

As a completely unrelated method to keep the costs of the synchronizations down, add an option to your application to trigger a synchronization manually and encourage users to use that option when they have their device connected to a cheap network.


问:
Is it necessary to read every single byte to check if a copied file is identical to the original?
I recently learned of a program called Total Commander. It's a Windows Explorer replacement and has its own stuff to copy files. To check whether the files are identical, instead of calculation a CRC, it literally checks every single byte, one at a time, on both the original and the copy.

My question is: Is this necessary? Can CRC or any other such technique go wrong? Should you, as a programmer, try and implement this perfect but slow system, or is it too extreme?

答:
Is it necessary to read every single byte to check if a copied file is identical to the original?
YES to be 100% sure

Is it necessary to read every single byte to check if a copied file is NOT identical to the original?
NO

Thus, to determine non-identicality quickly, first check metadata like file size and any checksum/CRC or MIME type that the OS/file-system/store might already be maintaining.  Since they are pre-calculated by that system, you don't pay this cost at the time of the comparison.

If that test passes, you still need to compare every byte individually if you need to be 100% certain, BUT NOTE that in modern pipelined CPUs, and using multiple threads and possibly multiple processors/CPUs, doing block comparisons of large files is REALLY fast and efficient because the process is highly parallelizable.  Way faster than ANY kind of mathematical computation involving each byte (though some algorithms are possibly also parallelizable, but perhaps not so easily or so well).  That's because CPUs that are pipelined can do block-comparison operations of memory in microcode or even hardware (really fast) and disk-to-memory subsystems are highly optimized to bringing huge blocks of files to/from memory, all done in parallel and with hardware.   If your application does this sort of thing regularly, and it's a known performance bottleneck, you'd be wise to implement this in well-written multithreaded code that takes advantage of your OS's and hardware's parallelization facilities (perhaps use a language that is designed for this).

Only if you want to process each file once and do multiple comparisons later (where you remember ["cache"] the summarized, or "compressed" [as JohnFX puts it] analysis result), will there be a significant benefit to doing so, and even then, only to prove difference (likely); to prove identicality, you'd still need to do the byte-by-byte comparison.


问:
Can and do compilers convert recursive logic to equivalent non-recursive logic?
I've been learning F# and it's starting to influence how I think when I'm programming C#. To that end, I have been using recursion when I feel the result improves readability and I can't envision it winding out to a stack overflow.

This leads me to ask whether or not compilers could automatically convert recursive functions to an equivalent non-recursive form?

答:
Yes, some languages and complilers will convert recursive logic to non-recursive logic.  This is known as tail call optimization - note that not all recursive calls are tail call optimizible.  In this situation, the compiler recognizes a function of the form:

```<code>int foo(n) {
  ...
  return bar(n);
}
</code>```

Here, the language is able to recognize that the result being returned is the result from another function and change a function call with a new stack frame into a jump.

Realize that the classic factorial method:

```<code>int factorial(n) {
  if(n == 0) return 1;
  if(n == 1) return 1;
  return n * factorial(n - 1);
}
</code>```

is not tail call optimizatable because of the inspection necessary on the return.

To make this tail call optimizeable,

```<code>int _fact(int n, int acc) {
    if(n == 1) return acc;
    return _fact(n - 1, acc * n);
}

int factorial(int n) {
    if(n == 0) return 1;
    return _fact(n, 1);
}
</code>```

Compiling this code with gcc -O2 -S fact.c (the -O2 is necessary to enable the optimization in the compiler, but with more optimizations of -O3 it gets hard for a human to read...)

```<code>_fact:
.LFB0:
        .cfi_startproc
        cmpl    $1, %edi
        movl    %esi, %eax
        je      .L2
        .p2align 4,,10
        .p2align 3
.L4:
        imull   %edi, %eax
        subl    $1, %edi
        cmpl    $1, %edi
        jne     .L4
.L2:
        rep
        ret
        .cfi_endproc
</code>```

One can see in segment .L4, the jne rather than a call (which does a subroutine call with a new stack frame).

Please note this was done with C.  Tail call optimization in java is hard and depends on the JVM implementation -- tail-recursion + java and tail-recursion + optimization are good tag sets to browse.  You may find other JVM languages are able to optimize tail recursion better (try clojure (which requires the recur to tail call optimize), or scala).

Body:
Yes, some languages and complilers will convert recursive logic to non-recursive logic.  This is known as tail call optimization - note that not all recursive calls are tail call optimizible.  In this situation, the compiler recognizes a function of the form:

int foo(n) {
  ...
  return bar(n);
}

Here, the language is able to recognize that the result being returned is the result from another function and change a function call with a new stack frame into a jump.

Realize that the classic factorial method:

int factorial(n) {
  if(n == 0) return 1;
  if(n == 1) return 1;
  return n * factorial(n - 1);
}

is not tail call optimizatable because of the inspection necessary on the return.

To make this tail call optimizeable,

int _fact(int n, int acc) {
    if(n == 1) return acc;
    return _fact(n - 1, acc * n);
}

int factorial(int n) {
    if(n == 0) return 1;
    return _fact(n, 1);
}

Compiling this code with gcc -O2 -S fact.c (the -O2 is necessary to enable the optimization in the compiler, but with more optimizations of -O3 it gets hard for a human to read...)

_fact:
.LFB0:
        .cfi_startproc
        cmpl    $1, %edi
        movl    %esi, %eax
        je      .L2
        .p2align 4,,10
        .p2align 3
.L4:
        imull   %edi, %eax
        subl    $1, %edi
        cmpl    $1, %edi
        jne     .L4
.L2:
        rep
        ret
        .cfi_endproc

One can see in segment .L4, the jne rather than a call (which does a subroutine call with a new stack frame).

Please note this was done with C.  Tail call optimization in java is hard and depends on the JVM implementation -- tail-recursion + java and tail-recursion + optimization are good tag sets to browse.  You may find other JVM languages are able to optimize tail recursion better (try clojure (which requires the recur to tail call optimize), or scala).


答:
Tread carefully.

The answer is yes, but not always, and not all of them. This is a technique that goes by a few different names, but you can find some pretty definitive information here and at wikipedia.

I prefer the name "Tail Call Optimization" but there's others and some people will confuse the term.

That said there are a couple important things to realize:

To optimize a tail call, the tail call requires parameters that are known at the time the call is made. That means  if one of the parameters is a call to the function itself, then it cannot be converted into a loop, because this would require arbitrary nesting of said loop which cannot be expanded at compile time.

C# does not reliably optimize tail calls. The IL has the instruction to do so which the F# compiler will emit, but the C# compiler will emit it inconsistently, and depending on the JIT situation, the JIT may or may not do it at all. All indications are you should not rely on your tail calls being optimized in C#, the risk of overflow in doing so is significant and real

Title: Can and do compilers convert recursive logic to equivalent non-recursive logic?

Body:
I've been learning F# and it's starting to influence how I think when I'm programming C#. To that end, I have been using recursion when I feel the result improves readability and I can't envision it winding out to a stack overflow.

This leads me to ask whether or not compilers could automatically convert recursive functions to an equivalent non-recursive form?


问:
Does Agile (scrum) require one server environment?
Is it necessary/recommend/best practice/any other positive to use only one server environment to perform all development, unit testing and QA?

If so, is it then wise/part of Agile to then have only one staging environment before Live?

Considering that this could mean internationally distributed teams of developers and testers in different time zones is this wise?

This is something being implemented by our QA manager. The opinion put forward is that doing all the dev and testing on a single server is "Agile." The staging environment would be a second environment, and then live.

答:
Agile is:

Individuals and interactions over processes and tools

Working software over comprehensive documentation

Customer collaboration over contract negotiation

Responding to change over following a plan

Set up your development environment to reflect and support these principles.

Scrum is a way to manage your work, not your development environment.


问:
Is Java (still) the cross platform language of choice?
When I started using Java in the nineties, it was all "Write once, run anywhere!" from day one. That was probably all true then and I was a part of the choir as well.

I am not sure what to think about that anymore, considering all the other languages using multi platform runtimes (python, flash, perl, html, php...). But I am still seeing lots of arguments that says you should use Java because it is supposedly better for cross platform development.

So, Is that still true today? Is Java still the language of choice for multi platform development?

Please be specific with focus on cross platform aspects.

I am not asking for general language feature comparisons.

Update: Great responses so far! Most answers seems to be favoring Java or web. Any input from the script crowd?

答:
scripting style languages such as python also make cross platform development easier. Now, whether you like Python (or other such languages) depends on you, and we probably don't need to start that debate here.

Java tries to force you to write code which will run portably, while python allows you to write portable code. The actual python language itself will run portably, but external libraries may or may not. Additionally, python will freely give access to platform specific services.

Does Java an advantage there? I think in either case you can write the portable code with similar ease. That is, you can write code and it will usually work on different platforms. But you cannot get away with just writing code and assuming it will work everywhere. I've worked on a python project which produced version for Windows, Linux, and Mac and we ran into very few cross platform issues. (The only one I remember was due to a bug in the library we were using pygame, which caused drawing issues on Linux. This was fixed by upgrading the version of pygame we used)

Another issue is deployment. If you want to distribute standalone programs that run your code you will have to produce different versions for different platforms. For Java you can distribute one version and assume that the user has Java installed or can install it. In this case Java probably wins in the simplicity of deployment department.

In the end, I think it comes down to what language you like working with and what kind of deployment you need to perform.


问:
What operating systems use both a Render thread and a UI thread?
Microsoft employees commonly describe Windows 8 as having both a Render thread and UI thread.

Typically they say the Render thread performs animations and the UI thread handles most other operations: parsing, layout, applying templates, data binding, input processing, most app callbacks, etc.

Animations can be calculated from beginning to end when they are created. Sometimes the changes to the property being animated don’t affect rest of the objects in a scene. These are called independent animations and they are run on the composition thread instead of the UI thread. This guarantees that they remain smooth because the composition thread is updated at a consistent cadence...

Is this a common architecture or unique to Windows 8? What about Windows Phone 8? Android? iOS?

答: AmigaDOS did, which is why you still find Amigas running small TV station text feeds.</p>

ContentLicense: CC BY-SA 4.0


问:
What's with the aversion to documentation in the industry?
There seems to be an aversion to writing even the most basic documentation. Our project READMEs are relatively bare. There aren't even updated lists of dependencies in the docs.

Is there something I'm unaware of in the industry that makes programmers dislike writing documentation? I can type out paragraphs of docs if needed, so why are others so averse to it?

More importantly, how do I convince them that writing docs will save us time and frustration in the future?

答:
Documentation is not executed as code is. As a result there are often not effective feedback loops to verify that the documentation is in place and is complete. This is the same reason that code comments tend to rot.

Donald Knuth promoted Literate Programming as a way of improving the quality of software, effectively writing the documentation with the code. I've seen a few projects that have used this approach quite effectively.

Personally I try to stick to the modern trend of keeping the public API of your code as readable as possible, and to use unit tests to document usage for other developers. I think this is part of the bigger idea of having your API be of a form that can be explored and discovered. I think this approach is part of what HATEOAS tries to achieve with web services.


问:
What are some techniques I can use to refactor Object Oriented code into Functional code?
I've spent about 20-40 hours developing part of a game using JavaScript and HTML5 canvas.  When I started I had no idea what I was doing.  So it started as a proof of concept and is coming along nicely now, but it has no automated tests.  The game is starting to become complex enough that it could benefit from some automated testing, but it seems tough to do because the code depends on mutating global state.

I'd like to refactor the whole thing using Underscore.js, a functional programming library for JavaScript.  Part of me thinks I should just start from scratch using a Functional Programming style and testing.  But, I think refactoring the imperative code into declarative code might be a better learning experience and a safer way to get to my current state of functionality.

Problem is, I know what I want my code to look like in the end, but I don't know how to turn my current code into it.  I'm hoping some people here could give me some tips a la the Refactoring book and Working Effectively With Legacy Code.

For example, as a first step I'm thinking about "banning" global state.  Take every function that uses a global variable and pass it in as a parameter instead.

Next step may be to "ban" mutation, and to always return a new object.

Any advice would be appreciated.  I've never taken OO code and refactored it into Functional code before.

答:
Having authored several projects in functional style JavaScript, allow me to share my experience. I will focus on high level considerations, not specific implementation concerns. Remember, there are no silver bullets, do what works best for your specific situation.

Pure Functional vs Functional Style

Consider what you want to gain from this functional refactoring. Do you really want a pure functional implementation, or just some of the benefits a functional programming style can bring, such as referential transparency.

I have found the latter approach, what I call functional style, to mesh well with JavaScript and is usually what I want. It also allows selective non functional concepts to be carefully used in code where they make sense.

Writing code in a more purely functional style is also possible in JavaScript, but is not always the most appropriate solution. And Javascript can never be purely functional.

Functional Style Interfaces

In functional style Javascript, the most important consideration is the boundary between functional and the imperative code. Clearly understanding and defining this boundary is essential.

I organize my code around functional style interfaces. These are collections of logic that behave in a functional style, ranging from individual functions to entire modules. The conceptual separation of interface and implementation is important, a functional style interface may be implemented imperatively, as long as the imperative implementation does not leak across the boundary.

Unfortunately in Javascript, the burden of enforcing functional style interfaces falls entirely on the developer. Also, language features, such as exceptions, make a truly clean separation impossible.

Since you will be refactoring an existing codebase, start by identifying existing logical interfaces in your code that can be cleanly moved to a functional style. A surprising amount of code may already be functional style. Good starting points are small interfaces with few imperative dependencies. Everytime you move over code, existing imperative dependencies are eliminated and more code can be moved over.

Keep iterating, gradually working outwards to push large parts of your project onto the functional side of the boundary, until you are happy with the results. This incremental approach allows testing individual changes and makes identifying and enforcing the boundary easier.

Rethink Algorithms, Data Structures, and Design

Imperative solutions and design patterns often don't make sense in functional style. Especially for data structures, direct ports of imperative code to functional style can be ugly and slow. A simple example: would you rather copy every element of a list for a prepend or cons the element onto the existing list?

Research and evaluate existing functional approaches to problems. Functional programming is more than just a programming technique, it is a different way of thinking about and solving problems. Projects written in the more traditional functional programming languages, such as lisp or haskell, are great resources in this regard.

Understand the Language and Builtins

This is an important part of understanding the functional imperative boundary and will effect interface design. Understand what features can be safely used in functional style code and which can not. Everything from which builtins may throw exceptions and which, like [].push, mutate objects, to objects being passed by reference and how prototype chains work. A similar understanding of any other libraries you consume in your project is also required.

Such knowledge allows making informed design decisions, like how to handle bad input and exceptions, or what happens if a callback function does something unexpected? Some of this can be enforced in code, but some just requires documentation on the proper usage.

Another point is how strict your implementation should be. Do you really want to try enforcing the correct behavior on maximum call stack errors or when the user redefines some builtin function?

Using Non Functional Concepts Where Appropriate

Functional approaches are not always appropriate, especially in a language like JavaScript. The recursive solution may be elegant until you start getting maximum call stack exceptions for larger inputs, so perhaps an iterative approach would be better. Similarly, I use inheritance for code organization, assignment in constructors, and immutable objects where they make sense.

As long as the functional interfaces are not violated, do what makes sense and what will be easiest to test and maintain.

Example

Here is an example of converting some very simple real code to functional style. I don't have a very good large example of the process, but this small one touches on a number of interesting points.

This code builds a trie from a string. Ill start with some code based on the top section of John Resig's trie-js build-trie module. Many simplifications / formatting changes have been made and my intent is not to comment on the quality of original code (There are much clearer and cleaner ways to build a trie, so why this c style code comes up first in google is interesting. Here's a quick implementation that uses reduce).

I like this example because I don't have to take it all the way to a true functional implementation, just to functional interfaces. Here is the starting point:

```<code>var txt = SOME_USER_STRING,
    words = txt.replace(/\n/g, "").split(" "),
    trie = {};

for (var i = 0, l = words.length; i < l; i++) {
    var word = words[i], letters = word.split(""), cur = trie;
    for (var j = 0; j < letters.length; j++) {
        var letter = letters[j];
        if (!cur.hasOwnProperty(letter))
            cur[letter] = {};
        cur = cur[ letter ];
    }
    cur['$'] = true;
}

// Output for text = 'a ab f abc abf'
trie = {
    "a": {
        "$":true,
        "b":{
            "$":true,
            "c":{"$":true}
        "f":{"$":true}}},
    "f":{"$":true}};
</code>```

Let's pretend this is the entire program. This program does two things: convert a string to a list of words and build a trie from the list of words. These are the existing interfaces in the program. Here is our program with the interfaces more clearly expressed:

```<code>var _get_words = function(txt) {
    return txt.replace(/\n/g, "").split(" ");
};

var _build_trie_from_list = function(words, trie) {
    for (var i = 0, l = words.length; i < l; i++) {
        var word = words[i], letters = word.split(""), cur = trie;
        for (var j = 0; j < letters.length; j++) {
            var letter = letters[j];
            if (!cur.hasOwnProperty(letter))
                cur[letter] = {};
            cur = cur[ letter ];
        }
        cur['$'] = true;
    }
};

// The 'public' interface
var build_trie = function(txt) {
    var words = _get_words(txt), trie = {};
    _build_trie_from_list(words, trie);
    return trie;
};
</code>```

Just by defining our interfaces, we can move _get_words to the functional style side of the boundary. Neither replace or split modifies the original string. And our public interface build_trie is functional style too, even though it interacts with some very imperative code. In fact, this is a fine stopping point in most cases. More code would get overwhelming, so let me overview a few other changes.

First, make all the interfaces functional style. This is trivial in this case, just have _build_trie_from_list return an object instead of mutating one.

Handling Bad input

Consider what happens if we call build_trie with an array of characters, build_trie(['a', ' ', 'a', 'b', 'c',  ' ', 'f']). The caller assumed this would behave in a functional style, but instead it throws an exception when .replace is called on the array. This may be the intended behavior. Or we could do explicit type checks and make sure the inputs are as we expected. But I prefer duck typing.

Strings are just arrays of characters and arrays are just objects with a length property and non-negative integers as keys. So if we refactored and wrote new replace and split methods that operates on array-like objects of strings, they don't even have to be strings, our code could just do the right thing. (String.prototype.* will not work here, it converts the output to a string). Duck typing is a totally separate from functional programming, but the larger point is that bad input should always be considered.

Fundamental redesign

There are also more fundamental considerations. Assume that we want to build the trie in functional style as well. In the imperative code, the approach was to construct the trie one word at a time. A direct port would have us copy the entire trie every time we need to make an insertion to avoid mutating objects. Clearly that is not going to work. Instead, the trie could be constructed node by node, from the bottom up, so that once a node is completed, it never has to be touched again. Or another approach entirely may be better, a quick search shows many existing functional implementations of tries.

Hope the example clarified things a bit.

Overall, I find writing functional style code in Javascript is a worthwhile and fun endeavor. Javascript is a surprisingly capable functional language, albeit too verbose in its default state.

Good luck with your project.

A few personal projects written in functional style Javascript:

parse.js - Parser Combinators

Nu - Lazy streams

Atum - Javascript interpreter written in functional style Javascript.

Khepri - Prototype programming language I use for functional Javascript development. Implemented in functional style Javascript.

Body:
Having authored several projects in functional style JavaScript, allow me to share my experience. I will focus on high level considerations, not specific implementation concerns. Remember, there are no silver bullets, do what works best for your specific situation.

Pure Functional vs Functional Style

Consider what you want to gain from this functional refactoring. Do you really want a pure functional implementation, or just some of the benefits a functional programming style can bring, such as referential transparency.

I have found the latter approach, what I call functional style, to mesh well with JavaScript and is usually what I want. It also allows selective non functional concepts to be carefully used in code where they make sense.

Writing code in a more purely functional style is also possible in JavaScript, but is not always the most appropriate solution. And Javascript can never be purely functional.

Functional Style Interfaces

In functional style Javascript, the most important consideration is the boundary between functional and the imperative code. Clearly understanding and defining this boundary is essential.

I organize my code around functional style interfaces. These are collections of logic that behave in a functional style, ranging from individual functions to entire modules. The conceptual separation of interface and implementation is important, a functional style interface may be implemented imperatively, as long as the imperative implementation does not leak across the boundary.

Unfortunately in Javascript, the burden of enforcing functional style interfaces falls entirely on the developer. Also, language features, such as exceptions, make a truly clean separation impossible.

Since you will be refactoring an existing codebase, start by identifying existing logical interfaces in your code that can be cleanly moved to a functional style. A surprising amount of code may already be functional style. Good starting points are small interfaces with few imperative dependencies. Everytime you move over code, existing imperative dependencies are eliminated and more code can be moved over.

Keep iterating, gradually working outwards to push large parts of your project onto the functional side of the boundary, until you are happy with the results. This incremental approach allows testing individual changes and makes identifying and enforcing the boundary easier.

Rethink Algorithms, Data Structures, and Design

Imperative solutions and design patterns often don't make sense in functional style. Especially for data structures, direct ports of imperative code to functional style can be ugly and slow. A simple example: would you rather copy every element of a list for a prepend or cons the element onto the existing list?

Research and evaluate existing functional approaches to problems. Functional programming is more than just a programming technique, it is a different way of thinking about and solving problems. Projects written in the more traditional functional programming languages, such as lisp or haskell, are great resources in this regard.

Understand the Language and Builtins

This is an important part of understanding the functional imperative boundary and will effect interface design. Understand what features can be safely used in functional style code and which can not. Everything from which builtins may throw exceptions and which, like [].push, mutate objects, to objects being passed by reference and how prototype chains work. A similar understanding of any other libraries you consume in your project is also required.

Such knowledge allows making informed design decisions, like how to handle bad input and exceptions, or what happens if a callback function does something unexpected? Some of this can be enforced in code, but some just requires documentation on the proper usage.

Another point is how strict your implementation should be. Do you really want to try enforcing the correct behavior on maximum call stack errors or when the user redefines some builtin function?

Using Non Functional Concepts Where Appropriate

Functional approaches are not always appropriate, especially in a language like JavaScript. The recursive solution may be elegant until you start getting maximum call stack exceptions for larger inputs, so perhaps an iterative approach would be better. Similarly, I use inheritance for code organization, assignment in constructors, and immutable objects where they make sense.

As long as the functional interfaces are not violated, do what makes sense and what will be easiest to test and maintain.

Example

Here is an example of converting some very simple real code to functional style. I don't have a very good large example of the process, but this small one touches on a number of interesting points.

This code builds a trie from a string. Ill start with some code based on the top section of John Resig's trie-js build-trie module. Many simplifications / formatting changes have been made and my intent is not to comment on the quality of original code (There are much clearer and cleaner ways to build a trie, so why this c style code comes up first in google is interesting. Here's a quick implementation that uses reduce).

I like this example because I don't have to take it all the way to a true functional implementation, just to functional interfaces. Here is the starting point:

var txt = SOME_USER_STRING,
    words = txt.replace(/\n/g, "").split(" "),
    trie = {};

for (var i = 0, l = words.length; i < l; i++) {
    var word = words[i], letters = word.split(""), cur = trie;
    for (var j = 0; j < letters.length; j++) {
        var letter = letters[j];
        if (!cur.hasOwnProperty(letter))
            cur[letter] = {};
        cur = cur[ letter ];
    }
    cur['$'] = true;
}

// Output for text = 'a ab f abc abf'
trie = {
    "a": {
        "$":true,
        "b":{
            "$":true,
            "c":{"$":true}
        "f":{"$":true}}},
    "f":{"$":true}};

Let's pretend this is the entire program. This program does two things: convert a string to a list of words and build a trie from the list of words. These are the existing interfaces in the program. Here is our program with the interfaces more clearly expressed:

var _get_words = function(txt) {
    return txt.replace(/\n/g, "").split(" ");
};

var _build_trie_from_list = function(words, trie) {
    for (var i = 0, l = words.length; i < l; i++) {
        var word = words[i], letters = word.split(""), cur = trie;
        for (var j = 0; j < letters.length; j++) {
            var letter = letters[j];
            if (!cur.hasOwnProperty(letter))
                cur[letter] = {};
            cur = cur[ letter ];
        }
        cur['$'] = true;
    }
};

// The 'public' interface
var build_trie = function(txt) {
    var words = _get_words(txt), trie = {};
    _build_trie_from_list(words, trie);
    return trie;
};

Just by defining our interfaces, we can move _get_words to the functional style side of the boundary. Neither replace or split modifies the original string. And our public interface build_trie is functional style too, even though it interacts with some very imperative code. In fact, this is a fine stopping point in most cases. More code would get overwhelming, so let me overview a few other changes.

First, make all the interfaces functional style. This is trivial in this case, just have _build_trie_from_list return an object instead of mutating one.

Handling Bad input

Consider what happens if we call build_trie with an array of characters, build_trie(['a', ' ', 'a', 'b', 'c',  ' ', 'f']). The caller assumed this would behave in a functional style, but instead it throws an exception when .replace is called on the array. This may be the intended behavior. Or we could do explicit type checks and make sure the inputs are as we expected. But I prefer duck typing.

Strings are just arrays of characters and arrays are just objects with a length property and non-negative integers as keys. So if we refactored and wrote new replace and split methods that operates on array-like objects of strings, they don't even have to be strings, our code could just do the right thing. (String.prototype.* will not work here, it converts the output to a string). Duck typing is a totally separate from functional programming, but the larger point is that bad input should always be considered.

Fundamental redesign

There are also more fundamental considerations. Assume that we want to build the trie in functional style as well. In the imperative code, the approach was to construct the trie one word at a time. A direct port would have us copy the entire trie every time we need to make an insertion to avoid mutating objects. Clearly that is not going to work. Instead, the trie could be constructed node by node, from the bottom up, so that once a node is completed, it never has to be touched again. Or another approach entirely may be better, a quick search shows many existing functional implementations of tries.

Hope the example clarified things a bit.

Overall, I find writing functional style code in Javascript is a worthwhile and fun endeavor. Javascript is a surprisingly capable functional language, albeit too verbose in its default state.

Good luck with your project.

A few personal projects written in functional style Javascript:

parse.js - Parser Combinators

Nu - Lazy streams

Atum - Javascript interpreter written in functional style Javascript.

Khepri - Prototype programming language I use for functional Javascript development. Implemented in functional style Javascript.


问:
Is it evil to model JSON responses to classes when they are mostly smilar?
Here's the problem :

While implementing a C# wrapper for an online API (Discogs) I've been faced to a dilemma : quite often the responses returned have mostly similar members and while modeling these responses to classes, some questions surfaces on which way to go would be the best.

Example :

Querying for a 'release' or a 'master' will return an object that contains an array of 'artist', however these 'artists' do not exactly have the same members.

Currently I decided to represent these 'artists' as a single 'Artist' class, against having respective 'ReleaseArtist' and 'MasterArtist' classes which soon becomes very confusing even though another problem arises : when a category (master or release) does not return these members, they will be null. Though it might sound confusing as well I find it less confusing than the former situation as I've tackled the problem by simply not showing null members when visualizing these objects.

Is this the right approach to follow ?

An example of these differences :

```<code>public class Artist
{
    public List<Alias> Aliases { get; set; }
    public string DataQuality { get; set; }
    public List<Image> Images { get; set; }
    public string Name { get; set; }
    public List<string> NameVariations { get; set; }
    public string Profile { get; set; }
    public string Realname { get; set; }
    public string ReleasesUrl { get; set; }
    public string ResourceUrl { get; set; }
    public string Uri { get; set; }
    public List<string> Urls { get; set; }
}

public class ReleaseArtist
{
    public string Join { get; set; }
    public string Name { get; set; }
    public string Anv { get; set; }
    public string Tracks { get; set; }
    public string Role { get; set; }
    public string ResourceUrl { get; set; }
    public int Id { get; set; }
}
</code>```

Edit :

I decided to keep things as simple as they can be : separated.

There are few weird names but it'll always be less confusing than the previous situations.

答:
I've also ran into similar issues and I ended up going the other way -- check out disqussharp for visceral details. The tactic I used there was a common base class with variants for things that changed between different calls.

I think having a single class -- or at least a common base class with the common properties -- is vastly more convenient for consumers and that is the way to go. There also isn't a law that says your classes that you return need to match the wire implementations if that makes more sense to callers of your library. If the service was that convenient then why would you be writing a wrapper in the first place?


问:
When should I care about performance?
For the longest time in places like Java's IRC channel, SO, and other places I've been told something along the lines of "Worry about how the code looks and its readability/understandability now, and performance later if absolutely necessary". So for the longest time, I haven't really been OCD about performance for my small desktop or web apps, just removing the obviously inefficient.

Most responses are "What about scalability?". Thats a legitimate point, but if my app was only built to parse, say, files 10,000 lines long, should I make my code a mess for the small percentage of people that are going to shove in a 1,000,000 line file?

My main question is when should I trade the easy but somewhat inefficient ways of doing tasks for big giant complicated beasts that do things extremely quickly but destroy any possible ways of upgrading and make the code excessively difficult and prone to rewriting anyway by the next developer?

答:
Um - Never?

Seriously, code should always be written so as to be easily understood and maintained.

With regard to when to deal with performance problems, deal with them once you identify them, don't pre-optimize your code because then you'll just be guessing about where the performance problems are.

If your code is written so as to be clear, concise, understandable, and maintainable then you or another programmer should have no problem refactoring the code to make it more efficient.

Title: When should I care about performance?


问:
Where can I find statistics on worldwide developers and software companies?
I try to find an answer of a very difficult question. The question is:

How many developers and how many software companies are there in the world?

For example if I check the Statistic Austria page I can see that in Austria there are 8383 companies with 35522 employees defined as "Computer programming, consultancy and related activities" and another 4102 companies with 15171 employees defined as "Information service activities".

This statistic is good, but it is only for Austria. Is there a similar for Europe, USA, Worldwide?

答:
Most developed countries keep statistics, although they all use slightly different standards for what they measure, so it's hard to compare.

For the United States, there are 1,336,300 programmers, according to the Bureau of Labor Statistics.

The United Kingdom has 333,000 "software professionals," according to the Office for National Statistics.

In Canada there are 387,000 people working in IT according to Statistics Canada.

Japan has 1,016,929 people working in "information services" according to Official Statistics of Japan

The BLS maintains a detailed list of online statistics agencies

With a bit more research you can probably gather data for the rest of the world; if you do, please edit this answer (I will make it community wiki) so that we can develop a single source of information.


问:
php templating with codeigniter
I am currently develop a website application in codeigniter, and I'd like to do something in PHP / CodeIgniter where I can make a common template for separate sections of the website.  I was thinking that I would keep the header / footer in a separate php files & include them separately.

The thing I'm not sure about is the content beneath the header and above the footer.  This website application will contain a lot of different pages, so I'm having a hard time figuring how what's the best way to do this.

答:
You can use Hook , or giving the parameter in every your method.
Example :

```<code>Class My_controller extends CI_Controller{

    public function index(){
        $data = array(
            'container' => 'contain'
        );

        $this->load->view('base_view', $data);
    }

}
</code>```

and also give your base_view.php (as a main view) the value from your sended variable.

```<code><html>
<head>
    <title>Your title here</title>
</head>
<body>
    <header></header>

    <section id="container">
        <?php $this->load->view($container); ?>
    </section>

    <footer></footer>
</body>
</code>```

Hope that helps..

Title: php templating with codeigniter

Body:
You can use Hook , or giving the parameter in every your method.
Example :

Class My_controller extends CI_Controller{

    public function index(){
        $data = array(
            'container' => 'contain'
        );

        $this->load->view('base_view', $data);
    }

}

and also give your base_view.php (as a main view) the value from your sended variable.

<html>
<head>
    <title>Your title here</title>
</head>
<body>
    <header></header>

    <section id="container">
        <?php $this->load->view($container); ?>
    </section>

    <footer></footer>
</body>

Hope that helps..


问:
What source control do I need for a large project in an average company?
I know Git is great for open source projects. But I was wondering: for a company with 20 programmers working on a 1 year project, which source control system is desirable? From what I heard Git uses pulling; wouldn't it be less than desirable to need to go through someone else to get your changes in the main trunk? Especially when everyone is working at the same time?

That's just of an example I was wondering about. I know how to use SVN but even at my last job we didn't use it on our projects, since everything was done in PHP and those were typically standalone 1 week projects. I just had SVN for my local code and didn't need to use it with others.

So what are good source controls, and specifically why is it good for this?

答:
I used to have the view that source control was just a tool, and that each of the products did more or less the same thing.  And then the point of these distributed version control systems clicked with me.

Distributed version control allows you to have more than one central repository.  Imagine code changes migrating from the local developer repository, to the feature repository, to the product repository, into the QA repository and finally into the released repository.

Personally I use a commercial product called Kiln, that's based on Hg, but the key feature is distributed version control. It revolutionises the flow of new code from developer into a released product.


问:
Effective way of keeping past projects with their working development environment?
I find that whenever I want to go run a past project, it will take a long time before I can find it and before I have everything set-up again for it to be able to run.

For example, I have python projects I created in Linux, and it depends on software packages that are easily installed in Linux, yet I no longer have the Linux VM I was using.  And some of my other projects depend on other variables like web server configuration, PATH variables, sdk, IDE, OS version, device, etc.

Does someone have an effective way of handling this issue?  As of now I have only concerned myself with keeping the source code backed up yet it is difficult re-establish the working development environment and it is also difficult to keep the working development environment around as well.

答:
Most systems (languages, runtimes or operating systems) have some standardized way of installing software and configurations, so try to use those. Such as:

Maven or Gradle for Java

CPAN for Perl

rpm for RedHat / Fedora

dpkg/apt-get for Linux

MSI packages for Windows

Then make installation instructions explaining exactly what needs to be installed / what steps are necessary:

Provide short instructions on what you assume to be installed (base OS, base runtime such as Java / Perl / Python...)

Write a short script that performs the required installations (ideally just a single invokation of a tool like Maven)

Test this on a fresh install (such as on a VM)

Then you should be able to recreate the environment, and others should also be able to do so (which may be important if it's not a solo project).

You might need to store the necessary installation packages somewhere, or you could just include download instructions (unless the system keeps track of those, such as apt-get or Maven). That depends on how much you trust the providers of the packages - there's probably no need to store core Debian packages, but with some small free software project, it might be a good idea.

The VM solution will also work, and is probably less work in the short
run (just keep the VM). However, I feel this solution offers more
flexibility, for example when changing the environment.


问:
Is knowing .NET only enough for a successful career in IT industry?

Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.

答:
William Hung parlayed his bad singing on American Idol into a career as a C-list celebrity. This doesn't mean that I would generally advise somebody to pursue bad singing as the foundation of a career in entertainment. Can you have a successful career as a developer only knowing .Net? Sure, thousands of people do. That doesn't mean it's a good career strategy.

I fear your question is perilously close to asking "What is the minimum I can do to be a successful developer?". The trouble is that the software job market is competitive, and becoming more so every day. Aiming to do the minimum is a recipe for a very vulnerable career.

A much more reasonable (and harder) question is how do you allocate your time between mastering your primary platform, and keeping up to date with important developments on other platforms. Obviously you can't know everything, and you'd be well justified in devoting most of your time to developing your .Net expertise. But simply adopting a rule that you ignore all other platforms is lazy. If you are going to have a robust career you've got to continually exercise your judgement and critical faculties to figure out what developments in which platforms are going to be significant to the industry.


问:
Why not have a High Level Language based OS? Are Low Level Languages more efficient?
Without being presumptuous, I would like you to consider the possibility of this.
Most OS today are based on pretty low level languages (mainly C/C++)
Even the new ones such as Android uses JNI & underlying implementation is in C

In fact, (this is a personal observation) many programs written in C run a lot faster than their high level counterparts (eg: Transmission (a bittorrent client on Ubuntu) is a whole lot faster than Vuze(Java) or Deluge(Python)). Even python compilers are written in C, although PyPy is an exception.

So is there a particular reason for this? Why is it that all our so called "High Level Languages" with the great "OOP" concepts can't be used in making a solid OS?

So I have 2 questions basically.

Why are applications written in low level languages more efficient than their HLL counterparts? Do low level languages perform better for the simple reason that they are low level and are translated to machine code easier?

Why do we not have a full fledged OS based entirely on a High Level Language?

答:
Microsoft has done some very interesting research in this direction, if you look into Singularity:

http://research.microsoft.com/en-us/projects/singularity/

Also, Mothy Roscoe et al have been working on Barrelfish which uses the Eclipse constraint programming language as an OS service to sort out all kinds of OS management and resource allocation problems:

http://www.barrelfish.org/


答:
A lot depends on where you put the division between low-level and high-level languages. For example, different people tend to put a language like C++ on different sides of that divide.

Regarding your questions:

I don't believe there is such a difference between low-level and high-level languages, but more a difference between interpreted languages and languages that compile to native instructions.

But there might also be a difference in culture between programmers, where the once that use a low level language focus more on the performance aspects of the (design) choices they make.

If you consider C++ to be high-level, then there is at least one OS written entirely in a high-level language (Symbian OS is written in C++). What stops you from writing an OS in most high-level languages are two things:

An OS needs low-level access to memory and hardware and perform dirty tricks on them. This kind of access is generally considered unsafe for application-level programs, so many high-level languages don't allow it.

An OS needs to execute without support software being present, such as interpreters. This makes it extremely hard to write an OS in a language that can't easily be compiled into native instructions.

Title: Why not have a High Level Language based OS? Are Low Level Languages more efficient?

Body:
Without being presumptuous, I would like you to consider the possibility of this.
Most OS today are based on pretty low level languages (mainly C/C++)
Even the new ones such as Android uses JNI & underlying implementation is in C

In fact, (this is a personal observation) many programs written in C run a lot faster than their high level counterparts (eg: Transmission (a bittorrent client on Ubuntu) is a whole lot faster than Vuze(Java) or Deluge(Python)). Even python compilers are written in C, although PyPy is an exception.

So is there a particular reason for this? Why is it that all our so called "High Level Languages" with the great "OOP" concepts can't be used in making a solid OS?

So I have 2 questions basically.

Why are applications written in low level languages more efficient than their HLL counterparts? Do low level languages perform better for the simple reason that they are low level and are translated to machine code easier?

Why do we not have a full fledged OS based entirely on a High Level Language?


答:
A main reason for the dominance of C for operating systems lies in history - current mainstream operating systems like Windows and all forms of Unix (BSD, Solaris, HP-UX, MacOS X, ... as well as clones like Linux) go back a long time, before OO and other "high level" constructs became mainstream.

For the core of the operating system besides performance there are needs to e very specific about the hardware instructions and one needs full control over memory which languages like C do very well.

For embedded systems there sometimes are operating systems using higher level languages for greater parts of the system. One notable example is JavaOS by Sun.

For widespread operating systems an notable example not using C also is the classic MacOS before MacOS X - that was in large parts written in a dialect of Pascal which allowed some form of object orientation.


问:
Author has inserted copyright into code with gnu public license notice - implications?
I've found a project on Github that I'm interested in contributing to which claims to be open source and has a GPL license included with it.

But the original author has added a copyright notification to each source file. I'm not sure why but I don't feel right contributing to a project that's always going to have someone else's name on it. It really breaks the community-created feel, and makes me uneasy about what the author might choose to do with the project next.

What are the implications of copyrighting open source GPL code as so? What power does this give the original author over a contributor?

```<code># Copyright (C) 2012, 2013 __AUTHORNAME__
# This file is part of __PROJECTNAME__.
#
# __PROJECTNAME__ is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# __PROJECTNAME__ is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
</code>```

答:
It is actually a requirement of the GPL license to put such a copyright statement in your source files (see here).

One point that is common among all copyright licenses is that you can't claim authorship for something you didn't write. This isn't always explicitly written down for contributions to a project, but if you contribute a significant piece of code, then you have the right to be named as co-author of the software.

Being named as co-author means that you have agreed to release the software under the stated license conditions (e.g. GPL). But it also means that the original author can't change the license conditions without your consent.

Being named as the (co-)author of the software also gives you the power to enforce the license and to bring copyright violations to justice. If people break the conditions of your GPL software, then it is your rights that get violated in the eyes of the law, not mine, even if you use a license that gives me a lot of rights.

Because of both points above, there are a number of organisations (among whom the FSF, who own the GNU software) that require you to sign over your copyrights to them.


答:
The QA manager might get his idea from the seemingly common interpretation of Agile where a team delivers a completely (QA-)tested product each spring that can be rolled out to the customers and he extrapolated that to reach the conclusion that it can be best achieved with a single development/QA environment.

And it might be one way to implement Agile practices, but it certainly is not the only way. I have worked with scrum in an environment where the development and QA teams were largely separate, and the QA team was the "customer" of the development team. In such an environment, the development and QA teams naturally work on different servers/deployments.

We can't really advise if a single dev/QA server environment is going to work for you. It depends too much on how you are used to work and how well the different people can cope with the occasional broken build.

One thing is for certain: Agile does not dictate anything with regard to how you set up your development (and related) environments.

Title: Does Agile (scrum) require one server environment?

Body:
Is it necessary/recommend/best practice/any other positive to use only one server environment to perform all development, unit testing and QA?

If so, is it then wise/part of Agile to then have only one staging environment before Live?

Considering that this could mean internationally distributed teams of developers and testers in different time zones is this wise?

This is something being implemented by our QA manager. The opinion put forward is that doing all the dev and testing on a single server is "Agile." The staging environment would be a second environment, and then live.


问:
How can I keep current with Python coding style?
I've been using Python since version 2.2. I do pick up new language constructs like for example with statement or dictionary/set comprehensions. However, I've realized that even though I'm being consistent with PEP-8, for existing constructs I'm using old style, rather than new style (for example except Exception, e instead of except Exception as e).

Is there a resource which would have either most current style guide, or even better a list of changes in Python's coding style?

答:
I'd look through the What's new documentation; whenever new syntax has been introduced it is invariably an improvement over the old.

Each What's New document (one per minor version, so for 2.5, 2.6, etc.) starts by summarising the Python Enhancement Proposals (PEP) that made it to that release. New syntax, functions and modules that you want to know about are invariably listed as a PEP.

The next documents you can look for is to search for blog posts, presentations and articles about "Idiomatic Python"; these usually try to teach you good, often newer, python style:

David Goodger (Python core dev): Code Like a Pythonista: Idiomatic Python

Raymond Hettinger (Another core dev): Transforming Code into Beautiful, Idiomatic Python (YouTube video, Slides)

Jeff Knupp: Writing Idiomatic Python (e-book), initial blog post that started the e-book.

Last but not least, try answering questions on Stack Overflow on the python tag; any style mistakes you make will be swiftly pointed out to you. It is a very swift path to discovering what better style is availabe. :-)


问:
What is the process or term for viewing HTML/CSS using localhost?
I have recently used some software, which come as a regular setup file, where you install your software, and then when you run it, opens the browser, uses the localhost with some specific port number to connect to the software, and runs it from there. I find it quite useful and interesting. But I even don't know whether this kind of software and programming methodology have a name or not. Therefore, I would like to learn which programming languages, APIs, and frameworks are specifically designed for this purpose?

One example to this is Metasploit. You can download its setup file, and install it casually like any other software, then when everything finishes, and you want to use the software. It will open the browser and connect to,

```<code>http://localhost:3790/
</code>```

where Metasploit will load and start.

答:
Browser Based Software means HTML and CSS

The ability it view it locally during localhost is a nice convenience but it is not a significant factor.  It's just a way to view it locally using a special address before transferring the file to a remote server and then viewing it over the internet.

This model - of having files show in a browser using localhost - also applies to development in any of the major development platforms - Java, PHP, Ruby on Rails, etc and the software tools and IDE's such as RubyMine.  It will also apply to almost any software that is browser based.

If the software doesn't support viewing locally with localhost you can also just file -> open from the browser menu and see it locally that way.


问:
At what size of data does it become beneficial to move from SQL to NoSQL?
As a relational database programmer (most of the time), I read articles about how relational databases don't scale, and NoSQL solutions such as MongoDB do.
As most of the databases I have developed so far have been small to mid scale, I have never had a problem that hasn't been solved by some indexing, query optimization or schema redesign.

What sort of size would I expect to see MySQL struggling with. How many rows?

(I know this is going to depend on the application, and type of data stored. the one that got me thing was basically a genetics database, so would have one main table, with 3 or 4 lookup tables. The main table will contain amongst other things, a chromosome reference, and a position coordinate. It will likely get queried for a number of entries between two potions on a chromosome, to see what is stored there).

答:
How big a data?

There are two significant thresholds:

whole data fits in the RAM

whole index data fits in the RAM

With fast SSDs the first threshold became bit less of an issue, unless you have crazy high traffic.

ACIDity

One of the problem with scaling RDBMSes is that by design they are ACID, which means transactions and row level locks (or even table level in some older/simpler RDBMSes). It can be limiting factor if you have lot of queries modifying lot of data running at same time. NoSQL solutions usually go for eventual consistency model.

How do RDBMS scale on data size?

It's not entirely true that RDBMS cannot scale on data size, there are two alternatives: vertical partitioning and horizontal partitioning (aka sharding).

Vertical partitioning is basically keeping unrelated tables on separate DB servers, thus keeping size of each one below thresholds mentioned above. This makes join these tables using plain SQL less straight forward and less efficient.

Sharding means distributing data from one table among various servers, based on specific key. This means that for look ups you know which server to query based on that key. However, this complicates queries that are not look ups on the sharding key.

In case of both kind of partitioning, if you go to extremes, you basically end up with same situation as NoSQL databases.