问:
Big project layout : adding new feature on multiple sub-projects
I want to know how to manage a big project with many components with version control management system.

In my current project there are 4 major parts.

Web

Server

Admin console

Platform.

The web and server part uses 2 libraries that I wrote.  In total there are  5 git repositories and 1 mercurial repository. The project build script is in Platform repository. It automates the whole building process.

The problem is when I add a new feature that affects multiple components I have to create branch for each of the affected repo. Implement the feature. Merge it back. My gut feeling is "something is wrong".

So should I create a single repo and put all the components there? I think branching will be easier in that case. Or I just do what I am doing right now. In that case how do I solve this problem of creating branch on each repository?

答:
In the situation you describe, you are not getting any benefit from having multiple repositories, but you do have a cost: you can't roll back to an older version of a repository, and have any confidence that your system will continue to work. This is because your code is tightly coupled across repositories. As confidence in the ability to roll back is one of the main benefits of source control, this isn't the situation you want to be in.

The solution is to define your repository structure based on the coupling of the code within it: if project component A shares only stable interfaces with project component B, then they can be placed in separate repositories. Otherwise, they should be co-located in the same repository. A more granular repository layout will reflect a better factored system architecture.

OwnerDisplayName: Shiplu


问:
function exit condition on parameter consistency check
When checking for parameter consistency a the top of a function body, what is the best strategy?

This one:

```<code>protected void function(Object parameter)
    if (parameter == null)
        return;

    //... do things
}
</code>```

...or this one:

```<code>protected void function(Object parameter)
    if (parameter != null) {
        //... do things
    }
}
</code>```

答:
The first one is the better one because if you have more than one parameter to check it is much simplier to follow the flow. E.g.:

```<code>protected void function(Object a, Object b, Object c) {
    if (a == null) {
        return;
    }
    if (b == null) {
        return;
    }
    if (c == null) {
        return;
    }
    // Do stuff
}
</code>```

Also as James noted I would use Exceptions if you language supports them.

ContentLicense: CC BY-SA 3.0

Body:
The first one is the better one because if you have more than one parameter to check it is much simplier to follow the flow. E.g.:

protected void function(Object a, Object b, Object c) {
    if (a == null) {
        return;
    }
    if (b == null) {
        return;
    }
    if (c == null) {
        return;
    }
    // Do stuff
}

Also as James noted I would use Exceptions if you language supports them.


问:
Why is it rare to collect analytics/usage data in open source software?
So, I've been developing some analytic software at my work and also have started to take more notice to analytics in general. For instance, I recently installed Google Analytics on my blog(which is custom and open source).

I mostly make open source software outside of work, so I think it might be cool to be capable of gathering some form of usage data and such on how my tools are used, opt-in only of course. However, this seems to almost never be done. Why? What's with the taboo of analytics in open source software?

