答:
In the original book that coined the terms Observer and Mediator, Design Patterns, Elements of Reusable Object-Oriented Software it says that the Mediator pattern can be implemented by using the observer pattern.  However it can also be implemented by having Colleagues (roughly equivalent to the Subjects of the Observer pattern) have a reference to either a Mediator class or a Mediator interface.

There are many cases when you would want to use the observer pattern, they key is that on object should not know what other objects are observing it's state.

Mediator is a little more specific, it avoids having classes communicate directly but instead through a mediator.  This helps the Single Responsibility principle by allowing communication to be offloaded to a class that just handles that.

A classic Mediator example is in a GUI, where the naive approach might lead to code on a button click event saying "if the Foo panel is disabled and Bar panel has a label saying "Please enter date" then don't call the server, otherwise go ahead", where with the Mediator pattern it could say "I'm just a button and have no earthly business knowing about the Foo panel and the label on the Bar panel, so I'll just ask my mediator if calling the server is O.K. right now."

Or, if it is implemented using the observer pattern the button would say "Hey, observers (which would include the mediator), my state changed (someone clicked me).  Do something about it if you care".  In my example that probably makes less sense, but sometimes it would, and the difference between Observer and Mediator would be more one of intent than a difference in the code itself.

Title: Mediator vs Observer?

Body:
Can someone provide me with a canonical answer on the differences between an Observer and a Mediator, and a summary of when you should use one pattern over the other?

I am unsure of what kind of situation would require an Observer and what kind would require a Mediator


问:
Is it a good practice to name the returned variable "result"?
Is it a good practice to call the variable a method returns with a variable name result?

For instance:

```<code>public Zorglub calculate() {
    Zorglub result = [...]
    [...]
    return result;
}
</code>```

Or should I name it by its type?

```<code>public Zorglub calculate() {
    Zorglub zorglub = [...]
    [...]
    return zorglub;
}
</code>```

I have seen both in the wild, if I need to choose one what reasons could make me prefer the former or latter (or any better name)?

I am mainly thinking about Java.

答:
In Object Pascal this is not a choice. You have to assign value to the Result variable somewhere in the code of the function.

Example:

```<code>function AddIntegers( A,B: Integer): Integer;
begin
  Result := A + B;
end;
</code>```

