问:
Can concurrent code (threads, distributed computing, etc.) be directly ported to single-threaded/non-networked platforms?
Take an arbitrary "perfect" multi-threaded program, on an arbitrary multi-threaded platform, using an arbitrary programming language.

Assuming that this "perfect" multi-threaded program:

is flawless in terms of race conditions

handles shared memory perfectly

may/may not use a locking mechanism (thread suspension or mutexes fall into this category)

has no unforeseen bugs (100% bug free)

uses no complicated language/system specific constructs that cannot be translated to another system under any circumstance

and assuming that this arbitrary platform

is/isn't POSIX compliant (doesn't matter)

uses a familiar threading model

doesn't turn the locking mechanism into a whirlwind of voodoo spaghetti code (arguably)

and assuming this arbitrary language

doesn't use any domain-specific threading constructs (such as Java's synchronized keyword)

is platform agnostic at the very core (such as C and variants)

can be cross-compiled to many different architectures/platforms (isn't limited to the platform its on)

can the code inherently be implemented in such a way that it runs as expected on a single-threaded platform?

For instance, in lieu of threads the single-threaded platform uses a co-routine-like model to simulate threads. Is there a fundamental design flaw with such concepts that would inhibit the ability to run the program in this thread-absent/thread-emulated environment?

The answer to this broad question is very platform-specific, but as I alluded to earlier I'm interested in whether or not there is an inherent proprietariness with multi-threading that makes them impossible to port to non-threaded environments.

Additionally (and more concretely), are there any specific, mainstream platforms/architectures that wouldn't allow such a scenario to occur?

答:
There are two main types of multitasking:

Cooperative - where code explicitly calls a function to say "do something else now"

Pre-emptive - where the threading system automatically stops one thread to allow another to run

These days, most multitasking code is pre-emptive, although event driven code (e.g. Twisted) is cooperative. I do remember using Visual Basic in the 90s and within long running jobs, having to put in calls to DoEvents. That was cooperative multitasking.

The distinction matters, because if your app is coded for pre-emptive multitasking, you can't switch it to cooperative, unless you make substantial modifications. In that sense, the answer to your question is no - you can't take a pre-emptive threaded program and make it run cooperatively using coroutines.

However, if your operating system provides a fine-grained alarm function, it is usually possible to write your own pre-emptive threading library. Roughly speaking, you have an alarm every 50ms or so, and switch to the next waiting thread. So in this sense, the answer is yes - you start by writing a pre-emptive threading library for the single-threaded platform, then you port your application quite easily.


问:
What argument passing mechanism does python use, and where is this officially documented?
As far as I am aware, python is generally referred to as 'call-by-sharing', but does it implement this with call-by-value (like Java) or call-by-reference? or something else? I would appreciate if this could be answered with official python documentation (in which I can't seem to find the answer) as opposed to anything subjective.</p>

答: The semantics of passing and assigning are exactly the same in Python as in Java. Java is described on StackExchange and elsewhere on the Internet (as well as by you in your question) as pass-by-value ony, and these terms must be used consistently across languages to be meaningful; therefore, Python is pass-by-value only.

ContentLicense: CC BY-SA 3.0


问:
On-the-fly, random partition of a range of numbers [0,N] in groups of max M size
Suppose that you have a range of numbers from 0 to N that you want to randomly separate in groups of max M sequential numbers. This is easily done with a bitmap and a random number generator, but it is not space efficient for very large instances of N.

So, what I want is a generator that, given a number N and M, will start producing non-overlapping groups in a random order and with random size, with less than O(N) space efficiency.

E.g. for N = 7 and M = 3, a valid output is the following:

```<code>4
1, 2
3
5, 6, 7
0
</code>```

Does anyone know an algorithm that can help in producing such an output?

答:
Actually generating random non-overlapping groups in a random order would be a pain in the neck. For example, you'd selected a random "start"; then search existing groups to make sure start is usable and find the "highest possible end" for that start; then select a random "end" that's between "start" and "highest possible end". As long as you're selecting a random "start" you can't avoid some sort of search.

Instead, split it into 2 parts: generate random non-overlapping groups in ascending order; then shuffle them to so they end up in random order.

Generating random non-overlapping groups in ascending order is simple. Each group begins where the previous group ends, and you just need a random length.


问:
Algorithm Analysis: In practice, do coefficients of higher order terms matter?
Consider an^2 + bn + c. I understand that for large n, bn and c become insignificant.

I also understand that for large n, the differences between 2n^2 and n^2 are pretty insignificant compared to the differences between, say n^2 and n*log(n).

However, there is still an order of 2 difference between 2n^2 and n^2. Does this matter in practice? Or do people just think about algorithms without coefficients? Why?

答:
In the end the runtime [seconds] of the implementation of an algorithm is the deciding factor but the coefficients and the big-O notation help you in inventing efficient algorithms.

The big-O notation tells you how the algorithm behaves if the number of inputs/.. n changes dramatically (orders of magnitude). You mostly use it in a relative sense, i.e. increases polynomial, linear, nlog(n), ...

If you compare two algorithms which have similar big-O terms you should include the coefficients. It could be that the worse order algorithm but with a better coefficient is actually faster for your typical data sets and you don't want to miss that.

And finally in practise people often just take some implementations and let them run against each other. Gives you a practical view close to reality (used hardware and typical data sets) but dependent on the implementation, hardware and used data sets.

All together is the best.


问:
Would you use C, today, for a software project?
If yes, where and why would you use it?

If no, please provide an explanation to why C is not acceptable to you.

答:
Yes, in fact I have recently!

I like programming in C. I do most my programming in python, but there are times when I need fast code and I really enjoy the elegance that come from the simplicity of the language.

The project I'm working on now is a database, which, as you can imagine, is performance critical. At the moment I'm using C and some python, but it will eventually be predominantly, if not entirely C.

ContentLicense: CC BY-SA 2.5


问:
Is generating a large random number more unique than generating each digit in that number?
I'm using a PRNG (PHP's default rand() implementation) to generate unique 16 digit numbers. Does it make sense to generate digits one by one, or the number at once?

I'm using PHP.

答:
With a PRNG that has equal probability for "single decimal digits" as well as "16-digit decimal numbers", no, they should be equal.

However, the PRNG is unlikely to have perfect probability for base-10 numbers, so "possibly". It would depend on how much this influences the probabiity for any specific digit.

Bear in mind that a 16-digit number is up to 54 bits, so this may influence your decision as to if you should generate you number in pieces or not.


问:
Tag and/or branch strategies for environments when using git
I've been researching git deployment flows and have seen many post-receive hooks that will check out master.  Few of them however detail how you might set up a beta server that could be running any arbitrary commit ref.

My first thought was that you could set up a branch per environment and then push it.  But I'm wondering if that has any inherent limitations, especially if someone wants to test a beta with "slightly behind" code.

After that, I figured a tag might be nice because then you can tag any reference anywhere in the repository and whatever it's set to is what gets checked out by the beta.
The only drawbacks there would be that I could see the repository getting polluted with deployment information.

So, specific questions are:

Is there a body of information in my repository with better semantics that I can use in lieu of just hard-coding beta/staging/live environment information in tags/branches?

Should I be using branches or tags to do any of this?

Will I need one bare repository per environment so that each one can have a different post-commit hook?

答:
Some facts:

Git is a source control management system, not a deployment tool or configuration management tool

There are many stable deployment tools out there: TAR, RPM, Fabric, etc.

Ditto for configuration management tools: Puppet, Chef

Released history is immutable (the alternative is just crazy)

A product is in beta for several commits

Conclusions:

Branches/tags used for ephemeral configuration either have to be deleted (making history mutable) or use a custom naming scheme (cluttering up the history) to avoid collisions when for example a new revision becomes the active beta

With so much custom semantics you will require a lot of custom code to release this

OwnerDisplayName: anon


问:
Advanced subversion techniques, what am I missing?
I started using SVN about 9 months ago and it's been a game changer to say the least.  Although, I feel I'm still a bit lost.  I feel like there is a lot more I need to take advantage of to really step up my application development.

For example

I would like to be able to quarantine any volatile/major changes into some kind of 'sub-repository' or something.  I'm finding that major changes are impeding minor bug fixes that are quite urgent.  How can I push one simple update without pushing incomplete or broken code?

答:
Have you looked at Subversion Branches at all?

One common technique is to keep your Trunk stable, applying critical fixes as required. You then create a branch for each new significant piece of work. Developers working on that project check out the branch and commit to the branch. It does not affect the Trunk until you decide to merge the branch back to the main trunk as part of your final integration.

Another approach is to have a branch for a particular Release, to avoid any other work accidentally being done on the trunk causing issues. You can bug-fix the 'Release Branch' as required and then fold those fixes back to the trunk when ready.

Your developers can have multiple working copies checked out - the trunk and any branches - or can swap between the trunk and a particular branch with the svn switch command.

I do not recommend having lots of 'sandbox' working copies that you keep separately checkout as (a) this prohibits collaboration with others and (b) it will be too easy to accidentally commit not-working-yet changes to the main trunk.


问:
Using Constructors in Java
I would like to know why do we need to use constructors in examples like this:http://math.hws.edu/eck/cs124/javanotes5/c5/s2.html. I think even if there are no constructors the programs mentioned in the link might run.The code is:

```<code>    public class PairOfDice
    {
    public int die1;   // Number showing on the first die.
    public int die2;   // Number showing on the second die.
    public PairOfDice() {
            // Constructor.  Rolls the dice, so that they initially
            // show some random values.
        roll();  // Call the roll() method to roll the dice.
    }

    public PairOfDice(int val1, int val2) {
            // Constructor.  Creates a pair of dice that
            // are initially showing the values val1 and val2.
        die1 = val1;  // Assign specified values
        die2 = val2;  //            to the instance variables.
    }

    public void roll() {
            // Roll the dice by setting each of the dice to be
            // a random number between 1 and 6.
        die1 = (int)(Math.random()*6) + 1;
        die2 = (int)(Math.random()*6) + 1;
    }

} // end class PairOfDice
</code>```

Is constructors used to improve the readability of the program?Could anyone help me.

答:
The purpose of a constructor is to initialise the class's members to a known good state.  This class has two members - die1 and die2.

The class gas been given two constructors, one of which initialises the members to random numbers, the other initialises them to the values provided.

It's not really about readability.  It's to ensure that every instance of that class is always in a valid state from the moment it's constructed.

Title: Using Constructors in Java


问:
PrePros license MIT but shareware at the same time?
PrePros a compiler for the LESS/CSS languages is licensed under MIT

But from version 5.0 it being presented as 'Shareware' which requires payment and activation, although it does not impose any limits but prompts you to pay and Activate

I really don't understand what the deal is here. Am I required to pay for using it or not?

答:
What happened is that the owners of PrePros changed the license going from version 4 to version 5.

Version 4 of PrePros is available under the MIT license and can be used, changed and redistributed freely.

Version 5 of PrePros does not have an explicit copyright license, so you must assume that you are not allowed to make changes or redistribute it. Given the free download option, it can be assumed that you are allowed to use it for free, but with the restriction of the nagging. To get rid of the nagging (and possibly other features or rights) you need to pay.


问:
Should an object load itself?
although I'm programming in C++ for some time now, I'm always faced with design decisions (probably due to the language's flexibility). One such problem is deciding if a method should be part of the class or not.

As an example, oftentimes, I have a Simulation class similar to the following,

```
<code>
class Simulation{
public:
    Simulation(void);
    bool init(const char* init_file){
        //...
        particles_ = read_particles(init_file);
        //etc
    }
    //or even,
    bool init(int argc, char* argv[]);
    void run(void);
private:
    std::vector particles_;
    //Other private members
};
</code>
```

Here, I'm not sure if this init method, which parses a file and initializes the simulation should really be a class method. A different way to implement similar functionality, would be to have an external function or class which handles the parsing of either the command line arguments or the initialization file, and calls appropriate methods of the Simulation class.

```
<code>
bool init_simulation(Simulation& sim, const char* init_file){
    //...
    Particles particles = read_particles(init_file);
    sim.set_particles(particles);
    //etc
}
</code>
```

On the one hand it's easier to implement the functionality as a class method and it avoids having to introduce new classes/structs, specifically for passing parameters. On the other hand, externally handling the initialization, means that one can more easily extend it, although any changes on the Simulation class will propagate to the function.

What is the preferred design in situations similar to the one described above, and how should I approach similar design decisions?

答:
[Note: This question already has an accepted answer, and this answer only adds more arguments to it - but it is too long for a comment].

One such problem is deciding if a method should be part of the class or not.

I have found a very good guideline offered by A. Stepanov on this question:

He basically says that objects should be constructed from fully constructed data members. If the construction of an object requires extra processing (for example, reading the data from a file), it should be done by an external factory function. This maximizes flexibility and reusability. (Eventually, you could set the factory function as a friend).

An example:

```<code>class Simulation{
public:
    Simulation(std::vector<particle> particles);
        // instance keeps it's own copy,
        // so we might as well construct
        // it in the argument itself and
        // pass it into particles_ using
        // std::move

    void run();
private:
    std::vector<particle> particles_;
};

// factory function only
Simulation load(std::istream& in) // use an istream instance here
                                  // (see below for reasoning)
{
    std::vector<particle> particles;
    particle p;
    while(in >> particle)
        particles.emplace_back(std::move(p));
    return Simulation{ std::move(particles) };
}
</code>```

Test code (working with hardcoded particles):

```<code>std::vector<particle> p = test::get_particles();
Simulation s{ std::move(p) };
</code>```

Test code (loading particles function):

```<code>std::string serialized_particles = "jdfkdfhaljkdfhlakjdfhalsjkfh";
std::istringstream in{ serialized_particles };
auto s = load( in );
</code>```

Production code:

```<code>std::string path_to_file{ "/tmp/aaaaa" };
std::ifstream in{ path_to_file };
auto s = load( in );
</code>```

Outside of this example (and your particular case), the guideline I use to determine if a function should be a member or not, is solved by answering these questions:

does the functionality apply to all instances? (if yes, it should be a member)

does the functionality require an active instance? (if no, it should not be a member)

does the functionality apply to an instance in any state? (if no, function should probably not be a member)

Title: Should an object load itself?

Body:
[Note: This question already has an accepted answer, and this answer only adds more arguments to it - but it is too long for a comment].

One such problem is deciding if a method should be part of the class or not.

I have found a very good guideline offered by A. Stepanov on this question:

He basically says that objects should be constructed from fully constructed data members. If the construction of an object requires extra processing (for example, reading the data from a file), it should be done by an external factory function. This maximizes flexibility and reusability. (Eventually, you could set the factory function as a friend).

An example:

class Simulation{
public:
    Simulation(std::vector<particle> particles);
        // instance keeps it's own copy,
        // so we might as well construct
        // it in the argument itself and
        // pass it into particles_ using
        // std::move

    void run();
private:
    std::vector<particle> particles_;
};

// factory function only
Simulation load(std::istream& in) // use an istream instance here
                                  // (see below for reasoning)
{
    std::vector<particle> particles;
    particle p;
    while(in >> particle)
        particles.emplace_back(std::move(p));
    return Simulation{ std::move(particles) };
}

Test code (working with hardcoded particles):

std::vector<particle> p = test::get_particles();
Simulation s{ std::move(p) };

Test code (loading particles function):

std::string serialized_particles = "jdfkdfhaljkdfhlakjdfhalsjkfh";
std::istringstream in{ serialized_particles };
auto s = load( in );

Production code:

std::string path_to_file{ "/tmp/aaaaa" };
std::ifstream in{ path_to_file };
auto s = load( in );

Outside of this example (and your particular case), the guideline I use to determine if a function should be a member or not, is solved by answering these questions:

does the functionality apply to all instances? (if yes, it should be a member)

does the functionality require an active instance? (if no, it should not be a member)

does the functionality apply to an instance in any state? (if no, function should probably not be a member)


问:
Advantages of unmanaged code
tl;dr: Why would I ever choose to write/compile unmanaged1 code?

Lets assume that I am starting a new project. I have decided to write in a C-like language - probably one of C, C++, C# or Java. C# and Java are managed (well, Java runs in the JVM, but lets assume that it is same thing). Managed GCC plugins exist (although I have not used any, so I do not know if they are any good). Managed code has lots of advantages:

You do not have to worry about explicitly garbage collecting (which is fiddly)

It is much harder to memory leak

It is trivial to implement - just choose the correct language or right compiler flags

e.g. use C#, or use MCP for GCC

Improved interoperability if you are compiling into IL

Type safety, array bound and index checking etc

In my opinion (which could be wrong - and I am trying to ascertain why it is wrong) it is better almost always to used managed code. However unmanaged languages exist and managed languages have unmanaged flags, so there must be some reasons for choosing it over managed code. What are the reasons?

Edit: As Deduplicator points out it is possible to use a GC in non-managed code (either third party or one you create yourself). This leads to another related question: Does everybody compiling native C/C++ code use a GC? If not, what are the advantages for not using a GC?

1. For the purpose of this question I am borrowing John Bode's definition of "Managed" (below) - anything that runs in a virtual machine, not just the Microsoft definition of managed code.  I count Java as a "managed" language in that it runs in a VM.

答:
Legacy - native code long predates managed1 code, and there are still native apps to maintain;

Performance - all things being equal, native code should be faster and have a smaller memory footprint than managed code (things are rarely equal though, and for I/O bound tasks, the difference is negligible); also, non-deterministic garbage collection can play hell with realtime code;

System or hardware-specific hacks - native code may have access to system calls or libraries that the managed code doesn't (such as for parallel processing or vector processing, although I imagine most managed languages should be able to expose an API for such operations);

No VM available - you may be targeting a system for which no VM has been developed, or doesn't have the resources to run managed code (such as a microcontroller or other embedded system); also, your target system may not need the capabilities of a full-up VM (predominately CPU-bound tasks, limited I/O, etc.).

I work exclusively with native code (C++ on Linux).  There's no reason beyond inertia that we couldn't use managed code, but for our purposes it works pretty well.  Given that we run several hundred client instances on a single server, we could use every cycle we can get.

1.  By which I mean anything that runs in a virtual machine, not just the Microsoft definition of managed code.  I count Java as a "managed" language in that it runs in a VM.

Title: Advantages of unmanaged code


问:
How should I break this user story into tasks
I am trying to understand how to create user stories and tasks. I have read articles stating that you should create small user stories and they should be a "vertical slice" of functionality instead of a "horizontal slice".

I have a user story:

As a buyer I want to add items to the shopping cart so that I later can buy the items.

From my understanding tasks should be the things you have to do in order to complete this user story. Am I right if the tasks should also be created as "vertical slices" instead of "horizontal". Instead of creating a task for "create shopping cart model" I would have a task "Update shopping cart service to be able to add products".

But with that task I only have one task, is it to big, should it be broken down in another way? Is it bad that a user story only have one task?

答:
I don't tend to think of tasks as "slices". They are the things you need to do in order to implement a given user story, so are often things like make a schema change, add a new class, add a new method, add a page, style the page etc. You wouldn't typically have one task to implement the whole feature. If you're going to think of them as either vertical or horizontal slices through a user story, they are definitely more horizontal.

Taking a vertical slice of a user story is typically used for splitting one large user story into several smaller ones if your team conclude that it is too big, e.g. if it gets an estimate of an infinite number of story points in planning poker.

If this were the case for your shopping cart example, with a little bit of artistic license, I might break it down into the following different user stories:

As a buyer I want an add to basket button on every product page so that I can click it to add the product to my basket once that functionality is implemented.

As a buyer I want to enter the quantity I want to add to my basket so that I can add more that the default of one.

As a buyer I want a quantity of items to be added to my basket when I click the button so that I can later buy the items.

As a buyer I want a confirmation screen telling me what I've just added to my basket so that I can correct any errors I might have made.

These are vertical slices through all layers of the system, each implementing data storage, business logic, user interface and everything else needed for a working, albeit not feature complete, system.

This is however the exception, only to be used to deal with user stories which are uncomfortably large. Typically a user story will be of a manageable size and can be broken down into tasks to describe the steps you will take to implement it.


答:
Constructors are not used for readability. In fact, I cannot think an example in which a constructor could be user for readability.

The constructor in the example just gives an initial value to class members.

The class has two constructors:

One constructor doesn't receive any parameters. This constructors randomly generates a value for each member by calling the roll() method.

The other constructor allows you to set the initial value of the class members.

You are right when you say the class could work without constructors, making it clear that an empty constructor is implied (inherited from Object), so in reality the class will have at least one an empty constructor.

But... as the following no-constructor alternatives show, one could soon reach to the conclusion that providing constructors makes the class more usable:

Constructor-less example 1.

Here, to ensure members have a valid state(*), they where initialized on declaration with a value of one:

```<code>public class PairOfDice {
       public int die1 = 1;
       public int die2 = 1;
       public void roll() {
          die1 = (int)(Math.random()*6) + 1;
          die2 = (int)(Math.random()*6) + 1;
       }
}
</code>```

Constructor-less example 2.

Here, in addition to what was done above, setters were provided to change the value of members arbitrarilly, but then it would be possible to change the values after roll, which is not desirable.

```<code>public class PairOfDice {
    public int die1=1;
    public int die2=1;
    public void setDieOneValue(int i){die1=i;};
    public void setDieTwoValue(int i){die2=i;};
    public void roll() {
        die1 = (int)(Math.random()*6) + 1;
        die2 = (int)(Math.random()*6) + 1;
    }
}
</code>```

Constructor-less example 3.

Here members values are randomly generated on initialization. Notice repeated code.

```<code>public class PairOfDice {
    public int die1=(int)(Math.random()*6) + 1;
    public int die2=(int)(Math.random()*6) + 1;
    public void roll() {
        die1 = (int)(Math.random()*6) + 1;
        die2 = (int)(Math.random()*6) + 1;
    }
}
</code>```

(*) by valid state I mean that the members have values that enforce the business rules, or runtime errors. For example, die values should be in the range 1..6 so one should garantee that they don't have zero value at initialization.  A business rule is a rule imposed by the "business". The "bunisess" or dice rolling says that die have faces from one to six (I know theere are ther kind of dices but for the sake of simplicity we will leave them out). Having a dice throw a value of 0 would probably make the program fail. That's what is meant by valid state.

Title: Using Constructors in Java

Body:
I would like to know why do we need to use constructors in examples like this:http://math.hws.edu/eck/cs124/javanotes5/c5/s2.html. I think even if there are no constructors the programs mentioned in the link might run.The code is:

```<code>    public class PairOfDice
    {
    public int die1;   // Number showing on the first die.
    public int die2;   // Number showing on the second die.
    public PairOfDice() {
            // Constructor.  Rolls the dice, so that they initially
            // show some random values.
        roll();  // Call the roll() method to roll the dice.
    }

    public PairOfDice(int val1, int val2) {
            // Constructor.  Creates a pair of dice that
            // are initially showing the values val1 and val2.
        die1 = val1;  // Assign specified values
        die2 = val2;  //            to the instance variables.
    }

    public void roll() {
            // Roll the dice by setting each of the dice to be
            // a random number between 1 and 6.
        die1 = (int)(Math.random()*6) + 1;
        die2 = (int)(Math.random()*6) + 1;
    }

} // end class PairOfDice
</code>```

Is constructors used to improve the readability of the program?Could anyone help me.

Body:
Constructors are not used for readability. In fact, I cannot think an example in which a constructor could be user for readability.

The constructor in the example just gives an initial value to class members.

The class has two constructors:

One constructor doesn't receive any parameters. This constructors randomly generates a value for each member by calling the roll() method.

The other constructor allows you to set the initial value of the class members.

You are right when you say the class could work without constructors, making it clear that an empty constructor is implied (inherited from Object), so in reality the class will have at least one an empty constructor.

But... as the following no-constructor alternatives show, one could soon reach to the conclusion that providing constructors makes the class more usable:

Constructor-less example 1.

Here, to ensure members have a valid state(*), they where initialized on declaration with a value of one:

public class PairOfDice {
       public int die1 = 1;
       public int die2 = 1;
       public void roll() {
          die1 = (int)(Math.random()*6) + 1;
          die2 = (int)(Math.random()*6) + 1;
       }
}

Constructor-less example 2.

Here, in addition to what was done above, setters were provided to change the value of members arbitrarilly, but then it would be possible to change the values after roll, which is not desirable.

public class PairOfDice {
    public int die1=1;
    public int die2=1;
    public void setDieOneValue(int i){die1=i;};
    public void setDieTwoValue(int i){die2=i;};
    public void roll() {
        die1 = (int)(Math.random()*6) + 1;
        die2 = (int)(Math.random()*6) + 1;
    }
}

Constructor-less example 3.

Here members values are randomly generated on initialization. Notice repeated code.

public class PairOfDice {
    public int die1=(int)(Math.random()*6) + 1;
    public int die2=(int)(Math.random()*6) + 1;
    public void roll() {
        die1 = (int)(Math.random()*6) + 1;
        die2 = (int)(Math.random()*6) + 1;
    }
}

(*) by valid state I mean that the members have values that enforce the business rules, or runtime errors. For example, die values should be in the range 1..6 so one should garantee that they don't have zero value at initialization.  A business rule is a rule imposed by the "business". The "bunisess" or dice rolling says that die have faces from one to six (I know theere are ther kind of dices but for the sake of simplicity we will leave them out). Having a dice throw a value of 0 would probably make the program fail. That's what is meant by valid state.


答:
A lot of it is inertia. C has become the lingua franca of computers. Practically every computer architecture, no matter how obscure or exotic, has a C compiler. Practically every OS defines its binary interface for system calls and dynamically linked libraries in terms of C. Most higher level languages have a mechanism for calling C code. Therefore, if you want a library to be usable in the widest possible variety of hardware and programming languages, you'd write it in C. If you don't necessarily need it to run on every single computer architecture but still want it to be usable from pretty much every language, you could write it in a higher level language but provide a C interface.

Along that same vein, there's ease of interoperability. One of the reasons to use C++ is that it's almost a strict superset of C, so you don't need to do much of anything to make use of existing C code or wrap your own code in a C interface.

For extremely performance-critical, array-intensive code, it may be necessary to go with unchecked array access, which is something higher level languages generally don't provide (other than through calling C code) since you get undefined behavior if you get it wrong.

Another reason to use a language with manual memory allocation is for writing extremely safety-critical, reliable, real-time software. For example, NASA's Jet Propulsion Labs' coding standards for C forbids recursion and dynamic memory allocation after initialization, so that they can statically guarantee an upper bound on memory usage and allocation/deallocation time. However, there do exist real-time garbage collecting algorithms that guarantee predictable performance, so it's not impossible to write predictable software in higher level languages. Maybe there's just no combination of suitable higher level language implementations and static analysis tools available for the hardware and OS they use.

Title: Advantages of unmanaged code

Body:
tl;dr: Why would I ever choose to write/compile unmanaged1 code?

Lets assume that I am starting a new project. I have decided to write in a C-like language - probably one of C, C++, C# or Java. C# and Java are managed (well, Java runs in the JVM, but lets assume that it is same thing). Managed GCC plugins exist (although I have not used any, so I do not know if they are any good). Managed code has lots of advantages:

You do not have to worry about explicitly garbage collecting (which is fiddly)

It is much harder to memory leak

It is trivial to implement - just choose the correct language or right compiler flags

e.g. use C#, or use MCP for GCC

Improved interoperability if you are compiling into IL

Type safety, array bound and index checking etc

In my opinion (which could be wrong - and I am trying to ascertain why it is wrong) it is better almost always to used managed code. However unmanaged languages exist and managed languages have unmanaged flags, so there must be some reasons for choosing it over managed code. What are the reasons?

Edit: As Deduplicator points out it is possible to use a GC in non-managed code (either third party or one you create yourself). This leads to another related question: Does everybody compiling native C/C++ code use a GC? If not, what are the advantages for not using a GC?

1. For the purpose of this question I am borrowing John Bode's definition of "Managed" (below) - anything that runs in a virtual machine, not just the Microsoft definition of managed code.  I count Java as a "managed" language in that it runs in a VM.


问:
Scrum: Is it ok for the design/UX of user story to occur in the same sprint as implementation
I am currently in a sprint (two weeks) where the designer is tasked with defining the requirements and UX of a particular user story.

In the same sprint, I am to implement this design. During sprint planning, I had to take a wild guess as to how long this undefined user story would take.

Today I finally received the design. Unfortunately, the design is incomplete/vague and is more akin to a client's requirements than a design. However, from this, I can still see that I have not nearly estimated enough.

To make matters worse this is not the first time. In the last sprint, the exact same thing happened. I flagged it in our retrospective and the scrum master did not have an answer of how to solve this, instead of saying "that's just development for you". Ironically he gets annoyed if the burn down is not on target...

Now I am going to have to ask/work with the designer to get his job done. This is going to hold me up as I have completed all my other tasks.

So my question is

 A) <s>how do you handle dependencies in sprint planning?</s> EDIT: Is it ok for the design/UX of user story to occur in the same sprint as implementation

 B) how should I now approach the sprint? Re-estimate the current user story and watch the burndown turn into a burn up and be viewed as incompetent/unproductive? Or add a new task to the current sprint along the lines of "help the designer create a suitable design"