答:
We , FOSS Advocates hates beings tracked. We feel that is breach of Privacy.
Thats why we using Linux instead of Proprietary OSes and Chromium instead of Chrome (just Edward Snowden Leaked how much we are being tracked not just by Internet Giants , but also by Microsoft and Apple.

Tracking inside Opensource software is useless and We will fork it and make a Track-less version anyways. So whats the point?

Call us freaks , we do not even trust Mozilla Firefox and Google Chrome so we use forked version of those eg : For Firefox www.geticeweasel.org , for chrome : http://www.srware.net/en/software_srware_iron_download.php

Users of source base distros like gentoo , compiles from sources only. Experts goes as far as reading lines of code of the software they using before even compile.


问:
Are Ruby on Rails / Grails the fastest frameworks for getting sites up quickly?
I'm considering using Grails for a new website, but am open to other/new programming languages and frameworks.  I have done development using J2EE/JSF2, ASP.NET, and PHP.  Is Grails or Ruby on Rails pretty much the best way to get functionality up and running quickly?

Some initial thoughts:

DJango looks similar to RoR/Grails and I'd consider it

GWT is an interesting concept but it doesn't seem like turnaround time is quite as fast

Thanks,
-Jon

答:
When using CakePHP, I can spin up a web app faster than...  a... really fast guy.  Anyway, it's fast.  Drop the files in your web root folder, configure two files (about three lines to change in each). And start coding.

Because it favors convention over configuration it will take some experience to ensure that it's configured optimally, but I guarantee that with equal levels of experience, CakePHP sports the most rapid deployment out of any framework, probably period.

That said, the original CakePHP project was a PHP clone of rails (it isn't anymore), so I'm sure rails is quick to deploy as well.

ContentLicense: CC BY-SA 2.5


问:
Coding Convention: C++ Header/Interface Files
I'm reading through a PDF on C++ programming from this page on Stanford's site.  It says that when you're creating a C++ header file for a library interface, use a #ifndef preprocessor command to make sure you don't compile the same interface twice.

So, your header would look something like this:

```<code>/**
  MyFile.h
*/

#ifndef _MyFile_h
#define _MyFile_h

// Function prototypes

#endif
</code>```

But, I've always heard people say that using preprocessor commands like #define is (or quickly leads to) bad coding practice.  I'm just starting to learn C++, so I don't want to get something ingrained that is bad.

Question: Is it "proper" coding style to use preprocessor commands as above?

答: This is one of the few uses of C++ macros that is widely accepted.  It is usually called an include guard. As an alternative, most modern compilers support #pragma once.  This is much cleaner, but slightly less portable.


答:
The thing is called 'internal include guard', and is common practice -- if done well. Your small example  manages to have two mistakes:

the guard must be full: first to last line. Nothing before and after.

beginning with underscore + capital letter is reserved for implementation, so not proper to use, make it MYFILE_H_INCLUDED_, or better like compilers make it, add a GUID. As it must not be repeated in a different .h file. Certainly use

#pragma once is better if supported and can be combined with the include guard.

As the macro name is not used for anything else it will not have its common problems; also except for the pragma there is no real way to allow multiple inclusion of headers, and that is quite needed.

Title: Coding Convention: C++ Header/Interface Files

Body:
I'm reading through a PDF on C++ programming from this page on Stanford's site.  It says that when you're creating a C++ header file for a library interface, use a #ifndef preprocessor command to make sure you don't compile the same interface twice.

So, your header would look something like this:

```<code>/**
  MyFile.h
*/

#ifndef _MyFile_h
#define _MyFile_h

// Function prototypes

#endif
</code>```

But, I've always heard people say that using preprocessor commands like #define is (or quickly leads to) bad coding practice.  I'm just starting to learn C++, so I don't want to get something ingrained that is bad.

Question: Is it "proper" coding style to use preprocessor commands as above?


问:
What is meant by binary compatibility? What is its importance during serialization/deserialization in a language like Java that deals in byte code?
In computing what is meant by binary compatibility?

I read about it in context of serialization/deserialization that this process of serialize/deserialize should be binary compatible. What does it mean in this context? In particular I am interested in understanding the role of binary compatibility in a language like Java that deals with byte code.

This quote is from Effective Java:

When a serializable class is revised, it is important to check that
  it is possible to serialize an instance in the new release and
  deserialize it in old releases, and vice versa. The amount of testing
  required is thus proportional to the product of the number of
  serializable classes and the number of releases, which can be large.
  These tests cannot be con-structed automatically because, in addition
  to binary compatibility, you must test forsemantic compatibility. In
  other words, you must ensure both that the
  serialization-deserialization process succeeds and that it results in
  a faithful replica of the original object. The greater the change to a
  serializable class, the greater the need for testing. The need is
  reduced if a custom serialized form is carefully designed when the
  class is first written (Items 75, 78), but it does not vanish
  entirely.

答:
It just means the deserializer has to use the same binary format as the serializer did.  For example, consider serializing a string.  There are several different binary formats for a string, even though they represent the same data semantically.  One way is to first serialize a number representing the length of the string, then write the individual characters.  Another way is to just write out the characters and use a null character to signal the end of the string.

One serializer could use 16 bits to represent the length and one could use 32.  If it's a unicode string, one serializer could use UTF-8 encoding, one could use UTF-16 encoding, and one could write out a field specifying which encoding it is using in that particular instance.

That's just something as simple and commonplace as a string.  When you get to the object layer and higher, there are many more variations for how you can represent something in a binary stream.  If your serializer and deserializer aren't binary compatible, you'll get garbage out when you try to deserialize.

Sometimes the binary format will change over time, so a deserializer has to be aware of all previous formats in order to remain backwards compatible.  Serialized formats often include a version field for this express purpose.


答:
There are certain language feature that do get abused by some programmers who have not learned better. Over time, the trend of abuse leads to large consensus of "practice/feature X is bad" and then propagates into an almost a knee-jerk reaction of "OMG I see practice/feature X in this code, this code must be burned"

Global variables or singletons is another great example of this. There is ABSOLUTELY a need to have them and use them WHEN appropriate. The problem is that 98% of code you see out there, these practices should not be used.

As someone who is new to the language you need to learn what each feature does, but don't discount and forget about it just because you heard from somewhere that it is bad. Learn why it is bad and learn to code a better way so you do not need to use it.  But after you get through all that, there will absolutely be times when preprocessor is the right answer for certain types of problems.

Biggest problem with preprocessor (besides not being typesafe and all that...) is that people put code in there.  Then, maybe a bit more code, then maybe an if-statement. When you debug code with preprocessor, all you see is the point of execution on your macro with no useful idea of what's going on behind it.

As an extreme case, I once worked with a guy who had 200+ line macros. When he needed to debug them, he would copy-paste them directly into the code where the macro was used and remove all '\' from line ends.  Then when he was done, he would put the macro back in place, copy-paste all that code back and manually put back all '\' on line ends.  Now that is something YOU SHOULD NEVER EVER DO... NEVER :)


问:
Which are the significant algorithms for humankind in past decades?
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...

答: Sorting algorithm. </p>

Body: Sorting algorithm.


答:
Web analytics are ridiculously easy to implement (the server already collects all of the necessary information on which pages are hit), and there was a lot of financial incentive to develop them (since they can directly impact how much business a company gets from their web site), so they took off and have received a lot of development effort to make them easy to use and ubiquitous.

Desktop software (both open source and commercial) has a few obstacles compared to this:

Harder to implement - Information isn't automatically collected, so you'll likely have to add some tracking calls yourself.

More privacy concerns - It's something that users have to opt in to.

Additionally, analytics aren't always as useful as they first appear:

If feature A is used more than feature B, is it because B isn't as useful, or is it because B is too hard to use, or is it because not enough people know that B is there?

I suspect that desktop analytics would be harder to interpret.  Analytics require interpretation (statistical analysis, visualization, etc.).  For the web, companies like Google have commoditized analytics: there was enough financial incentive to justify the effort to make the data so easy to understand that anyone can easily benefit from it.  This hasn't happened for desktop software; even if you could get the raw data, interpreting it would be more work.

Open source software in particular has the reputation (stereotype) of not giving a lot of attention to usability, so it's not surprising that it hasn't used a (relatively) advanced usability technique.

With that said, some desktop open source software does to analytics.  For example:

Firefox has telemetry (usage tracking), health reports, and crash reporting.

ToME (an open source computer game) tracks player statistics and uses it to help balance gameplay.

Debian and Ubuntu have popcon to track which packages are used.

In each case, the projects are large enough to be able to afford the difficulty of implementation (Firefox), or already have an online component (ToME and popcon) and so can more easily overcome the implementation and privacy concerns.

Title: Why is it rare to collect analytics/usage data in open source software?

Body:
So, I've been developing some analytic software at my work and also have started to take more notice to analytics in general. For instance, I recently installed Google Analytics on my blog(which is custom and open source).

I mostly make open source software outside of work, so I think it might be cool to be capable of gathering some form of usage data and such on how my tools are used, opt-in only of course. However, this seems to almost never be done. Why? What's with the taboo of analytics in open source software?


问:
IXRepository and test problems
Recently had a doubt about how and where to test repository methods.

Let the following situation: I have an interface IRepository like this:

```<code>public interface IRepository<T>
    where T: class, IEntity
{
    IQueryable<T> Query(Expression<Func<T, bool>> expression);
    // ... Omitted
}
</code>```

And a generic implementation of IRepository

```<code>public class Repository<T> : IRepository<T>
    where T : class, IEntity
{
    public IQueryable<T> Query(Expression<Func<T, bool>> expression)
    {
        return All().Where(expression).AsQueryable();
    }
}
</code>```

This is an implementation base that can be used by any repository. It contains the basic implementation of my ORM.

Some repositories have specific filters, in which case we will IEmployeeRepository with a specific filter:

```<code>public interface IEmployeeRepository : IRepository<Employee>
{
    IQueryable<Employee> GetInactiveEmployees();
}
</code>```

And the implementation of IEmployeeRepository:

```<code>public class EmployeeRepository : Repository<Employee>, IEmployeeRepository // TODO: I have a dependency with ORM  at this point in Repository<Employee>. How to solve? How to test the GetInactiveEmployees method
{
    public IQueryable<Employee> GetInactiveEmployees()
    {
        return Query(p => p.Status != StatusEmployeeEnum.Active || p.StartDate < DateTime.Now);
    }
}
</code>```

Questions

Is right to inherit Repository<Employee>?

The goal is to reuse code once all implementing IRepository already been made. If EmployeeRepository inherit only IEmployeeRepository, I have to literally copy and paste the code of Repository<T>.

In our example, in EmployeeRepository : Repository<Employee> our Repository lies in our ORM layer. We have a dependency here with our ORM impossible to perform some unit test.

How to create a unit test to ensure that the filter GetInactiveEmployees return all Employees in which the Status != Active and StartDate < DateTime.Now. I can not create a Fake/Mock of IEmployeeRepository because I would be testing? Need to test the actual implementation of GetInactiveEmployees.

The complete code can be found on Github

答:
This strikes me as a has-a relationship, since as you mention this class is acting as a filter. So rather than inheriting it should have a private IRepository<Employee> field that it can receive when EmployeeRepository is constructed.

Having the option to provide an IRepository<Employee> would allow you to mock/fake it and separate the testing concerns.

Yes, you don't need to create a mock object of the thing you're testing. You just need to be able to isolate the method's behaviour by providing ideal objects for the object you are testing to manipulate.

Title: IXRepository and test problems


问:
Services in Model Layer
I understand services should have no state and no business logic.

How can you implement a service like AuthentificationService considering these rules?

All the methods in a service should be static?

答:
Let's look at the various parts of your question.

I understand services should have no state and no business logic.

Your statement (and assumption) is only partly correct.

Services should not have state.

This is mostly true, rounded up to almost always true.  The problem is that coding state into a service gets to be a real pain.  Keeping track of the state; client requests; timeouts; disconnects; slow responses; load balancing; distributed service provisioning; session hijacking; etc... all adds up to a lot of overhead.  So it's just easier to not have state in the service.  The problems listed mostly go away, and the features are easier to implement.

Services should not have business logic.

Not true.  In fact, a service is essentially a manifestation of business logic.  A service must provide a function.  That function represents something of value to the business, and is generally a piece of the organization's business logic.

All the methods in a service should be static?

I think this depends upon what you mean by static.  If by static you mean only a single instance of the service, then the answer is "maybe."  And I think this aspect would be driven more by your language of choice for the service than anything else.

But if you mean "unchanging" then the answer is yes.  A service should provide a deterministic response to a properly formatted response.  How it generates that response may change, but the form and nature of the response should be static.  A service is an API, and once released to the wild then it should not change.  If a change is required then consider applying versions to your services.

How can you implement a service like AuthentificationService considering these rules?

See above for the misunderstandings in your base assumptions.

Many frameworks provide this service out of the box so long as you plug the framework into your authentication provider. The general approach is that credentials are based to the Authenticate service which returns an ephemeral token upon successful authentication.  The other client based calls then make that token part of their call to the other services.  Those services or an intermediate layer verify that the token is still valid and then allow the service call to proceed.

You could make the semantic argument that the token represents a "state" for the client session.  But the token or "state" tracking is handled by the client and there are very simplistic rules on the service side in order to validate and handle that "state."  Many / all of the woes associated with stateful services are still avoided.

Title: Services in Model Layer


答: Public/private key encryption is pretty darn important. Internet commerce would be nowhere as ubiquitous without it.</p>

Title: Which are the significant algorithms for humankind in past decades?

Body:
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...


问:
Why do C# and Java use reference equality as the default for '=='?
I've been pondering for a while why Java and C# (and I'm sure other languages) default to reference equality for ==.

In the programming I do (which certainly is only a small subset of programming problems), I almost always want logical equality when comparing objects instead of reference equality. I was trying to think of why both of these languages went this route instead of inverting it and having == be logical equality and using .ReferenceEquals() for reference equality.

Obviously using reference equality is very simple to implement and it gives very consistent behavior, but it doesn't seem like it fits well with most of the programming practices I see today.

I don't wish to seem ignorant of the issues with trying to implement a logical comparison, and that it has to be implemented in every class. I also realize that these languages were designed a long time ago, but the general question stands.

Is there some major benefit of defaulting to this that I am simply missing, or does it seem reasonable that the default behavior should be logical equality, and defaulting back to reference equality it a logical equality doesn't exist for the class?

答:
The short answer: Consistency

To answer your question properly, though, I suggest we take a step backwards and look to the issue of what equality means in a programming language. There are at least THREE different possibilities, which are used in various languages:

Reference equality: means that a = b is true if a and b refer to the same object. It would not be true if a and b referred to different objects, even if all the attributes of a and b were the same.

Shallow equality: means that a = b is true if all the attributes of the objects to which a and b refer are identical. Shallow equality can easily be implemented by a bitwise  comparison of the memory space that represents the two objects. Please note that reference equality implies shallow equality

Deep equality: means that a = b is true if each attribute in a and b is either identical or deeply equal. Please note that deep equality is implied by both reference equality and shallow equality. In this sense, deep equality is the weakest form of equality and reference equality is the strongest.

These three types of equality are often used because they are convenient to implement: all three equality checks can easily be generated by a compiler (in the case of deep equality, the compiler might need to use tag bits to prevent infinite loops if a structure to be compared has circular references). But there is another problem: none of these might be appropriate.

In non-trivial systems, equality of objects is often defined as something between deep and reference equality. To check whether we want to regard two objects as equal in a certain context, we might require some attributes to be compared by where it stands in memory and others by deep equality, while some attributes may be allowed to be something different altogether. What we would really like is a “forth type of equality”, a really nice one, often called in the literature semantic equality. Things are equal if they are equal, in our domain. =)

