问:
What techniques are used in solving code golf problems?

"Regular" golf vs. code golf:

Both are competitions.  Both have a well-defined set of rules, which I'll leave out for simplicity.  Both have well-defined goals; in short, "use fewer hits/characters than your competitors."

To win matches, athletic golfers rely on

equipment

Some situations call for a sand wedge; others, a 9-iron.

techniques

The drive works better when your feet are about shoulder width apart and your arms are relaxed.

and strategies

Sure, you could take that direct shortcut to the hole... but do you really want to risk the water hazard or sand bunker when those trees are in the way and the wind is so strong?  It might be better to go around the long way.

What do code golfers have that's analagous to athletic golfers' equipment, techniques and strategies?

Sample answer to get this started: use the right club!  Choose GolfScript instead of C#.

答:
I'd say that thorough knowledge of the syntactical oddities of your language help. Here is one I found in Ruby when doing a bit of code golf:

Instead of

```<code>require "sequel"
require "nokogiri"
require "chronic"
</code>```

You can do something like this:

```<code> body_of_your_program if %w{sequel nokogiri chronic}.each{|i| require i}
</code>```

With this kind of thing, you too can write incredibly elaborate Ruby one-liners!

In Ruby and Perl, you also get the magic variables like "$_" which can be used to do all sorts of magic with strings and regexes. Is your data not strings? Well, you might want to turn it into strings.

Obviously, in C, the preprocessor is your friend.

Body:
I'd say that thorough knowledge of the syntactical oddities of your language help. Here is one I found in Ruby when doing a bit of code golf:

Instead of

require "sequel"
require "nokogiri"
require "chronic"

You can do something like this:

 body_of_your_program if %w{sequel nokogiri chronic}.each{|i| require i}

With this kind of thing, you too can write incredibly elaborate Ruby one-liners!

In Ruby and Perl, you also get the magic variables like "$_" which can be used to do all sorts of magic with strings and regexes. Is your data not strings? Well, you might want to turn it into strings.

Obviously, in C, the preprocessor is your friend.


问:
What are the Top Developer Productivity Tools/Plugins for Java in Eclipse?
I personally use CodeRush in Visual Studio 2010 to do refactoring, write code faster with templates and generally navigate my code 10 times faster than stock VS.  Recently, I've been working on another Android app and got to thinking...What are the top productivity plugins for Eclipse?

Preferably free. I'm looking for plugins that help write in Java, not PHP or Rails or any of the other languages Eclipse supports.

答:
I personally turn to Checkstyle to keep my code on the straight and narrow.  It helps point out where my design is growing to bloated and I need to step back and refactor.  eclipse-cs is one plugin for eclipse for use with Checkstyle.

JUnit, of course, would be the other defacto tool of choice for my development, but then I this is pretty much supported out of the box if you are using eclipse.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Experiments correlating code metrics to bug density
I'm wondering if someone has done some experiments correlating code metrics (SLOC, Cyclomatic Complexity, etc) with bug density in Object Oriented applications.

I'm not looking for experiments that only prove or disprove a correlation, but on both. I'm not trying to find a silver bullet as I believe that the bug density of a project might correlate to one or more metrics for a given project or team and the correlation can change during the lifetime of the project / team.

My goal is to

Measure all interesting metrics for 2-3 months (we already have quite a few from sonar).

Find one metric that correlates with the number of new bugs.

Do a root-cause analysis to check why this happens (e.g. Do we lack a certain design skill?).

Improve the skill and measure change for a couple of itereations.

Rinse and repeat from 2.

If you don't have any experience on this, but remember seeing a paper / blog on this subject, I would appreciate if you can share it.

So far I've found the following links with some information about this subject

Do Bugs Reside in Complex Code? - just the slides from a presentation.

Changes and Bugs: Mining and Predicting Development Activities - Just slides frmm a presentation. Bottom line the more dependencies, the higher the chances of bugs (I think this is quite a general rule).

Failure is a four-letter word - A parady about the correlation between bugs and metrics.

答:
I have discussed possible correlations in one of my blog posts:

Correllation between Cyclomatic Complexity and Bugs density: Is this the real Issue?

The answer is no. Keeping the size constant, studies show no
  correlation between CC and defect density. However, there are other
  two interesting correlations to study:

The first one is: Does CC strongly correlate with the duration of
  detecting and fixing defects? In other words, if CC is lower, would we
  spend less time debug and fix defects?

The second one is: Does CC strongly correlate with the Fault Feedback
  Ratio (FFR, the average number of defects which results from applying
  one change or fixing one defect)?

It needs more investigation to see if anyone has ever studied this
  correlation empirically. But, my gut feeling and the feedback I get
  from the teams I work with is that there is strong positive
  correlation between cyclomatic complexity on one side and the duration
  of detecting and fixing a defect or the change impact on another side.

This is a good experiment to do. Keep alert for the results!


问:
What are useful metrics for source code?
What are useful metrics to capture for source code?

How can metrics, like for example (Executable?) Lines of Code or Cyclomatic Complexity help with quality assurance or how are they beneficial in general for the software development process?

答:
What confuses me about code metrics is that it isn't done more. Most companies report on the efficiency of their employees, suppliers, and systems in place, but nobody seems to want to report on code. I will definitely agree with answers that state that more lines of code is a liability but what your code does is more important.

Lines Of Code:
As 'Ive mentioned this is a vital measurement and should be taken the most seriously, but on each level. Functions, classes, files and interfaces can indicate do-everything code that is hard to maintain and costly in the long term. It's infinitely hard to compare the total lines of code versus what a system does. It could be something that does many things and in that case there will be many lines of code!

Complexity:
This measurement is good to do on code bases you haven't worked on, and can give you a good indication of where problem areas lie. As a useful anecdote I measured complexity on one of my own code bases, and the highest complexity area was the one that I was spending the most time when I needed to change it. Working towards reducing the complexity resulted in a massive reduction in maintenance time. If management had these measurements at hand they could plan refactoring iterations or redesigns of specific areas of a system.

Code duplication:
This is a very important measurement as far as I'm concerned. Code duplication is a very bad sign and could point to either deep problems in low levels of a system's design or developers that are copy pasting, causing massive problems in the long term and systems that are unmaintainable.

Dependency Graphs
Finding bad dependencies and circular dependencies are an important measurement in code. This almost always points to an incorrect high level design that needs revising. Sometimes one dependency can suck in a whole lot of unnecessary other ones, because someone is using addNumber inside an e-mail library to do their finance calculations. Everyone is shocked when the e-mail library is changed and finance breaks. If everything is dependent on one thing it can also point to do-everything libraries that are hard to maintain and badly designed.

A good measurement will always tell you that every feature of a system has a small footprint. Less dependencies, less complexities, less duplication. This points to loose coupling and high cohesion.


问:
Does Silverlight have a future?
Recently I have read some articles/blogs/comments about the development and history of WPF and Silverlight. In some forums many developers and users criticize the performance of WPF applications (for example Visual Studio 2010). Actually the market share of Silverlight in comparison to Flash is not very high. At PDC 2010 Bob Muglia said something like "our Silverlight strategy and focus going forward has shifted...." and Microsoft wants to push HTML5 in the future.

Additionally, Microsoft has announced HTML5 being a core part of the Windows 8 and Windows Phone 8 ("Mango") platforms.

Recently I have started learning Silverlight and now I must ask myself, if I should continue investing time in learning these (in my opinions) very nice and powerful technologies!? Does they have a future? Does (Windows) desktop (client) applications have a future? Does so called "Rich Internet Applications" have a future? Or will HTML5 become the "absolute truth" in software development?

What is your opinion and what do you think?

答:
Not according to this artcile, they are streamlining it to make it easier to create cross platform code.

http://www.theregister.co.uk/2010/10/29/portable_library_project_silverlight_windows_phone/

Title: Does Silverlight have a future?


问:
Java solution for mutual authentication with smart card
I need to develop a Java solution for mutual authentication between Tomcat 6 (server) and SmartCard "IDGo 300" (client).

In order to do this I thought of the following scheme:

1.Tomcat (server) send to SmartCard (client) the request of his digital certificate (signed by CA).

2.Client enters PIN and selects an available certificate on the smart card, then the Applet sends his certificate (signed by CA) to Tomcat. Tomcat verifies the digital certificate and, if it is correct, sends the certificate back.

3.The applet verifies the certificate of the server, and, if the certificate is correct, sends a confirm to server.
The server gives full access to the client to use the web application.

I have some questions:

1.Is this scheme feasible?

2.I would like to manage everything through my applet and when the client disconnects the smart card, he loses access to the server.

答:
Take a look at the SmartCard API for Java

This specification describes the Java Smart Card I/O API defined by JSR 268. It defines a Java API for communication with Smart Cards using ISO/IEC 7816-4 APDUs. It thereby allows Java applications to interact with applications running on the Smart Card, to store and retrieve data on the card, etc.

The API is defined by classes in the package javax.smartcardio...


问:
Is Liskov Substitution Principle incompatible with Introspection or Duck Typing?
Do I understand correctly that Liskov Substitution Principle cannot be observed in languages where objects can inspect themselves, like what is usual in duck typed languages?

For example, in Ruby, if a class B inherits from a class A, then for every object x of A, x.class is going to return A, but if x is an object of B, x.class is not going to return A.

Here is a statement of LSP:

Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.