答:
First off, there is a big difference between dependencies between stories/tasks and uncertainty in the scope/effort of a story/task.

Dependencies are handled by giving the dependent task/story a lower priority than the task/story it depends on and possibly an annotation that it can't start before the other task/story is done.

Uncertainty should be addressed in the planning meeting by clarifying the work that needs to be done on the story. If it isn't possible to remove enough of the uncertainty, the story most likely doesn't meet your "Definition of Ready" and shouldn't be accepted into the sprint.

If, for some reason, the story really needs to go into the sprint, your only option left is to add a risk-buffer to the estimation.

For the current sprint, if you can't work on a story, just report that in the next daily meeting and perform whatever work is possible to reach the overall sprint goal of the team. You might also annotate the story as being blocked and by what.

After a sprint has started, it is in principle impossible to add new tasks to the sprint.

Also, if a task turns out to be more work than estimated, then you don't change the estimation, but you do report faithfully what the progress and remaining effort on the task is.

In the end, in Scrum, it is the team that promises to deliver something. If that promise can't be made, then it is a failure of the entire team, never of an individual within the team.

ContentLicense: CC BY-SA 4.0


答:
how do you handle dependencies in sprint planning?

Ideally, non-development dependencies are handled before sprint planning, so that you have a good definition of the backlog item to estimate effort against.