So we can come back to your question:

Is there some major benefit of defaulting to this that I am simply missing, or does
  it seem reasonable that the default behavior should be logical equality,
  and defaulting back to reference equality if a logical equality doesn't exist
  for the class?

What do we mean when we write ‘a == b’ in any language? Ideally, it should always be the same: Semantic equality. But that´s not possible.

One of the main considerations is that, at least for simple types like numbers, we expect that two variables are equal after assignment of the same value. See below:

```<code>var a = 1;
var b = a;
if (a == b){
    ...
}
a = 3;
b = 3;
if (a == b) {
    ...
}
</code>```

In this case, we expect that ‘a equals b’ in both statements. Anything else would be insane. Most (if not all) of the languages follow this convention. Therefore, with simple types (aka values) we know how to achieve semantic equality. With objects, that can be something completely different. See below:

```<code>var a = new Something(1);
var b = a;
if (a == b){
    ...
}
b = new Something(1);
a.DoSomething();
b.DoSomething();
if (a == b) {
    ...
}
</code>```

We expect that the first ‘if’ will always be true. But what do you expect on the second ‘if’? It really depends. Can ‘DoSomething’ change the (semantic) equality of a and b?

The problem with semantic equality is that it cannot be automatically generated by the compiler for objects, nor it´s obvious from the assignments. A mechanism must be provided for the user to define semantic equality. In object-oriented languages, that mechanism is an inherited method: equals. Reading a piece of OO code, we don´t expect a method to have the same exact implementation in all classes. We are used to inheritance and overloading.

With operators, though, we expect the same behavior. When you see ‘a == b’ you should expect the same type of equality (from the 4 above) in all situations. So, aiming for consistency the languages designers used reference equality for all types. It should not depend on whether a programmer has overridden a method or not.

PS: The language Dee is slightly different from Java and C#: the equals operator means shallow equality for simple types and semantic equality for user-defined classes (with the responsibility for implementing the = operation lying with the user — no default is provided). As, for simple types, shallow equality is always semantic equality, the language is consistent. The price it pays, though, is that the equals operator is by default undefined for user-defined types. You have to implement it. And, sometimes, that´s just boring.

Body:
The short answer: Consistency

To answer your question properly, though, I suggest we take a step backwards and look to the issue of what equality means in a programming language. There are at least THREE different possibilities, which are used in various languages:

Reference equality: means that a = b is true if a and b refer to the same object. It would not be true if a and b referred to different objects, even if all the attributes of a and b were the same.

Shallow equality: means that a = b is true if all the attributes of the objects to which a and b refer are identical. Shallow equality can easily be implemented by a bitwise  comparison of the memory space that represents the two objects. Please note that reference equality implies shallow equality

Deep equality: means that a = b is true if each attribute in a and b is either identical or deeply equal. Please note that deep equality is implied by both reference equality and shallow equality. In this sense, deep equality is the weakest form of equality and reference equality is the strongest.

These three types of equality are often used because they are convenient to implement: all three equality checks can easily be generated by a compiler (in the case of deep equality, the compiler might need to use tag bits to prevent infinite loops if a structure to be compared has circular references). But there is another problem: none of these might be appropriate.

In non-trivial systems, equality of objects is often defined as something between deep and reference equality. To check whether we want to regard two objects as equal in a certain context, we might require some attributes to be compared by where it stands in memory and others by deep equality, while some attributes may be allowed to be something different altogether. What we would really like is a “forth type of equality”, a really nice one, often called in the literature semantic equality. Things are equal if they are equal, in our domain. =)

So we can come back to your question:

Is there some major benefit of defaulting to this that I am simply missing, or does
  it seem reasonable that the default behavior should be logical equality,
  and defaulting back to reference equality if a logical equality doesn't exist
  for the class?

What do we mean when we write ‘a == b’ in any language? Ideally, it should always be the same: Semantic equality. But that´s not possible.

One of the main considerations is that, at least for simple types like numbers, we expect that two variables are equal after assignment of the same value. See below:

var a = 1;
var b = a;
if (a == b){
    ...
}
a = 3;
b = 3;
if (a == b) {
    ...
}

In this case, we expect that ‘a equals b’ in both statements. Anything else would be insane. Most (if not all) of the languages follow this convention. Therefore, with simple types (aka values) we know how to achieve semantic equality. With objects, that can be something completely different. See below:

var a = new Something(1);
var b = a;
if (a == b){
    ...
}
b = new Something(1);
a.DoSomething();
b.DoSomething();
if (a == b) {
    ...
}

We expect that the first ‘if’ will always be true. But what do you expect on the second ‘if’? It really depends. Can ‘DoSomething’ change the (semantic) equality of a and b?

The problem with semantic equality is that it cannot be automatically generated by the compiler for objects, nor it´s obvious from the assignments. A mechanism must be provided for the user to define semantic equality. In object-oriented languages, that mechanism is an inherited method: equals. Reading a piece of OO code, we don´t expect a method to have the same exact implementation in all classes. We are used to inheritance and overloading.

With operators, though, we expect the same behavior. When you see ‘a == b’ you should expect the same type of equality (from the 4 above) in all situations. So, aiming for consistency the languages designers used reference equality for all types. It should not depend on whether a programmer has overridden a method or not.

PS: The language Dee is slightly different from Java and C#: the equals operator means shallow equality for simple types and semantic equality for user-defined classes (with the responsibility for implementing the = operation lying with the user — no default is provided). As, for simple types, shallow equality is always semantic equality, the language is consistent. The price it pays, though, is that the equals operator is by default undefined for user-defined types. You have to implement it. And, sometimes, that´s just boring.


问:
What features should a programming language have to say it has good reusability?
What should a programming language have so that it can be said to promote good reusability? Only generics and functions come to my mind when I hear the word reusability. What else make a programming language good for writing easily reusable code?</p>

答: I would add objects and inheritance. This will allow code to be reused by a child type. </p>


答:
Namespaces are important to facilitate the ability for code to work together. When you have generic class or function names, you can very quickly run into collisions without namespaces.

If you are using an OO language, supporting interfaces and traits is superior to just supporting inheritance - it's easier to compose an object of other objects than it is to try and extend an object about which you know very little.

Title: What features should a programming language have to say it has good reusability?

Body: What should a programming language have so that it can be said to promote good reusability? Only generics and functions come to my mind when I hear the word reusability. What else make a programming language good for writing easily reusable code?</p>


答: A good module system is important. Go's interfaces (Java's are similar, I hear) are pretty great.</p>


答:
The first thing that comes to my mind is a good module system. To support re-use, the module system should:

be lightweight - a heavyweight module system will discourage use, which discourages re-use.

support versioning - if a client can ask for a specific version of another module, that will make it easier to independently evolve the different modules without breaking clients.

control namespace pollution - you don't want the module's internally-defined symbols to compete with those of your client code, so some for of controlled symbol export / import, or namespace definition, will be necessary.


答:
The first and foremost item would be a well defined unit of reuse and philosophy behind their implementation.  When you look at the most successful reuse implementations you essentially have components or plugins.  What makes those work are:

A well defined interface separating implementation and use

Well defined contracts for that interface

Consistent packaging (i.e. a way for the consumer of the component to discover what is available)

C# and Java provide the programming concept of an interface for just this purpose.  Interfaces don't require all implementations to share an object hierarchy which helps protect proprietary code from changing a base class to provide more visibility into subclass composition.  Many of the dependency injection frameworks from Spring(.Net) to MEF also define packaging requirements which complete the picture.

All of this can be done without an object oriented programming language as well.  For example, C uses the extern keyword to define the functions that are exposed for applications to use, as well as structs to package data.


答:
Dijkstra's algorithm

The algorithm exist in every router in the world, for identifying the best route between two nodes in a network.


问:
What makes Common Lisp "big"?
I've been learning both Common Lisp and Racket, and one thing that I consistently hear is that Racket is a much "smaller" language than Common Lisp. I was wondering what this really meant. As far as I can tell, the syntax for Common Lisp isn't that much bigger than for Racket.

Basically, I'm wondering what exactly about common lisp is bigger. Does it have more syntax that I just don't know about? Does it have bigger environments? Bigger executables? Bigger libraries? Or some combination thereof?

Please, this is not a "which one is better" thread, I would just like to know exactly what "bigger" means.

答:
Actually Common Lisp is no longer very big compared to several other languages. If you look at the spec of Common Lisp, then you see that the pages are very long and often about one construct. The Scheme standard for example describes a dozen features on a single page, where Common Lisp uses one page.

Languages like R6RS + Libraries + SRFI, Racket or R7RS big are not really smaller than ANSI Common Lisp.

Where Common Lisp is large: when you factor in some of the semi-standard libraries like the MOP, CLOS-based streams, etc. Manuals for some of the popular Common Lisp implementations tend to be large, because they provide a lot of features in an extensive way.

Title: What makes Common Lisp "big"?


答:
.equals() compares variables by their contents.
instead of == that compares the objects by their contents...

using objects is more accurate tu use .equals()

Title: Why do C# and Java use reference equality as the default for '=='?