So in Ruby, for example,

class T; end
class S < T; end
```

<p>violate LSP in this form, as witnessed by the property <em>q(x)</em> = <code>x.class.name == 'T'</code></p>

<hr>

<p><em>Addition.</em> If the answer is "yes" (LSP incompatible with introspection), then my other question would be: is there some modified "weak" form of LSP which can possibly hold for a dynamic language, possibly under some additional conditions and with only special types of <em>properties</em>.</p>

<hr>

<p><em>Update.</em> For reference, here is another formulation of LSP that I've found on the web:</p>

<blockquote>
  <p>Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.</p>
</blockquote>

<p>And another:</p>

<blockquote>
  <p>If S is a declared subtype of T, objects of type S should behave as objects of type T are expected to behave, if they are treated as objects of type T.</p>
</blockquote>

<p>The last one is annotated with:</p>

<blockquote>
  <p>Note that the LSP is all about expected behaviour of objects. One can only follow the LSP if one is clear about what the expected behaviour of objects is.</p>
</blockquote>

<p>This seems to be weaker than the original one, and might be possible to observe, but I would like to see it formalized, in particular explained who decides what the expected behavior is.</p>

<p>Is then LSP not a property of a pair of classes in a programming language, but of a pair of classes together with a given set of properties, satisfied by the ancestor class?  Practically, would this mean that to construct a subclass (descendant class) respecting LSP, all possible uses of the ancestor class have to be known?  According to LSP, the ancestor class is supposed to be replaceable with any descendant class, right?</p>

<hr>

<p><em>Update.</em>  I have already accepted the answer, but i would like to add one more concrete example from Ruby to illustrate the question.  In Ruby, each class is a module in the sense that <code>Class</code> class is a descendant of <code>Module</code> class. However:</p>

<pre class="lang-rb prettyprint-override"><code>class C; end
C.is_a?(Module) # => true
C.class # => Class
Class.superclass # => Module

module M; end
M.class # => Module

o = Object.new

o.extend(M) # ok
o.extend(C) # => TypeError: wrong argument type Class (expected Module)
</code>```

答:
In the context of LSP a "property" is something that can be observed on a type (or an object). In particular it talks about a "provable property".

Such a "property" could the existence of a foo() method that has no return value (and follows the contract set in its documentation).

Make sure you don't confuse this term with "property" as in "class is a property of every object in Ruby". Such a "property" can be a "LSP property", but it's not automatically the same!

Now the answer to your questions depends a lot on how stringent you define "property". If you say "the property of class A is that .class will return the type of the object", then B actually does have that property.

If, however, you define the "property" to be ".class returns A", then obviously B does not have that property.

However, the second definition isn't very useful, as you've essentially found a round-about way to declare a constant.


问:
Are small amounts of functional programming understandable by non-FP people?
Case: I'm working at a company, writing an application in Python that is handling a lot of data in arrays. I'm the only developer of this program at the moment, but it will probably be used/modified/extended in the future (1-3 years) by some other programmer, at this moment unknown to me. I will probably not be there directly to help then, but maybe give some support via email if I have time for it.

So, as a developer who has learned functional programming (Haskell), I tend to solve, for example, filtering like this:

```<code>filtered = filter(lambda item: included(item.time, dur), measures)
</code>```

The rest of the code is OO, it's just some small cases where I want to solve it like this, because it is much simpler and more beautiful according to me.

Question: Is it OK today to write code like this?

How does a developer that hasn't written/learned FP react to code like this?

Is it readable?

Modifiable?

Should I write documentation like explaining to a child what the line does?

```<code> # Filter out the items from measures for which included(item.time, dur) != True
</code>```

I have asked my boss, and he just says "FP is black magic, but if it works and is the most efficient solution, then it's OK to use it."

What is your opinion on this? As a non-FP programmer, how do you react to the code? Is the code "googable" so you can understand what it does? I would love feedback on this.

答:
Since developer community is regaining interest in functional programming, it is not unusual to see some functional programming in languages which were originally fully object oriented. A good example is C#, where anonymous types and lambda expressions enable to be much shorter and expressive through functional programming.

This being said, functional programming is weird for beginners. For example, when during a training course, I explained to the beginners how they can enhance their code through functional programming in C#, some of them were not convinced, and some said that the original code was easier to understand for them. The example I gave to them was the following:

Code before refactoring:

var categorizedProducts = new Dictionary<string, List<Product>>();

// Get only enabled products, filtering the disabled ones, and group them by categories.
foreach (var product in this.Data.Products)
{
    if (product.IsEnabled)
    {
        if (!categorizedProducts.ContainsKey(product.Category))
        {
            // The category is missing. Create one.
            categorizedProducts.Add(product.Category, new List<Product>());
        }

        categorizedProducts[product.Category].Add(product);
    }
}

// Walk through the categories.
foreach (var productsInCategory in categorizedProducts)
{
    var minimumPrice = double.MaxValue;
    var maximumPrice = double.MinValue;

    // Walk through the products in a category to search for the maximum and minimum prices.
    foreach (var product in productsInCategory.Value)
    {
        if (product.Price < minimumPrice)
        {
            minimumPrice = product.Price;
        }

        if (product.Price > maximumPrice)
        {
            maximumPrice = product.Price;
        }
    }

    yield return new PricesPerCategory(category: productsInCategory.Key, minimum: minimumPrice, maximum: maximumPrice);
}
```

<p><strong>Same code after refactoring by using FP:</strong></p>

<pre class="lang-cs prettyprint-override"><code>return this.Data.Products
    .Where(product => product.IsEnabled)
    .GroupBy(product => product.Category)
    .Select(productsInCategory => new PricesPerCategory(
              category: productsInCategory.Key,
              minimum:  productsInCategory.Value.Min(product => product.Price),
              maximum:  productsInCategory.Value.Max(product => product.Price))
    );
</code>```

This make me think that:

you should not worry if you know that the next developer who will maintain your code will have enough overall experience and some knowledge of functional programming, but:

otherwise, either avoid functional programming, or put a verbose comment explaining at the same time the syntax, the advantages and the possible caveats of your approach versus a non-functional programming one.

ContentLicense: CC BY-SA 4.0

Body:
Since developer community is regaining interest in functional programming, it is not unusual to see some functional programming in languages which were originally fully object oriented. A good example is C#, where anonymous types and lambda expressions enable to be much shorter and expressive through functional programming.

This being said, functional programming is weird for beginners. For example, when during a training course, I explained to the beginners how they can enhance their code through functional programming in C#, some of them were not convinced, and some said that the original code was easier to understand for them. The example I gave to them was the following:

Code before refactoring:

var categorizedProducts = new Dictionary<string, List<Product>>();

// Get only enabled products, filtering the disabled ones, and group them by categories.
foreach (var product in this.Data.Products)
{
    if (product.IsEnabled)
    {
        if (!categorizedProducts.ContainsKey(product.Category))
        {
            // The category is missing. Create one.
            categorizedProducts.Add(product.Category, new List<Product>());
        }

        categorizedProducts[product.Category].Add(product);
    }
}

// Walk through the categories.
foreach (var productsInCategory in categorizedProducts)
{
    var minimumPrice = double.MaxValue;
    var maximumPrice = double.MinValue;

    // Walk through the products in a category to search for the maximum and minimum prices.
    foreach (var product in productsInCategory.Value)
    {
        if (product.Price < minimumPrice)
        {
            minimumPrice = product.Price;
        }

        if (product.Price > maximumPrice)
        {
            maximumPrice = product.Price;
        }
    }

    yield return new PricesPerCategory(category: productsInCategory.Key, minimum: minimumPrice, maximum: maximumPrice);
}

Same code after refactoring by using FP:

return this.Data.Products
    .Where(product => product.IsEnabled)
    .GroupBy(product => product.Category)
    .Select(productsInCategory => new PricesPerCategory(
              category: productsInCategory.Key,
              minimum:  productsInCategory.Value.Min(product => product.Price),
              maximum:  productsInCategory.Value.Max(product => product.Price))
    );

This make me think that:

you should not worry if you know that the next developer who will maintain your code will have enough overall experience and some knowledge of functional programming, but:

otherwise, either avoid functional programming, or put a verbose comment explaining at the same time the syntax, the advantages and the possible caveats of your approach versus a non-functional programming one.


答:
I am a non-FP programmer and recently I was to modify my colleague's code in JavaScript. There was an Http-request with a callback which looked a lot like the statement included by you. I must say that it took me some time (like half an hour) to figure it all out (the code all in all wasn't very large).

There were no comments, and I think there was no necessity for any. I didn't even ask my colleague to help me understand his code.

Taking into account that I am working for about 1.5 years, I think most programmers will be able to understand and modify such code, since I did.

Besides, as Joachim Sauer said in his comment, there often are pieces of FP in many languages, like C# (indexOf, for instance). So many non-FP programmers deal with this quite often, and the code snippet you included isn't something dreadful or incomprehensible.

Title: Are small amounts of functional programming understandable by non-FP people?

Body:
Case: I'm working at a company, writing an application in Python that is handling a lot of data in arrays. I'm the only developer of this program at the moment, but it will probably be used/modified/extended in the future (1-3 years) by some other programmer, at this moment unknown to me. I will probably not be there directly to help then, but maybe give some support via email if I have time for it.

So, as a developer who has learned functional programming (Haskell), I tend to solve, for example, filtering like this:

```<code>filtered = filter(lambda item: included(item.time, dur), measures)
</code>```

The rest of the code is OO, it's just some small cases where I want to solve it like this, because it is much simpler and more beautiful according to me.

Question: Is it OK today to write code like this?

How does a developer that hasn't written/learned FP react to code like this?

Is it readable?

Modifiable?

Should I write documentation like explaining to a child what the line does?

```<code> # Filter out the items from measures for which included(item.time, dur) != True
</code>```

I have asked my boss, and he just says "FP is black magic, but if it works and is the most efficient solution, then it's OK to use it."

What is your opinion on this? As a non-FP programmer, how do you react to the code? Is the code "googable" so you can understand what it does? I would love feedback on this.


答:
Is it readable?

For me: Yes, but I have come to understand, that the Python community often seems to consider list comprehensions a cleaner solution than using map()/filter().

In fact, GvR even considered dropping those functions altogether.

Consider this:

```<code>filtered = [item for item in measures if included(item.time, dur)]
</code>```

Further, this has the benefit that a list comprehension will always return a list. map() and filter() on the other hand will return an iterator in Python 3.

Note: If you want to have an iterator instead, it's as simple as replacing [] with ():

```<code>filtered = (item for item in measures if included(item.time, dur))
</code>```

To be honest, I see little to no reason for using map() or filter() in Python.

Is it Modifiable?

Yes, certainly, however, there is one thing to make that easier: Make it a function, not a lambda.

```<code>def is_included(item):
    return included(item.time, dur)
filtered = filter(is_included, measures)
filtered = [item for item in measures if is_included(item)]
</code>```

If your condition becomes more complex, this will scale much easier, also, it allows you to reuse your check. (Note that you can create functions inside other functions, this can keep it closer to the place where it is used.)

How does a developer that hasn't written/learned FP react on code like this?

He googles for the Python documentation and knows how it works five minutes later. Otherwise, he shouldn't be programming in Python.

map() and filter() are extremely simple. It's not like you're asking them to understand monads. That's why I don't think you need to write such comments. Use good variable and function names, then the code is almost self explanatory. You can't anticipate which language features a developer doesn't know. For all you know, the next developer might not know what a dictionary is.

What we don't understand is usually not readable for us. Thus, you could argue it's no less readable than a list comprehension if you've never seen either of them before. But as Joshua mentioned in his comment, I too believe it's important to be consistent with what other developers use - at least if the alternative provides no substantial advantage.

Body:
Is it readable?

For me: Yes, but I have come to understand, that the Python community often seems to consider list comprehensions a cleaner solution than using map()/filter().

In fact, GvR even considered dropping those functions altogether.

Consider this:

filtered = [item for item in measures if included(item.time, dur)]

Further, this has the benefit that a list comprehension will always return a list. map() and filter() on the other hand will return an iterator in Python 3.

Note: If you want to have an iterator instead, it's as simple as replacing [] with ():

filtered = (item for item in measures if included(item.time, dur))

To be honest, I see little to no reason for using map() or filter() in Python.

Is it Modifiable?

Yes, certainly, however, there is one thing to make that easier: Make it a function, not a lambda.

def is_included(item):
    return included(item.time, dur)
filtered = filter(is_included, measures)
filtered = [item for item in measures if is_included(item)]

If your condition becomes more complex, this will scale much easier, also, it allows you to reuse your check. (Note that you can create functions inside other functions, this can keep it closer to the place where it is used.)

How does a developer that hasn't written/learned FP react on code like this?

He googles for the Python documentation and knows how it works five minutes later. Otherwise, he shouldn't be programming in Python.

map() and filter() are extremely simple. It's not like you're asking them to understand monads. That's why I don't think you need to write such comments. Use good variable and function names, then the code is almost self explanatory. You can't anticipate which language features a developer doesn't know. For all you know, the next developer might not know what a dictionary is.

What we don't understand is usually not readable for us. Thus, you could argue it's no less readable than a list comprehension if you've never seen either of them before. But as Joshua mentioned in his comment, I too believe it's important to be consistent with what other developers use - at least if the alternative provides no substantial advantage.


答:
We had this same discussion on a company I worked for last year.

The discussion concerned "magical code" and if it was to be encouraged or not. When looking into it a bit more it seemed that people had very different views on what actually was "magical code".
The ones who brought up the discussion seemed to mostly mean that expressions (in PHP) which used functional-style was "magical code" whereas developers who originated from other languages who used more FP style in their code seem to think that magical code was rather when you made dynamic inclusion of files through filenames and so on.

We never came to any good conclusion on this, more than that people mostly think code that looks unfamiliar is "magical" or hard to read.
So is it a good idea to avoid code that seems unfamiliar to other users?
I think that it depends on where it is used. I would refrain from using fp-style expressions (dynamic file inclusion and so on) in a main method (or important central parts of applications) where data should be tunnel in a clear and easy-to-read, intuitive, way. On the other hand, I do not think one should be afraid to push the envelope, the other developers will probably learn FP quickly if they are faced with FP code and maybe have some good in-house resource to consult on the issues.

TL;DR: Avoid in high level central part of the applications (which need to be read for an overview of the functionality of the application). Otherwise use it.


问:
Dynamic choice of compilers?
An application has the following logic:

client => created *.cpp => sent to the server => cl.exe + *.cpp =

*.exe

client => created *.cs => sent to the server => csc.exe + *.cs =

*.exe

client => created *.pas => sent to the server => PascalCompiler +

*.pas = *.exe

etc.

The language - C#. I hear that MSBUILD can help me, but I don't understand how to change compiler on server at runtime. Does anyone know of options other than Process class?

I'm trying to write an online system to test programs in programming contests. The programmer selects the compiler and sends the source code to the server for verification.

And I do not need to build the project, I just need to compile a single file.

答: If all you have to compile is a single file, then why not simply require developers to adhere to a file suffix standard and drive the compiler choice from the file type?  Just iterate through the directory, picking up every file in it and checking its suffix.  If it's a "known" suffix, then fire off the appropriate compile command in a separate thread.  When your loop ends, wait on all the children before scanning again.  You'll need some way to move or flag files once they've been processed and a notification mechanism to inform the submitters whether their compile failed or not, but those are fairly trivial details.</p>

Title: Dynamic choice of compilers?


答: As I understand it, there's nothing about introspection that would be incompatible with the LSP.  Basically, as long as an object supports the same methods as another, the two should be interchangable.  That is, if your code expects an Address object, then it doesn't matter if it's a CustomerAddress or a WarehouseAddress, as long as both provide (e.g.) getStreetAddress(), getCityName(), getRegion() and getPostalCode().  You could certainly create some kind of decorator that takes a different type of object and uses introspection to provide the required methods (e.g., a DestinationAddress class that takes a Shipment object and presents the ship-to address as an Address), but it's not required and certainly wouldn't prevent the LSP from being applied.

Title: Is Liskov Substitution Principle incompatible with Introspection or Duck Typing?

Body:
Do I understand correctly that Liskov Substitution Principle cannot be observed in languages where objects can inspect themselves, like what is usual in duck typed languages?

For example, in Ruby, if a class B inherits from a class A, then for every object x of A, x.class is going to return A, but if x is an object of B, x.class is not going to return A.

Here is a statement of LSP:

Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.

So in Ruby, for example,

class T; end
class S < T; end
```

<p>violate LSP in this form, as witnessed by the property <em>q(x)</em> = <code>x.class.name == 'T'</code></p>

<hr>

<p><em>Addition.</em> If the answer is "yes" (LSP incompatible with introspection), then my other question would be: is there some modified "weak" form of LSP which can possibly hold for a dynamic language, possibly under some additional conditions and with only special types of <em>properties</em>.</p>

<hr>

<p><em>Update.</em> For reference, here is another formulation of LSP that I've found on the web:</p>

<blockquote>
  <p>Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.</p>
</blockquote>

<p>And another:</p>

<blockquote>
  <p>If S is a declared subtype of T, objects of type S should behave as objects of type T are expected to behave, if they are treated as objects of type T.</p>
</blockquote>

<p>The last one is annotated with:</p>

<blockquote>
  <p>Note that the LSP is all about expected behaviour of objects. One can only follow the LSP if one is clear about what the expected behaviour of objects is.</p>
</blockquote>

<p>This seems to be weaker than the original one, and might be possible to observe, but I would like to see it formalized, in particular explained who decides what the expected behavior is.</p>

<p>Is then LSP not a property of a pair of classes in a programming language, but of a pair of classes together with a given set of properties, satisfied by the ancestor class?  Practically, would this mean that to construct a subclass (descendant class) respecting LSP, all possible uses of the ancestor class have to be known?  According to LSP, the ancestor class is supposed to be replaceable with any descendant class, right?</p>

<hr>

<p><em>Update.</em>  I have already accepted the answer, but i would like to add one more concrete example from Ruby to illustrate the question.  In Ruby, each class is a module in the sense that <code>Class</code> class is a descendant of <code>Module</code> class. However:</p>

<pre class="lang-rb prettyprint-override"><code>class C; end
C.is_a?(Module) # => true
C.class # => Class
Class.superclass # => Module

module M; end
M.class # => Module

o = Object.new

o.extend(M) # ok
o.extend(C) # => TypeError: wrong argument type Class (expected Module)
</code>```


答:
Here's the actual principle:

Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.