So for me is pretty natural have an "Result" (or "Retorno", as I spell it in Portuguese to avoid name conflict with language's reserved words) variable to receive an return value.

Of couse, if it's a very simple expression in a C-derived language, I won't bother  to declare an result variable - returning the expression directly.

ContentLicense: CC BY-SA 3.0

Body:
In Object Pascal this is not a choice. You have to assign value to the Result variable somewhere in the code of the function.

Example:

function AddIntegers( A,B: Integer): Integer;
begin
  Result := A + B;
end;

So for me is pretty natural have an "Result" (or "Retorno", as I spell it in Portuguese to avoid name conflict with language's reserved words) variable to receive an return value.

Of couse, if it's a very simple expression in a C-derived language, I won't bother  to declare an result variable - returning the expression directly.


问:
Feedback on this back-end stack
I'm planning to setup an scalable architecture capable of providing web services on a REST interface where JSON will be sent as a result.
The web services will be quite simple for a CRUD web 2.0 app.

I think javascript (nodejs + mongodb) is a good choice for the following reasons:

Easy to find javascript developers

Good performance

Easy to scale

Shared logic/language or possible reuse of code between database query language, back-end and web-client.

There are testing and logging frameworks for node

By the examples I've seen node seems light in terms of the lines of code needed to implement web services.

Questions:

I think of scaling a node app which supplies a web service as having
a central node which will be routing/balancing charge to each of the
node instances. Which will also help doing seamless updates, is
there any piece of software already implemented which can fit that
task?

Please point all the disadavantages or other advantages you find in this back-end stack

Any other good persistence choices other than MongoDB? Mainly this choice comes from the javascript query language and JSON schemas.

答:
Easy to find javascript developers

It's plenty easy to find mediocre JS developers. The good ones are rare. Especially a full stack front-end/node combo.

Shared logic/language or possible reuse of code between database query language, back-end and web-client.

Certainly possible but don't overvalue this too much. You need some rock solid infrastructure to make this happen.

There are testing and logging frameworks for node

There are testing and logging frameworks for everything. Even C.

However node does

Have solid performance

Easy scalability

make it easy to write web services

One recommendation I would give is you swap out that "Router" with a decent elastic load balancer

I think of scaling a node app which supplies a web service as having a central node which will be routing/balancing charge to each of the node instances. Which will also help doing seamless updates, is there any piece of software already implemented which can fit that task?

It's called an ELB. Do not re-invent that wheel (and if you do make it open source o/)

Please point all the disadavantages or other advantages you find in this back-end stack

This would involve knowing specific application requirements and features. It's a sensible structure, it's a sensible stack.

Any other good persistence choices other than MongoDB? Mainly this choice comes from the javascript query language and JSON schemas.

There are a whole bunch of noSQL solutions. Go explain your exact application to a noSQL expert and get his opinion. Offer him coffee.

Other then that the only main thing you forgot is in memory cache (Redis) attached to every node instance.

The other main thing you forgot is how to actually architecture the application inside the nodejs box. Overall your system level architecture seems decent. I'd totally recommend nCore for your node.js application infrastructure.

Title: Feedback on this back-end stack


问:
Mobile Web Security Articles
I'm starting to introduce mobile web apps to my company but my not-so-techie boss is worried about web security issues on mobile devices.

I'm new in the mobile world but as a web developer I know the basics about web security (like the best practices listed in OWASP) but I don't know if there's anything else that could make my mobile web app vulnerable specifically for mobile web browsers.

Also, I need an internet article readable from not-so-techie bosses that could help me convince him how secure our mobile web app could be if I apply the common web security best practices.

Can you help me with this?

PS. I'm using Java as my backend and jQuery Mobile as my frontend.

答: Your scenario has little to do with mobile web security and more to do with plain old fashioned remote access to stuff that used to be locked behind the old corporate firewall. So the same issues apply by and large. Mobile just adds some interesting wrinkles -- like spotty VPN support and higher chance of loss or theft of device. </p>

Title: Mobile Web Security Articles


问:
Are Vim or Emacs practical for languages like .Net or Java?
So, I am primarily a .Net developer who does some stuff in Java, Python and a few others from time to time. I have heard a lot of people praise Vim and Emacs for greatly increasing efficiency once the basics are nailed down. I can definitely see how many of the features could be very useful with sufficient practice, and even believe the learning curve is probably worth the effort. However...it seems that you would really have to be some sort of wizard of macros and hotkeys to be as efficient in Vim or Emacs as the average developer is in Visual Studio, Netbeans, Eclipse, or other platforms. I have been starting to learn to use Vim and think some of its features are awesome (column editing for example), but it seems that many of the tools provided by the heavy weight IDEs simply could not be replaced buy even the most juiced up text editor. A few processes I would be skeptical anyone could ever be more efficient at in Vim include (I know VS best, so I will stick to those):

generating dbml files for Linq-to-SQL

Automated testing

designing UIs

Creating/organizing projects and solutions

I know Vim and Emacs can do a lot of the same things very powerfully that VS can (like intellisense, refactoring, etc.) and it may be able to do some or all of the examples that I provided, but is it realistic to say that someone working on these platforms would actually benefit from Vim or Emacs?

答:
I find that using an IDE and vim (my personal favorite editor) are not mutually exclusive concepts.  When doing .NET development, I usually set up a hot-key combo that will open the current file I'm working on in the IDE in vim and put the cursor in the same place.  This way if I want to do the sort of thing that vim is great at, (like using macros, vertical editing, re-indenting, diffing, etc), then I hit the key combo and bang I have my favorite editor up, do my changes, save the file and quit, and then I'm back into the IDE again (you can set it up so the file reloads automatically when it's been edited outside the IDE in VS).  This way I get the best of both worlds.

I used to use scripting languages to manipulate text files in complicated ways.  Once I discovered the power of using vim's macros (and some other features as well) I discovered that I can do these kinds of edits/manipulations far more quickly and efficiently than I could with a scripting language.

It's very common for me to generate one off shell scripts to do some complicated things using vim, execute the shell script I built and then throw it away.

my 2 cents :)

ContentLicense: CC BY-SA 2.5


问:
Implicit vs explicit interfaces
I think I understand the actual limitations of compile-time polymorphism and run-time polymorphism. But what are the conceptual differences between explicit interfaces (run-time polymorphism. ie virtual functions and pointers/references) and implicit interfaces (compile-time polymorphism. ie. templates).

My thoughts are that two objects that offer the same explicit interface must be the same type of object (or have a common ancestor), while two objects that offer the same implicit interface need not be the same type of object, and, excluding the implicit interface that they both offer, can have quite different functionality.

Any thoughts on this?

And if two objects offer the same implicit interface, what reasons (beside the technical benefit of not needing dynamic dispatch w/ a virtual function lookup table, etc) are there for not having these objects inherit from a base object that declares that interface, thus making it an explicit interface? Another way of saying it: can you give me a case where two objects that offer the same implicit interface (and therefore can be used as types to the sample template class) should not inherit from a base class that makes that interface explicit?

Some related posts:

https://stackoverflow.com/a/7264550/635125

https://stackoverflow.com/a/7264689/635125

https://stackoverflow.com/a/8009872/635125

Here's an example to make this question more concrete:

Implicit Interface:

class Class1
{
public:
  void interfaceFunc();
  void otherFunc1();
};

class Class2
{
public:
  void interfaceFunc();
  void otherFunc2();
};

template <typename T>
class UseClass
{
public:
  void run(T & obj)
  {
    obj.interfaceFunc();
  }
};
```

<p>Explicit Interface:</p>

<pre class="lang-cxx prettyprint-override"><code>class InterfaceClass
{
public:
  virtual void interfaceFunc() = 0;
};

class Class1 : public InterfaceClass
{
public:
  virtual void interfaceFunc();
  void otherFunc1();
};

class Class2 : public InterfaceClass
{
public:
  virtual void interfaceFunc();
  void otherFunc2();
};

class UseClass
{
public:
  void run(InterfaceClass & obj)
  {
    obj.interfaceFunc();
  }
};
</code>```

An even more in-depth, concrete example:

Some C++ problems can be solved with either:

a templated class whose template type provides an implicit interface

a non-templated class that takes a base-class pointer which provides an explicit interface

Code that doesn't change:

class CoolClass
{
public:
  virtual void doSomethingCool() = 0;
  virtual void worthless() = 0;
};

class CoolA : public CoolClass
{
public:
  virtual void doSomethingCool()
  { /* Do cool stuff that an A would do */ }

  virtual void worthless()
  { /* Worthless, but must be implemented */ }
};

class CoolB : public CoolClass
{
public:
  virtual void doSomethingCool()
  { /* Do cool stuff that a B would do */ }

  virtual void worthless()
  { /* Worthless, but must be implemented */ }
};
```

<p><strong>Case 1</strong>. A non-templated class that takes a base-class pointer which provides an explicit interface:</p>

<pre class="lang-cxx prettyprint-override"><code>class CoolClassUser
{
public:
  void useCoolClass(CoolClass * coolClass)
  { coolClass.doSomethingCool(); }
};

int main()
{
  CoolA * c1 = new CoolClass;
  CoolB * c2 = new CoolClass;

  CoolClassUser user;
  user.useCoolClass(c1);
  user.useCoolClass(c2);

  return 0;
}
</code>```

Case 2. A templated class whose template type provides an implicit interface:

template <typename T>
class CoolClassUser
{
public:
  void useCoolClass(T * coolClass)
  { coolClass->doSomethingCool(); }
};

int main()
{
  CoolA * c1 = new CoolClass;
  CoolB * c2 = new CoolClass;

  CoolClassUser<CoolClass> user;
  user.useCoolClass(c1);
  user.useCoolClass(c2);

  return 0;
}
```

<p><strong>Case 3</strong>. A templated class whose template type provides an implicit interface (this time, not deriving from <code>CoolClass</code>:</p>

<pre class="lang-cxx prettyprint-override"><code>class RandomClass
{
public:
  void doSomethingCool()
  { /* Do cool stuff that a RandomClass would do */ }

  // I don't have to implement worthless()! Na na na na na!
}

template <typename T>
class CoolClassUser
{
public:
  void useCoolClass(T * coolClass)
  { coolClass->doSomethingCool(); }
};

int main()
{
  RandomClass * c1 = new RandomClass;
  RandomClass * c2 = new RandomClass;

  CoolClassUser<RandomClass> user;
  user.useCoolClass(c1);
  user.useCoolClass(c2);

  return 0;
}
</code>```

Case 1 requires that the object being passed in to useCoolClass() be a child of CoolClass (and implement worthless()). Cases 2 and 3, on the other hand, will take any class that has a doSomethingCool() function.

If users of the code were always fine subclassing CoolClass, then Case 1 makes intuitive sense, since the CoolClassUser would always be expecting an implementation of a CoolClass. But assume this code will be part of an API framework, so I cannot predict if users will want to subclass CoolClass or roll their own class that has a doSomethingCool() function.

答:
You've already defined the important point- one is run-time and the other is compile-time. The real information you need is the ramifications of this choice.

Compiletime:

Pro: Compile-time interfaces are much more granular than run-time ones. By that, what I mean is that you can use only the requirements of a single function, or a set of functions, as you call them. You don't have to always do the whole interface. The requirements are only and exactly what you need.

Pro: Techniques like CRTP mean that you can use implicit interfaces to default implementations of things like operators. You could never do such a thing with run-time inheritance.

Pro: Implicit interfaces are much easier to compose and multiply "inherit" than run-time interfaces, and don't impose any kind of binary restrictions- for example, POD classes can use implicit interfaces. There's no need for virtual inheritance or other shenanigans with implicit interfaces- a big advantage.

Pro: The compiler can do way more optimizations for compile-time interfaces. In addition, the extra type safety makes for safer code.

Pro: It's impossible to do value typing for run-time interfaces, because you don't know the size or alignment of the final object. This means that any case which needs/benefits from value typing gains big benefits from templates.

Con: Templates are a bitch to compile and use, and they can be fiddly porting between compilers

Con: Templates cannot be loaded at run-time (obviously), so they have limits in expressing dynamic data structures, for example.

Runtime:

Pro: The final type doesn't have to be decided until run-time. This means that run-time inheritance can express some data structures much easier, if templates can do it at all. Also you can export run-time polymorphic types across C boundaries, for example, COM.

Pro: It's much easier to specify and implement run-time inheritance, and you won't really get any compiler-specific behaviour.

Con: Run-time inheritance can be slower than compile-time inheritane.

Con: Run-time inheritance loses type information.

Con: Run-time inheritance is way less flexible.

Con: Multiple inheritance is a bitch.

Given the relative list, if you do not need a specific advantage of run-time inheritance, do not use it. It is slower, less flexible, and less safe than templates.

Edit: It's worth noting that in C++ particularly there are uses for inheritance other than run-time polymorphism. For example, you can inherit typedefs, or use it for type tagging, or use the CRTP. Ultimately, though, these techniques (and others) really fall under "Compile-time", even though they are implemented using class X : public Y.

Title: Implicit vs explicit interfaces


问:
How much documentation is enough?
How much technical (for future developers) documentation is enough? Is there a ratio between hours coding and hours documenting that's appropriate?

Papadimoulis argues that you should

produce the least amount of documentation needed to facilitate the most understanding,

Is that a good guideline, or are there specific things I should be creating?

答:
I've found that a risk-driven approach such as that presented in George Fairbanks' book Just Enough Software Architecture works extremely well for understanding how much documentation is enough.  You can read the section which presents this concept (chapter 3) on his website but the main idea is to:

Express the things that worry you about "system understanding" as risks

Prioritize the risks

Mitigate the risks until your team feels the project risk has been sufficiently reduced.  In this case you'll probably be creating some kind of documentation.

To help calibrate concerns so you can prioritize risks I've found it helpful to identify a couple of goals known as the Threshold of Success, that is the minimum set of goals your team thinks a "successful" project must achieve.  From a documentation perspective an example ToS might be something like "A developer should be able to build a simple plug-in within 4 hours of picking up the framework for the first time."

Now identify some risks.  With the system you've built (or are building) what are the things that worry your team most?  Phrase these as risk statements.  I like the SEI's condition-consequence style but there are others.  Examples:

The data model is large and complex; developers might not know which data elements to use in a given situation.

The system has API connection limits to increase reliability; developers might accidentally overstep the connection limit.

Plug-ins are consumed in several sequential steps; developers might not build plug-ins with these ordered steps in mind.

Now as a team, prioritize the risks.  Multi-voting works extremely well.

Mitigate the top priority risks, and repeat starting with identification until the risk of your project failing (defined by the Threshold of Success) is within a tolerable limit.  Generally this will mean you'll have some risks that the team agrees are not much of a concern.  Keep in mind that you probably won't want to mitigate all the risks.  An example mitigation strategy for the last risk above might be to create a tutorial.

Title: How much documentation is enough?


问:
Where should I put functions that are not related to a class?
I am working on a C++ project where I have a bunch of math functions that I initially wrote to use as part of a class. As I've been writing more code, though, I've realized I need these math functions everywhere.

Where is the best place to put them? Let's say I have this:

```<code>class A{
    public:
        int math_function1(int);
        ...
}
</code>```

And when I write another class, I can't (or at leat I don't know how to) use that math_function1 in that other class. Plus, I've realized some of this functions are not truly related to class A. They seemed to be at the beginning, but now I can see how they're just math functions.

What is good practice in this situation? Right now I've been copy-pasting them into the new classes, which I'm sure is the worst practice.

答:
As you already said, copy-pasting the code is the worst form of code reuse. If you have functions that don't belong to any of your classes or may be used in for several scenarios, the best place to put them would a helper or utility class. If they don't use any instance data, they can be made static, so you don't need to create an instance of the utility class to use it.

See here for a discussion of static member functions in native C++ and here for static classes in managed C++. You could then use this utility class wherever you would have pasted your code.

In .NET for instance, things like Min() and Max() are provided as static members on the System.Math class.

If all your functions are math-related and you would otherwiese have a gigantic Math class, you might want to break it down further and have classes like TrigonometryUtilities, EucledianGeometryUtilities and so on.

Another option would be to put shared functionality into a base class of the classes requiring said functionality. This works well, when the functions in questions need to operate on instance data, however, this approach is also less flexible if you want to avoid multiple inheritance and only stick to one base class, because you would be "using up" your one base class just to get access to some shared functionality.

ContentLicense: CC BY-SA 4.0


答:
Depends on how the project is organized and what sort of design patterns you are using, assuming this is strictly utility code you have the following options:

If you don't have to use objects for everything you could do something simple like just putting them all in a file without a class wrapper around them. This could be with or without a namespace although the namespace is recommended to prevent any issues in the future.

For managed C++ you can create a static class to contain them all; however, this doesn't really work the same as an actual class and my understanding is that it is a C++ anti-pattern.

If you aren't using managed C++ then you can just make use of static functions to allow you to access them and have them all contained in a single class. This may be useful if there are also other functions that you would want a proper instantiated object for by may also be an anti-pattern.

If you want to ensure that only one instance of the object containing the functions will exist then you can use the Singleton Pattern for a utility class which also allows you some flexibility in the future as you now have access to non-static attributes. This is going to be of limited use and only really applies if you need an object for some reason. Odds are if you do this you will already know why.

Note that the first option is going to be the best bet and the following three are of limited usefulness. That said though, you might encounter then just due to C# or Java programmers doing some C++ work or if you ever work on C# or Java code where the use of classes is mandatory.

Title: Where should I put functions that are not related to a class?

Body:
I am working on a C++ project where I have a bunch of math functions that I initially wrote to use as part of a class. As I've been writing more code, though, I've realized I need these math functions everywhere.

Where is the best place to put them? Let's say I have this:

```<code>class A{
    public:
        int math_function1(int);
        ...
}
</code>```

And when I write another class, I can't (or at leat I don't know how to) use that math_function1 in that other class. Plus, I've realized some of this functions are not truly related to class A. They seemed to be at the beginning, but now I can see how they're just math functions.