Body:
I've been pondering for a while why Java and C# (and I'm sure other languages) default to reference equality for ==.

In the programming I do (which certainly is only a small subset of programming problems), I almost always want logical equality when comparing objects instead of reference equality. I was trying to think of why both of these languages went this route instead of inverting it and having == be logical equality and using .ReferenceEquals() for reference equality.

Obviously using reference equality is very simple to implement and it gives very consistent behavior, but it doesn't seem like it fits well with most of the programming practices I see today.

I don't wish to seem ignorant of the issues with trying to implement a logical comparison, and that it has to be implemented in every class. I also realize that these languages were designed a long time ago, but the general question stands.

Is there some major benefit of defaulting to this that I am simply missing, or does it seem reasonable that the default behavior should be logical equality, and defaulting back to reference equality it a logical equality doesn't exist for the class?


问:
articles in variable names and hard-coding strings
re-edited by author: no this is not 2 questions. This is one question about code review questions containing two separate points. Please do not edit my question.

For naming variables, the two sides are regarding using articles (a, an, the) in the variable name (e.g. theBook vs. book -or- parseTheString vs. parseString).

For hard-coding strings, the three sides are whether to put all strings into constants (public static final) in a separate file (class or interface), put them all in the same file (private static final), or don't use constants for strings at all. (e.g. new Button("Click Me")  vs.  new Button(BUTTON_LABEL_CLICK)).  We also discuss the Hungarian notation issue quite a bit but I've seen that discussed here in other questions.

For a very long time it has been the defacto standard to not use articles in variable names (adds visual clutter without adding value) and to not have hard-coded strings sprinkled through the source code (a potential maintenance nightmare and very poor for internationalization). Now we are starting to see violations of these and the developers seem truly surprised when someone marks these as defects or at least needing attention. The manager has said they don't care one way or the other and these points are not in our company coding standards.

答:
Articles in Variable Names

They add little to no value in most cases, but make the code longer to read.

Usually, I'd rarely have a the need for the distinction between a "a" or "the" in the flow of a function, so it doesn't make sense to use articles.

It's a formal programming language and I am fine with it not reading exactly like a natural language. In fact, it's probably better this way, not everything's necessarily so great about natural languages.

There are a few cases where readability can benefit from using articles though, for instance if you want to implement a checker for a "is a" relationship with a method signature like boolean isA(Object o, Class<?> cl) (I'm not advocating this to be a good idea).

Hard-Coded Strings

It depends on whether you plan to reuse them or not, and whether that reuse is driven by semantics (and not just the fact that the String has the same content in different places) and spread across multiples classes or sub-systems.

To that extent, I usually use these rules:

If you have the same string multiple times and it has the same meaning acros multiple classes, then extract to constants in an interface.

If you have the same string multiple times within a single class and it has the same meaning within that class, then extract to constants within the class.

If you have only a few number of repetitions of as tring, or they just happen to be identical but aren't guaranteed to always be in the future, then I'd leave them inlined.

If any of the above would render maintenance difficult, screw rules 1 to 3 and do whatever works best for you.

Of course, make sure that the constant's name makes the code as semantically valid as the string it holds. That also applies for other things that aren't strings (like Predicates, for instance).


问:
.c FIle Dedicated to Data
Is it completely unheard of to have a .c file dedicated to just data? In my case, I'd be using it for global variables that are shared across two other .c files. Here's specifically how I'm using it.

```<code>// serverth.h

struct serverth_parameters {
    struct { // right now, this is the only struct needed
        char * root,
             * user,
             * public,
             * site;
    } paths;

    // I anticipate needing another struct here

};

#ifndef SERVERTH_SOURCE
extern struct serverth_parameters parameters;
#endif
</code>```

```<code>// serverth.c

#define SERVERTH_SOURCE
#include "serverth.h"

struct serverth_parameters parameters = {
    .paths = { // macros are actually used here
        "/srv",
        "/user",
        "/public"
        "/site"
    }
};
</code>```

parameters is a struct that's used for a websockets server, in two files:

One for HTTP (uses parameters.paths.site)

Two for proprietary protocols (both use .paths.user, one uses paths.public)

Is this a bad practice? Do people do this? Or, is it more conventional to just keep the data in the source file in which it is most relevant?

答:
In general I'd be wary of "dumping ground" files, where one would start listing global variables or long lists of #defines.

However, if by "globals" you actually meant that these globals would be constants, then that would seem acceptable, as long as they are structured and re-grouped in meaningful patterns, and that the extent of their reuse justifies to extract them to a separate file.

If these conditions aren't satisfied, then I'd usually restrain them to the file where they're expected to be used, if possible.

Include Guards

On a different note, I don't know how your files are compiled and what build system you use, but you might want to use compilation guards of the form:

```<code>#ifndef MY_MODULE
# define MY_MODULE

/* stuff here */

#endif
</code>```

Title: .c FIle Dedicated to Data

Body:
In general I'd be wary of "dumping ground" files, where one would start listing global variables or long lists of #defines.

However, if by "globals" you actually meant that these globals would be constants, then that would seem acceptable, as long as they are structured and re-grouped in meaningful patterns, and that the extent of their reuse justifies to extract them to a separate file.

If these conditions aren't satisfied, then I'd usually restrain them to the file where they're expected to be used, if possible.

Include Guards

On a different note, I don't know how your files are compiled and what build system you use, but you might want to use compilation guards of the form:

#ifndef MY_MODULE
# define MY_MODULE

/* stuff here */

#endif


答: Quicksort</p>

Body: Quicksort


问:
Coding to SOA, External Dependency
This has happend to me more than once, thought someone can give some insight.

I have worked on multiple projects where my project depends on external service. When I have to run the application locally, i would need that service to be up. But sometimes I would be coding to the next version of their service which may not be ready.

So the question is, is there already a way that can have a mock service up and running that i could configure with some request and responses?

For example, lets say that I have a local application that needs to make a rest call to some other service outside to obtain some data. E.g, say, for given a user, i need to find all pending shipments which would come from other service. But I dont have access to that service.

In order to run my application, i need a working external service but I dont have access to it in my environment. Is there a better way rather than having to create a fake service?

答:
One way is to create your own service which returns sample data in the same format as the external service - this is the mock service.

In this diagram, I have labelled the part of your application that connects to the service as the service client.
Here, you just configure your application to point to your mock service while developing.

Another, possibly better, way - which I have used myself, I'll describe it here in general terms - is to have the service client implement an interface, through which the rest of your application accesses the service. Then you can just create another implementation of the interface which returns mock data:

With this system, you just change which implementation to use as needed, either through a configuration variable or build condition. Another advantage is that you can start coding the application without any reference to the soa technology used, it gives you flexibility while you wait for the service to be ready.

Title: Coding to SOA, External Dependency


问:
Build website using a known language or a new one?
So there is a website that I want to build. It will be a review aggregator and probably a bit more. I want to build this website for three reasons:

I really think this website will be used by a reasonable amount of people

I want to practice my programming skills since currently at my job I am doing mostly scripting

Maybe learn a new language. I am currently torn though since my immediate reaction is that I want to use Java since I know it relatively well, like it, and feel it will allow me to put something up as quickly as possible. I would also like to use an existing Web Application Framework.

If I don't end up going with Java I would probably go with one of the following:

C#/.NET - I prefer static languages, and this is similar to Java.

Python - I use this at my job superficially and it seems that a lot
of people are using it.

Ruby - Seems to have a very well established framework

Scala - Has some similarities to Java but from what I read it's a
different paradigm

So I guess my question is under these circumstances do you think that I should build a website using a known language or a new one?

答:
Maybe JWT: http://www.webtoolkit.eu/

Instead of a new language, I'm suggesting a new library, that may be useful in another language (c++) later.

It's a new style (as far as I know) of website frameworks; it treats the webapp as a gui app, so instead of the request+response style, it's more a like an event based programming model.

There's a Java version and a C++ version. It's a bit low level compared to a lot of frameworks out there, like if you want to resize images to create thumbnails, you'd just use your external lib of choice.

It has good fall-back mechanisms, like it'll use websockets if available, then fall back to ajax, then to http.

It's cool because a lot of code you can write all on the server, like event handlers, and if it can predict the DOM changes, cached on the client for instant results in JS, or even work (to a limited extent) with just http.

Check out the widget gallery: http://www.webtoolkit.eu/widgets/forms


问:
How come javascript, being a prototype based language, doesn't have an easy way to access the prototype?
May be this is a stupid question, but I'm kind of intrigued.

Being JavaScript a prototype based language, with its pseudo-class function constructors sort of half baked (remember JavaScript: The Good Parts ...) I wonder how is it possible that it didn't have, right from the start, some easy way to access the prototype of each object.

By easy way I mean something like object.prototype, or object._prototype (and not the dirty proto)

For what I know, the Object.getPrototypeOf(obj) was just added in late 2008, almost 13 years after JavaScript was launched.

I'm asking this because I always wondered if JavaScript was ever meant to be used as a pure prototype based language, I mean, without using any function to construct objects (in other words, never using the new operator).

答:
Look up Object.create for an alternative to function constructors which I actually find very useful since they give you encapsulated instance vars via closure.

I'm not sure how long it's been available but I've been using <object>.constructor.prototype for some time now.

But really, JS was written in 10 days. It's been evolving from that rush job ever since. I'm not even sure they had prototype on function constructors when it was first released. Netscape's top brass wanted it to look like Java. Brendan Eich wanted it to work like Scheme (and decided he was making it look like C rather than Java, by which I assume he's stating he wasn't a huge fan even back then).

Also, Good Parts is a decent read but it's not the ultimate authority and Crockford has some really weird hang-ups about the language. Function constructors in particular which he's claimed are bad because you might forget to use new keyword and screw up. Well, you might forget to wear your pants in the morning too but you tend to notice pretty quick.

Took me a bit to find this but if you really want to know how it came about, it's best to go to the horse's mouth:

https://brendaneich.com/2008/04/popularity/


答:
PageRank

PageRank is a link analysis algorithm,
  named after Larry Page, used by the
  Google Internet search engine that
  assigns a numerical weighting to each
  element of a hyperlinked set of
  documents, such as the World Wide Web,
  with the purpose of "measuring" its
  relative importance within the set.


问:
Any tips in tackling extremely complex problems like the Hanoi Tower problem?
People often give me the "divide and conquer" tip, but I think for some problems it's not nearly enough. The problem with such a complex problem as the Hanoi Tower problem is that you can't even simulate or abstract parts of the problems even if you divide it into parts if you know what I mean. So, can anyone give me a step-by-step approach in tackling such a complex and difficult problem?</p>

答:
Divide and conquer is about making the problem so small that it is absolutely trivial to solve.  Then you make it slightly larger, and slightly larger, and look for patterns.

For Towers of Hanoi, what is the simplest possible problem?  One disk, moved straight to its destination.  The second simplest is two disks.  First you move one disk to a temporary spot, you move the second to the destination, then you move the first disk to the destination.

The next iteration is harder, but the trick here is to recognize that you already have proved you can move a stack of two disks, so you can abstract that away.  You move a stack of two to a temporary location, move the nth disk to its destination, then move the stack of two on top of it.

You now start to see a pattern emerge.  For n disks, you first move a stack of n-1 disks, then the nth disk, then you move the stack on top of it.  You know this is guaranteed to work, because you can define n-1 in terms of n-2, which you can define in terms of n-3, and so on until you eventually get to one disk, which is trivial.

Where people get into trouble is trying to hold every single iteration in their head at once.  You have to learn to trust that it works for n-1.

Here's a complete working implementation in C.  Pass in n as an argument.

```<code>#include <stdio.h>
#include <stdlib.h>

void hanoi(int n, const char* from, const char* to, const char* temp)
{
    if (n == 1)
    {
        printf("Move disk 1 from %s to %s.\n", from, to);
    }
    else
    {
        // Move n-1 sized stack to temporary location
        hanoi(n - 1, from, temp, to);

        printf("Move disk %d from %s to %s.\n", n, from, to);

        // Move n-1 sized stack from temp location to destination
        hanoi(n - 1, temp, to, from);
    }
}

int main(int argc, char* argv[])
{
    if (argc < 2)
        return -1;

    int n = atoi(argv[1]);

    hanoi(n, "left", "right", "middle");

    return 0;
}
</code>```

Body:
Divide and conquer is about making the problem so small that it is absolutely trivial to solve.  Then you make it slightly larger, and slightly larger, and look for patterns.

For Towers of Hanoi, what is the simplest possible problem?  One disk, moved straight to its destination.  The second simplest is two disks.  First you move one disk to a temporary spot, you move the second to the destination, then you move the first disk to the destination.

The next iteration is harder, but the trick here is to recognize that you already have proved you can move a stack of two disks, so you can abstract that away.  You move a stack of two to a temporary location, move the nth disk to its destination, then move the stack of two on top of it.

You now start to see a pattern emerge.  For n disks, you first move a stack of n-1 disks, then the nth disk, then you move the stack on top of it.  You know this is guaranteed to work, because you can define n-1 in terms of n-2, which you can define in terms of n-3, and so on until you eventually get to one disk, which is trivial.

Where people get into trouble is trying to hold every single iteration in their head at once.  You have to learn to trust that it works for n-1.

Here's a complete working implementation in C.  Pass in n as an argument.

#include <stdio.h>
#include <stdlib.h>

void hanoi(int n, const char* from, const char* to, const char* temp)
{
    if (n == 1)
    {
        printf("Move disk 1 from %s to %s.\n", from, to);
    }
    else
    {
        // Move n-1 sized stack to temporary location
        hanoi(n - 1, from, temp, to);

        printf("Move disk %d from %s to %s.\n", n, from, to);

        // Move n-1 sized stack from temp location to destination
        hanoi(n - 1, temp, to, from);
    }
}

int main(int argc, char* argv[])
{
    if (argc < 2)
        return -1;

    int n = atoi(argv[1]);

    hanoi(n, "left", "right", "middle");

    return 0;
}


问:
Best way to share (make accessible) to the world a maybe useful self-written utility script/program?
Throughout my life I've accumulated a fair share of scripts that have proven to be useful to me in many cases and might be useful to many others.  I look at things like todo.txt (which probably started off as just someone's personal text file manager) and even simpler ones online and sometimes I feel like I want to put my stuff out there for people who are looking for it to be able to use, open source.