And the excellent wikipedia summary:

It states that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may be substituted for objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.).

And some relevant quotes from the paper:

What is needed is a stronger requirement that constrains the behavior of sub-types: properties that can be proved using the specification of an object’s presumed type should hold even though the object is actually a member of a subtype of that type...

A type specification includes the following information:

 - The type’s name;

 - A description of the type's value space;

 - For each of the type's methods:

 --- Its name;

 --- Its signature (including signaled exceptions);

 --- Its behavior in terms of pre-conditions and post-conditions.

So on to the question:

Do I understand correctly that Liskov Substitution Principle cannot be observed in languages where objects can inspect themselves, like what is usual in duck typed languages?

No.

A.class returns a class.

B.class returns a class.

Since you can make the same call on the more specific type and get a compatible result, LSP holds. The issue is that with dynamic languages, you can still call things on the result expecting them to be there.

But let's consider a statically, structural (duck) typed language. In this case, A.class would return a type with a constraint that it must be A or a subtype of A. This provides the static guarantee that any subtype of A must provide a method T.class whose result is a type that satisfies that constraint.

This provides a stronger assertion that LSP holds in languages that support duck typing, and that any violation of LSP in something like Ruby occurs more due to normal dynamic misuse than a language design incompatibility.


问:
Are some NOP codes treated differently than others?
I'm curious about this, let's say I have:

```<code>00000000001 90                              nop
00000000002 90                              nop
00000000003 90                              nop
</code>```

Is it executed exactly the same as this?

```<code>00000000001 0F1F00                          nop        dword [ds:rax]
</code>```

What effect would the second example have as opposed to the first?

答: It appears that the second example should run quicker than the first.  In the first example, three separate instructions will be executed.  In the second, only one instruction.  The multi-byte NOPs are intended to be used for CPU "hints" (exactly how and when is apparently confidential).  They can be useful for alignment purposes (to start a tight loop on a cache line), but currently they have no other use.  It's unclear whether the CPU actually evaluates the arguments, so it's not possible to say whether it increases the instruction decoding time or incurs a memory access penalty.  Anybody with a good ICE want to test one of these and see what addresses pop up on a bus trace?</p>


答:
The C++ community recently got lambda's as well, and I believe they have roughly the same question. The answer may not be the same, though. The C++ equivalent would be:

```<code>std::copy_if(measures.begin(), measures.end(), inserter(filter),
  [dur](Item i) { return included(i, dur) } );
</code>```

Now std::copy isn't new, and the _if variants aren't new either, but the lambda is. Yet it's defined rather clearly in context: dur is captured and therefore constant, Item i varies in the loop, and the single return statement does all the work.

This looks acceptable to many C++ developers. I haven't sampled opinions on higher-order lambda's, though, and I would expect much less acceptance.

Body:
The C++ community recently got lambda's as well, and I believe they have roughly the same question. The answer may not be the same, though. The C++ equivalent would be:

std::copy_if(measures.begin(), measures.end(), inserter(filter),
  [dur](Item i) { return included(i, dur) } );

Now std::copy isn't new, and the _if variants aren't new either, but the lambda is. Yet it's defined rather clearly in context: dur is captured and therefore constant, Item i varies in the loop, and the single return statement does all the work.

This looks acceptable to many C++ developers. I haven't sampled opinions on higher-order lambda's, though, and I would expect much less acceptance.


问:
Issues Tracker for both developers and end users
currently, we have a closed source project on hand. However, we would like to have a communication channel together with our end users.

We would like to have our end users to know, what features we are currently working on, and what features they are going to get in next release.

We would like to know users' thought, on our planned features. They may always provide input/suggestion on our planned features.

We do not planned to host on our own server. Hence, a ready-available service is welcomed.

But we would like to remain our source code in closed model

Is there any web based service available for this purpose? Free or commercial doesn't matter.

答:
You can even try trello . Very easy and intuitive.
You can even get help on http://webapps.stackexchange.com about using trello.
If you look into the demo the Trello team has implemented exactly your use-case to demonstrate the usage of the features.

I am not affiliated in any way to the mentioned service, apart being a user of the system


问:
How do I assess tradeoff between robustness and "lazy" code in API design?
Postel's law:

Be conservative in what you do, be liberal in what you accept from others.

"Lazy" code (per The Pragmatic Programmer):

Be strict in what you will accept before you begin, and promise as little as possible in return.

I'm developing a finance (asset pricing, etc.) framework for Python. Question: when designing the API for the framework, what factors should I consider when I assess the tradeoff between being strict and being liberal re: inputs?

Example:

I have the following method that downloads stock prices from Yahoo.

```<code>def historical_prices(ticker, start=None, end=None, data='d', convert=True):
# Do stuff
</code>```

For the date arguments (start & end), I could:

Be strict, and only allow a string of ISO format YYYY-mm-dd, or

Be liberal and accept datetime objects, strings (of specified formats), etc.

答: I would code the main function with a specific format as the input. If there is a request to add more formats etc then create a function to overload the name that converts the date object etc into your format before calling your main function.</p>

OwnerDisplayName: MikeRand


问:
Using account (login) password in generated PDF?
Ever since I heard about programming, I was told that any password (especially the one used on login) should be stored in database using any kind of one-way hashing algorithm, and never ever as plain string. So, it can't be read directly from database, using any method.

Today I noticed that my bank (country department of Citi Group) is using my account (login) password to password-protect PDFs generated at the end of each month.

I'm curious: Are they breaching one of the most important security issue and are storing passwords in plain text in DB? Or is there any way to use hashed password from DB to password-protect generated PDF?

As far as my limited knowledge tells me, this isn't possible. And to use in PDF the same password as on login, it has to be actually read from DB upon PDF generation, which leads to a conclusion, that it is being stored there as plain text string.

This is a general question, on concepts of programming, not related to any particular language or technique, so I assume, it should be asked here, not in StackOverflow.

答:
There is nothing within your scenario that says the organization is storing passwords in plain text.

There's a number of options I can think of off-hand.

They could be relying upon the encryption capabilities of their database.  This is reversible and would make your password available for other encryption.

They could be running their own encryption algorithm (either symmetric or asymmetric) over the password to secure it.  Again, this is reversible.

They could be storing your password during your login session and using that to generate your end-of-month PDF files.  Not a great idea, but it would make your password readily available.  You don't necessarily know when those reports are generated.  Could be a just-in-time scenario based upon your logging in.

They may also be using the same hashing mechanism that encrypted PDFs use, so they only need to use the hashed result in order to encrypt the PDF.  This would require a bit more effort on their part, but isn't completely implausible.

Or maybe they are storing it in plain text somewhere.

Don't jump to conclusions without gathering enough evidence to properly analyze the situation.  I would say that in this case there are a number of paths that they may be following that would leave your password secured but still provide the ability to encrypt your reports with your login password.


答:
It is going to be easier to accept the strict input, and reject any other forms, because you will have only one case to consider.

It really depends on your customers' requirements.  Do they need flexibility of input, i.e. Internationalization, or can they work comfortably with a single format.

Title: How do I assess tradeoff between robustness and "lazy" code in API design?

Body:
Postel's law:

Be conservative in what you do, be liberal in what you accept from others.

"Lazy" code (per The Pragmatic Programmer):

Be strict in what you will accept before you begin, and promise as little as possible in return.

I'm developing a finance (asset pricing, etc.) framework for Python. Question: when designing the API for the framework, what factors should I consider when I assess the tradeoff between being strict and being liberal re: inputs?

Example:

I have the following method that downloads stock prices from Yahoo.

```<code>def historical_prices(ticker, start=None, end=None, data='d', convert=True):
# Do stuff
</code>```

For the date arguments (start & end), I could:

Be strict, and only allow a string of ISO format YYYY-mm-dd, or

Be liberal and accept datetime objects, strings (of specified formats), etc.


问:
What was the first server-side language
I was thinking about different server-side languages and this question immediately cropped up in my mind. What was the first server-side programming language using which websites were being created? Was it java or some other language?

Note: I think some languages became prime server-side because they provided or rather aimed to provide better tools and libraries for easy development. I agree Java was not primarly server-side but it provided better tools and hence was and is used a lot.

答:
Back in the 'early days' of the web, people hacked web servers using non-standard APIs in whatever language they had handy. Back then, the NCSA HTTPd was the defacto standard, so you mostly used C, I believe. Certainly, each HTTP server product had it's own C API (Netscape had NSAPI, Microsoft ISAPI, etc).

To alleviate this, in 1993 the CGI standard (Common Gateway Interface) standard was developed, allowing a web server to interface with a local process to handle requests. Because web servers were almost exclusively run on UNIX systems, the interface uses environment variables to communicate with the process, and each new request is handled by a new process.

Because you could now use any UNIX process to answer a HTTP request, you could use any language you liked for CGI programs. Personally, I started using shell scripts at first (simply emailing the contents of a web form) but quickly picked up Perl and the emerging CGI.pm module. Per request performance didn't much factor into things yet, the web wasn't so busy at the time. If you needed a fast response time you used static files or one of the aforementioned C APIs to directly interface with the HTTP server.

Java didn't enter the world of computing until 1995, and was first aimed at in-browser applets before becoming popular as a server-side language. By that time, dedicated web application servers, extension modules such as mod_perl and dedicated web programming languages such as PHP, ASP and ColdFusion started to appear. Each of these have had their following, some still survive today. None of them were ever dominant or clearly "first".