What is good practice in this situation? Right now I've been copy-pasting them into the new classes, which I'm sure is the worst practice.


答:
C++ can have non-method functions just fine, if they do not belong to a class don't put them in a class, just put them at global or other namespace scope </p>

```<code>namespace special_math_functions //optional
{
    int math_function1(int arg)
    {
         //definition
    }
}
</code>```

Body:
C++ can have non-method functions just fine, if they do not belong to a class don't put them in a class, just put them at global or other namespace scope

namespace special_math_functions //optional
{
    int math_function1(int arg)
    {
         //definition
    }
}


问:
Has anyone thoroughly compared C# common coding standards?
Most of the C# programmers I know embrace one of the common coding standards. However being aware of the standards is one thing, telling the differences is another.

Browsing the common coding standards documents our there on C#, my first reaction was it's more of the same. Admittedly I didn't bother reading everything. Has anyone ever compared them and point out the major differences between them?

Microsoft's Design Guidelines for Developing Class Libraries

The IDesign C# Coding Standard, development guidelines, and best practices

Lance Hunt's C# Coding Standards

答:
I did perform such a comparison, as part of my job.

I was asked to write coding style guidelines for a software engineering department.  As this department was part of the military-industrial complex, the document I wrote was very detailed, and included parts of all of the documents you linked, as well as vast swaths of the Design Guidelines for Developing Class Libraries.

After I submitted my guidelines, I was asked to distill them down to 3 to 4 pages, and then to one crib sheet.  In the end, the guidelines were not adopted.  Instead, everyone in the department follows the rules encoded into Visual Studio.

Here is what I learned from the experience:

The coding style to adopt is the one your shop already uses, unless they decide to adopt a new one.

The guidelines for creating software libraries are already very well defined, and almost universally agreed upon by all, including the authors of the documents you linked.

The only real variations you are going to see in coding style that are not already universally agreed on are those variations having to do with member variables inside classes (which Microsoft has left up to the taste of individual developers).

The vast majority of the rules you need to know to develop a good coding style are already encoded in Visual Studio, FxCop, and other Code Analysis tools Microsoft provides.


问:
Mediator vs Observer?
Can someone provide me with a canonical answer on the differences between an Observer and a Mediator, and a summary of when you should use one pattern over the other?

I am unsure of what kind of situation would require an Observer and what kind would require a Mediator

答:
In simple terms (that I use to remember it):

Observer: Use when one objects wants to be informed of state changes in another (strictly speaking, using events is Observer)

In order to understand mediator, I find it easier when you consider Facade first: Facade aggregates the functionality of separate classes (entire subsystems sometimes) and provides that functionality in a single interface.

Mediator: Same as Facade, except that it combines the functionality of all of the aggregate classes to produce new functionality. (Good explanation here)

Title: Mediator vs Observer?


问:
Lexical Analysis without regular expressions
I've been looking at a few lexers in various higher level langauges (Python, PHP, Javascript among others) and they all seem to use regular expressions in one form or another. While I'm sure regex's are probably the best way to do this, I was wondering if there was any way to achieve basic lexing without regular expressions, maybe some sort of direct string parsing or something.

So yeah, is it possible to implement some sort of basic lexing in a higher level language* without using regular expressions in any form?

*Higher level languages being things like Perl/PHP/Python/Javascript etc. I'm sure there is a way to do it in C

答: There's nothing specific about regular expressions. They are simply shorthand which allows you to generate the code much easier, and implementations are commonly shipped. However, fundamentally, lexers are FSMs and regular expressions are just one way to achieve that goal.</p>


答: It makes sense to either do a lexical analysis with regular expressions, or skip this pass at all and do a much more flexible and powerful lexerless parsing with PEG or GLR.</p>

Title: Lexical Analysis without regular expressions

Body:
I've been looking at a few lexers in various higher level langauges (Python, PHP, Javascript among others) and they all seem to use regular expressions in one form or another. While I'm sure regex's are probably the best way to do this, I was wondering if there was any way to achieve basic lexing without regular expressions, maybe some sort of direct string parsing or something.

So yeah, is it possible to implement some sort of basic lexing in a higher level language* without using regular expressions in any form?

*Higher level languages being things like Perl/PHP/Python/Javascript etc. I'm sure there is a way to do it in C


答:
should I name it by its type?

No. Never. This is called Systems Hungarian and is trivially outdated by the idea of using a program which can display the type of any variable any time you need it.

Title: Is it a good practice to name the returned variable "result"?

Body:
Is it a good practice to call the variable a method returns with a variable name result?

For instance:

```<code>public Zorglub calculate() {
    Zorglub result = [...]
    [...]
    return result;
}
</code>```

Or should I name it by its type?

```<code>public Zorglub calculate() {
    Zorglub zorglub = [...]
    [...]
    return zorglub;
}
</code>```

I have seen both in the wild, if I need to choose one what reasons could make me prefer the former or latter (or any better name)?

I am mainly thinking about Java.


问:
Should source-code in textbooks and the like be translated?
A few weeks ago, my class was assigned to translate to Portuguese the book Real World Haskell. As I did the translation of the text and comments, I started to wonder if I should translate the code as well, as the instructor suggested. For example:

```data BookInfo = Book Int String [String]
              deriving Show```

would become

```data InfoLivro = Livro Int String [String]
               deriving Show```

Since I haven't read any software-related books in Portuguese, I don't know if that's a common practice, neither if it should be done this way. In the end, the code is a language mix (perhaps the example in Haskell is not a good one, since you can create synonyms quickly like type CadeiaDeCaracteres = String, but you get the point). So it doesn't really matter how hard you try, you'll have to rely on the reader previous experience with some sort of basic English words.

Knowing this, I really don't see the point in translating code, since we learn in the early days of our coding life it should be written in the universal language. Nevertheless, if the surrounding text (comments, for example, and text itself in a book) needs to be translated, what is possible and feasible in this matter? Can you provide me with some guidance of what to do?

答:
I'm brazilian [we speak portuguese here, ofc] and, when I can choose between the original or the translated version, I always take the original, since almost every book is translated to people who aren't programmers so commands and expressions lose their original meaning after the translation.

Another reason to want books in english is that everything on web [or the best things, like this site] is written in english, so you will be familiarized with the english term and you will be able to understand better other people code... [since a good programmer would code in english, at least from my POV]

If you need to read books in portuguese [or another language] prefer those written on that language [not translated].

To make it clear: if you are going to translate that book, try to keep all code in english [comments may be translated, but not vars or funcs] and don't try to translate stuff like 'array' to 'arranjo' or 'mouse' to 'rato' [at least I would prefer the english term, people on Portugal would prefer the second, I guess].


答: result is fine. I am able to understand the code in the first glance so the variable name served the purpose.</p>


问:
Is it legal/ethical to post production code?
This may sound silly or obvious but this is my case; I work at a company that recently implemented SAP and I was the responsible to generate/migrate the master data of the company which let me learn a lot from this system. SAP comes with its own language known as ABAP and since the system went live I've been learning and programming with it. Before ABAP I worked as a freelancer in other projects with VB6, VB.Net, C# and ASP.Net building a lot of stuff, here I've made some utilities that are been using daily, so I came with long experience in programming.

At first ABAP was difficult but eventually after long analysis, googling and trial and error I became the guy who makes basically all the development in SAP from reports, to user-exits, enhancements, BADIs, tables, dynpros, etc. Daily I learn more and more because of all the requests I receive which makes me investigate and code a lot everyday. It has become challenging and funny at the same time. You could be very productive in ABAP once you get into.

Ok, the question is - can I post how I resolved a certain thing in SAP? That implies that I'd publish production code. I feel doubtful about this.

答:
If you're that worried about it, just ask your employer.  Say, "I get a lot of programming help on a site called Stack Overflow.  I just wanted to make sure you're okay with occasionally posting small snippets of code in my questions and answers."

In my experience, they're unlikely to object, especially for code that's only incidental to your work or only used once then thrown away, like migration scripts or utilities.  I've had them okay even more substantial working code, like a plugin or module for third party software.


问:
Assembly in a research paper
I am doing a research paper on programming, and I need to somehow explain assembly... I've never learned the language, but I understand what it is used for and kinda what it looks like...

```<code>MOV A,47
ADD A,B
HALT
</code>```

And from what I understand, it is used for writing some compilers, small bits of code that need to be really fast, and other tasks... But this is kind of a question for people who have used/studied assembly and understand it fairly well. And no, I'm not asking for you to type up this segment of the research paper for me. That would be selfish. I just need a brief explanation, clarification on the subject (I'm just unsure if what I know is true or not) and a pointer in the right direction.