What's the best way to just put things out there where people who might want to find it would find it?  Should I start a well-read blog?  post in forums?  I don't want to advertise or spam it, just have it in some kind of way where anyone who would might be looking for something of similar functionality would find it through google or something.

答:
I have found github to be really useful as a place to open-source my code.  If you aren't familiar with github, it's a relatively secure backup-and-hosting system for git repositories of whatever you like.  There's also Gitorious, and Bitbucket, which also supports Mercurial.  Nevertheless, github seems to be winning mindshare.

Making the world aware of code is a lot trickier.  I think you could put your scripts into your online repository host of choice, and then link answers on stackoverflow to code samples in your repositories related to the question answered.  You could also edit some of your older but high-profile answers with links to examples online.

After that, a blog or other website that references your codebase, cross-linked with your new answers in technical StackExchange sites, seems like a good place to start being a higher hit in google searches.


答:
I feel like I see a fair number of people come by Stack Overflow to promote a tool they've made.  I think it's more in-tune with the Stack Overflow "vibe" if the tool is open source and the code is freely available on a popular host such as GitHub, Bitbucket, or Google Code rather than a paid product.

You definitely have to be careful if you choose this route -- blatant spamming will most likely get you banned, but if you provide careful, helpful answers on how to use your software to solve that person's specific problem, you add value to Stack Overflow while still promoting your work.

If the code you want to share isn't a fully cohesive toolset, you might want to just save the individual scripts as gists on GitHub rather than having a single repository with a variety of unrelated scripts in it so that it's easier to share a single script at a time.

Title: Best way to share (make accessible) to the world a maybe useful self-written utility script/program?

Body:
Throughout my life I've accumulated a fair share of scripts that have proven to be useful to me in many cases and might be useful to many others.  I look at things like todo.txt (which probably started off as just someone's personal text file manager) and even simpler ones online and sometimes I feel like I want to put my stuff out there for people who are looking for it to be able to use, open source.

What's the best way to just put things out there where people who might want to find it would find it?  Should I start a well-read blog?  post in forums?  I don't want to advertise or spam it, just have it in some kind of way where anyone who would might be looking for something of similar functionality would find it through google or something.


答:
Definitely learn a new language or library with this project in these conditions.  Your website seems like it's not under pressure to ship immediately, so you can take the time to learn something new as part of building the website.  You can build a couple of toy ones to start, and iterate to a stronger understanding of the tool you're trying to add to your toolset.

Learning a different programming paradigm is a great way to expand your horizons as a programmer, and leave you better prepared to deal with unusual code later in your career.  This is one of the ideas behind the book Seven Languages in Seven Weeks, which would be a great way to stretch your brain.  Even if you go for something you know better in this case, grab the book and work on it.  It can give you insights into programming problems you might not otherwise have.

Of the options you list, I think learning Scala would probably stretch your brain the most, as it is the most different paradigm to Java on that list.  Scala has some strong functional programming aspects, which provide a contrast to the OOP paradigm of Java. Scala works on the JVM,  so there are probably plenty of Scala development tools that would plug into tools you're familiar with from your Java development.  This could get you up and running sooner, and reduce overall frustration.

I'm primarily a Python programmer, so I think this would also be a good choice.  Learning more Python could make you more productive at work.  Also, Python is a multiparadigm programming language, which would give you an opportunity to learn elements of functional programming and imperative programming paradigms in a language that you already have some familiarity with. in a language    There are a number of web application frameworks for Python with years of history behind them.  I'm most familiar with CherryPy, but it's old and weird and you might be better off starting with Pyramid, Django or something simple like WebOb.

Most importantly, however you choose to build this project, keep stretching yourself and challenging yourself. A broader understanding of programming and programming languages makes it easier to later pick up new languages and frameworks when you inevitably need to do so.  It's a great investment into a vital programming career.

Title: Build website using a known language or a new one?

Body:
So there is a website that I want to build. It will be a review aggregator and probably a bit more. I want to build this website for three reasons:

I really think this website will be used by a reasonable amount of people

I want to practice my programming skills since currently at my job I am doing mostly scripting