Title: What was the first server-side language


问:
GDI low on memory
I am fresh to Visual C++. While moving forward in the book "Programming Windows with MFC", I came across GDI (Graphics Device Interface) and use of paint brush. The book says a brush cannot be created if your GDI is low on memory.

I want to know when and how does GDI get low on memory? And more important, what is the reason that we cannot create brush when GDI is low on memory?

答:
This depends a bit on the Version of Windows that you are targeting, but suffice to say that when you create a GDI object such as a brush or path, GDI will allocate some memory for that object either in your application memory or a shared server process memory (%SYSTEM\csrss.exe). In some versions of Windows, some of this memory is allocated in Kernel mode.

See this old, old, old article for how much memory and where

If you never release the object, GDI won't reclaim the memory. Suffice to say, there's a limit to how much is available (not necessarily proportional to the RAM in your PC). The actual limits vary, from Windows 95 upwards. It can be affected by overall application load (i.e. lots of graphical apps loaded, some of which are leaky), graphics driver issues, a number of concurrent users all competing for resource (e.g. Terminal server).

If you want to see it run out, do something like this:

```<code>CBitmap * pbm; while (true) { pbm = CBitmap::CreateBitmap(...); Sleep(0); }
</code>```

Further reading:

Resource Leaks: Detecting, Locating, and Repairing Your Leaky GDI Code

BUG: GDI memory leak in Developer Studio IDE

GDI is low on memory - close one or more windows and try again

Out of memory messages when you have large numbers of programs running

Title: GDI low on memory

Body:
This depends a bit on the Version of Windows that you are targeting, but suffice to say that when you create a GDI object such as a brush or path, GDI will allocate some memory for that object either in your application memory or a shared server process memory (%SYSTEM\csrss.exe). In some versions of Windows, some of this memory is allocated in Kernel mode.

See this old, old, old article for how much memory and where

If you never release the object, GDI won't reclaim the memory. Suffice to say, there's a limit to how much is available (not necessarily proportional to the RAM in your PC). The actual limits vary, from Windows 95 upwards. It can be affected by overall application load (i.e. lots of graphical apps loaded, some of which are leaky), graphics driver issues, a number of concurrent users all competing for resource (e.g. Terminal server).

If you want to see it run out, do something like this:

CBitmap * pbm; while (true) { pbm = CBitmap::CreateBitmap(...); Sleep(0); }

Further reading:

Resource Leaks: Detecting, Locating, and Repairing Your Leaky GDI Code

BUG: GDI memory leak in Developer Studio IDE

GDI is low on memory - close one or more windows and try again

Out of memory messages when you have large numbers of programs running


答:
The first server-side programs were probably extensions to the webservers themselves, which AFAIK were all written in C.

But in the discussions that led to the CGI standard you can already see that the API between webserver and server-side code was implicitly assumed to be language agnostic (based on stdin/stdout), and people talked of "scripts", which is a strong hint that they were thinking of shell scripts (with C as an alternative for high performance).