But, if that was "just development for you" last sprint, then that was probably going to be just development for you this sprint, so you should really have increased your estimate there and then on upcoming tasks that are in a similar state. This is not being vindictive, and it would be a mistake to let it come over as such.

What it does is shows the uncertainty of estimation without a relatively solid design to estimate against. Perhaps, this will encourage your managers to make sure that a product backlog item is properly defined; but at worst it will cover your back. No one complains when a job come in under-budget.

However, you didn't do that, and now your question is ...

how should I now approach the sprint?

The whole purpose of Scrum as a project management tool is to identify problems early, which you've done. Flag it up to your management, let them decide what to do with the sprint. If they try to blame you, be humble and ask how they suggest you approach similar situations in future, to avoid the same problem, even if you don't truly believe that it's fair.

At the end of the day, these are project management issues, and if you try to solve them within your own bubble, you're setting yourself up to fail. And, when you do, you'll be angry because it'll fall on you, not on the managers who failed to solve the problem when you flagged it up to them.

Title: Scrum: Is it ok for the design/UX of user story to occur in the same sprint as implementation

Body:
I am currently in a sprint (two weeks) where the designer is tasked with defining the requirements and UX of a particular user story.

In the same sprint, I am to implement this design. During sprint planning, I had to take a wild guess as to how long this undefined user story would take.