Maybe learn a new language. I am currently torn though since my immediate reaction is that I want to use Java since I know it relatively well, like it, and feel it will allow me to put something up as quickly as possible. I would also like to use an existing Web Application Framework.

If I don't end up going with Java I would probably go with one of the following:

C#/.NET - I prefer static languages, and this is similar to Java.

Python - I use this at my job superficially and it seems that a lot
of people are using it.

Ruby - Seems to have a very well established framework

Scala - Has some similarities to Java but from what I read it's a
different paradigm

So I guess my question is under these circumstances do you think that I should build a website using a known language or a new one?


答: PageRank, love it or hate it, but it affects decisions and actions of millions people worldwide googling on a daily basis. </p>


问:
How to solve the problem of nested comments
It appears in not just one language that comments can't be nested. Do you have a good solution for this problem? One workaround in C/C++ and Java is to only use the single-line comment but it becomes impossible then to comment out a larger block. I'm facing something like this:

```<code></li><!--
                <li><!-- Save -->
</code>```

So I must manually go through and edit the comments. Can you advice how we should handle this, in many languages? I'm not sure but maybe python has a solution for this with the ''' way that might be able to include a # comment in python?
`

答:
The best solution is, obviously, to just not nest your comments. Nested comments are usually a sign that you are using comments wrong. The most common example is commented-out code that contains comments itself, and the fix is to remove the code instead of commenting it out.

That said, many programming languages have more than one type of comment syntax, and you can use this fact to nest at least one level deep. For example, in Java:

```<code>/* This is commented out!
Foo.bar.baz();
// And now for something completely different...
Quux.runWith(theMoney);
*/
</code>```

Also, in many languages, at least one type of comment is kind-of-nestable; in C-like languages, line comments inside line comments are ignored:

```<code>// some_commented_out(code);
// // This is a comment inside the comment!
// // Still inside the nested comment.
// some_more_code_in(outer_comment);
</code>```

Most IDEs support commenting entire blocks of code with line comments in one action, and they handle this kind of commenting style correctly. The same example in Python:

```<code># some_commented_out(code)
# # This is a comment inside the comment!
# # Still inside the nested comment.
# some_more_code_in(outer_comment)
</code>```

Often, coding standards for a particular project have rules about which comment style to use when; a common convention is to use block comments (/* */) for method and class documentation, and inline comments (//) for remarks inside method bodies and such, e.g.:

```<code>/**
 * Helper class to store Foo objects inside a bar.
 */
public class Foobar {
    /**
     * Stores a Foo in this Foobar's bar, unless the bar already contains
     * an equivalent Foo.
     * Returns the number of Foos added (always 0 or 1).
     */
    public int storeFoo(Foo foo) {
        // Don't add a foo we already have!
        if (this.bar.contains(foo)) {
            return 0;
        }
        // OK, we don't have this foo yet, so we'll add it.
        this.bar.append(foo);
        return 1;
    }
}
</code>```

With such a style, it is unlikely that you'll ever need to nest /* */ comments (if you have to temporarily disable entire methods or classes, renaming them work just as nicely, if not better); and // comments do nest, at least with a little help from your IDE.

Finally, to disable code, you have other options in many programming languages; for example, in C, you can leverage the preprocessor:

```<code>this_is(activated);
#if 0
this_is(!activated);
/* Comments inside this block don't really nest, they are simply removed
   along with the rest of the block! */
#endif
</code>```

In dynamic languages, you can often just use regular if statements instead:

```<code><?php

if (0) {
   // This should never run...
   some_stuff_that_should_never_run();
}
</code>```

However, unlike the CPP example, this strategy requires the source file as a whole to be syntactically valid, so it's by far not as flexible.

And finally, there are at least some languages that allow for nested comments. In case you're interested, wikipedia has a nice comparison chart.

Body:
The best solution is, obviously, to just not nest your comments. Nested comments are usually a sign that you are using comments wrong. The most common example is commented-out code that contains comments itself, and the fix is to remove the code instead of commenting it out.

That said, many programming languages have more than one type of comment syntax, and you can use this fact to nest at least one level deep. For example, in Java:

/* This is commented out!
Foo.bar.baz();
// And now for something completely different...
Quux.runWith(theMoney);
*/

Also, in many languages, at least one type of comment is kind-of-nestable; in C-like languages, line comments inside line comments are ignored:

// some_commented_out(code);
// // This is a comment inside the comment!
// // Still inside the nested comment.
// some_more_code_in(outer_comment);

Most IDEs support commenting entire blocks of code with line comments in one action, and they handle this kind of commenting style correctly. The same example in Python:

# some_commented_out(code)
# # This is a comment inside the comment!
# # Still inside the nested comment.
# some_more_code_in(outer_comment)

Often, coding standards for a particular project have rules about which comment style to use when; a common convention is to use block comments (/* */) for method and class documentation, and inline comments (//) for remarks inside method bodies and such, e.g.:

/**
 * Helper class to store Foo objects inside a bar.
 */
public class Foobar {
    /**
     * Stores a Foo in this Foobar's bar, unless the bar already contains
     * an equivalent Foo.
     * Returns the number of Foos added (always 0 or 1).
     */
    public int storeFoo(Foo foo) {
        // Don't add a foo we already have!
        if (this.bar.contains(foo)) {
            return 0;
        }
        // OK, we don't have this foo yet, so we'll add it.
        this.bar.append(foo);
        return 1;
    }
}

With such a style, it is unlikely that you'll ever need to nest /* */ comments (if you have to temporarily disable entire methods or classes, renaming them work just as nicely, if not better); and // comments do nest, at least with a little help from your IDE.

Finally, to disable code, you have other options in many programming languages; for example, in C, you can leverage the preprocessor:

this_is(activated);
#if 0
this_is(!activated);
/* Comments inside this block don't really nest, they are simply removed
   along with the rest of the block! */
#endif

In dynamic languages, you can often just use regular if statements instead:

<?php

if (0) {
   // This should never run...
   some_stuff_that_should_never_run();
}

However, unlike the CPP example, this strategy requires the source file as a whole to be syntactically valid, so it's by far not as flexible.

And finally, there are at least some languages that allow for nested comments. In case you're interested, wikipedia has a nice comparison chart.


答:
C and C++ does have a nested block comments:

```<code>#if 0
#endif
</code>```

Many highlighting editors understand this as a comment and many other will at least highlight it as any other conditionally disabled code.

In many other languages you have to rely on editor support. For languages that only have line-based comments (perl, python, ruby, shell...) it is rather simple to prepend the comment character to all lines in a range, so most editors can do this. You can still tell what were comments before commenting out the whole block because the comment character is doubled — doing it simply is advantage here.

XML and SGML is probably biggest pain, it's comment definition is just stupid. The comments would have been trivial to nest, but they not only don't, it is completely prohibited to have -- inside comment. Unfortunately I don't know which editors have good support for commenting out in SGML/XML.

Title: How to solve the problem of nested comments

Body:
It appears in not just one language that comments can't be nested. Do you have a good solution for this problem? One workaround in C/C++ and Java is to only use the single-line comment but it becomes impossible then to comment out a larger block. I'm facing something like this:

```<code></li><!--
                <li><!-- Save -->
</code>```

So I must manually go through and edit the comments. Can you advice how we should handle this, in many languages? I'm not sure but maybe python has a solution for this with the ''' way that might be able to include a # comment in python?
`

Body:
C and C++ does have a nested block comments:

#if 0
#endif

Many highlighting editors understand this as a comment and many other will at least highlight it as any other conditionally disabled code.

In many other languages you have to rely on editor support. For languages that only have line-based comments (perl, python, ruby, shell...) it is rather simple to prepend the comment character to all lines in a range, so most editors can do this. You can still tell what were comments before commenting out the whole block because the comment character is doubled — doing it simply is advantage here.

XML and SGML is probably biggest pain, it's comment definition is just stupid. The comments would have been trivial to nest, but they not only don't, it is completely prohibited to have -- inside comment. Unfortunately I don't know which editors have good support for commenting out in SGML/XML.


答:
While not a general solution, and certainly not ideal, one way to tackle this particular problem is to use the server side template processing language to do block comments for nested code comment elements.  This leaves the content essentially intact, but prevents sending it to the client browser. </p>

<p>That doesn't help a lot if the file is otherwise straight and pure content that requires no other server side processing.  In that case and the more general case of nested comments, ask why do you want to do that.  In most of those cases, one might find that the best way to handle it is to not handle it all.  In other words, if you want to eliminate a section, then eliminate it, and let version control handle remembering the differences if that section as an artifact ever needs to be resurrected. </p>

Body:
While not a general solution, and certainly not ideal, one way to tackle this particular problem is to use the server side template processing language to do block comments for nested code comment elements.  This leaves the content essentially intact, but prevents sending it to the client browser.

That doesn't help a lot if the file is otherwise straight and pure content that requires no other server side processing.  In that case and the more general case of nested comments, ask why do you want to do that.  In most of those cases, one might find that the best way to handle it is to not handle it all.  In other words, if you want to eliminate a section, then eliminate it, and let version control handle remembering the differences if that section as an artifact ever needs to be resurrected.