For a research paper (I need to explain this VERY simply...) what is purpose of using Assembly in today's society? Of course it was important back in the day but now with all the high level languages, when is this low level language used?

答:
Perhaps the biggest use of assembly is the need to be able to read it:

to check to see what your optimizing compiler has come up with

debugging cases where you don't have debug symbols built in

Even if the great majority of your work doesn't need knowledge of assembly, it greatly widens the scope of what is possible.  It is also necessary for reverse engineering and the like.  Finally, in order to really understand the strengths and weaknesses of your platform -- to have a baseline grasp of what is difficult and what is easy -- an understanding of your processing architecture includes understanding its machine code.

There are also still cases (aside from OS bootstrapping and compiler writing) where writing assembly is the best solution -- usually specialized/embedded processors like microcontrollers and DSP's.  Not everything has robust system tools ab initio: if you can't do it yourself, you become a hostage to your toolset.

Title: Assembly in a research paper


答:
scalable

REST

CRUD

web 2.0

nodejs

mongodb

A lot of hot keywords that don't really mean much. You could have simply said "I'm planning on building a webservice."

I personally don't have a problem with using JS - it's a good language, but I don't think 'finding developers' is a good reason to choose the language - good programmers can code in any language.

I recommend you check out couchDB. It's a single piece of software that, here, can serve the role of both node and mongo. It will scale better individually than Node and mongo scale together, and it's relatively easy to use if you can write a map/reduce function.

BUT, it sounds to me like you're putting the cart before the horse. You don't need to worry about scalability until scalability becomes a problem, and scalability is a good problem to have. I would recommend you write everything in the language that you know best and can produce the fastest in, and worry about scaling when you need to scale.

Title: Feedback on this back-end stack

Body:
I'm planning to setup an scalable architecture capable of providing web services on a REST interface where JSON will be sent as a result.
The web services will be quite simple for a CRUD web 2.0 app.

I think javascript (nodejs + mongodb) is a good choice for the following reasons:

Easy to find javascript developers

Good performance

Easy to scale

Shared logic/language or possible reuse of code between database query language, back-end and web-client.

There are testing and logging frameworks for node

By the examples I've seen node seems light in terms of the lines of code needed to implement web services.

Questions:

I think of scaling a node app which supplies a web service as having
a central node which will be routing/balancing charge to each of the
node instances. Which will also help doing seamless updates, is
there any piece of software already implemented which can fit that
task?

Please point all the disadavantages or other advantages you find in this back-end stack

Any other good persistence choices other than MongoDB? Mainly this choice comes from the javascript query language and JSON schemas.


问:
Which NoSQL repository is most suitable for a Twitter-type architecture?
In an upcoming project I need to create a Twitter like web application  where the basic idea is to read / write short messages and status updates (similar to tweets) and group these messages (just like hashtags)

Also users can have followers and can see their status updates.

I'm estimating between 10 - 50 million message writes in a span of 1 - 2 months, and for reads it could be anything in the millions. Reads will surely be higher than writes.

I already decided that some kind of NoSQL is probably the best approach to storing this data, but I don't know which one would be the best fit for my needs.

I looked at Hadoop / Cassandra / HBase but it seems a little bit of overkill. I'm also considering MongoDB.

The whole web app will be setup on Nginx, PHP with a RESTful architecture (front-end only on mobile phones)

答:
Why not use what Twitter itself uses? It looks like Twitter uses a few different approaches to get what you are looking for. If it needs to work exactly like Twitter as you describe then use the tools that they have proven work together. This is a great article that goes over where to start from:

How Twitter Uses NoSQL

http://www.readwriteweb.com/cloud/2011/01/how-twitter-uses-nosql.php

Websites that have the kind of volume that you describe are not built in a day and may need several iterations to really work perfectly. I suggest getting in there and seeing what really works for your problems after real world testing.


答: its not just what you name the result (I am particular to 'r'), but also how its used. for instance, if you're going to have a return variable, then every return statement should return it.  don't have 'return r;' at the end, but sprinkle things like 'return m * x + b;" throughout the method/function. use "r = m * x + b; return r;" instead.</p>


答:
33 & 1/3rding that you should not worry about scale until you need to worry about scale. Personally I would not bet my farm on node at this point unless I had some capable C hackers available to fix it -- it is just too young to ride and not be able to rebuild the engine if you needed to IMHO. I'd also be leery of mongodb -- it is fast, but at a pretty bad cost in terms of data integrity. CouchDb is probably a better choice if you want to stay on *nix. RavenDb is compelling if that isn't a requirement. Either of those options could probably run the whole app without node.

In any case, the mantra to repeat isn't webscale, it is Minimum Viable Product.

Title: Feedback on this back-end stack


答:
The Observer pattern works well when no coordination between the observers is necessary and the observes relationship goes one way.

For example, let objects B and C observe object A.  When object A fires event X, then object B should execute method Y() and object C should execute method Z().  If methods B.Y() and C.Z() are totally independent and require no coordination, then go ahead and use the observer pattern.

On the other hand, if B.Y() must be executed before C.Z() then you will want to use the Mediator pattern where the mediator encapsulates this coordination.  In this scenario, mediator M would observe object A and would have references to objects B and C.  When A fires event X, M will handle the event and call B.Y() and C.Z() in the prescribed order.

Also, if objects A, B and C need to observe each other then using a mediator as an intermediary will go a long way to decouple these objects and avoid spaghetti code.

Title: Mediator vs Observer?


答:
Whenever you need to name anything in code, you should provide names that are descriptive, meaningful, and readable. The case of a return variable is a particularly good example of where people tend to become complacent about naming.

If you have a function that is clearly named, and you only need a single line of code, then you can skip the naming entirely. Making your methods short and single purpose is always the ideal that you should be aiming for. However, it is the case that sometimes you do need to complete a function with several lines of code.  I those cases it is always advisable to name your variable to match the purpose of your function.

If the purpose of the function is to return the result of a calculation or a decision algorithm, then result is a perfectly adequate name for your variable to use, but what if your function is returning an item from a list? What if your function is serving some other purpose that has nothing to do with math or lists?  In those cases, it is better to provide the variable with a meaningful name that relates to why the function was created. Sure, you could simply use result if you wanted to because it's a name that isn't likely to clash with anything else, however from a readability perspective it makes more sense to name your variable more meaningfully and in context.


问:
What is the best way to allow a client to contribute to a project?
We've been building a CRM for a client. Now that the first major phase has been finished, and a second one agreed upon, the client would like to pick up some of the work, making minor amendments to the database schema and business processes the first phase while we build the second.

I'm undecided whether this is at all practical, but assuming it is, I'd like some pointers on which measures can be taken to make this at all workable. Here's what I've got so far:

Until now, the client has mostly seen the project from a user's point of view; clearly, a two-part seminar ought to take place where we introduce him to the inner workings:

first, showing the existing database schema and, by way of example, extending it,

then, showing some sample code, and writing a new business process for the schema enhancement.

The code currently resides in an internal Subversion repository. While we could set up a public one or one on his network (which we can VPN to), I feel a distributed system would work better. I appear to be the only one who feels that way, however, so I could use some good convincing arguments.

I'm not sure how to mandate/ensure that code that runs in production is committed. Seems like "x made a critical, undocumented change right before going on vacation; now y's trying to figure out this bug that's been occurring ever since" disasters are inevitable. Ideally, all changes, before deployment, would:

be documented in an issue tracking system,

occur on a separate testing environment first, and

have to pass automated tests.

Alas, I doubt the discipline for any of those will prevail.

Assume that a plug-in architecture or separate project aren't viable options, because 1) the former doesn't exist, and 2) the latter would prohibit the client from looking at and possibly modifying existing code, an ability I believe he would insist on.

答:
Someone who is usually in the role of the client here chiming in. I honestly wouldn't have this problem because if it got this far you'd be in my source control, using my CI setup and my QA setup to test things. This arrangement can be pretty difficult to setup -- I get lots of pushback from the consultants, especially getting things going. Having process intereferes with billable hours it seems.

I think your perspective is quite honestly a bit skewed. First, keep in mind that it isn't your code base but rather our codebase. Second is that, in most cases, the IT shop on the client side has vastly more motivation to make sure this product works as designed and is easy to maintain, manage and support going forward. Diving back in to fix bugs is not more billable hours to us unlike most consultants. Moreover, building things to be easily configurable and fail in predictable ways are vastly more important when you own the operations side of the coin too. You might just end up with a higher quality project because part of the development staff is not constrained by billable hours.

Insofar as how to make it work, DCVS is definitely the way to go if it can be made to happen. Choosing something neutral (bitbucket, github) can help. Having CI in place is also a godsend here -- harder for things to get out of whack when everyone knows it got out of whack on the last commit. If you can force things to deploy via CI -- something we typically have to force upon vendors -- you can really ensure all changes are committed. Training-wise, have you considered pairing with the client for a few days? That might be a good way to establish the lateral ties you'll need. Overall the best bet is to convince everyone they are on the same team. Because they are on the same team.


问:
What defines a software architect?
At what  point does a developer stop being simply a developer and turns into a software architect. Or in other words, what's the minimum job description of a software architect?  </p>

答:
I could probably come up with 2 pages of humor here, but I'll assume you are taking this seriously. So, I'll respond as seriously as I can.

First thing you must understand: @Craig is right... differnet organizations mean different things. For some, it's just part of their advancement track and doesn't really mean much beyond that. For others, its a distinct role and very often, they get subverted out of doing any code or other hands on work and so lose their efficiency.