Today I finally received the design. Unfortunately, the design is incomplete/vague and is more akin to a client's requirements than a design. However, from this, I can still see that I have not nearly estimated enough.

To make matters worse this is not the first time. In the last sprint, the exact same thing happened. I flagged it in our retrospective and the scrum master did not have an answer of how to solve this, instead of saying "that's just development for you". Ironically he gets annoyed if the burn down is not on target...

Now I am going to have to ask/work with the designer to get his job done. This is going to hold me up as I have completed all my other tasks.

So my question is

 A) <s>how do you handle dependencies in sprint planning?</s> EDIT: Is it ok for the design/UX of user story to occur in the same sprint as implementation

 B) how should I now approach the sprint? Re-estimate the current user story and watch the burndown turn into a burn up and be viewed as incompetent/unproductive? Or add a new task to the current sprint along the lines of "help the designer create a suitable design"


问:
How do you handle versioning in a multi-sided project?
I know it's a broad question so I'll try to be as specific as possible.
This question is more an "organisational" question than a technical one.

We have a multi-sided project with these main components:

A server, hosting the core business logic (data models)

A backoffice for clients which uses the core business logic

An application API (REST) which uses the core business logic too

There are smartphone apps (iOS and android) using the application API

There are another tablet app (android) different from the smartphone one using the same application API.

Soon, I'll be in production with active clients. And as any project, I'll need to maintain all different components over time. That means all of the following can be upgraded:

the code of core business logic in the server (used by the back-office, the API, and as a side effect, by mobile apps)

the API itself (used by both smartphone and tablet apps)

all the mobile apps (via appstore/googleplay)

Of course, server-side parts (core business logic code and API code) can be changed immediately by myself. However, new mobile apps must be downloaded by the clients on the appstore/googleplay, and I can't be sure they're up to date.

Could you provide any guidance, good practices tips, to make theses upgrades smooth and, unrisked for the client?

Which component do I need to "version"? How to ensure everything works even if the client does not upgrade its mobile app? Should I force him to upgrade to make my work easier?

In a word, how should I organize to make my multi-sided-project live over time?

答:
As you can't control when the mobile apps will be updated to a new release, you need to version at least your REST API. If you don't it will be impossible to make backwards-incompatible changes to that interface.

Besides the REST API, it is a good idea to version also the other communication interfaces that go over a network interface. That way, you are also not forced to upgrade all backoffice clients at the same time as the servers and you can implement a gradual migration to a new version with a "beta test" period.

Besides versioning the communication interfaces, you should also try to make the changes backwards compatible as much as possible. Ideally you might roll out a new interface version that still fully supports the old clients so that they don't notice anything has changed.


问:
Why aren't there code overviews for open-source projects?
There are very complex open source projects out there, and to some of them I think I could make some contributions, and I wish I could, but the barrier to entry is too high for a single reason: for changing one line of code at a big project you have to understand all of it.

You don't need to read all the code (even if you read, it won't be sufficient) and understand all every single line does and why, because the code probably is modularized and compartimentized, so there are abstractions in place, but even then you need to get an overview of the project so you can know where are the modules, where does one module interface with other, what exactly each module do and why, and in which directories and files are each of these things happening.

I'm calling this code overview, as the name of a section that open source projects could have in the website or documentation explaining their code to outsiders. I think it would benefit potential contributors, as they would be able to identify places where they could build, the actual primary coders involved, as they would be able to, while writing everything, reorganize their minds, and would help users, as they would be help to understand and better report bugs they experience and maybe even become contributors.