问:
if i have many calls of single method that returns field value, is it better to make a local variable?
In a method, i have calls of single method of another object that returns field value, like foo.value(), which is defined like Field value() {return this.value;} Is it better to make a local variable, like Field value = foo.value() and use it. Or use many method calls of a single method? Why? How does it correlate with number of method calls, like for 3, 5, 10 what will be better and why it may be a concern?

Edit: field doesn't change anyhow during the flow of a method, just the same value all the time.

Edit2: does it depend on programming language? If it's important, it's java.

答:
For the sake of clarity, I would suggest using final Field value = foo.value() (final since you specify the value doesn't change) if you have more than a single method call. Performance wise there will be no difference, the JIT compiler will likely completely inline all the calls to a simple accessor method.

There are a few reasons to prefer this: most important is that this shows whoever is reading the code that you are definitely using the same variable, and it definitely does not change (by use of final). This is more clear than using multiple methods calls - whoever is reading it will need to chase down if it really is using the same thing each time you call a method. Less importantly, if the method name changes, it only needs to change in one spot here, instead of needing to modify it at each point where it is used.


问:
How do I explain the value of refactoring to stakeholders?
How do I convince project managers, product owners, business analysts, clients and various other stakeholders that refactoring is a worthwhile and productive part of the development process?

As developers we all know that requirements change or are never fully explained from the start, and therefore how we wrote a piece of code in the past doesn't make sense now and needs to change. We know that if we redesign a some code now it will save us headaches in the long run. We know that if we keep our codebase clean and tidy, it will improve maintainability and ultimately lead to better code.

But however I put this to stakeholders, I just can't seem to get the value across. To them, refactoring is an unconstructive waste of time (by its very definition - the user should see no change in the application). To them it delivers no business value (or at least no immediate business value) because it delivers no new features, and they will strongly resist any refactoring.

I can't be involved in a codebase where refactoring doesn't happen because I've been there before and I've seen how it ends up. So instead i sneak it in when working on a feature. I would far rather be doing it openly so the stakeholders can get a clearer idea of the development process.

Any ideas on how to get this across?

答:
I much prefer not to bother non-technical people with such technical details. To me, refactoring is just part of the process of delivering a feature (and thus is part of the estimation for the features).

If you really have to sell refactoring to non-technical people, I would sell it as a bug-prevention measure (by reducing complexity and duplication, you reduce the risk of introducing bugs) and a X-fold time-saver for the next feature (it is far easier to add new features to well-structured maintainable code).
That way, the value is not so much in the business value it adds now, but in the increased productivity next week/month/year.


答:
If you are sure that the value does not change there is no reason to save this in a local variable.

Java HotSpot has the ability to detect such repeated call and will inline the method call.

Therefore it is more a matter of taste than anything else.

EDIT
Also for renaming: most IDEs support refactoring method calls.

Title: if i have many calls of single method that returns field value, is it better to make a local variable?

Body:
In a method, i have calls of single method of another object that returns field value, like foo.value(), which is defined like Field value() {return this.value;} Is it better to make a local variable, like Field value = foo.value() and use it. Or use many method calls of a single method? Why? How does it correlate with number of method calls, like for 3, 5, 10 what will be better and why it may be a concern?

Edit: field doesn't change anyhow during the flow of a method, just the same value all the time.

Edit2: does it depend on programming language? If it's important, it's java.


问:
Difference between the Adapter pattern and the Proxy pattern?
As far as I understand, the adapter pattern is creating a wrapper object for our real object of interest, simply one more level of indirection, which provides flexibility. The flexibility is in that if the real object's interface is changed, then we change the wrapper interface pointing at the real object, leaving the client-side exposed interface unchanged.

The proxy pattern is the same, with the difference that every proxy wrapper provides only a coherent subset of the real object's functionality. Why would this be useful when we strive to make "one class for one purpose" is beyond me.

Have I gotten this correctly?

答:
Not entirely.

The primary purpose of the adapter pattern is to change the interface of class/library A to the expectations of client B. The typical implementation is a wrapper class or set of classes.
The purpose is not to facilitate future interface changes, but current interface incompatibilities.

The proxy pattern also uses wrapper classes, but for a different purpose. The purpose of the proxy pattern is to create a stand-in for a real resource. Reasons for using a proxy can be

The real resource resides on a remote computer (the proxy facilitates the interaction with the remote resource)

The real resource is expensive to create (the proxy ensures the cost is not incurred unless/until really needed)

The most important thing is that a proxy provides a drop-in replacement for the real resource it is a stand-in for, so it must provide the same interface.

ContentLicense: CC BY-SA 4.0


问:
All images in one folder for a website?
When creating websites, is it better to have a lot of images in one folder, or have them separated?

It's something that has always been in my mind but I never researched enough about it, and googling didn't give me many answers.

So I have been building mostly sites for real estate agencies since I started, and I always liked to organize the images by folders, lets say in webroot/photos/$propertyId/ but sometimes I've seen websites storing all the images in a folder, and differencing them mainly by the name.

I never had to build a huge website, so this has been in my mind but didn't concern me too much, but I would like to know, generally which of the 2 ways is a better approach. Is there really a human noticeable performance difference when performing different action like searching/deleting those files?

Keep in mind that sometimes there's not a images limit on the galleries, so having one column per image path/name in the property's row is not often an option for me, I would have to use another table to relate them.

Also I would like to mention that for example in my last project I had to manage tens of GB's of images, we had like 300000 properties and they had lets say an average of 10 pictures per property.

答:
Most file system limits how many files you can have in a directory, which means you are forced to use subdirs anyway if the amount can grow indefinitely. Beware there is a limit on number of dirs as well (which is usually lower, say 32000 on ext3)

If you can calculate the exact path to a file then there is no performance problem reading that file.

Listing files in a huge directory can get really, really slow. I know this from experience.

I'd recommend use the id  and then the modulu (%) operator to figure out where to put the file. Simple and scalable. For instance the path to image with id 12345 could be created like this:

```<code>12345 % 1000 = 345
</code>```

Ends up in:

```<code>/webroot/photos/345/12345.png
</code>```

Title: All images in one folder for a website?

Body:
Most file system limits how many files you can have in a directory, which means you are forced to use subdirs anyway if the amount can grow indefinitely. Beware there is a limit on number of dirs as well (which is usually lower, say 32000 on ext3)

If you can calculate the exact path to a file then there is no performance problem reading that file.

Listing files in a huge directory can get really, really slow. I know this from experience.

I'd recommend use the id  and then the modulu (%) operator to figure out where to put the file. Simple and scalable. For instance the path to image with id 12345 could be created like this:

12345 % 1000 = 345

Ends up in:

/webroot/photos/345/12345.png


答:
I think we need to distinguish between refactoring and redesign here.

Refactoring is embedded deep into small development loops, it shouldn't span more than a TDD cycle or a task and should certainly not be a separate Story. It's one of those micro practices that make your code quality code. Since in Agile quality is not negotiable, and since refactoring is basically invisible at the stakeholder level, you shouldn't even have to tell your stakeholders you're doing it, much like you don't tell them you're using this design pattern or that programming style.

Redesign on the other hand can last much longer. It's changing whole parts of your code base to reduce technical debt. It may be replacing tight coupling with dependency injection on a whole module, it may be introducing AOP to get rid of duplicate logging code, it may be revising the way your data access objects work to allow for more efficient database queries. Sure, you aren't changing any functionality, but the impact such large reworks can have on the project is worth mentioning to decision makers. This is where you typically create a technical story or a spike in your backlog after the stakeholder has approved the idea. Even if they're not that easy to find, there are generally more arguments you can use than with simple refactoring - performance, bug fixing, maintenance cost, deployment cost, codebase learning curve cost, etc. And if they don't deem the effort worthy - well, it's their product and you've made sure to warn them about what might happen.

So my advice would be : don't try to convince stakeholders about how you're working every minute as a professional - this is not negotiable. Try to do more refactoring so as to minimize the amount of redesign you'll have to justify afterwards.

Title: How do I explain the value of refactoring to stakeholders?

Body:
How do I convince project managers, product owners, business analysts, clients and various other stakeholders that refactoring is a worthwhile and productive part of the development process?

As developers we all know that requirements change or are never fully explained from the start, and therefore how we wrote a piece of code in the past doesn't make sense now and needs to change. We know that if we redesign a some code now it will save us headaches in the long run. We know that if we keep our codebase clean and tidy, it will improve maintainability and ultimately lead to better code.

But however I put this to stakeholders, I just can't seem to get the value across. To them, refactoring is an unconstructive waste of time (by its very definition - the user should see no change in the application). To them it delivers no business value (or at least no immediate business value) because it delivers no new features, and they will strongly resist any refactoring.

I can't be involved in a codebase where refactoring doesn't happen because I've been there before and I've seen how it ends up. So instead i sneak it in when working on a feature. I would far rather be doing it openly so the stakeholders can get a clearer idea of the development process.

Any ideas on how to get this across?


问:
Which are the significant algorithms for humankind in past decades?
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...

答: Soundex is a phonetic algorithm for indexing names by sound.</p>


问:
Does the ray tracing algorithm involves rasterization of image?
I am constructing a ray tracing algorithm , i know that the first step is to develop camera and view plane specifications.
Now is the next step performing rasterization algorithm on image before a BVH tree is constructed so that intersection tests can be performed?

Kindly Guide

答:
That I'm aware, intersection tests are done using the geometry prior to having the individual pixels.  You don't need to worry about rasterization until near the end when you're trying to determine what color a pixel should have based on what you've discovered.  And really, you're talking about a sort of antialiasing.  In ray tracing, that basically amounts to jostling the camera by very small amounts and averaging the pixel colors so that you end up with pixels that better reflect what you're raytracing.

Strictly speaking, you don't need this in order to have a ray tracer.  You should focus on getting an image first.  Once you have that, then you can apply antialiasing on the image data obtained.


答:
The alternative is to store the files themselves in a database (as large byte blocks). However, this turns out to have an impact on performance, and some say it's not really what databases were built for.

The one advantage of databases I've heard is that it's more secure - someone rummaging on the webserver's filesystem could grab the images, but it would be more difficult for them if it's in a database. (And of course, you lose that security if you cache images anywhere, which would be my one recommendation to help performance)

Also, it may be worth noting another alternative is hosting images with professionals like Amazon. It costs some money, but users are connected to servers close to themselves, and all your server needs to do is maintain the correct URLs for each image.

Title: All images in one folder for a website?

Body:
When creating websites, is it better to have a lot of images in one folder, or have them separated?

It's something that has always been in my mind but I never researched enough about it, and googling didn't give me many answers.

So I have been building mostly sites for real estate agencies since I started, and I always liked to organize the images by folders, lets say in webroot/photos/$propertyId/ but sometimes I've seen websites storing all the images in a folder, and differencing them mainly by the name.

I never had to build a huge website, so this has been in my mind but didn't concern me too much, but I would like to know, generally which of the 2 ways is a better approach. Is there really a human noticeable performance difference when performing different action like searching/deleting those files?

Keep in mind that sometimes there's not a images limit on the galleries, so having one column per image path/name in the property's row is not often an option for me, I would have to use another table to relate them.

Also I would like to mention that for example in my last project I had to manage tens of GB's of images, we had like 300000 properties and they had lets say an average of 10 pictures per property.


问:
Why the current enthusiasm for Functional Programming?
I've been hearing a lot of enthusiasm about functional programming languages lately, with regards to Scala, Clojure, and F#.  I've recently started studying Haskell, to learn the FP paradigm.

I love it, it's really fun, and fits my math background.

But will it ever really matter?  Obviously, it's hardly a new idea.

Here's my questions:

What has contributed to the recent FP enthusiasm?  Is is merely boredom with OO, or has something changed to make FP more needed than before?

Is this indicative of a FP future?  Or is this a fad, like object orient databases?

In other words, can anyone help me understand where this comes from and where it might be going?

答:
I think the main answer to that question is 'exposure'.

Functional programming is nothing new, I was taught Haskell at university some 12 years ago and loved it.  But rarely got to use the language in my professional work.

Recently there have been a number of languages gaining traction in the main stream that use a multi-paradigm approach; F#, JavaScript being prime examples.

JavaScript in particular, especially when used with a functional-style framework language like jQuery or Prototype, is becoming an everyday language for many people due to all the work on dynamic modern websites.  This exposure to the functional style makes people realise the power it grants, especially when one is able to drop back to an imperative style at will.

Once people are exposed, they try out more fully fledged variants of functional languages and start to use them for day-to-day tasks.

With F# becoming a first-class language in Visual Studio 2010 and jQuery (et al) becoming so important, it is becoming realistic to use these languages, rather than just something obscure to play with or make isolated programs.

Remember that code has to be maintainable - a critical mass of developers must use and support languages in order for companies to feel safe in using them.


问:
Mnemonic for always overriding equals when you override hashCode?
We java developers always know that you should always override equals() when you override hashCode(), but I consistently have trouble remembering this rule.

What is a clever mnemonic to help Java developers remember this?

答:
Using FindBugs or CheckStyle as part of your build process?

Or set your IDE to warn about this? At least Eclipse can be configured for that since Eclipse 3.5, and NetBeans.

Note that your IDEs can also probably generate them for you (more or less correctly).


问:
Isn't GPL enough to make a software free as in free speech?

Background

I have read people rebutting the fact that a certain software is free as in free speech, even when it is licensed under GPL.

Some say Java isn't free because to obtain a professional certification you must get it from Oracle.

Some say Java JDK is not free to re-distribute.

Some people even say the openJDK is not free or open.

But Java is officially GPL.

Questions

Doesn't GPL explicitly mean you are free to re-distribute ?

Isn't GPL enough to make a software free as in free speech ?

How can Java be both GPL and not-free as in free speech ?

Is there is any license that trully makes a software free beyond any possible subjetive point of view?

EDIT: These question is not about names or trademarks, it's about the code.

答:
Java is free. You can redistribute it according to the GPL.

You can even fork Java and distribute that. But may not name it Java anymore. After forking it is something different.

BTW IANAL. Ask a lawyer if in doubt.


答:
Being GPL means that:

Anyone can create a fork, that is, a modification, to the "original" code.

Anyone who distributes a modified version have to credit the original authors

Anyone who distributes a modified binary version also have to distribute the source code of that binary version to anyone they give/sell it to.

More details

This is something very different from trademarks, something the Java name is. That trademark belongs to Oracle, so nobody else may distribute a similar product (even if based on the same sources) and call it "Java". "OpenJava", "FreeJava" and "JavaTheLanguageNotTheCoffee" should be fine.

[Generic 12 page IANAL disclaimer]

Title: Isn't GPL enough to make a software free as in free speech?

Body:
Background

I have read people rebutting the fact that a certain software is free as in free speech, even when it is licensed under GPL.

Some say Java isn't free because to obtain a professional certification you must get it from Oracle.

Some say Java JDK is not free to re-distribute.

Some people even say the openJDK is not free or open.

But Java is officially GPL.

Questions

Doesn't GPL explicitly mean you are free to re-distribute ?

Isn't GPL enough to make a software free as in free speech ?

How can Java be both GPL and not-free as in free speech ?

Is there is any license that trully makes a software free beyond any possible subjetive point of view?

EDIT: These question is not about names or trademarks, it's about the code.


答:
"Free" is a pretty vaguely defined word, and you'll never find a definition with which absolutely everyone agrees.

In the case of Java, a lot of doubt probably stems from the fact that the JDK used to be partially closed source - the OpenJDK project was started only in 2006. Some of hte things you read may be from before that time.

With the GLP-licensed OpenJDK now being the reference implementation, Java has become a lot "freer" than it used to be, probably "free" enough for most people.

But there remain two pain points:

The test suite that certifies an alternative implementation's compatibility with Java standards is not GPL - it's under a very restrictive license that doesn't even allow you to run the code unless your implementation is derived from the OpenJDK.

The patent lawsuit of Oracle vs. Google over Android's Dalvik VM gave a alot of people doubts over Oracle's commitment to "freedom". Having the code under the GPL doesn't mean much when adapting it may violate patents.


答:
They have the GPL'd openJDK and their own license for JavaSE (JRE and SDK, which is technically Oracle JDK to differentiate it).

The OpenJDK is maintained by Oracle and follows suit with the developments on JavaSE.

So... yes, openJDK is free as in free speech. And you are perfectly free to take that code, fork it, and release your own better version of Java. Say, the Libre version. But unless there was a schism, no one would use it and it would wither and die. Because everyone uses Oracle's Java, and Oracle is steering the boat.

Even though the license makes a perfectly free option, you have to look at the politics involved. Take OpenOffice for example. An open project, woo. But then Oracle bought Sun,  took over the project, and some people didn't like where they were steering things. And because it's an open source project they split off, make LibreOffice, and the world moved on.

Even with a legally open and free license you still have to flex that muscle every now and then. There's a strong similarity with liberties and rights in general. Being open and free ALLOWS you to do what you want with Java, but that doesn't mean that you're going to break Oracles grip on it. Oracle controls Java, despite whatever license of whatever version it has.


问:
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 think that it depends on what level of support you need.

I use git at home for my fun projects when having a problem costs me time, but I can spend the time learning what I need to fix it.

At work we use Perforce because having 24/7 tech support is imperative. We have people working on the code in New York, Germany, Ireland, and Japan all the time. If there is a problem we have to get an answer ASAP. In my experience the people at Perforce really know what they are doing and are receptive to suggestions.


问:
How to construct UML activity diagram reflecting real programmed source code as docs
Please, tell me the things I must use for modeling an (Enterprise Architect) activity diagram of

```<code>object1.method1() calls object2.method2()
</code>```

I'm able to dragndrop a method of a class from model tree-view to my diagram, and it appears as new action there. But there is no hint about its belonging object. Also I don't get it which arrow type I must use to model that one calls the other.

My feeling is it's not very appropriate for constructing documentation of typical call scenarios of my application. You know I want to create UML docs for what we've programmed until now.

答:
Activity diagrams don't use the concept of objects, as they usually don't show who does what, but only which actions/decisions are taken.
You could use partitions (also called swim lanes) to indicate who executes the actions, but if you have more than two or three objects interacting, this can become rather unreadable.

For describing the interactions between several objects, it will be better to use a sequence diagram or a communication diagram (sometimes referred to by its old name of collaboration diagram).