The point at which you stop being a developer and start being an architect is the point at which you spend 90%+ of your time engaged in the following

Writing specs / drawing pretty pictures

Meetings with management/Stakeholders

Researching what technologies you should be using instead of learning what your team is using today.

Wondering what the code for your apps looks like because you haven't seen the code in 4 months

Short of it is that an architect is the interface between the dev team and the stakeholders (the BA is the opposite). They need to be able to understand the business side and the technical details, but truth is, they are likely to not "get their hands dirty" all that often. Their primary 'technical' skills need to be with UML, a word processor, other technical drawing tools, and presentation software. So, in most cases, within a few years, they will start to become less and less effective as their knowledge of coding becomes dated (e.g. they are trying to think in C++ while the project is in C# or Java). At that point, the smart people learn how to lean on and learn from the hands on folks. The others become a pain in rear because they have a harder and harder time relating to state of the art.

OwnerDisplayName: mumtaz

LastEditorDisplayName: mumtaz

Title: What defines a software architect?


问:
Do coding puzzles make good interview questions
I am interviewing candidates for Java programmer positions.

My colleague insists in filling more than half of the interview with java coding puzzles.His view is that, if candidates are able to navigate through the loops, then they must be good.

One such example of coding puzzle is

```<code>        i=0;
        for( i=1 ; i< 10 ;i++)
        {
                if(i%3 ==0) i++; break;
                if(i%2 ==0) i++;

         }
          print(i);
</code>```

Follow up: what happens if break is removed ?

答: If I were to give a definitive answer, I would say no, riddles are bad for interviews.  What if the person you are interviewing is great at puzzles, but lousy or maybe let us say inexperienced at Java coding.  Maybe the riddle solver will be able to come up to speed quicker than the average programmer, but are you willing to wait?  If you are hiring for a Java developer, hire someone who dreams Java in their sleep.  Perhaps if the environment were one where projects and technologies change quickly and the applicant might be programming in a number of different languages on a number of different platforms using a number of different frameworks in the next 2-3 years then I would be more inclined to go with the riddle solver.</p>


答:
It is generally accepted that any code written for your employer belongs to your employer.  Even if you take production code, and clean it up so that it is something else that you aren't using in production in order to post it on a blog or on a Q/A site, your employer still owns the code.

In most cases, there is generally little harm in posting small snippets of code for the purposes of solving problems.  Your boss should accept that you sometimes need to go outside the company to seek help when you can solve the problem entirely in house. If your intention however was to post something interesting to a personal blog, you may find yourself on shaky ground.

The best way to cover yourself both ethically and legally is to send your boss an email asking for permission to post your code snippets (cleansed or otherwise).  Even better, ask your boss what the company policy is when it comes to posting code snippets to blogs and Q/A sites, and what your reasoning is, then leave it to your boss to tell you what is permitted.  Try to get this in writing as either a letter/email or in a policy document - such as an employee hand book.

Title: Is it legal/ethical to post production code?

Body:
This may sound silly or obvious but this is my case; I work at a company that recently implemented SAP and I was the responsible to generate/migrate the master data of the company which let me learn a lot from this system. SAP comes with its own language known as ABAP and since the system went live I've been learning and programming with it. Before ABAP I worked as a freelancer in other projects with VB6, VB.Net, C# and ASP.Net building a lot of stuff, here I've made some utilities that are been using daily, so I came with long experience in programming.

At first ABAP was difficult but eventually after long analysis, googling and trial and error I became the guy who makes basically all the development in SAP from reports, to user-exits, enhancements, BADIs, tables, dynpros, etc. Daily I learn more and more because of all the requests I receive which makes me investigate and code a lot everyday. It has become challenging and funny at the same time. You could be very productive in ABAP once you get into.

Ok, the question is - can I post how I resolved a certain thing in SAP? That implies that I'd publish production code. I feel doubtful about this.


答:
It is common for "work for hire" types of contracts to have a clause where you as an employee give up the copyright. There are some local variations to what extent you give up the copyright, but as a general rule you are not allowed to publish code or other documents that is specifically owned by the company as that would become a copyright violation.

That said, you can go usually around the problem by writing an example instead. You should ask the management of the company about posting it as well if you believe it is too close to production code. Try to reason by leaning towards goodwill and that you're not revealing any production code.


问:
Does having Master's degree in Computer Science help your career?
I am curious about experiences of programmers who have gone beyond college or university and now work in the industry. I am not talking about academia (you need PhD there anyway). Do you have a Master's degree? Has it helped your career? Are there any other benefits besides the knowledge one gains while pursuing the degree?</p>

答: For me, it adds a few years to my experience.  Often you will see like 3-5 years + bachelors's or 1-3 years + master's in a job description, and it my case having a Master's degree has given me the benefit of the doubt.  I started off as an FPGA designer, and now that I am a web developer, managers could care less about the years I spent doing that so the years the degree gives me are so valuable.  Skillwise, no way!  No difference in quality between a programmer with a bachelor's and a programmer with a master's.  Many other things you can do to make yourself a better programmer</p>


问:
Why do variables need a type?
So we write:

```<code>Customer c = new Customer();
</code>```

Why is the design not such that we write:

```<code>c = new Customer();
c.CreditLimit = 1000;
</code>```

The compiler can work out c points to a Customer and allow Customer's members to be invoked on c?

I know we may want to write:

```<code>IPerson c = new Customer();
IPerson e = new Employee();
</code>```

so as to be able to write:

```<code>public string GetName(IPerson object)
{
    return object.Name
}

string name = GetName(c); // or GetName(e);
</code>```

But if we wrote:

```<code>c = new Customer();
e = new Employee();
</code>```

we could still write:

```<code>public string GetName(object)
{
    return object.Name
}

string name = GetName(c); // or GetName(e);
</code>```

The compiler could complain about the code immediately above if the type of object c references does not support a Name property (as it can check which members are used on the argument/parameter within the method), or the runtime could complain.

Even with C#'s dynamic keyword, we are still using a variable 'type' (determined at runtime). But why does a variable need a type at all? I am sure there must be a good reason, but I can't think of it!

答:
But why does a variable need a type at all?

This may catch bugs where an invalid, wrongly typed expression is assigned to a variable. Some languages have dynamic typing, which sacrifices the correctness guarantees of a type per variable for the kind of flexibility that you seem to desire.

Types may allow the compiler to generate more efficient code. Dynamic typing means type checks have to be performed at runtime.

OwnerDisplayName: sturdytree

Title: Why do variables need a type?

OwnerDisplayName: larsmans


答:
Assuming you had a variable one (set to 1) and attempted to evaluate one + one. If you had no idea of type, then 1 + 1 will be ambiguous. You can argue that 2 or 11 could be correct answers. It becomes ambiguous if context isn't given.

I've seen this happen in SQLite where the databases types were inadvertently set to VARCHAR instead of INT and when operations were done people were getting unexpected results.

In c# if context infers a type, you can use the var keyword.

```<code>var c = new Customer();
var e = new Employer();
</code>```

Will compile c and e with the inferred types at compile time.

Title: Why do variables need a type?

Body:
So we write:

```<code>Customer c = new Customer();
</code>```

Why is the design not such that we write:

```<code>c = new Customer();
c.CreditLimit = 1000;
</code>```

The compiler can work out c points to a Customer and allow Customer's members to be invoked on c?

I know we may want to write:

```<code>IPerson c = new Customer();
IPerson e = new Employee();
</code>```

so as to be able to write:

```<code>public string GetName(IPerson object)
{
    return object.Name
}

string name = GetName(c); // or GetName(e);
</code>```

But if we wrote:

```<code>c = new Customer();
e = new Employee();
</code>```

we could still write:

```<code>public string GetName(object)
{
    return object.Name
}

string name = GetName(c); // or GetName(e);
</code>```

The compiler could complain about the code immediately above if the type of object c references does not support a Name property (as it can check which members are used on the argument/parameter within the method), or the runtime could complain.

Even with C#'s dynamic keyword, we are still using a variable 'type' (determined at runtime). But why does a variable need a type at all? I am sure there must be a good reason, but I can't think of it!

Body:
Assuming you had a variable one (set to 1) and attempted to evaluate one + one. If you had no idea of type, then 1 + 1 will be ambiguous. You can argue that 2 or 11 could be correct answers. It becomes ambiguous if context isn't given.

I've seen this happen in SQLite where the databases types were inadvertently set to VARCHAR instead of INT and when operations were done people were getting unexpected results.

In c# if context infers a type, you can use the var keyword.

var c = new Customer();
var e = new Employer();

Will compile c and e with the inferred types at compile time.

OwnerDisplayName: BicycleDude


答:
So professional programmers don't have to figure out whether

```<code>10 + "10"

is "1010" or 20....
</code>```

What it is a an error, at compile time with a statically typed language or run time witha dynamically typed one. Well sane ones anyway.

Title: Why do variables need a type?

Body:
So professional programmers don't have to figure out whether

10 + "10"

is "1010" or 20....

What it is a an error, at compile time with a statically typed language or run time witha dynamically typed one. Well sane ones anyway.

OwnerDisplayName: Tony Hopkinson


问:
JavaScript for a non-programmer
2 years ago I starded learning AS3 in order to get hired at a web design company. A few months later, I ditched it, because I discovered that I'm better at design; so now I'm a web designer.

Recently, I decided that knowing JavaScript would be nice and helpful, so i started with Essential JavaScript Training from Lynda.com. Untill today, I was under the impression that my knowledge of programming was somewhat basic. What happened today...?
I learned (through trial and error) that variables are only valid in the functions that they're defined in. This turned my world upside down. I was like: "that makes sense now..." thinkin of the all the headaches that the lack of this specific piece of knowledge gave me.
How could I have missed such a fundamental thing while learning AS3 (and now JS)? I didn't. And I remember reading a at least three books on AS3, but none of them taught me about programming.

So what I want to ask you, is if you could recommend me a good JavaScript book from which i can learn programming, too, besides syntax.

Thanks! And sorry for my bad english :)