But still I have never seen one of these "code overviews". Why? Are there things like these and I'm missing them? Things that do the same job as I am describing? Or is this a completely useless idea, as everybody, except for me, can understand projects with thousands lines of code easily?

答:
Because there are far more open-source programmers than open-source technical writers.

Documentation takes maintenance and time to keep up to date.  The more bulky the documentation, the more it takes.  And documentation that isn't in sync with the code is worse than useless: it misleads and conceals instead of revealing.

A well documented code base is better than one less documented, but documentation can easily take as long as writing the code in the first place.  So your question is, is it better to have a well documented code base, or a code base that is twice as large?  Is the cost to keep the documentation up to date whenever code changes worth the contributions of extra developers it may or may not bring?

Shipping code wins.  Reducing the amount of effort put into things other than shipping code can make code ship more often, and be more likely to ship before it runs out of resources.

This doesn't mean that things beside shipping matter.  Documentation adds value to the project, and with a large enough project the interconnect cost of adding another developer might be far higher than adding a documentor.  And, as noted, documentation can increase investment in the project (by making it easier for new programmers to join).

However, nothing sells like success: a project that isn't working or doing anything interesting rarely attracts developers either.

Documentation of a code base is a form of meta-work.  You can spend a lot of time writing up fancy documents describing a code base that doesn't do much of value, or you can spend time making stuff that consumers of your code base want and make your code base have value.

Sometimes making things harder makes those who do the task better.  Either due to a higher degree of commitment to the project (spending hours upon hours learning the architecture), or because of skill bias (if you are already an expert in related tech, getting up to speed will be faster, so the barrier of lack of such documentation is less important: thus more experts join the team, and fewer beginners).

Finally, for reasons noted above the current developers are likely to be experts on the code base.  Writing such documentation doesn't help them understand the code base much, as they already have the knowledge, it only helps other developers.  Much of open source development is based off of "scratching an itch" that the developer has with the code: lack of documentation that already says what the developer knows rarely itches.


答:
In terms of official documentation, per the Programming FAQ:

Remember that arguments are passed by assignment in Python.

Elsewhere in the docs:

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object).

where the footnote adds:

Actually, call by object reference would be a better description, since if a mutable object is passed, the caller will see any changes the callee makes to it (items inserted into a list).

This is consistent with the rest of Python's assignment model, for example:

```<code>def somefunc(y):
    y.append(1)

x = [0]
somefunc(x)
print x
</code>```

is similar to:

```<code>x = [0]
y = x
y.append(1)
print x
</code>```

in that the object assigned to the name x is also assigned to the name y (albeit only within somefunc in the former).

Title: What argument passing mechanism does python use, and where is this officially documented?

Body: As far as I am aware, python is generally referred to as 'call-by-sharing', but does it implement this with call-by-value (like Java) or call-by-reference? or something else? I would appreciate if this could be answered with official python documentation (in which I can't seem to find the answer) as opposed to anything subjective.</p>

Body:
In terms of official documentation, per the Programming FAQ:

Remember that arguments are passed by assignment in Python.

Elsewhere in the docs:

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object).

where the footnote adds:

Actually, call by object reference would be a better description, since if a mutable object is passed, the caller will see any changes the callee makes to it (items inserted into a list).

This is consistent with the rest of Python's assignment model, for example:

def somefunc(y):
    y.append(1)

x = [0]
somefunc(x)
print x

is similar to:

x = [0]
y = x
y.append(1)
print x

in that the object assigned to the name x is also assigned to the name y (albeit only within somefunc in the former).


答:
First, I'm lets start off by framing the problem a little differently. You've asked which pieces of software you need to "version". Version is an overloaded term in CS, and could mean about 100 different things. The primary things I would look at is:

Version Control - Version control is a configuration management tool that helps you keep track of snapshots and history of your development.  ALL CODE SHOULD BE UNDER VERSION CONTROL. I don't care if it just the convenience scripts you add to your bin folder, anything that was worth spending time writing is worth the two seconds to add to a revision control software.

Configuration Management - How do I control what is in the build. All software should have some degree of configuration management. I like to describe to managers the difference between version control and configuration management as version control is just a tool for tracking the history of development, while configuration management is the guidelines for how we create the history, and how we do things like decide the code is good.

Software versioning - assigning names to releases of code. This is the thing that many people latch onto when they first see the problem because they are use to seeing "MineSweeper 7.1.29290149210" or whatever on the stuff they buy, but honestly I find this the most minor part of a much bigger problem. To be honest, just useing the hash generated by 1 and not care all that much that its not human readable is perfectly fine to do.

So since it is the most nebulous and most interesting to me, I'm just going to focus on #2. There is no one-size-fits-all, cookie-cutter solution to configuration management. Rules that work well for a team of 2 or 3 can be too loose to keep sanity in a project that takes hundreds of workers. Rules that work the big team may require way too much overhead for the small team. You'll most likely have to cobble something of your own to get something together, but I'd use the following list as a way to develop the specs for your configuration management system:

How can I keep track of the versions (and associated problems with them) that I am supporting in the market place?

How will I decide which development paths are ready for release to production systems? (It could also be ready for any other step in a process)

Who should have control/manage the configuration of the system? What is the workflow for adding code to be distributed to other developers?

How am I going to control the interaction between interacting parts? How will I know if changing a part will break the rest of the system?

How will we improve our configuration management system over time.

Need help answering the questions above? You should probably hire a consultant or software engineering manager...answering that can fill textbooks and is way out of scope for this type of forum.

Title: How do you handle versioning in a multi-sided project?

Body:
I know it's a broad question so I'll try to be as specific as possible.
This question is more an "organisational" question than a technical one.

We have a multi-sided project with these main components:

A server, hosting the core business logic (data models)

A backoffice for clients which uses the core business logic

An application API (REST) which uses the core business logic too

There are smartphone apps (iOS and android) using the application API

There are another tablet app (android) different from the smartphone one using the same application API.

Soon, I'll be in production with active clients. And as any project, I'll need to maintain all different components over time. That means all of the following can be upgraded:

the code of core business logic in the server (used by the back-office, the API, and as a side effect, by mobile apps)

the API itself (used by both smartphone and tablet apps)

all the mobile apps (via appstore/googleplay)

Of course, server-side parts (core business logic code and API code) can be changed immediately by myself. However, new mobile apps must be downloaded by the clients on the appstore/googleplay, and I can't be sure they're up to date.

Could you provide any guidance, good practices tips, to make theses upgrades smooth and, unrisked for the client?

Which component do I need to "version"? How to ensure everything works even if the client does not upgrade its mobile app? Should I force him to upgrade to make my work easier?

In a word, how should I organize to make my multi-sided-project live over time?


问:
What preconditions should be checked while adding/removing a listener?
Imagine the following interface:

```<code> interface Service {
   addListener(Listener l)
   removeListener(Listener l)
 }
</code>```

Should I check for null values while add/remove? Is it a good idea on remove to check if the listener was registered before (e.g. listener B was never registered and should be removed)?

What behaviour helps developers here to identify problems without creating new ones like IllegalArgumentExceptions?

答:
Good question.  I believe that such methods don't require its own check simply because:

NullPointerException is thrown should the event occur, so assuming you tested that case at least once, you would know if null were passed.

If you begin adding checks for addListener or removeListener, then you really would have to perform basic checks on every method in order to stay consistent throughout your code, which will have a negative impact on performance and readability.

I think the critical point behind checks like these is to ensure that parameters are what they should be within reasonable margins.  If you are the only one calling said method and in only a couple places, adding these checks is superfluous.  If anything, use junit to test specific methods utilizing these events to ensure that everything goes as expected.

When do you really need to perform these checks?

There is a serious possibility that the parameter getting passed may be null, and for one reason or another, you cannot check prior to passing it onto Service.addListener.  One possibility might be a library using reflection like Spring.

*Your* program is not calling these methods.  If you're writing a library to be used by others, it is a good practice to check all public methods that you intend to be called by the program using your library.

You're entering a rather sensitive part of your program where a lot could go wrong.  You need to be able to make certain assumptions about your input and you need for them to not be proven wrong, preferably not on a production computer during your lunch hour break.  (I call these sanity checks)