Shortly thereafter, the first language that really dominated web development was Perl (not least because it's basically shell scripts on steroids), and that is probably your best answer.

Java came later and took over much of Perl's marketshare due to Sun's marketing efforts, and because it delivered a good combination of performance (via thread-based servers), safety (no buffer overflows) and conventional C-like syntax. But it never really achieved dominance the way Perl did for a while.

Title: What was the first server-side language

Body:
I was thinking about different server-side languages and this question immediately cropped up in my mind. What was the first server-side programming language using which websites were being created? Was it java or some other language?

Note: I think some languages became prime server-side because they provided or rather aimed to provide better tools and libraries for easy development. I agree Java was not primarly server-side but it provided better tools and hence was and is used a lot.


答:
Well it depends on what you understand by a server. Certainly there were servers applications written (even web) before Java was launched; also, according to its creators Java is not a server-side programming language, but a general-purpose language.

From the begins, client-server relied on dumb clients connecting to mainframes; these were probably programmed in C or COBOL, but as Java they were not designed as server-languages.

Title: What was the first server-side language


问:
How to structure a development team
I am the manager of a team of 11 software developers who look after my company's web sites / web applications, running up to 4 concurrent projects plus day-to-day support at any time. Within the 11 developers there is a mixture of technical skills, job titles and experience, although the team structure is flat with all 11 developers reporting directly to me.

The whole team having a single manager is starting to prove not to scale very well. I am starting to be spread too thinly so want to reduce my number of direct reports. All the ways I can think to do this have significant downsides:

Have junior developers report to senior ones. This reduces the time spent on development by the best technicians.

Split the team by software product, e.g. developers 1-6 work on intranet and 7-11 work on external sites, with each section having new team lead (possibly a new job description with more management / mentoring / coaching responsibility than the current senior developers). This adds artificial silos and might make it difficult to get an "intranet developer" to work on an external website if I want them to.

Keep the structure flat and add managerial support in the shape of Project Managers / Team Administrators just to take the pressure off. This doesn't solve the problem as the team can't go on growing like this forever.

Is there a standard way of solving this problem which I am missing?

If not, how have others of you solved this problem?

答:
That structure will mainly depend on project specifications

Ideally, there should be 3 juniors per senior developer in a team. Consequently, there are  2-3 senior developers per a teach lead.

Thus, only tech leads will report to PM on progress status of the project. Described structure still assumes that for a non-technical issues (vacation, time-off, conflicts, etc.) everyone can have access to PM.

One of the relatively successful software development teams I was a part of went something like this, on a per-project basis:

A Software Development Manager/Senior Developer/Mentor, to whom everyone else reported directly.

A project manager, who kept schedules, facilitated requirements and acceptance negotiation, and did communications. Everyone dotted-line reported to this person, too.
A documentation person (who occasionally was also the PM, but only when expertise permitted).

A mix of 1-3 developers or senior developers, depending on the project's needs.

A junior developer when available.

Someone assigned from a QA pool.

An infrastructure person (a role often fulfilled by the manager, since he had solid SA competency as well).

It worked perfectly fine, and I loved that organization. On the other hand, I was the Software Development Manager, and the team's organization structure was evolving.

Title: How to structure a development team


答:
Some quick thoughts:

Sub-teams are a good idea: 11 direct reports without any structure is too large for a workable team (you won't have enough time for direct coaching, and team meetings with that many people will tend to be unproductive).

Consider separating operations out from development - it's a slightly different skillset and being interrupted by operational issues all day can seriously harm development productivity on projects.

As a result of the first two points, I think you should have perhaps 3 subteams - Intranet, External Sites and Operations. The operations guys will deal with all day-to-day issues / maintenance fixes etc. while the two development teams focus on delivering new projects / value to the business.

Cycle people between teams on a regular basis. This can be either occasional (e.g. having people do review of code in another subteam), for a project or on a permanent basis. But make sure it is understood that team roles will change whenever there is a business need - nobody "owns" a specific role forever.

Don't add more managers/administrators - this is a surefire way to reduce the overall effectiveness / productivity of your teams. Have the most experienced person in each subteam play a team lead / coach role. Make sure that they see their role here as coaching and making the whole team succeed, and make sure that they are equipped to behave in this way rather than act a "task manager".

Your role should be focused on external stakeholder management, prioritisation of resources / tasks within the group, and acting as "head coach". You'll need to handle the occasional escalated issue from the sub-teams, but in general you should encourage them to solve problems themselves without coming to you.

If you are highly technical yourself you may also choose to play an architect / design assurance role. If not, find someone who can, within the team or elsewhere.....

Also, it's always worth going and (re)reading the Agile Manifesto, and especially the twelve principles.

Title: How to structure a development team

Body:
I am the manager of a team of 11 software developers who look after my company's web sites / web applications, running up to 4 concurrent projects plus day-to-day support at any time. Within the 11 developers there is a mixture of technical skills, job titles and experience, although the team structure is flat with all 11 developers reporting directly to me.

The whole team having a single manager is starting to prove not to scale very well. I am starting to be spread too thinly so want to reduce my number of direct reports. All the ways I can think to do this have significant downsides:

Have junior developers report to senior ones. This reduces the time spent on development by the best technicians.

Split the team by software product, e.g. developers 1-6 work on intranet and 7-11 work on external sites, with each section having new team lead (possibly a new job description with more management / mentoring / coaching responsibility than the current senior developers). This adds artificial silos and might make it difficult to get an "intranet developer" to work on an external website if I want them to.

Keep the structure flat and add managerial support in the shape of Project Managers / Team Administrators just to take the pressure off. This doesn't solve the problem as the team can't go on growing like this forever.

Is there a standard way of solving this problem which I am missing?

If not, how have others of you solved this problem?


答:
I would say definitely yes!

There are many aspects of functional programming, and using higher-order functions, as in your example, is only one of them.

For example, I consider writing pure functions to be extremely important for any software written in any language (where by "pure" I mean no side-effects), because:

they're easier to unit test

they're much more composable than side-effecting functions

they're easier to debug

I also often avoid mutating values and variables -- another concept borrowed from FP.

Both of these techniques work fine in Python and other languages that aren't commonly classified as functional.  They are often even supported by the language itself (i.e. final variables in Java).  Thus, future maintenance programmers won't face a humongous barrier to understanding the code.


问:
Is restricting sessions to an absolute IP likely to have a wide impact on mobile networks?
Our website currently restricts a cookie-based session to the IP address that was originally sent the Set-Cookie HTTP header. In the past a user's IP would rarely change, so this didn't present much inconvenience. However, some of our clients accessing via 3G devices are experiencing session failures due to this IP restriction.

I know little about the network infrastructure used for mobile networks. Do the majority of providers attempt to route connections to a common public IP in order to maintain compatibility with websites like ours, or should I consider restricting sessions to an IP range instead?

答:
Do the majority of providers attempt to route connections to a common public IP in order to maintain compatibility with websites like ours, or should I consider restricting sessions to an IP range instead?

Short answer: IP addresses have no relationship to a user's identity.  Furthermore, you cannot accurately predict what address, or block of addresses will be assigned to a user.

Longer answer:
IP addresses change constantly in mobile environments, and they even change infrequently for wireline customers.

Since you are essentially using an IP address to map to the user's identity, the algorithm is indeed broken as you suspected.  It does not matter whether you managed to make this work successfully in the past; that success was a reflection of a limited sample size, and not the result of good design.

Abstracting into provider-specific address ranges are an inadequate workaround for the problem.  You will spend substatial time quantifying the address ranges used by providers; and certainly find frustration after a client steps on a plane, then later reautheticates hundreds of miles from previous attempts (usually resulting in a completely new address block from the mobile provider).  Further complicating this issue will be the almost seamless use of IPv4 / IPv6 / tunneling between IPv4&IPv6 for some providers as they try to manage the limited IPv4 address space.  In short, there is no guarantee that the same user will always receive the same IP address, or that the address they have is in a 100% predictable address block.

OwnerDisplayName: tjbp

OwnerDisplayName: Mike Pennington


答:
As Mike pointed out above.It is better not to restrict IP Address or a map an ip address
to a user's identity

Both wired and wireless internet service providers give their customers a dynamic ip addresses or static ip addresses .
All internet service providers do not provide static ip addresses to their customers.
some providers provide static ip addresses  and some do not provide static ip addresses.

Title: Is restricting sessions to an absolute IP likely to have a wide impact on mobile networks?

Body:
Our website currently restricts a cookie-based session to the IP address that was originally sent the Set-Cookie HTTP header. In the past a user's IP would rarely change, so this didn't present much inconvenience. However, some of our clients accessing via 3G devices are experiencing session failures due to this IP restriction.

I know little about the network infrastructure used for mobile networks. Do the majority of providers attempt to route connections to a common public IP in order to maintain compatibility with websites like ours, or should I consider restricting sessions to an IP range instead?


问:
Why aren't macros included in most modern programming languages?
I know that they are implemented extremely unsafely in C/C++. Can't they be implemented in a safer way? Are the disadvantages of macros really bad enough to outweigh the massive power they provide?</p>

答:
Macros can be implemented very safely in some circumstances - in Lisp for example, macros are just functions that return transformed code as a data structure (s-expression). Of course, Lisp benefits significantly from the fact that it is homoiconic and the fact that "code is data".

An example of how easy macros can be is this Clojure example which specifies a default value to be used in the case of an exception:

```<code>(defmacro on-error [default-value code]
  `(try ~code (catch Exception ~'e ~default-value)))

(on-error 0 (+ nil nil))               ;; would normally throw NullPointerException
=> 0                                   ;l; but we get the default value
</code>```

Even in Lisps though, the general advice is "don't use macros unless you have to".

If you aren't using a homoiconic language, then macros get much trickier and the various other options all have some pitfalls:

Text-based macros - e.g. the C preprocessor - simple to implement but very tricky to use correctly as you need to generate the correct source syntax in textual form, including any syntactical quirks

Macro-based DSLS - e.g. the C++ template system. Complex, can itself result in some tricky syntax, can be extremely complex for compiler and tool writers to handle correctly since it introduces significant new complexity into the language syntax and semantics.

AST/bytecode manipulation APIs - e.g. Java reflection / bytecode generation - theoretically very flexible but can get very verbose: it can require a lot of code to do quite simple things. If it takes ten lines of code to generate the equivalent of a three line function, then you haven't gained much with your meta-programming endeavours...

Furthermore, everything a macro can do can ultimately be achieved in some other way in a turing complete language (even if this means writing a lot of boilerplate). As a result of all this trickiness, it's not surprising that many languages decide that macros aren't really worth the all effort to implement.

Body:
Macros can be implemented very safely in some circumstances - in Lisp for example, macros are just functions that return transformed code as a data structure (s-expression). Of course, Lisp benefits significantly from the fact that it is homoiconic and the fact that "code is data".

An example of how easy macros can be is this Clojure example which specifies a default value to be used in the case of an exception:

(defmacro on-error [default-value code]
  `(try ~code (catch Exception ~'e ~default-value)))

(on-error 0 (+ nil nil))               ;; would normally throw NullPointerException
=> 0                                   ;l; but we get the default value

Even in Lisps though, the general advice is "don't use macros unless you have to".

If you aren't using a homoiconic language, then macros get much trickier and the various other options all have some pitfalls:

Text-based macros - e.g. the C preprocessor - simple to implement but very tricky to use correctly as you need to generate the correct source syntax in textual form, including any syntactical quirks

Macro-based DSLS - e.g. the C++ template system. Complex, can itself result in some tricky syntax, can be extremely complex for compiler and tool writers to handle correctly since it introduces significant new complexity into the language syntax and semantics.

AST/bytecode manipulation APIs - e.g. Java reflection / bytecode generation - theoretically very flexible but can get very verbose: it can require a lot of code to do quite simple things. If it takes ten lines of code to generate the equivalent of a three line function, then you haven't gained much with your meta-programming endeavours...

Furthermore, everything a macro can do can ultimately be achieved in some other way in a turing complete language (even if this means writing a lot of boilerplate). As a result of all this trickiness, it's not surprising that many languages decide that macros aren't really worth the all effort to implement.


问:
Tips on persuading boss that code review is a good thing
Let's say one works in a hypothetical company that has several developers that rarely worked together on projects and the Boss didn't believe that code reviews are worth the time and cost.

What are various arguments that could be presented in this scenario that will portray the benefit of code review?  Furthermore, what are the potential arguments against code review here and how can these be countered?

答:
If you have to justify yourself for such basic stuff, you have a bigger problem.

You are the expert, your team should decide what practices you use. Maybe you should start to convince your boss of that very important principle.

Your boss is supposed to decide WHAT to do and more importantly WHY doing it. You should take care of the HOW build it

(that doesn't means you can't suggest what and why do things in your company of course). A great boss should encourage his employees to participate in enterprise strategy)

However here is how I view peer code reviews:

Because programming is a very intensive intellectual work, one person can't ensure everything is perfect. Therefore code review ensure that:

vulnerabilities or bugs are found before the app is shipped

constant mutual education between developers (almost for free) is achieved

code respect standard for easier app maintenance

code match the requirements

Everyone is taking direct benefits of it:

the developer that increases his/her knowledge and can pass his own to his/her team mates

the customer/user that has less bugs and spend less in maintenance

the boss that has more happy customers/users and spend less in trainings


问:
What does it mean when we say that some function is polynomially bigger/smaller than some other function?
I was going over this video lecture on  master theorem from Introduction to Algorithm  and while explaining case A of the  master theorem professor says that some function f(n) is polynomially smaller than some other function at point 53:08 seconds:

What does it mean for a function to be polynomially smaller than this function?

I am confused here as polynomially is not equivalent to poly-logarithmically. Has the professor used the wrong term here ? It is highly unlikely though since he goes on to say the same term a number of times.

答:
In short: a smaller(bigger) exponent of n.

It relates directly to a part of my answer to an earlier question of yours here:

, which basically says that n to some power grows faster, if the exponent is bigger, regardless of constant factors.

In case 1, function f(n) is assumed to be polynomially smaller than this one:

Don't get scared by the logarithm here, it is just a number, because a and b are constants, so is log_b(a). (Which is why poly-logarithmically does not enter the picture, in that case)

It is then defined to what class of functions f(n) must belong to. This is already the answer to your question "what it means to be polynomially smaller":

All it means is, that the exponent of n must be less than log_b(a): You subtract a positive number (epsilon) from it.

This is another way of looking at it:

The polynomially bigger one has more factors of n: epsilon more. (or less in the case of smaller)

At 57:30 he gives an example, where he ends up in case 1: He compares f(n) = n with n^2. f(n) is polynomially smaller because 1 < 2.


问:
Software design by pseudocoding?
Do you know a good way to design (i.e. write down) software with a method based on pseudocode?

I'm new to software design and read some information about UML. My humble class hierarchies are good so far, however, after it gets complex I notice that with "seeing the whole" picture I could have used a different structure for more future extendability. As Python is good to prototyping I'm almost fine with just starting to write, but not quite.

So I tried UML class diagrams, but they don't seem to help me much. The problems I solve there I can trivially do in my head. But I do notice additional design requirements once I start to pseudocode the actual methods.

So if you wanted to design by pseudocode, how would you do it? I believe for me a method which is roughly 1-to-1 with code works best. But most UML software doesn't even show the method's code (as opposed to pictures in e.g. GoF).

Someone claimed UML is for documentation and presentation only and not that great for design? I also get that feeling. I thought pure UML and some simplistic whiteboard sketches were the way to design software until googling I found Envision APDT.

So is agile development something I should look out for or do they randomly call that agile -  I thought agile is about schedule only? Or am I designing incorrectly (with UML) - does anyone design by pseudocode? How can I find a good tool for that?

答:
```<code> I thought agile is about schedule only?
</code>```

It is not just planning. Agile software development is more about being a evolutionary development and  a time-boxed iterative delivery with adaptive planning which encourages flexible response to changes requested by product owner.

```<code> Or am I designing incorrectly (with UML) - does anyone design by pseudocode?
</code>```

In my experience charts are much easier to understand from a client stand perspective. They are visually appealing and many times very colorful and easy to follow. However, it is very hard to maintain charts due to the nature of disconnect with the actual application code. Every time a change is made in the application the developer has to take the time to update all documentation including charts. However, that problem can be easily eliminated once there is a BA in the team or company, who understands client business process well and can manage the UML diagrams.

Tools like UML can make this process easier but only works well with object oriented programming. Pseudo code is much easier for technical teams. The process of creating this code greatly increases the speed of the actual programming language development phase.

There are some other alternatives that you may look as well:

Data Flow Diagrams

State Diagrams

Process Flow Charts

Good references to look: Software Design Tutorials. In addition, i would personally advice to read a good blog on Pseudocode or Code? posted by Coding Horror - my favorite blog to read :)

All in all, there are some trade-offs that you need to consider.

Title: Software design by pseudocoding?

Body:
 I thought agile is about schedule only?

It is not just planning. Agile software development is more about being a evolutionary development and  a time-boxed iterative delivery with adaptive planning which encourages flexible response to changes requested by product owner.

 Or am I designing incorrectly (with UML) - does anyone design by pseudocode?

In my experience charts are much easier to understand from a client stand perspective. They are visually appealing and many times very colorful and easy to follow. However, it is very hard to maintain charts due to the nature of disconnect with the actual application code. Every time a change is made in the application the developer has to take the time to update all documentation including charts. However, that problem can be easily eliminated once there is a BA in the team or company, who understands client business process well and can manage the UML diagrams.

Tools like UML can make this process easier but only works well with object oriented programming. Pseudo code is much easier for technical teams. The process of creating this code greatly increases the speed of the actual programming language development phase.

There are some other alternatives that you may look as well:

Data Flow Diagrams

State Diagrams

Process Flow Charts

Good references to look: Software Design Tutorials. In addition, i would personally advice to read a good blog on Pseudocode or Code? posted by Coding Horror - my favorite blog to read :)

All in all, there are some trade-offs that you need to consider.


答:
To quote Wikipedia's article on LSP, "substitutability is a principle in object-oriented programming." It is a principle and part of the design of your program. If you write code that depends on x.class == A, then it is your code that is violating LSP. Note this kind of broken code is also possible in Java, no duck typing necessary.

Nothing in duck typing inherently breaks LSP. Only if you misuse it, as in your example.

Additional thought: doesn't explicitly checking for an object's class defeat the purpose of duck typing, anyway?


问:
Is micro-optimisation important when coding?
I recently asked a question on Stack Overflow to find out why isset() was faster than strlen() in PHP. This raised questions around the importance of readable code and whether performance improvements of micro-seconds in code were worth even considering.

My father is a retired programmer, and I showed him the responses. He was absolutely certain that if a coder does not consider performance in their code even at the micro level, they are not good programmers.

I'm not so sure - perhaps the increase in computing power means we no longer have to consider these kind of micro-performance improvements? Perhaps this kind of considering is up to the people who write the actual language code? (of PHP in the above case).

The environmental factors could be important - the Internet consumes 10% of the world's energy. I wonder how wasteful a few micro-seconds of code is when replicated trillions of times on millions of websites?

I'd like to know answers preferably based on facts about programming.

Is micro-optimisation important when coding?

My personal summary of 25 answers, thanks to all.

Sometimes we need to really worry about micro-optimisations, but only in very rare circumstances. Reliability and readability are far more important in the majority of cases. However, considering micro-optimisation from time to time doesn't hurt. A basic understanding can help us not to make obvious bad choices when coding such as

```<code>if (expensiveFunction() || counter < X)
</code>```

Should be

```<code>if (counter < X || expensiveFunction())
</code>```

(Example from @zidarsk8) This could be an inexpensive function and therefore changing the code would be micro-optimisation. But, with a basic understanding, you would not have to, because you would write it correctly in the first place.

答:
IMHO code-readability is more important than micro-optimization because in most part of cases micro-optimization does not worth it.

Article about non-sense micro-optimizations:

As most of us, I am tired to read blog posts about non-sense
  micro-optimizations like replacing print by echo, ++$i by $i++, or
  double quotes by single quotes. Why? Because 99.999999% of the time,
  it is irrelevant. Why? Because 99.99% of the time, you'd better
  install a PHP accelerator like APC, or add these missing indexes on
  your database columns, or try to avoid those 1000 database requests
  you have on the homepage.

print uses one more opcode because it actually returns something. We
  can conclude that echo is faster than print. But one opcode costs
  nothing, really nothing.

I have tried on a fresh WordPress installation. The script halts
  before it ends with a "Bus Error" on my laptop, but the number of
  opcodes was already at more than 2.3 millions. Enough said.

So in most cases micro-optimization saves 1 operation among of millions, but makes readability worse.


答:
Be strict in what you accept. The be liberal in what you accept, and be strict what you return, is based on a world of independent agents, for instance SMTP servers. If a mail server sends you a faulty email, and you can rescue it, that's better than a cryptic error to the sender of the mail.

However, when you're designing an API to be consumed by other programmers, it's different story. They get immediate feedback when they provide wrong input. The other option of guessing what they mean is very dangerous. If you accept 14-12 as december fourtheenth, and 14-10 as october fourteenth, what will your program do with 10-12? Better to be strict, and error with one of them, that way your program will behave in a predictable manner, which is much more important than being able to accept everything.


答:
Code review can get multiple developers familiar with same code. This is a good thing. What if the original author decides to quit or worse, something bad happens to him. If code reviews are done regularly, others can take over quickly.

Peers maybe able to spot potential bugs or performance issues during code review. This reduces QA and development effort. This can compensate for the additional cost involved in code reviews.

Code reviews promote knowledge sharing. Peers can tell of better ways or alternate ways of doing stuff. I myself have learnt a lot from my peers through code reviews.

Code reviews help reinforce coding guidelines followed by the team. If the team doesn't have one, that needs to be rectified. Code is meant to be written once and read many times. Coding guidelines are a step towards readable code. Code is meant to be readable by peers. What better way than to have code reviews to ensure readability?

Title: Tips on persuading boss that code review is a good thing

Body:
Let's say one works in a hypothetical company that has several developers that rarely worked together on projects and the Boss didn't believe that code reviews are worth the time and cost.

What are various arguments that could be presented in this scenario that will portray the benefit of code review?  Furthermore, what are the potential arguments against code review here and how can these be countered?


问:
How have languages influenced CPU design?
We are often told that the hardware doesn't care what language a program is written in as it only sees the compiled binary code, however this is not the whole truth. For example, consider the humble Z80; its extensions to the 8080 instruction set include instructions like CPIR which is useful for scanning C-style (NULL-terminated) strings, e.g. to perform strlen(). The designers must have identified that running C programs (as opposed to Pascal, where the length of a string is in the header) was something that their design was likely to be used for. Another classic example is the Lisp Machine.

What other examples are there? E.g. instructions, number and type of registers, addressing modes, that make a particular processor favour the conventions of a particular language? I am particularly interested in revisions of the same family.

答:
One example is MIPS, which has both add and addu for trapping and ignoring overflow respectively. (Also sub and subu.) It needed the first type of instruction for languages like Ada (I think--I've never actually used Ada though) which deal with overflows explicitly and the second type for languages like C that ignore overflows.

If I remember correctly, the actual CPU has some additional circuitry in the ALU for keeping track of overflows. If the only language people cared about was C, it wouldn't need this.


答:
The Burroughs 5000 series was designed to efficiently support ALGOL, and Intel's iAPX-432 was designed to efficiently execute Ada.  The Inmos Transputer had it's own language, Occam.  I think the Parallax "Propeller" processor was designed to be programmed using its own variant of BASIC.

It's not a language, but the VAX-11 instruction set has a single instruction to load a process context, which was designed after a request from the VMS design team.  I don't remember the details, but ISTR it took so many instructions to implement that it put a serious upper limit on the number of processes they could schedule.

Title: How have languages influenced CPU design?

Body:
We are often told that the hardware doesn't care what language a program is written in as it only sees the compiled binary code, however this is not the whole truth. For example, consider the humble Z80; its extensions to the 8080 instruction set include instructions like CPIR which is useful for scanning C-style (NULL-terminated) strings, e.g. to perform strlen(). The designers must have identified that running C programs (as opposed to Pascal, where the length of a string is in the header) was something that their design was likely to be used for. Another classic example is the Lisp Machine.

What other examples are there? E.g. instructions, number and type of registers, addressing modes, that make a particular processor favour the conventions of a particular language? I am particularly interested in revisions of the same family.


问:
Emotional attachment to code
As an employee of a company, when you write code do you feel like you have an attachment to it? Do you feel that you have some ownership of the code? Or do you write it completely detached from it without any concern about what happens to it after you've moved onto something else?

EDIT: I'm not talking about writing bad code and then running...

答:
I love the codes I write. I understand them and tailor them so others will too. When people come upto me and say "Dude,we're still using that script you wrote for us. It's so stable and portable", I love that feeling of pride and ownership.

There's no harm in getting attached to your code if you can see where it's going to end up i.e If it's all in-house and you know who or what you're programming for, then I'd actually say it's a good thing to get attached . Coz you'll only love creating more pieces of brilliance,that much more.

On the other hand (fully aware that I might be reiterating what @S.Lott said) if the code Is going to end up as a client's property, then there's no meaning in getting sentimental over it. It's like...taking care of your friend's puppy when he's gone on vacation. :-/

Title: Emotional attachment to code


问:
Eager Loading Constraints
The thing is, eager loading some object with all of it's associations reduces the queries made to the database, but the query time is greatly increased.

The question is: This increased query time in the end pays off the database not being hitted so often?

It seems to me that you are avoiding one problem and falling into another one.

Obs.: Would put eager-loading tag if i had reputation enough. Someone could create it and edit this observation.

答:
The fact that you have to ask this question is, in itself, a big hint that there is no unambiguous answer. If eager loading were always better, framework writers would  have turned it into the unchangeable default; if it were always worse, they wouldn't offer it. Here are some aspects of the situation I can think of that could be relevant:

How deep is your typical object tree? The more objects you reference indirectly from the first one, the greater the speed difference during loading becomes.

How fast is your database connection? The farther away it is from your code, the more noticeable this difference becomes.

Do you have enough RAM to store the typical results of eager loading? Caching things in memory usually leads to an overall speedup, until you overflow one step in your memory hierarchy - then it can become drastically slower. Which one happens depends on your typical workload.

What is your characteristic entity access pattern? If you actually walk the tree of connected objects during normal operation, then eager loading does precisely that, and quicker than the naive database queries would. If accesses are unpredictable and only want to read very specific nodes in your web of objects, it can create large overhead for little use.

As always in such matters, the technique is worthwhile in some situations and over-engineering in others. Only you, with the specialized knowledge of your actual requirements, can tell which it is for you - and as always, usually you can't tell without measuring.

Title: Eager Loading Constraints


答:
When programming in assembly language, writing pseudo-code makes a lot of sense.  The algorithm could be verified before expending the effort to manually translate it to assembly language and then debug the translation.  It still made some sense for first-generation compiled languages like FORTRAN IV, where the only control construct was GOTO, all variables (except formal arguments) were global, and variable names were limited to six characters.

Today we do very little programming in assembly language, and I see little value in writing pseudo-code instead of just writing code.  In a decent language, the actual code will follow the pseudo-code almost word for word, and the pseudo-code is just a waste of time.

However, I don't start coding at the bottom.  I follow TDD and start with a test.  Then I start coding at the top, and gradually work my down to the bottom as needed to get the tests to pass.

The alternative to pseudo-code is not writing 1000 lines of low-level classes.  Instead start at the top, calling the ideal but non-existent API for your domain.  Then build the API.

Title: Software design by pseudocoding?

Body:
Do you know a good way to design (i.e. write down) software with a method based on pseudocode?

I'm new to software design and read some information about UML. My humble class hierarchies are good so far, however, after it gets complex I notice that with "seeing the whole" picture I could have used a different structure for more future extendability. As Python is good to prototyping I'm almost fine with just starting to write, but not quite.

So I tried UML class diagrams, but they don't seem to help me much. The problems I solve there I can trivially do in my head. But I do notice additional design requirements once I start to pseudocode the actual methods.

So if you wanted to design by pseudocode, how would you do it? I believe for me a method which is roughly 1-to-1 with code works best. But most UML software doesn't even show the method's code (as opposed to pictures in e.g. GoF).

Someone claimed UML is for documentation and presentation only and not that great for design? I also get that feeling. I thought pure UML and some simplistic whiteboard sketches were the way to design software until googling I found Envision APDT.

So is agile development something I should look out for or do they randomly call that agile -  I thought agile is about schedule only? Or am I designing incorrectly (with UML) - does anyone design by pseudocode? How can I find a good tool for that?


问:
Can I link to a GPL library from a closed source application?
Okay, before everyone goes shouting about duplicate questions, yes, I've already seen several questions like this here. But none answer the question.

If I link against a GPL-ed library without modifying that library, do I need to release my source code?

According to this question, the answer is yes!

But this answer is not satisfactory to me. The answer basically says that I cannot use GPL code in any way without making my code open source.

But if the previous is true then that would indicate that no person or organization could ever release any proprietary software on Linux ever. Which must be wrong. Simply because in order for any application to do anything useful, open files, write to the console, create TCP connections, the application must be linked to libc which is GPL-ed.

So my question is this: If the GPL states, as all the previous answers on the site say it does, that a program which links to another GPL program must be GPL itself, how is it possible to create/release/sell any proprietary application at all which runs on Linux? Since as I described above that application must be liked to GPL code just to run on Linux.

A more practical example say I link to a shared library which is GPL-ed in a non-GPL application, would that force the non-GPL application to become GPL-ed? More specifically if I use a GPL library without modifying it, and then distribute that library as an .so or .dll, would that require my application be open source?

答:
If you link to a GPL lib then you have created a derived work and your code must be GPL  - this is different to LGPL code which specifically allows dynamic linking of differently licensed code. The system libraries including libc, are all LGPL.

There is also a special exemption for the Linux kernel headers and libgcc (the library implicitly called to by the compiler).


问:
How to implement a software development process in an existing project?
My question involves setting up a Software Development process. If you came in to an existing project that had no formal methodology or process set up, and then were asked to set one up yourself, how would you handle it? I have looked into various methodologies like Agile, or subsets thereof like XP, but these are primarily aimed at how to set up new projects. I am rather unsure how to implement them into an existing project.

Also, many of these are aimed at web or desktop applications. My software project is an embedded system, so while many aspects of them are applicable, it is a bit overwhelming trying to figure out which one to use and how to convert it for use in an embedded system. Unit testing on embedded hardware (especially with a Single Board Computer for which no simulator exists) is incredibly difficult, particularly if the software is very far along, and to add a hardware abstraction layer to aid unit testing would involve tearing up the code dramatically.

What tips would you have for setting up a Software Development Process for an existing project, for a programmer that knows how to program, but is new to software development process management?

答:
First of all do it step by step. It's hard to teach old dog new tricks and if you try to implement all at once - nothing will get implemented.

Here are some questions that may help you to figure out if you are ready for methodology ;)

Code repository (do you use code repository? do you have branching strategy? if I ask you who and when introduced last major bug / feature and why - can you tell me?)

Do you have a road map of the project? Are you able which commits in the repository are directly related with accomplishing the next major goal.

Do you have a bug tracker?

Do you know (have written down) the process of deploying your app? Who decides when you deploy? Who merges the changes to the release branch of code repository? etc..

Do you have code guidelines in place? (variable names, function names, test names etc.)

Maybe this is not directly answering your question but I'm writing from experience. I also once was assigned a task to implement methodology in a company. Unfortunately it's hard to build methodology if code is send between programmers in zip files, stored in a dozen of shared folders without versions and nobody knows where code from few years ago is stored.

If you can answer all of the above questions and still feel good about the state of things the tip for implementing methodology is - choose what makes you feel comfortable.

If you have a strong base (repository, road map, bugtracker, deployment workflow, code guidelines) just test methodologies one by one and see which works best for you and your team.


问:
Cpu-heavy web server
When reading about web servers, frameworks, etc most of the time I notice that the goal is to have a technology that has the next features:

Able to handle as many connections as possible.

Fit an I/O model (connections to DBs and other web services).

Those features fit the actual web model but I am interested in knowing which technologies will fit a heavy-cpu user case.

For example, Node.js is a technology that really shines when you have to write an application that uses a lot of I/O. On the other hand, due to the Node.js nature of being evented, It is not suitable for being use in CPU-heavy user cases.(video encoding, machine learning, graphics)

I also have take a look at Haskell web frameworks like Snap and Warp and at the benchmarks they really are fast.

Are they Haskell web frameworks suitable for CPU-heavy problem? Which other languages/technologies are candidates?

答:
You will need a technology that allows you to add as much cpu as you need.

As you will most likely outgrow a single server, for Java you need an application server which is built to span several servers.  An example is Glassfish 3.1 which can be clustered to do exactly this.

See http://glassfish.java.net/public/clustering31.html for more.

Title: Cpu-heavy web server


问:
best practices for NoSQL database design
I have just started using a NoSQL document based database (MongoDB) and i'm curious about the best practices for designing databases.

I presume the architecture should be different from relational databases? Should I still aim for a normalized database?

For example I have a particular use case;

I have a user with a rental history (array of addresses) should that
  array be an array on the user or as a separate collection with a
  shared key?

答:
Appropriate approach for NoSQL database design is a DDD (Domain Driven Design ).
For some people who used to design RDBMS, NoSql looks like Sql anti-patterns and it make more sense when considered in a scope of a DDD.

Depending on usage of addresses, you may define it as a value object inside your rental history model/entity.

Here you are some references that might clear the thoughts on design with NoSQL:

A Managers Guide to NoSQL

Wakanda: NoSQL for Model-Driven Web applications - NoSQL matters 2012

Addressing the NoSQL Criticism

Our experience with Domain Events