答:
Video Tutor : Douglas Crockford: "The JavaScript Programming Language"(4 videos)

Though Crockford can confuse you initially, he can get basic concepts straight in JavaScript.

Text Tutor : A very detailed tutor available on Mozilla Development Center on Javascript

Title: JavaScript for a non-programmer


问:
How should I handle multi-tasking in a WPF application?
In most of the multi-tasking CRM applications I've seen, MdiWindow is used to allow users to open multiple windows at the same time.

But MdiWindow doesn't seem to be commonly used in WPF. Looking through Codeplex, I only found one abandoned MdiWindow project.

In some of the WPF-based CRM applications I've seen, they create a dashboard and only let users work on one thing at a time.

What's the best way to handle multi-tasking in a WPF application? Is there a better alternative to MdiWindow in WPF?

答:
Your question, as I understand it, seems to be about GUI Design in general rather than WPF in particular.

For presenting secondary information, you have the options of:

0 - MDI Windows (allows the presentation and automatic organization of several windows simultaneously)

1 - Docked windows as in VS2010 (allows user to organize the workspace so that he/she can focus on the specific desired windows)

2 - Tabs as suggested by Rachel (this shows only part of the information and hides the rest)

3 - Wizards

4 - Accordion displays (somewhat rare but allows you expand only bands of interest)

There are 3rd party tools that provide all the above functions in slick ways.

Some of the key points to consider when selecting which interface is to think of this:

A - Does the user really need to see/interact with all this information together or at once? Remember that no one can type or look (actively) at 2 windows simultaneously. Your ystem should display necessary information for taking a business decision together in one display when possible. Other (secondary) information could be obtained via navigation to modal windows. Most people will not be able to look at 40 different fields on the screen to make a decision or take an action. You will usually find that in business applications, a process is composed of steps, and each step has its own data. You should be able to complete a business process without having to display many windows at the same time. You should evaluate navigation between windows as an alternative (as in (3)).

B - Is the information presented in each window independent of other open windows? If not, you will be heading for somewhat complex programming. To make all windows respond to a change in one window may be tricky. Be careful.

To summarize, your business process, required data volume, ease of use and ease of implementation should all be elements in your choice. For example, if changing information in 1 window causes other windows (or tabs) to change, your program could be complex and you probably want to avoid doing this.


答:
You have a perfectly valid point, languages that do not keep track of the type of a variable exist, and are called "dynamically-typed". The category includes languages such as JavaScript, Perl, Lisp, and Python.

The advantage that we get from a statically typed language is some additional compile-time error checking.

Suppose, for example, that you have the following method:

```<code>public addCustomerContact(Customer client, Employee contact) {
   ...
}
</code>```

It would be possible, if you have a customer bob and an employee james in your code, to mistakenly call addCustomerContact(james, bob), which is invalid. But if the compiler doesn't know the types of the variables, it can't warn you that you've made an invalid call, instead, an error occurs at runtime...and since dynamically-typed languages don't check the type of parameters passed in to methods, that problem occurs whenever your code attempts to use customer-only properties of the james object, or employee-only properties of the bob object. That may be long after the pair (james, bob) was added to the list of customer contacts.

Now, you might wonder, why can't the compiler still infer the type of james and bob, and still warn us? That may sometimes be possible, but if variables really have no type, then we could do the following:

```<code>var james;
var bob;
if (getRandomNumber() > 0.5) {
   james = new Customer();
   bob = new Employee();
} else {
   james = new Employee();
   bob = new Customer();
}
</code>```

It's perfectly legal to assign any value to any variable, since we said variables have no type. That also means we can't always know the type of a variable, because it could be of different types based on different paths of execution.

In general, dynamically typed languages are used for scripting languages, where there is no compilation step, and so compilation errors don't exist, meaning the extra keystrokes needed to give variables type wouldn't be very useful.

There are some distinct advantages to dynamically typed languages as well, mostly in terms of less code being needed to implement the same design: interfaces need not be written, because everything is "duck typed" (we only care what methods/properties an object has, not what class the object belongs to), variables need not be given explicit type...with the trade off that we find out about somewhat fewer bugs before we start running our code.

Title: Why do variables need a type?

Body:
You have a perfectly valid point, languages that do not keep track of the type of a variable exist, and are called "dynamically-typed". The category includes languages such as JavaScript, Perl, Lisp, and Python.

The advantage that we get from a statically typed language is some additional compile-time error checking.

Suppose, for example, that you have the following method:

public addCustomerContact(Customer client, Employee contact) {
   ...
}

It would be possible, if you have a customer bob and an employee james in your code, to mistakenly call addCustomerContact(james, bob), which is invalid. But if the compiler doesn't know the types of the variables, it can't warn you that you've made an invalid call, instead, an error occurs at runtime...and since dynamically-typed languages don't check the type of parameters passed in to methods, that problem occurs whenever your code attempts to use customer-only properties of the james object, or employee-only properties of the bob object. That may be long after the pair (james, bob) was added to the list of customer contacts.

Now, you might wonder, why can't the compiler still infer the type of james and bob, and still warn us? That may sometimes be possible, but if variables really have no type, then we could do the following:

var james;
var bob;
if (getRandomNumber() > 0.5) {
   james = new Customer();
   bob = new Employee();
} else {
   james = new Employee();
   bob = new Customer();
}

It's perfectly legal to assign any value to any variable, since we said variables have no type. That also means we can't always know the type of a variable, because it could be of different types based on different paths of execution.

In general, dynamically typed languages are used for scripting languages, where there is no compilation step, and so compilation errors don't exist, meaning the extra keystrokes needed to give variables type wouldn't be very useful.

There are some distinct advantages to dynamically typed languages as well, mostly in terms of less code being needed to implement the same design: interfaces need not be written, because everything is "duck typed" (we only care what methods/properties an object has, not what class the object belongs to), variables need not be given explicit type...with the trade off that we find out about somewhat fewer bugs before we start running our code.


答:
When you identify the type that your variable represents, you are making a statement about a couple of things.  You are identifying the memory allocation requirements for your variable, and you are defining compatibility and range rules for your variable. It provides a way to avoid confusion about your intentions for the data you are storing, and to provide you with a relatively cheap means to identify potential problems in your code at compile time.

If you declare the following variables:

```<code>myVar      = 5;
myOtherVar = "C";
</code>```

What can you infer about these variables? Is myVar signed or unsigned? Is it 8-bit, 64-bit, or something in between? Is myOtherVar a String (effectively an array) or a Char? Is it ANSI or Unicode?

By supplying specific data types, you provide the compiler with clues as to how it can optimize the memory requirements for your application. Some languages don't bother to much with this sort of thing, allowing those matters to be dealt with at runtime, while other languages will allow a certain amount of dynamic typing because by analyzing the code the data types can be inferred.

Another point with strongly typed languages, is that it saves you from needing to provide instructions to the compiler every time you use a variable. Can you imagine how horrible and unreadable your code would become if every time you accessed a variable, you were force to effectively cast it to tell the compiler what type of value it was?!!

Title: Why do variables need a type?

Body:
When you identify the type that your variable represents, you are making a statement about a couple of things.  You are identifying the memory allocation requirements for your variable, and you are defining compatibility and range rules for your variable. It provides a way to avoid confusion about your intentions for the data you are storing, and to provide you with a relatively cheap means to identify potential problems in your code at compile time.

If you declare the following variables:

myVar      = 5;
myOtherVar = "C";

What can you infer about these variables? Is myVar signed or unsigned? Is it 8-bit, 64-bit, or something in between? Is myOtherVar a String (effectively an array) or a Char? Is it ANSI or Unicode?

By supplying specific data types, you provide the compiler with clues as to how it can optimize the memory requirements for your application. Some languages don't bother to much with this sort of thing, allowing those matters to be dealt with at runtime, while other languages will allow a certain amount of dynamic typing because by analyzing the code the data types can be inferred.

Another point with strongly typed languages, is that it saves you from needing to provide instructions to the compiler every time you use a variable. Can you imagine how horrible and unreadable your code would become if every time you accessed a variable, you were force to effectively cast it to tell the compiler what type of value it was?!!


问:
Learning the rules of chess
A similar question asks whether a computer can learn to play optimally in chess by analyzing thousands of games.

If a machine can look at the state of the board for a few games of chess (or a few games of checkers) in the beginning and after each move, can it be programmed to learn the rules of the game?

If it can, to what extent (e.g., would it be able to account for castling or promotion) would this work? Which machine learning algorithms would make this possible?

答:
This is a philosophical question. You might as well ask if a person could learn to play chess solely by observing people while they play chess. In fact it is basically the same kind of question Nelson Goodman asks in his great book Fact, Fiction, and Forecast: how can we move from a finite set of observations already made to a prediction of future observations. The observations already made would be the observed chess moves so far and the future observations would be all chess moves that haven't happend yet. The questions is, is there a nomological relation between past observations and future observations (as opposed to the purely causal relation between past events and future events)?

If we interpret the word nomological as by a law of nature or logic and nothing can ever happen in disaccord to this law then, there is certainly no such relation, since the first person who moves a castle diagonally, would break the law of nature and the universe as we know it would collapse.