I'm mainly referring to addListener, though to answer your other question about removeListener, I usually don't find it necessary to know whether or not a listener was removed.  If that information is important, you could optionally return the listener that was removed or null otherwise, though I would only do so if that information were needed (and it usually isn't in my experience).

I hope that helps!


答:
First and foremost, you should be consistent with the framework convention. Java is a big world to be sure. I use Java for Android, and here the convention is rather permissive.

For example, setOnClickListener allows you to pass in null - this is a crude but nonambiguous way of removing the listener.

From Android source code:

```<code>public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
// [snip]

/**
 * Register a callback to be invoked when this view is clicked. If this view is not
 * clickable, it becomes clickable.
 *
 * @param l The callback that will run
 */
  public void setOnClickListener(OnClickListener l) {
      if (!isClickable()) {
          setClickable(true);
      }
      getListenerInfo().mOnClickListener = l;
  }
</code>```

Null is fine:

```<code>  /**
   * Return whether this view has an attached OnClickListener.  Returns
   * true if there is a listener, false if there is none.
   */
  public boolean hasOnClickListeners() {
      ListenerInfo li = mListenerInfo;
      return (li != null && li.mOnClickListener != null);
  }
</code>```

Where multiple listeners are allowed, removing a listener is a tolerant operation, too:

```<code>/**
 * Remove a listener for layout changes.
 *
 * @param listener The listener for layout bounds change.
 */
public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
    ListenerInfo li = mListenerInfo;
    if (li == null || li.mOnLayoutChangeListeners == null) {
        return;
    }
    li.mOnLayoutChangeListeners.remove(listener);
}
</code>```

mOnLayoutChangeListeners is an ArrayList, and ArrayList.remove(Object object)  doesn't crash on an inexistent item - it merely returns false.

The bottom line is the robustness principle - be conservative in what you do, be liberal in what you accept from others.

When in doubt, I'd go with liberal, unless you have a solid reason not to. It's simplier and less surprising. Consistency is the king, and the principle of astonishment is based on consistency.

Any preconditions should be clearly documented. Your definition of interface Service doesn't by itself promise to throw exceptions when null is passed in.

@NonNull and @Nullable annotations may help to remove ambiguity, and they are supported by good IDEs such as IntelliJ Idea or Android Studio.

Title: What preconditions should be checked while adding/removing a listener?

Body:
Imagine the following interface:

```<code> interface Service {
   addListener(Listener l)
   removeListener(Listener l)
 }
</code>```

Should I check for null values while add/remove? Is it a good idea on remove to check if the listener was registered before (e.g. listener B was never registered and should be removed)?

What behaviour helps developers here to identify problems without creating new ones like IllegalArgumentExceptions?

Body:
First and foremost, you should be consistent with the framework convention. Java is a big world to be sure. I use Java for Android, and here the convention is rather permissive.

For example, setOnClickListener allows you to pass in null - this is a crude but nonambiguous way of removing the listener.

From Android source code:

public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
// [snip]

/**
 * Register a callback to be invoked when this view is clicked. If this view is not
 * clickable, it becomes clickable.
 *
 * @param l The callback that will run
 */
  public void setOnClickListener(OnClickListener l) {
      if (!isClickable()) {
          setClickable(true);
      }
      getListenerInfo().mOnClickListener = l;
  }

Null is fine:

  /**
   * Return whether this view has an attached OnClickListener.  Returns
   * true if there is a listener, false if there is none.
   */
  public boolean hasOnClickListeners() {
      ListenerInfo li = mListenerInfo;
      return (li != null && li.mOnClickListener != null);
  }

Where multiple listeners are allowed, removing a listener is a tolerant operation, too:

/**
 * Remove a listener for layout changes.
 *
 * @param listener The listener for layout bounds change.
 */
public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
    ListenerInfo li = mListenerInfo;
    if (li == null || li.mOnLayoutChangeListeners == null) {
        return;
    }
    li.mOnLayoutChangeListeners.remove(listener);
}

mOnLayoutChangeListeners is an ArrayList, and ArrayList.remove(Object object)  doesn't crash on an inexistent item - it merely returns false.

The bottom line is the robustness principle - be conservative in what you do, be liberal in what you accept from others.

When in doubt, I'd go with liberal, unless you have a solid reason not to. It's simplier and less surprising. Consistency is the king, and the principle of astonishment is based on consistency.

Any preconditions should be clearly documented. Your definition of interface Service doesn't by itself promise to throw exceptions when null is passed in.

@NonNull and @Nullable annotations may help to remove ambiguity, and they are supported by good IDEs such as IntelliJ Idea or Android Studio.


答:
Are there things like these and I'm missing them? Things that do the same job as I am describing?

There is an excellent book called The Architecture of Open Source Applications that provides detailed descriptions of a variety of high-profile open source software projects. However, I'm not sure if it exactly fills the role you're imagining, because I believe its primary audience is intended to be developers looking for patterns to follow when creating their own applications, not new contributors to the projects featured in the book (though I'm sure it could be helpful there).

Title: Why aren't there code overviews for open-source projects?

Body:
There are very complex open source projects out there, and to some of them I think I could make some contributions, and I wish I could, but the barrier to entry is too high for a single reason: for changing one line of code at a big project you have to understand all of it.

You don't need to read all the code (even if you read, it won't be sufficient) and understand all every single line does and why, because the code probably is modularized and compartimentized, so there are abstractions in place, but even then you need to get an overview of the project so you can know where are the modules, where does one module interface with other, what exactly each module do and why, and in which directories and files are each of these things happening.

I'm calling this code overview, as the name of a section that open source projects could have in the website or documentation explaining their code to outsiders. I think it would benefit potential contributors, as they would be able to identify places where they could build, the actual primary coders involved, as they would be able to, while writing everything, reorganize their minds, and would help users, as they would be help to understand and better report bugs they experience and maybe even become contributors.

But still I have never seen one of these "code overviews". Why? Are there things like these and I'm missing them? Things that do the same job as I am describing? Or is this a completely useless idea, as everybody, except for me, can understand projects with thousands lines of code easily?


问:
Why is it you never get as much done as you'd planned?
I always start the day thinking "I'll easily get this done by the end of the day" and set what looks like a realistic target.

So why do I never hit it? The task always ends up taking 3x longer due to unforeseen bugs, last minute changes etc.

Is it just me?  I don't seem to be getting any better predicting what can be done in a day.

答:
Urgent/Important Matrix may be worth considering to see where does your day go.  Is it on urgent but not important stuff like unprepared meetings and interruptions?  Is it on urgent and important stuff you didn't know at the start of the day?  Just an exercise to consider where does your time go.

I'd tend to think most interesting things are important or else why are they interesting?  Just a thought.


答:
This post makes an interesting point about your question.

In a more practical way, if you have 3 components:

2 Consumers: a Front-End and a Mobile App

1 API provider: a Back-End

You could use the typical M.m.p (Major.minor.patch) versioning scheme for each but, on your Back-End url you could put something as http://youhost/M.m/resourceURI.

As you evolve and the changes in the API do not affect your contract with the consumers you keep the M.m as is in the URL. From the moment you make a change in the BackEnd that affects your consumers (be it change in behavior or an object that is different) you use a M.m+1, M+1.m+1 or M+1.m.

The way to keep things running is to deploy the new Back-End concurrently with the old, while your users install the new consumers, and slowly discontinue the older API.

You can see a way better answer than mine, here:
Versioning REST API on Stackoverflow


问:
Twitter in app browser + user agent string
Recently (I believe some weeks ago) with the latest update of the Twitter app for iOS, all links found inside tweets are opened in Twitter's build-in browser. My question is how to find Twitter's browser agent so I can display custom messages.

For example:
If browser is Twitter's in-app browser then display a custom message via HTML+PHP. It seems that there is no known agent available.
Any help would be appreciate.

答:
I tweeted to http://whatsmybrowser.org and then opened it up using the latest Twitter app on iOS as of 12/1/14.  Here is my user agent:

http://www.whatsmybrowser.org/b/IQBX258

Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B435


问:
Should I use automatic properties?
I'm new to C# coming from a Java background. I'm working on a take home assignment for a coding interview. I normally write my code as following(Java):

```<code>public class Test {

   //fields

   private string fieldA;
   private int fieldB;

   public Test () {
      //.....
   }

   public String getFieldA() {
      return fieldA;
   }

   //ETC.
}
</code>```

The point is that I use getters/setters like above. Now, I have a coding assignment to do for a job interview, and using C# I have stumbled across automatic properties. I was initially slightly confused about it but understand what it does now and have used it.

So for fields I would write

```<code>public string fieldA {get; set;}
</code>```

It feels weird declaring fields public like that and doesn't it violate some OOP encapsulation principles ?

My question is, should I just go ahead and use automatic properties to show interviewers that I know what it is? In case I want to prevent setting a field I could just use:

```<code>public string fieldA {get; private set;}
</code>```

But would it appear like I don't follow encapsulation "rules", I obviously wouldn't want to risk that. I could write it out as I do in Java.

In general what is your view on using automatic properties ?

答:
I would use AutoProperties only for DTO where you just create object to transfer between boundaries and without any behaviour.

My experience with auto properties are:

No way to create readonly fields! -> Solved in C# vNext

Developers do not think about encapsulation.

They tend to make to much public

Properties force you to create to much mutable state

With IList/ICollection you have problems

No way to expose IReadOnlyList / IReadOnlyCollection

So may advice is:

c'tor should express your dependencies and readonly data.

never expose List / Collection, expose Readonly Collections

change data through methods

value objects should be changed in atomar manner

Title: Should I use automatic properties?


问:
What are my rights if software didn't come with a license?
I have downloaded some software which I'm using. I'd like to include it in my project but I don't know if I'm allowed to do so due to the software not having a license.

What are my rights? If the software doesn't have a license, does that mean that I am allowed to do whatever I want with the software?

答: In the vast majority of countries, you have absolutely no rights. Copyright automatically belongs to the author by default so until they explicitly grant you rights, you don't have any.</p>


问:
On-the-fly, random partition of a range of numbers [0,N] in groups of max M size
Suppose that you have a range of numbers from 0 to N that you want to randomly separate in groups of max M sequential numbers. This is easily done with a bitmap and a random number generator, but it is not space efficient for very large instances of N.

So, what I want is a generator that, given a number N and M, will start producing non-overlapping groups in a random order and with random size, with less than O(N) space efficiency.

E.g. for N = 7 and M = 3, a valid output is the following:

```<code>4
1, 2
3
5, 6, 7
0
</code>```

Does anyone know an algorithm that can help in producing such an output?

答:
I created a partitioning program with space usage O(1) but running time O(N^2).  You can find the source code here.  In the comments there is a good explanation of the shuffling algorithm used.

The key part of this program is the shuffling step, which is the step that takes O(N^2) time.  Doc Brown asked "how can you shuffle N elements in less than O(N) space"?  I extracted the shuffling logic and created a separate program which is listed below.

To get the full explanation, please refer to the source code linked above.  The following is a brief explanation:

The shuffling function simulates a Fisher-Yates shuffle, where you swap the array[0] with array[r], where r is a random number in the range [0..N-1].  Then you swap array[1] with array[r], where r is a new random number in the range [1..N-1].  You keep moving down the array, swapping random elements, until you reach the end of the array.

To use O(1) space, there is no array.  Instead, for each new random element that we select, we need to replay the previous swaps in backwards order in order to figure out where the array element really came from.  In essence, we pick a random element, and then we undo the swaps that came before it to determine where the original position of the element was.  We can replay the previous swaps by simply reseeding the random number generator back to a previously saved seed.

Edit: After posting this solution, I found this stackoverflow question which lists some better ways to create a permutation of N numbers in constant space.  So if you substitute one of those solutions in for my shuffling function, you can do better than O(N^2) time and still use O(1) space.

/* Given a number N, shuffle the elements from 0..N-1 and print them. */
/* This algorithm uses O(1) space but uses O(N^2) time.               */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>

static void shuffle(int n);

int main(int argc, char *argv[])
{
    if (argc < 2) {
        printf("Usage: shuffle N\n");
        exit(0);
    }

    shuffle(atoi(argv[1]));
    return 0;
}

static void shuffle(int n)
{
    uint32_t seedOriginal = time(NULL);
    uint32_t seed         = 0;
    int      i            = 0;
    int      j            = 0;
    int      slot         = 0;

    for (i=0;i<n;i++) {
        seed = seedOriginal;
        srand(seed);

        // Skip n-i-1 random numbers.
        for (j=n-i-1;j>0;j--)
            rand();

        // Select an array slot from [i..n-1].
        slot = i + (rand() % (n - i));

        // Find out what that slot corresponds to in the original order.
        // We do this by backtracking through all the previous steps.
        for (j=i-1;j>=0;j--) {
            int r = j + (rand() % (n - j));

            // Every time we see the slot we are looking for, we switch
            // to looking for slot j instead, because at this previous step
            // we swapped array[j] with array[slot].
            if (r == slot)
                slot = j;
        }

        // Slot is now the correct element we are looking for.
        printf("%d\n", slot);
    }
}
```


问:
Lucene full text search of 6 million records
I want to implement Lucene for full text search. I have a table with 6 million records in an sql database. Each minute around thousand new rows will be added from the application.

Index creation in Lucene takes a lot of time. Each time I delete or create a new index from the database because the user needs to see the updated records on search.

How can I have fast enough search capability?

1) I need updated and history values on search
2) The maximum delay should be 2 seconds

答:
Lucene indexes don't have to be recreated from scratch each time they're changed.  Much like your database tables, you can insert new records, delete old ones and affect an update using a delete/add pair.

Most databases have a mechanism which will allow calling external code, and you can leverage this in triggers that run on INSERT, UPDATE and DELETE to maintain your index.  Alternately, you can do the updates outside the database as your batches of data arrive, but you risk having (bigger) synchronization problems if something fails mid-stream.

Also, consider whether or not using Lucene is even necessary.  Oracle, PostgreSQL and MySQL (and probably others) all have pre-integrated full-text search that may be good enough for your application and won't need much additional work on your part.


问:
Lock data in DB while external API call is pending?
I have an interesting situation, and I am looking for the best way to solve it. My app runs like this:

1) The user gets a Promotion Pin from Some Company, and I have a db table with these pins also. The user submits my form to recieve a reward.

2) I first check if the pin is valid/non-expired using a basic stored procedure.

3) I contact a third party API to send them the reward.

4) I retire the pin using a basic stored procedure.

My issue is, how do I guarantee that the pin is not reused again while the API call is pending. I know this is a split second operation, but I would rather remove this possibility.

答: If your PIN is valid only once, then why don't you write the stored procedure using DELETE INTO so that, given the proper isolation level, you know the PIN can be used exactly once. Then you query the temp table you inserted into to see if it has any values--if it does, the PIN is valid. That way you can eliminate step 4 entirely.


问:
How can a company sell licenses for GPLed software without violating rights of others
There are tons of questions like "Can I use GPLed code X in my commercial project?" but I found nothing which answers my question.

I take ExtJS as an example, but actually you can any commercial / community edition dual licensed software.

If I contribute to the community edition, isn't my contribution GPLed?

Even if my contribution was small (like a bug fix) how come they're allowed to sell it?

Disclaimer: I know, we're not lawyers. Just wondering.

答:
Software can be dual licensed if all the copyright holders agree. Most companies that have a dual licensed product and accept contributions have some form of contributor license agreement that must be accepted before you can contribute code. In the case of ExtJS, it says:

You hereby grant to Sencha and to recipients of software distributed
  by or on behalf of Sencha a perpetual, worldwide, non- exclusive,
  no-charge, royalty-free, irrevocable copyright license to reproduce,
  prepare derivative works of, publicly display, publicly perform,
  sublicense, and distribute Your Contributions and such derivative
  works.

You are giving them your code and the right to do with it whatever they want, including GPL license it, commercially license it, etc.


问:
Is doing Parent.call from the child object a right way to implement Inheritance in JavaScript?
I came across this piece of code. It didn't look that right to me. Is this the right way to implement super in JavaScript? If not, what is the right way?

```<code>function Person(name){
  this.name = name;
}

function Student(name){
  Person.call(this, name);
}