But even if, in fact, by some freak accident of nature, every move any chess player in the world would make from now on, was valid (nobody would ever make any mistakes or try to cheat and even people clueless about the rules of chess would start pushing chess pieces around randomly across the board, but accidently always according to the rules), that would not convince us that there is a law of nature (or a law of logic) that forced all of this. We'd consider it purely accidental.

Ludwig Wittgenstein covered similar ground in his Philosophical Investigations. He insists that any set of observations is in accordance to arbitrarily many, and even conflicting, rules. For example, if all chess games observed by me would have happend in the afternoon, then my rule could be in the afternoon the bishop can only be moved diagonally. That the time of day is unimportant to the game is something that couldn't have been observed by me since I haven't observed chess games during different times of the day. Or, incidentally, if I have never observed a woman playing chess, then the rule could be the bishop can only be moved by men at all. What is relevant to an observation and what is not is determined as a prerequisite to the observation and cannot be part of the observation itself.

BTW: Wittgenstein's solution to the problem is quite similar to that of Goodman. I won't spoil the surprise, though ;-)

Addendum:

In the days when Sussman was a novice, Minsky once came to him as he
  sat hacking at the PDP-6.

"What are you doing?", asked Minsky. "I am training a randomly wired
  neural net to play Tic-tac-toe", Sussman replied. "Why is the net
  wired randomly?", asked Minsky. "I do not want it to have any
  preconceptions of how to play", Sussman said.

Minsky then shut his eyes. "Why do you close your eyes?" Sussman asked
  his teacher. "So that the room will be empty." At that moment, Sussman
  was enlightened.

OwnerDisplayName: Yktula

Title: Learning the rules of chess


答: AFIAK all languages with dynamic typing are interpreted languages.  That's already very inefficient, adding the inefficiency of dynamic typing isn't going to be a big loss of time.  A compiled language, though, won't be actually referring to things by name when it's running.  (Barring the occasional use of .net reflection or the like--features which are very slow compared to the underlying language.)  Searching for all those names is going to be slow, slow, slow.</p>

Title: Why do variables need a type?


问:
Will correctness proofs of code ever go mainstream?
All but the most trivial programs are filled with bugs and so anything that promises to remove them is extremely alluring. At the moment, correctness proofs are code are extremely esoteric, mainly because of the difficultly of learning this and the extra effort it takes to prove a program correct. Do you think that code proving will ever take off?</p>

答:
I stumbled on this question, and I think that this link might be interesting:

Industrial Applications of Astrée

Proving the absence of RTE in a system used by Airbus with more than 130K lines of code in 2003 does not seem to be bad, and I wonder will there be anybody say that this is not real world.


问:
Are XML Schemas bad for constantly evolving file formats?
I'm struggling with a client-server project where I have Java apps out on the Internet that store data to a backend server. The format of this data is well-defined, but the project is constantly evolving, so the definition keeps changing! To cope with the change I defined a simple REST interface on the server that offers only key-value storage. Clients can store or retrieve a chunk of data by referencing a unique key. This is nice because I don't have to modify the server interface (or the backend database) when the data format changes. To the server, it's just a bunch of opaque blobs.

Of course, the issue then becomes, "What goes inside the blob?" For that I wrote an XML Schema that defines the content of a blob. At first it was great, since the Schema gives a bunch of nice things "for free": A formal yet human-readable spec of the file format, automatic validation of its contents, marshalling/unmarshalling to a stream, and auto-generated Java classes for programmatic access to the data.

But then change happened! The Schema had to be altered, and naturally I ran into forward- and backward-compatibility issues. To deal with the constantly changing Schema, I came up with a solution that embeds a version number into the XML namespace, and I apply a series of XSL Stylesheets to "upgrade" any given blob to the latest version. For example, I'm now on version 1.3 of my Schema, so when I unmarshal a blob, I run it through a 1.0-to-1.1 XSLT, then a 1.1-to-1.2 XSLT, and finally a 1.2-to-1.3 XSLT. This works, but it's not sustainable because the chain keeps getting longer, which lowers performance and sucks up memory, plus I have to keep writing new Stylesheets, which takes time and isn't fun.

Now here's the funny thing... In addition to the Java clients, the project also has iOS apps as clients, and iOS has none of the nice enterprise-y features associated with XML Schemas. There's no validation of the stream, no auto-generation of Objective-C classes, etc., just a low-level event-driven XML parser. But ironically I'm finding this so much easier! For example, if the XML gets a new element, I just add a new if clause. If an element goes away, I remove its clause. Basically, I do a "best effort" at interpreting the XML stream, silently ignoring any unrecognized elements. I don't need to think about what version the file format is or whether it's valid. Plus this is much faster because there's no XSLT chaining, and it saves a lot of my time because I don't have to write any XSLT code.

So far this approach has worked out great, and I've not missed having an XML Schema on the iOS side. I'm now wondering if a Schema, despite its nice feature set, is totally the wrong technology for a file format that often changes. I'm thinking about ditching my XML Schema altogether and using the same "best effort" low-level approach in Java that I'm doing in iOS.

So is my negative assessment of XML Schemas correct? Or is there something I've missed? Perhaps I need to rethink the server interface? Or maybe I shouldn't have been using XML in the first place? I'm open to all suggestions. Thanks for reading!

答:
I think you are really asking a broader question, "is having a strict definition of a file format a good thing for a rapidly evolving project".

To answer your immediate question, though: yes, they are.  The XML schema gives you a strict definition of the format, answer a lot of questions about validity, provides great documentation, and allows you to confidently know that a specific version of the document has a specific form.

They are not the be-all and end-all, though: they define structure, not semantics, so you can still change the "meaning" of a tag between version of the document without having to change the schema.  That causes just as much trouble.

To answer the question I think you are asking: yes, the XML schema is a good thing.

It is forcing you to address a painful fact, which is that your data exchange is constantly changing versions, and that means you have to adapt your system to account for that.

If you only had the IOS model, where you take a "rough guess" at what this version means, you open the door to all sorts of trouble in the long run.  For example, it becomes trivial for someone to assume that "element foo being present means version 1.2, so tag bar means ...".

That is great, right until version 2.0 adds back the foo element, with a different meaning, and tag bar isn't even there.  Welcome to "inconsistent behaviour" city.

If you use XML without schemas, or JSON, or something else that doesn't impose that cost on you then only a tiny bit of the problem goes away.  You still have to deal with all four versions of the input, but you have less tools to help you out.

You should, in my opinion, generally prefer to make the pain of changes proportional to their real, long term cost.  Changing the data exchange format has a high long term cost - you have to deal with compatibility, with data upgrades, and that sort of thing.

If that costs little you will be tempted to do it a lot, and then will pay the maintenance cost tomorrow.  If it costs more now, you might think harder - can you do more than one thing in this change?  Can you get away without it?  Can you do it smarter?

In short, I think your real problem is that your file format changes often, not that you used (or didn't use) XML schemas.

(Also, are your users really happy if the server or client randomly drops content that is represented in the newer version?  I would be surprised if that remains true forever - another of those long term costs you need to recognise somewhere...)


答:
Whether it helps your career is hard to tell. Certain industries and hiring managers may have a preference for or against. You could get a job at a university without being an academician, but they prefer people with higher education.

It can help you be a better writer and consumer of research literature. Most of your courses will have a written component (they did the last course I took). A key is to have professors who will critique your writing and research and give quality feedback and force you to work at a higher level.

Of course, you can get by without it and learn this on your own. It's not a requirement and doesn't benefit everyone. Most people will get high grades, but not everyone gets the good recommendation.

Title: Does having Master's degree in Computer Science help your career?

Body: I am curious about experiences of programmers who have gone beyond college or university and now work in the industry. I am not talking about academia (you need PhD there anyway). Do you have a Master's degree? Has it helped your career? Are there any other benefits besides the knowledge one gains while pursuing the degree?</p>


答: Perhaps generally speaking it can help but it also depends on the hiring manager. I hire .NET developers to join my team. As a developer, I am pretty picky about who I hire since we're handling some seriously sensitive data and large sums of money as well. We are a small, agile, passionate team of software developers that range from high school grads to masters degrees in CS and even Physics. I don't really ever look at college degrees, or even work experience in your early years. I want to see how you communicate, get along with the team, handle real problems, and of course show me the code. You think you're a bad ass programmer? Show me the proof. You have to be working on some sort of open source project, have a github/bitbucket/CodePlex/etc... account with something going on it. Degrees are paper - it's all about what you can do.


答:
You might be interested in "scannerless parsers", which don't have a separate tokenization step. One explanation of the benefits of scannerless parsers is given at the beginning of this paper: Disambiguation Filters for Scannerless Generalized LR Parsers. (There are disadvantages, too, though.)

(PEGs, which have been mentioned in other answers, can also be used to construct scannerless parsers.)


问:
In what areas of programming is algorithm run time actually an important issue?
Sometimes I hear people say that because of the speed of processors and the amount of memory available, algorithm efficiency and runtime aren't, in practice, of major concern.

But I imagine there are still areas where such considerations do remain of paramount importance.  Two that come to mind are in algorithmic trading, where thousands of transactions must be conducted in fractions of a second, and embedded systems programming, where memory and power are often scarce.  Am I right about these examples ?  and what other areas would also be examples?

答:
Speed is always in demand. I guess you are correct. Here are some examples were neat algorithms are in demand:

Cryptography

Searching large databases

Sorting and merging

Text searching (non-indexed), including wildcards

Math problems with intensive calculations

Simulation

Data Mining Applications

Animation

AI

Computer vision


答:
A variable does not need to have an associated type. Languages where this is true include Lisp, Scheme, Erlang, Prolog, Smalltalk, Perl, Python, Ruby, and others.

It's also possible for a variable to have a type, but you might not have to write the type in the program. This is usually called type inference. ML, Haskell, and their descendants have powerful type inference; some other languages have it in lesser forms, such as C++'s auto declarations.

The main argument against type inference is that it damages readability. It's usually easier to understand code when the types are written down.

Title: Why do variables need a type?


答:
There are some cases where algorithm run-time might not be a big deal, because we've gotten to the point that you can simply punch through a longer-running algorithm with more powerful hardware. But there are definitely some places where speed-ups are essential.

Generally speaking, anything using huge datasets will be a problem. When you have something that scales poorly with n, and then you make n a really huge number, you have a problem. I suspect if you went over to the Computational Science beta site and poked around a bit, you could find plenty of problems in need of better, faster algorithms. Some areas that I've run into:

Particularly complex statistical analysis. A combination of inefficient algorithms and large data sets can mean massive slowdowns. For some studies, this might not matter, but what if you're trying to do something with fast turn around? "It will come off the server in a month" is probably a bad thing when you're running a chemical/nuclear/biological threat surveillance system.

Data mining on large data sets.

Simulations involving many variables.

Generally speaking, scientific computing generally seems to be an area where the complexity of what's being programmed generates opportunities for serious slowdowns if your algorithm is sluggish (many of them suffering from very large n's). And, as you mentioned, there's financial applications. When milliseconds can determine whether you make or lose money on a trade, "good enough" algorithms aren't going to cut it if there's something better that can be done.