Student.prototype = new Person();
var a = new Student('test');
var b = new Student('test2');
</code>```

答:
The first part is pretty common, it's just a way to get the constructor of the subtype to share the functionality of the supertype's constructor. Notice that Person.call doesn't invoke Person as a constructor here, it invokes it as a regular function using the this binding from the Student being constructed.

It's probably a bit more common to see it written like this:

```<code>Person.apply(this, arguments);
</code>```

If you don't like the idea of writing the name of the parent constructor explicitly and are looking for something generic like "super" you could do this instead:

```<code>this.constructor.prototype.constructor.apply(this, arguments);
</code>```

You don't usually see this, though, because it's pretty unwieldy and you probably already have a reference to the parent constructor at the point where you're doing this anyway.

The second part is widely regarded as being incorrect. Don't do this:

```<code>Student.prototype = new Person();
</code>```

Do this instead.

```<code>Student.prototype = Object.create(Person.prototype);
</code>```

Object.create(Person.prototype) gives you an object with Person.prototype in its prototype chain without executing the Person constructor (which could have side effects and is unnecessary).

Body:
The first part is pretty common, it's just a way to get the constructor of the subtype to share the functionality of the supertype's constructor. Notice that Person.call doesn't invoke Person as a constructor here, it invokes it as a regular function using the this binding from the Student being constructed.

It's probably a bit more common to see it written like this:

Person.apply(this, arguments);

If you don't like the idea of writing the name of the parent constructor explicitly and are looking for something generic like "super" you could do this instead:

this.constructor.prototype.constructor.apply(this, arguments);

You don't usually see this, though, because it's pretty unwieldy and you probably already have a reference to the parent constructor at the point where you're doing this anyway.

The second part is widely regarded as being incorrect. Don't do this:

Student.prototype = new Person();

Do this instead.

Student.prototype = Object.create(Person.prototype);

Object.create(Person.prototype) gives you an object with Person.prototype in its prototype chain without executing the Person constructor (which could have side effects and is unnecessary).


答:
You can introduce an expiry column for your pins. Once you query the pin table to see if your pin is valid (and not expired), you update that expiry date to current time.

If your API call succeeds, No further action is required and you have a record of what has happened (you have only done one db write). If the API call fails, you need to go set the expiry date to Null so that records becomes available again.

Title: Lock data in DB while external API call is pending?

Body:
I have an interesting situation, and I am looking for the best way to solve it. My app runs like this:

1) The user gets a Promotion Pin from Some Company, and I have a db table with these pins also. The user submits my form to recieve a reward.

2) I first check if the pin is valid/non-expired using a basic stored procedure.

3) I contact a third party API to send them the reward.

4) I retire the pin using a basic stored procedure.

My issue is, how do I guarantee that the pin is not reused again while the API call is pending. I know this is a split second operation, but I would rather remove this possibility.


问:
Reuse a small method from Apache Ant: How to do that correctly
I adapted some code from the Apache Ant project in my work. The part I used is really small: ~70 lines, ~2000 characters. Adding dependency to ant to use that a single method seemed like an overkill.

The project I work on is internal to the company, so I initially included a javadoc like

```<code>    @see original source
</code>```

for my colleagues to know the code wasn't mine.

Then I encountered this summary at tldrlegal which states that this is not enough, and to do this properly I have to do much more:

Include Copyright

Include License: Including the full text of license in modified software.

State Changes: Stating significant changes made to software.

Include Notice: If the library has a "NOTICE" file with attribution notes, you must include that NOTICE when you distribute. You may append to this NOTICE file.

From this I deduce that I actually have to include NOTICE file from ant (it's like 10 lines), somehow redistribute Apache 2 license text with the project, and include a monster comment like this before the function body or before the beginning of my class:

```<code>   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
</code>```

Is there a more compact but still correct way to do it, or is there no other way? Introducing lots of changes because I only use a minuscule part of the project (namely, a single ~70-line method) will negatively impact code-review quality and maintainability of the final code.

P.S. I don't seek professional law advice, just some common-sense-based guidelines for this situation, preferrably with examples from other open-source projects.

答: The easiest way to get around it is to document what you need the function to do, and then give that specification to your coworker and ask them to re-write it. Seventy lines isn't a ton to rewrite, but if you were to rewrite it right now you'd know how Apache did it and possibly (unintentionally) copy their code or way of doing it. If you think the Apache code is so great that you would rather have their code, you have to play by the full set of rules you already outlined - there's not really a way around it.

Body:
I adapted some code from the Apache Ant project in my work. The part I used is really small: ~70 lines, ~2000 characters. Adding dependency to ant to use that a single method seemed like an overkill.

The project I work on is internal to the company, so I initially included a javadoc like

```<code>    @see <a href="...">original source</a>
</code>```

for my colleagues to know the code wasn't mine.

Then I encountered this summary at tldrlegal which states that this is not enough, and to do this properly I have to do much more:

Include Copyright

Include License: Including the full text of license in modified software.

State Changes: Stating significant changes made to software.

Include Notice: If the library has a "NOTICE" file with attribution notes, you must include that NOTICE when you distribute. You may append to this NOTICE file.

From this I deduce that I actually have to include NOTICE file from ant (it's like 10 lines), somehow redistribute Apache 2 license text with the project, and include a monster comment like this before the function body or before the beginning of my class:

```<code>   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
</code>```

Is there a more compact but still correct way to do it, or is there no other way? Introducing lots of changes because I only use a minuscule part of the project (namely, a single ~70-line method) will negatively impact code-review quality and maintainability of the final code.

P.S. I don't seek professional law advice, just some common-sense-based guidelines for this situation, preferrably with examples from other open-source projects.


问:
Confusion about inheritance
I know I might get downvoted for this, but I'm really curious.

I was taught that inheritance is a very powerful polymorphism tool, but I can't seem to use it well in real cases.

So far, I can only use inheritance when the base class is an abstract class.

Examples :

If we're talking about Product and Inventory, I quickly assumed that a Product is an Inventory because a Product must be inventorized as well. But a problem occured when user wanted to sell their Inventory item. It just doesn't seem to be right to change an Inventory object to it's subtype (Product), it's almost like trying to convert a parent to it's child.

Another case is Customer and Member. It is logical (at least for me) to think that a Member is a Customer with some more privileges. Same problem occurred when user wanted to upgrade an existing Customer to become a Member.

A very trivial case is the Employee case. Where Manager, Clerk, etc can be derived from Employee. Still, the same upgrading issue.

I tried to use composition instead for some cases, but I really wanted to know if I'm missing something for inheritance solution here.

My composition solution for those cases :

Create a reference of Inventory inside a Product. Here I'm making an assumption about that Product and Inventory is talking in a different context. While Product is in the context of sales (price, volume, discount, etc), Inventory is in the context of physical management (stock, movement, etc).

Make a reference of Membership instead inside Customer class instead of previous inheritance solution. Therefor upgrading a Customer is only about instantiating the Customer's Membership property.

This example is keep being taught in basic programming classes, but I think it's more proper to have those Manager, Clerk, etc derived from an abstract Role class and make it a property in Employee.

I found it difficult to find an example of a concrete class deriving from another concrete class.

Is there any inheritance solution in which I can solve those cases?

Being new in this OOP thing, I really really need a guidance.

Thanks!

答:
One of the best examples I've read described things this way (paraphrased) using a zoo:

The base class was Animal.
It has (properties) of size and color.
It could (methods) eat, sleep, and reproduce.

Now, we have different animals in the zoo.

Monkeys, Tigers, Dolphins.

As classes, they inherited from Animal, so they all had size and color and they could all eat, sleep, and reproduce.

For fields, we consider these:
Dolphins have fins and blowholes
Monkeys and Tigers have tails
Tigers have Claws.

For methods in the class we could consider these things:
Monkeys could also (method) climb.
Tigers could also climb and they also hunt.
Dolphins could swim.
So can tigers.

Now, Dolphins can't climb, so climbing would not be something you could move to the parent (Animal) class, but you could put them in the Monkey and Tiger class.

They are ALL Animals, so they all share SOME properties, but they each have some different properties NOT shared by all animals.

Likewise, they can all do some of the same things - like eating and reproducing, but some things only certain animals can do - like swim, and climb - so those things would be tied to each specific animal and NOT ALL Animals.

In your case, let's look at the Employee structure.

All Employees would have an employee ID, name, other related info about the employee.

A generic employee could possibly have these methods:
ClockIn
ClockOut

A Clerk would be a class inherited from employee
would have all the above but perhaps might also have properties for certifications on certain pieces of equipment -
registers, scanners, etc - these COULD be handled other ways as well, but working within inheritance we shall simplify it here.

A clerk would be able to
RingUp
ProcessReturns
SearchInventory

A Manager could either be inherited from Clerk or directly from Employee...  perhaps they could both inherit from an interface (assuming such is available in the language of choice) or from other classes as well...
IClerkDuties - which defines Ringup, ProcessReturns, and SearchInventory but does not implement them.

And then the manager would have IClerkDuties and IManagerDuties.
IManagerDuties could have such things as HireEmployee, BerateEmployee, FireEmployee, RateEmployeePerformance...

BUT, all of these would be EMPLOYEES - and any code needing to affect or use the employee class would work on or with all of these.

Title: Confusion about inheritance


问:
Differences between API Gateways and ESBs?
The company I work for is evaluating some middleware solutions for governace, metering and security of web services. Currently, we're using an Enterprise Service Bus (ESB) for this purpose, but some cool guys in management decided they are going to deploy some API Management Middleware.

I researched a bit about these API Management (aka API Gateway) Solutions but couldn't find the difference between them and actual ESBs. I evaluated some white papers from Mule, WSO2, Oracle etc, but the features offered by both products seem to be almost the same. The question is, what an API Management can do that an ESB cannot do and vice-versa? What value can be added to an IT Infrastructure by replacing an ESB for an API Gateway?

答:
The reason you're getting the concepts jumbled up is that the vendors are selling them in a package. But they are definitely separate concepts.

An API Gateway provides a central access point for managing, monitoring, and securing access to your publicly exposed web services. It would also allow you to consolidate services across disparate endpoints as if they were all coming from a single host. For example let's say you had ten different service endpoints that were all part of a single "suite" of services. Rather than informing consumers of your service to use service1.yourcompany.com for one service and service2.yourcompany.com for another and so forth, you can instead have them all point to api.yourcompany.com/service1 or api.yourcompany.com/service2 and the gateway would be responsible for redirecting the requests to the appropriate endpoints.

An ESB is an internal "Bus" that allows applications and services to communicate with each other in an uncoupled fashion. All applications can hook into the bus and they can receive  any message that interests them when published by another application. They can also publish their own messages that another application may listen for and respond to. The applications are not responsible for connecting with each other directly, they publish their messages to the bus and all interested parties listen and react.

Logically the API Gateway is not a replacement for an ESB but rather an enhancement for a service oriented architecture.