Title: In what areas of programming is algorithm run time actually an important issue?

Body:
Sometimes I hear people say that because of the speed of processors and the amount of memory available, algorithm efficiency and runtime aren't, in practice, of major concern.

But I imagine there are still areas where such considerations do remain of paramount importance.  Two that come to mind are in algorithmic trading, where thousands of transactions must be conducted in fractions of a second, and embedded systems programming, where memory and power are often scarce.  Am I right about these examples ?  and what other areas would also be examples?


答: I think search engines like Google and Bing are one of the biggest areas where complex algorithms are used and they play a key role in speeding up results with relevance ( page ranking ) bringing more utility to the users.


问:
Moving from a CVCS to a DVCS in a big company, what is the right way to do it?
I just started a new job and I'm currently at the process of trying to introduce a DVCS (mercurial, but the actual DVCS is not really a matter of discussion at this point, it could also be git) to the company (big, multinational). So far I've gotten nothing but positive attention, even at managerial and directive level, but I want to make sure I'm not at all disruptive to the organization or anyone's jobs.

The way the developers are set up is in a team room, so there's a lot of communication going on. There is also an integrator, that communicates on a daily basis two or three times with the team leader. Also, there are more development teams on other parts of the world, maybe 20 offices in 6 or 7 countries.

Company culture is open and there would be no problem pilot testing the tool  but the real question is (in capital letters):

HOW DO YOU CONVINCE MANAGEMENT AROUND ALL THE OFFICES OVER THE WORLD THAT ITS A SANE THING TO DO AND WILL ACTUALLY BRING HAPPINESS AND PRODUCTIVITY TO DEVELOPERS? (say pilot testing and showing it works is just one part of the answer).

Elaborating on the context...

Does it make sense to make the switch?, yes (note: current SCM is Perforce). I've witnessed several sources of frustration classic to centralized source control management, including:

People accidentally breaking other's builds or stepping on each others' toes while submitting code revisions.

This is not often as the responsible must wear a pink hat (hilarious stuff) until the build is fixed, but the hat is still there, and when builds get broken it affects the other offices around the world.

DVCS to the rescue: Builds are now broken in a single office, people lose the fear to use version control and can actually second-guess themselves after or check with a peer by sharing their changes easier and not necessarily with the rest of the group.

Unnecessary bureaucracy when it comes to granting access (e.g. looks like everyone is granted access to most of the code).

There is a dedicated group of admins who take 1 to 3 days to grant access to the code, meanwhile other developers must ask their peers for the code just to look at it... but AFAIK, the often wait instead.

DVCS to the rescue: Administration does not have to be centralized on a little group of overwhelmed people, new employees get the code from the project's responsible (1st level) or a peer with repository access (2nd level) who could even review their code and submit it along with his/her changes.

Complaints with regards to slowness due to network latency. Not that directly, but sometimes a) The perforce server is down, b) Internet is down, c) Internet or perforce server is slow. Yes, not that often, but it is annoying enough to kick you off your train of thought sometimes.

DVCS to the rescue: When using the DVCS you obviously don't need a network connection. Worst case scenario?, share your changes over LAN or sneakernet (with patch queues).

Trouble when trying to collaborate with external providers that do not necessarily belong to the organization. This happens often enough and security is a concern here AFAIK, and clients suffer from the access bureaucracy.

DVCS to the rescue: So granting access to a subrepo here would be the ideal solution here... also, clients themselves could use version control among themselves without needing to set up their own server and they would be able to integrate better to the internal workflow as currently Perforce access access to the local network, and thus more bureaucracy which is not necessarily security here, as external collaborators still have access to thumbdrives and email. Actual security would be having externals work in-situ... in a dungeon or something, and grope them à la TSA on their way out to make sure they are not getting the code out.

Workaround to integrate modules from other repositories. Requires additional maintenance/effort from the developers. **They actually wrote themselves (I think) a plugin to make Perforce fetch files from other repositories in other parts **

DVCS to the rescue: Their solution looks a lot like the mercurial subrepo feature, which uses a file (.hgsub) to indicate what code goes where, but they have to maintain the other repositories' states in the same file (which is done separately and automatically by mercurial in the .hgsubstate file).

Working with the source code requires to mark files for edit in advance. This adds an annoying extra step IMHO. If you don't do this the file will be in read only mode and you will not be able to edit it on your IDE, also, this in my opinion makes the local copy prone to low integrity. This trait of Perforce makes me think there was a lazy developer that didn't want to make the client check the files against the repository before versioning the changes. It also makes me think/personify Perforce as an idiot paranoid that says "DON'T CHANGE THE FILES WITHOUT TELLING ME OR THE SQUIRRELS WILL COME AND EAT ME!".

DVCS to the rescue: Well... I guess any other SCM software knows there are no carnivore squirrels.

Little project integrity in developers' machines (see previous point; its harder to add changes without previously indicating them to Perforce). You don't need a DVCS for this... but if you make changes locally and for some reason forgot to add them, you are going to have a hard time detecting it. Once you detect it there is a two step command line instruction thing I saw somewhere to detect changes you did without telling Perforce.

Given that context what would you say is the best way to... ?:

Know/demonstrate if the migration would actually benefit the employees and the company.

Ease the embracement of change, or at least make it look like its worth the effort

Not complicate others' jobs.

Convince management worldwide.

Avoid making the integrator's job a royal pain.

My second question (and focusing on the last point) I've always been a DVCS evangelist mainly because it eases the work and collaboration between developers... but up to this point I've never been faced with having to consider the integrators' perspective (the one in charge of coordinating teams' source code, creating and releasing the builds... from across the globe) who at some point might have to face two SCM sources or at least the migration itself. Then, how can the migration process affect integrators the least?.

答:
The best way is to do a pilot with one existing team and record what the issues are.  In my experience, the biggest obstacle to using a DVCS in an enterprise is the lack of structure.  A DVCS is more of an SCM framework than a full solution.  You have to add a lot of glue to make it work in a large organization, which is why things like kiln exist.

You may also want to do a gradual migration.  Perforce has recently added some features to make it more appealing to DVCS fans, namely streams and sandbox.  Being familiar with the benefits of those concepts would ease the transition and maybe even obviate it.  There are also things like git-p4 that could enable a gradual transition.


问:
Might I run into any trouble if I plug into an existing service/application with my own application and charge for it?
I know this is more of a lawyer question, however I figure someone here has probably done this and can give me a quick answer.

Lets take a moderately extreme case. I build an adapter for a website that translates the requests and markup into a more formal API. I then take this API I developed and build a mobile app on it.

So in short I take a site that doesn't support mobile. Build a mobile application, and then charge for the mobile application.

I am not talking about charging for any of the original product. Simply the extension to the product.

I ask because there is a site I would really like to build a mobile app for, because it would make my life easier, and it would be pretty gravy if I could earn some cash on the side from the work as well.

答:
I think you should put the following to the test:

Is your application violating any licensing agreements or patents?

Will your application be accessing protected content bypassing the security measures?

If the answer to both of these questions is no then I don't see there being any legal issues with your charging for your application.


问:
How to prioritize tasks when you have multiple programming projects running in parallel?
Say you have 5 customers, you develop 2 or 3 different projects for each. Each project has Xi tasks.

Each project takes from 2 to 10 man weeks.

Given that there are few resources, it is desired to minimize the management overhead.

Two questions in this scenario:

What tools would you use to prioritize the tasks and track their completion, while tending to minimize the overhead?

What criteria would you take into consideration to determine which task to assign to the next available resource given that the primary objective is to increase throughput (more projects finished per time unit, this objective conflicts with starting one project and finishing it and then moving on to the next)?

Ideas, management techniques, algorithms are welcome

答:
Given your scenario, I would ask the customer's to prioritize the projects that you are working on for them. I would not choose these projects by those with "the highest profit ratios" as your sending your customer the message that all you are interested in is their money. You want your customer to know that you're interested in helping them solve their software problems.

Then the process of determining what you work on next is a conversation between you and them, where you explain what resources you have available to devote to their project(s) and which they would prioritize first.

They may not be thrilled that you are telling them that you can't do everything they want, but they'll appreciate that your putting them in charge of what they consider important.

Another side effect of this process is that you can manage the customer's expectation better.