问:
Correctly disposing objects upon server termination
I am working on a large C++ project. It consists in a server that exposes a REST API, providing a simple and user-friendly interface for a very broad system comprising many other servers. The codebase is quite large and complex, and evolved through time without a proper design upfront. My task is to implement new features and refactor/fix the old code in order to make it more stable and reliable.

At the moment, the server creates a number of long-living objects that are never terminated nor disposed when the process terminates. This makes Valgrind almost unusable for leak detection, as it is impossible to distinguish between the thousands of (questionably) legitimate leaks from the "dangerous" ones.

My idea is to ensure that all objects are disposed before termination, but when I made this proposal, my colleagues and my boss opposed me pointing out that the OS is going to free that memory anyway (which is obvious to everybody) and disposing the objects will slow down the shutdown of the server (which, at the moment, is basically a call to std::exit). I replied that having a "clean" shutdown procedure does not necessarily imply that one must use it. We can always call std::quick_exit or just kill -9 the process if we feel impatient.

They replied "most Linux daemons and processes don't bother freeing up memory at shutdown". While I can see that, it is also true that our project does need accurate memory debugging, as I already found memory corruption, double frees and uninitialised variables.

What are your thoughts? Am I pursuing a pointless endeavour? If not, how can I convince my colleagues and my boss? If so, why, and what should I do instead?

答:
IMHO, the lifetimes of these objects should never just be made and left to die when the system shuts down. This reeks of global variables, which we all know are bad bad bad bad bad. Especially in the age of smart pointers, there is no reason to do this other than laziness. But more importantly, it adds a level of technical debt to your system that someone may have to deal with some day.

The idea of "technical debt" is that when you take a shortcut like this, when someone wants to change the code in the future (lets say, I want to be able to make the client go into "offline mode" or "sleep mode", or I want to be able to switch servers without restarting the process) they will have to put the effort in to do what you are skipping doing. But they will be maintaining your code, so they won't know nearly as much about it as you do, so it will take them much longer (I'm not talking 20% longer, i'm talking 20x longer!). Even if it is you, then you're going to have not worked on this particular code for weeks or months, and it'll take much longer to dust off the cobwebs in order to implement it correctly. The increase in time that needs to be spent to deal with bad design decisions is the interest on the technical debt.

In this case, it appears you have very tight coupling between the server object and the "long lived" objects...there are times when a record could (and should) outlive the connection to the server. Maintaining every single change to an object in a server can be prohibitively expensive, so its usually better that the spawned objects really be chached handles to the server object, with save and update calls that actually change the server. This is commonly called the active record pattern. See:

http://en.wikipedia.org/wiki/Active_record_pattern

In C++, i'd have each active record have a weak_ptr to the server, which could throw things intelligently if the server connection goes dark. These classes can be either lazily or batch populated, depending on your needs, but the lifetime of those objects should only be where they are used.

See also:

Is it a waste of time to free resources before I exit a process?

The other


答:
Add a switch to the server process that can be used during valgrind measurements that will release all of the memory. You can use this switch for testing. The impact will be minimal during normal operations.

We had a long running process that would take several minutes to releases 1000’s of objects. It was much more efficient to just exit and let them die. Unfortunately, as you indicate, this made it difficult to detect true memory leaks with valgrind or any other tools.

This was a good compromise for our testing while not impacting normal performance.

ContentLicense: CC BY-SA 3.0

Title: Correctly disposing objects upon server termination

Body:
I am working on a large C++ project. It consists in a server that exposes a REST API, providing a simple and user-friendly interface for a very broad system comprising many other servers. The codebase is quite large and complex, and evolved through time without a proper design upfront. My task is to implement new features and refactor/fix the old code in order to make it more stable and reliable.

At the moment, the server creates a number of long-living objects that are never terminated nor disposed when the process terminates. This makes Valgrind almost unusable for leak detection, as it is impossible to distinguish between the thousands of (questionably) legitimate leaks from the "dangerous" ones.

My idea is to ensure that all objects are disposed before termination, but when I made this proposal, my colleagues and my boss opposed me pointing out that the OS is going to free that memory anyway (which is obvious to everybody) and disposing the objects will slow down the shutdown of the server (which, at the moment, is basically a call to std::exit). I replied that having a "clean" shutdown procedure does not necessarily imply that one must use it. We can always call std::quick_exit or just kill -9 the process if we feel impatient.

They replied "most Linux daemons and processes don't bother freeing up memory at shutdown". While I can see that, it is also true that our project does need accurate memory debugging, as I already found memory corruption, double frees and uninitialised variables.

What are your thoughts? Am I pursuing a pointless endeavour? If not, how can I convince my colleagues and my boss? If so, why, and what should I do instead?


问:
Shortest path to visit all nodes
I am given a set of tourist attractions(nodes identified by x, y) and i need to find the shortest path to visit them.

The way i thought of it, is i will ignore if there are streets available and consider the streets always go the way a segment uniting the two points does. However, i need to find the shortest path through them; is this a correct approach to solving this problem?

From what i have read, i should apply the Traveling Salesman Problem or the Chinese Postman Problem, but i cannot figure out which one is more suitable for my case?

Also, if i am to apply TSP, is it better to go at it with a dynamic approach or a genetic algorithm one? Can you please provide an efficient implementation, if possible, as i have found only few resources and i am uneasy as to their efficiency.

答:
I won't present an efficient algorithm.

You may have a look at zero-supressed decision diagrams (ZSDD / ZDD) to enumerate all paths and represent every path in a compact form.

Zero-Suppressed BDDs for Set Manipulation in Combinatorial Problems by Shin-ichi Minato (NTT LSI Laboratories)

since you now have a compact representation you can search for the minimal solution more efficient.

You may have a look Donald Ervin Knuth's book 'The Art of Computer Programming. Volume 4.a' Chapter 7.1.4 which focusses on this topic.

Title: Shortest path to visit all nodes


问:
Cognitive Modeling Programming vs Imperative Programming vs Declarative Programming
I'm reading this article by John Funge about Cognitive Modeling for Computer Games:   http://www.qrg.northwestern.edu/resources/aigames.org/1999/fungegame99.pdf

And some further detailed reading about it in this URL:

http://www.msci.memphis.edu/~classweb/public_html/comp7990/Spring2000/Wally/Presentation5/tsld014.htm

I'm having a hard time to understand the CML:
I understand it's some kind of mix between Imperative and Declarative programming, I just didn't understand how:

For example the following pseudo-code in Imperative Programming:

Declare a new List called ExpensiveItemsNames;

  Foreach Item in Items:

   If ItemPrice > 100 then

  Add ItemName to ExpensiveItemsNames

vs the Declerative version: (using SQL)

SELECT ItemName FROM Items

  WHERE ItemPrice > 100

What would be the CML version of it?

And how does CML help the programmer? I didn't understand that too.

As well, in the further detailed (as mentioned before - meaning the second link I put) website they also talk about pruning to reduce the space complexity.

While I know what is pruning, I couldn't understand it's relation to CML.  They look like two unrelated things to me at the moment.

And also regarding pruning - in the original article it is not mentioned, but in "further detailed" website it mentions later a preprocessing stage - I didn't understand if it's related to the CML or not.

Ok, I understand that my initial saying that CML "it's some kind of mix between Imperative and Declarative programming" isn't true (though it is written in the article: "...but the distinguishing
features of CML are the intuitive way domain knowledge
can be specified and how it affords a game developer familiar
control structures to focus the power of the reasoning engine.
This forms an important middle ground between regular
logic programming (as represented by Prolog) and traditional
imperative programming (as typified by C)"

As far as I understand CML should answer these problems:

1. "if we are
not extra careful about how we represent a character’s
knowledge we can deprive them of “common sense” as
they reason about the effects of their actions. What is the meanin of "extra careful" and how does it affect the "common sense" of the character? And how does CML help?

2
. "how to provide a convenient
mechanism to allow the programmer to strike
a balance between lots of fast pre-programmed behavior
and more expensive run-time decision making".

I have my assumptions to this, but i'm not convinced they are true:

 If we use only pre-programmed character, then the complexity can be also very hard to program and also very complex in terms of memory and the pre-processing running time.

 However if we use only  run-time decision making, then the character will be very "stupid" or it will have to start calculating a lot each step.

CML provides something in between, in the form of "reasoning engine", which fills details during run-time.

I didn't understand though how CML does this.

 The article mentions it does calculations every once in a while: "In this way a character can anticipate that after
a certain time period, or event, it will be ignorant of some
aspect of its world, and it can plan to sense and re-plan.  But i'm not sure I understood correctly.

The "further detailed" link mentions pruning, though the article doesn't. Perhaps this is a necessary part of CML?

3. "by using interval arithmetic to integrate sensing
into our underlying theoretical framework, we enable
characters to generate plans of action even when
they find themselves in highly complex, dynamic virtual
worlds.

I think the meaning of "interval" here is the space of what the character knows, and not the time intervals mentioned earlier. Is this also a necessary part of CML?

So those are a few more questions I would be happy to understand better if someone knows.

答:
Imperative Programming, Declarative Programming, Functional Programming and Object Oriented Programming are all "programming paradigms" - different ways of writing a solution to a problem.

Cognitive Modelling is a solution to a problem (specifically, a very old solution to the problem of modelling "intelligence"), and not a way of writing a solution to a problem and not a programming paradigm.

You could implement Cognitive Modelling with imperative programming (e.g. have a "plan(entity)" function), or implement Cognitive Modelling with OOP (e.g. have a "merman::plan()" method), or implement it with functional programming (e.g. have a "newstate = plan(oldState)" function).

You could also invent a special (domain specific) language for Cognitive Modelling; and in that case your special language could use any programming paradigm you like.


问:
Are there programming languages that support both static and dynamic typing?
Being either static or dynamic should be something completely supported in the language. Static vs dynamic shouldn't be something that you have to turn on and off, switching between basically 2 languages.

I'm talking full blown mixed typing madness like this thing:

```<code>class MyClass {
  function myMethod(x: int, y: int){        # one parameter is typed, the other not
    return <cast_to_int> y.return_integer(x); #casting to guarantee the contract
  }
}

MyClass static_obj = MyClass();  #statically typed instantiation;
var dynamic_obj = {};   #dynamically typed instantiation
dynamic_obj.return_integer = (function (x) {return x*2}) #dynamic method creation

static_obj.myMethod(3, dynamic_obj)     # This returns 6

dynamic_obj.return_integer = (function (x) {return x+1}); # dynamic member reassignment

static_obj.myMythod(3, dynamic_obj)   # this returns 4

static_obj.myMethod('asdf', dynamic_obj) # This can't compile, because of typing

# and also this crazy thing; Notice that the static interface of the method is respected
if (<user input> == 2){
    static_obj.myMethod = (function (x: int, y){return x + y.yet_some_other_method(x);})
}

# but when the static contract is not respected, it doesn't compile
static_obj.myMethod = (function (a, b, c) {return 'asdf'}) # Compile time error
</code>```

I'm interested in this topic because I really like that API discoverability in static languages is great (thing i liked about Java, C# and ABAP for a while), but I also like testing stuff at run time, monkey patching, REPLs, reassignment, and crazy reflection magic (which I liked about JavaScript and Python).

I'm aware of Dart's static type checker, but that's not enough, because it provides no actual static guarantees.

I'm also not interested in type inferrence. I want true static running next to true dynamic behavior. I also am aware that I can use mapping types like python's dict, or any JS object, or Java's HashMap) to pass around data  (or even functions), but Java's mappings can't carry methods in them, Python's dicts can't (out of the box) have methods in them, and even though JS simply laughs at any kind of static restrictions - adding methods at runtime that DO get access via the this keyword to the context object is something really cool (I know Python does it too, when adding functions on the class object, but NOT on class instances).

My curiosity was also sparked by this paper:
Static typing where possible, dynamic typing where needed

And the API discoverability argument came from my own experience, but this paper seems to support it:
http://personales.dcc.uchile.cl/~rrobbes/p/ICPC2014-idetypes.pdf

答: Yes. C# as of 4.0 is probably the most common example, with the dynamic keyword. There are likely other good examples that I am forgetting or don't know about.


答:
(Disclaimer: I know nothing about CML, artificial intelligence, simulations software, autonomous software agents, or whatever topic that is discussed here in this question. My answer is just based on my limited knowledge and the links you provided.)

Short answer: the terms you mentioned belong to different categories or abstraction levels, so it is hard to make comparison, analogies, or examples.

As @Brendan says, Imperative and Declarative are programming (coding) paradigms.

Based on the links you provided, Cognitive Modeling Programming appears to be most similar to either Logic Programming or Event-driven Programming, used within the context of software simulations of autonomous agents.

Inside a software simulation of autonomous agents, there is:

A world, along with all of its physical, deterministic mechanics

One or more agents, each of which separately:

Receives stimuli (senses, input) from the world

Does its own logic

Use the output of its own logic to control its own actuators (motors)

In some types of simulations, direct communication between two agents is allowed. This adds an extra mode of input (receiving message) and output (sending message) to each agent.

After completing a single time step, when all decisions have been made and all physical effects have been applied, the simulation software advances the time step and re-runs the decision-making and physical-effects all over again.

Agents are allowed to carry their memory forward, to reuse them in future time steps.

In some more realistic and advanced simulations,

Agents can have reasoning behavior. This requires each agent to make use of a inductive engine.

Agents can use statistical, pattern recognition, or machine learning systems to make decisions and to improve the model over time.

The reason I say "software simulation of agents" belongs to "a type of software application" as opposed to a paradigm is because nothing is said about how the agents does its own logic. In fact, many different programming paradigms have been put into use in implementing the logic of these agents. I have already mentioned a few possibilities above; there are many more paradigms being used in practice.

The Cognitive Modeling Programming in the links you provided appears to be one implementation of a domain-specific language, as @Brendan says.

Does it qualify as a programming language?

If you have obtained:

A syntax and grammar for this programming language,

A software implementation which you can run on a computer to verify what you have read about this programming language,

Then yes, it is a programming language for your purpose. Otherwise, it is merely a programming language you have read about, but have not yet verified for yourself.

I will say this as a pragmatist. Practically speaking, you should not treat it as if it is a real language, unless you are an academia, in which you trust the author(s) and the editor(s) under which it is published, or you are a student, in which you engage in a game of pretend-play with your instructor during the course of study.

Title: Cognitive Modeling Programming vs Imperative Programming vs Declarative Programming

Body:
I'm reading this article by John Funge about Cognitive Modeling for Computer Games:   http://www.qrg.northwestern.edu/resources/aigames.org/1999/fungegame99.pdf

And some further detailed reading about it in this URL:

http://www.msci.memphis.edu/~classweb/public_html/comp7990/Spring2000/Wally/Presentation5/tsld014.htm

I'm having a hard time to understand the CML:
I understand it's some kind of mix between Imperative and Declarative programming, I just didn't understand how:

For example the following pseudo-code in Imperative Programming:

Declare a new List called ExpensiveItemsNames;

  Foreach Item in Items:

   If ItemPrice > 100 then

  Add ItemName to ExpensiveItemsNames

vs the Declerative version: (using SQL)

SELECT ItemName FROM Items

  WHERE ItemPrice > 100

What would be the CML version of it?

And how does CML help the programmer? I didn't understand that too.

As well, in the further detailed (as mentioned before - meaning the second link I put) website they also talk about pruning to reduce the space complexity.

While I know what is pruning, I couldn't understand it's relation to CML.  They look like two unrelated things to me at the moment.

And also regarding pruning - in the original article it is not mentioned, but in "further detailed" website it mentions later a preprocessing stage - I didn't understand if it's related to the CML or not.

Ok, I understand that my initial saying that CML "it's some kind of mix between Imperative and Declarative programming" isn't true (though it is written in the article: "...but the distinguishing
features of CML are the intuitive way domain knowledge
can be specified and how it affords a game developer familiar
control structures to focus the power of the reasoning engine.
This forms an important middle ground between regular
logic programming (as represented by Prolog) and traditional
imperative programming (as typified by C)"

As far as I understand CML should answer these problems:

1. "if we are
not extra careful about how we represent a character’s
knowledge we can deprive them of “common sense” as
they reason about the effects of their actions. What is the meanin of "extra careful" and how does it affect the "common sense" of the character? And how does CML help?

2
. "how to provide a convenient
mechanism to allow the programmer to strike
a balance between lots of fast pre-programmed behavior
and more expensive run-time decision making".

I have my assumptions to this, but i'm not convinced they are true:

 If we use only pre-programmed character, then the complexity can be also very hard to program and also very complex in terms of memory and the pre-processing running time.

 However if we use only  run-time decision making, then the character will be very "stupid" or it will have to start calculating a lot each step.

CML provides something in between, in the form of "reasoning engine", which fills details during run-time.

I didn't understand though how CML does this.

 The article mentions it does calculations every once in a while: "In this way a character can anticipate that after
a certain time period, or event, it will be ignorant of some
aspect of its world, and it can plan to sense and re-plan.  But i'm not sure I understood correctly.

The "further detailed" link mentions pruning, though the article doesn't. Perhaps this is a necessary part of CML?

3. "by using interval arithmetic to integrate sensing
into our underlying theoretical framework, we enable
characters to generate plans of action even when
they find themselves in highly complex, dynamic virtual
worlds.

I think the meaning of "interval" here is the space of what the character knows, and not the time intervals mentioned earlier. Is this also a necessary part of CML?

So those are a few more questions I would be happy to understand better if someone knows.


问:
The modern way to perform error handling...
I've been pondering this problem for a while now and find myself continually finding caveats and contradictions, so I'm hoping someone can produce a conclusion to the following:

Favour exceptions over error codes

As far as I'm aware, from working in the industry for four years, reading books and blogs, etc. the current best practice for handling errors is to throw exceptions, rather than returning error codes (not necessarily an error code, but a type representing an error).

But - to me this seems to contradict...

Coding to interfaces, not implementations

We code to interfaces or abstractions to reduce coupling. We don't know, or want to know, the specific type and implementation of an interface. So how can we possibly know what exceptions we should be looking to catch? The implementation could throw 10 different exceptions, or it could throw none. When we catch an exception surely we're making assumptions about the implementation?

Unless - the interface has...

Exception specifications

Some languages allow developers to state that certain methods throw certain exceptions (Java for example, uses the throws keyword.) From the calling code's point of view this seems fine - we know explicitly which exceptions we might need to catch.

But - this seems to suggest a...

Leaky abstraction

Why should an interface specify which exceptions can be thrown? What if the implementation doesn't need to throw an exception, or needs to throw other exceptions? There's no way, at an interface level, to know which exceptions an implementation may want to throw.

So...

To conclude

Why are exceptions preferred when they seem (in my eyes) to contradict software best practices? And, if error codes are so bad (and I don't need to be sold on the vices of error codes), is there another alternative? What is the current (or soon to be) state of the art for error handling that meets the requirements of best practices as outlined above, but doesn't rely on calling code checking the return value of error codes?

答:
Right-biased Either.

It can't be ignored, it must be handled, it's completely transparent.
And IF you use the correct left handed error type it conveys all the same information as a java exception.

Downside? Code with proper error handling looks disgusting (true of all mechanisms).


答:
A great example of this is Dylan. You can use static and dynamic typing in Dylan, e.g.,

```<code>define method double(a :: <integer>) => (result :: <integer>)
    2 * a
end
</code>```

or

```<code>define method double(a) => (result)
    2 * a
end
</code>```

This extends to variables, etc. Another more mild example is REBOL, but only in its function definitions, e.g.,

```<code>double: func [a [integer!]] [a * 2]
double: func [a] [a * 2]
</code>```

Function parameters are the only place in REBOL any kind of type checking (or declaration, for that matter) is permitted.

Title: Are there programming languages that support both static and dynamic typing?

Body:
Being either static or dynamic should be something completely supported in the language. Static vs dynamic shouldn't be something that you have to turn on and off, switching between basically 2 languages.

I'm talking full blown mixed typing madness like this thing:

```<code>class MyClass {
  function myMethod(x: int, y: int){        # one parameter is typed, the other not
    return <cast_to_int> y.return_integer(x); #casting to guarantee the contract
  }
}

MyClass static_obj = MyClass();  #statically typed instantiation;
var dynamic_obj = {};   #dynamically typed instantiation
dynamic_obj.return_integer = (function (x) {return x*2}) #dynamic method creation

static_obj.myMethod(3, dynamic_obj)     # This returns 6

dynamic_obj.return_integer = (function (x) {return x+1}); # dynamic member reassignment

static_obj.myMythod(3, dynamic_obj)   # this returns 4

static_obj.myMethod('asdf', dynamic_obj) # This can't compile, because of typing

# and also this crazy thing; Notice that the static interface of the method is respected
if (<user input> == 2){
    static_obj.myMethod = (function (x: int, y){return x + y.yet_some_other_method(x);})
}

# but when the static contract is not respected, it doesn't compile
static_obj.myMethod = (function (a, b, c) {return 'asdf'}) # Compile time error
</code>```

I'm interested in this topic because I really like that API discoverability in static languages is great (thing i liked about Java, C# and ABAP for a while), but I also like testing stuff at run time, monkey patching, REPLs, reassignment, and crazy reflection magic (which I liked about JavaScript and Python).

I'm aware of Dart's static type checker, but that's not enough, because it provides no actual static guarantees.

I'm also not interested in type inferrence. I want true static running next to true dynamic behavior. I also am aware that I can use mapping types like python's dict, or any JS object, or Java's HashMap) to pass around data  (or even functions), but Java's mappings can't carry methods in them, Python's dicts can't (out of the box) have methods in them, and even though JS simply laughs at any kind of static restrictions - adding methods at runtime that DO get access via the this keyword to the context object is something really cool (I know Python does it too, when adding functions on the class object, but NOT on class instances).

My curiosity was also sparked by this paper:
Static typing where possible, dynamic typing where needed

And the API discoverability argument came from my own experience, but this paper seems to support it:
http://personales.dcc.uchile.cl/~rrobbes/p/ICPC2014-idetypes.pdf

Body:
A great example of this is Dylan. You can use static and dynamic typing in Dylan, e.g.,

define method double(a :: <integer>) => (result :: <integer>)
    2 * a
end

or

define method double(a) => (result)
    2 * a
end

This extends to variables, etc. Another more mild example is REBOL, but only in its function definitions, e.g.,

double: func [a [integer!]] [a * 2]
double: func [a] [a * 2]

Function parameters are the only place in REBOL any kind of type checking (or declaration, for that matter) is permitted.


答:
Java sort of has this with the Object class.

```<code>int myMethod(int x, Object y) {
  return x > 0 ? x : (int)y;
}

void go() {
  Object obj;
  if(Math.random() > 0.5)
    obj = 3;
  else
    obj = "hello";
  myMethod(-5, obj); // throws ClassCastException if obj is a String
}
</code>```

In Java 8, lambda functions are introduced, so you can put functions inside maps, though it's a bit unwieldy:

```<code>Map myObj = new HashMap();
myObj.put("add",
          (BiFunction) (Object x, Object y) -> ((Number) x).intValue() + ((Number) y).intValue());
BiFunction addition = (BiFunction) myObj.get("add");
int apply = (int) (Number) addition.apply(3, 2.2);
</code>```

Body:
Java sort of has this with the Object class.

int myMethod(int x, Object y) {
  return x > 0 ? x : (int)y;
}

void go() {
  Object obj;
  if(Math.random() > 0.5)
    obj = 3;
  else
    obj = "hello";
  myMethod(-5, obj); // throws ClassCastException if obj is a String
}

In Java 8, lambda functions are introduced, so you can put functions inside maps, though it's a bit unwieldy:

Map myObj = new HashMap();
myObj.put("add",
          (BiFunction) (Object x, Object y) -> ((Number) x).intValue() + ((Number) y).intValue());
BiFunction addition = (BiFunction) myObj.get("add");
int apply = (int) (Number) addition.apply(3, 2.2);


问:
readability vs shorter code in returning from function
In something as simple as

```<code>int sq(int x) { int y = x*x; return y; }
</code>```

versus

```<code>int sq(int x) { return (x*x); }
</code>```

the former function requires an extra IL step.

EDIT: IL code from the first example, using the current C# compiler from VS 2013 Update 4 (.NET Framework 4.5.1), code from the optimized release version:

```<code>  IL_0000:  ldarg.0
  IL_0001:  ldarg.0
  IL_0002:  mul
  IL_0003:  stloc.0   // These two instructions
  IL_0004:  ldloc.0   // seem to be unneccessary
  IL_0005:  ret
</code>```

and from the second example:

```<code>  IL_0000:  ldarg.0
  IL_0001:  ldarg.0
  IL_0002:  mul
  IL_0003:  ret
</code>```

Is that IL extra step indicative of data being copied in memory? Is this difference still present when using something seemingly better optimized? (C?)

If yes to first or both: can I use the latter, especially when the returned data takes a lot of space, and presumably a lot of time to be moved in memory? Or should I favor the former, because it is more readable? LINQ makes it easy to have whole functions inside a long return() line, but my example faces the same choice were it C. Speed or readability?

In general, would you put the last bit of maths between the parentheses in the return line?

答:
I'm going to directly challenge that the first example is more readable. In this code, it is very clear what is happening, you take an int x and return x*x.

```<code>int sq(int x) {
    return (x*x);
}
</code>```

Adding an extra instruction (y=x*x; return y) adds nothing to readability, and in fact makes me wonder what I might be missing (eg. were there lines you've removed), because you are assigning a new variable.

However, in the general "readability vs. speed" argument, I would suggest readability trumps all others. In most cases, programmer time is vastly more expensive than computation or storage. CodeGolf.StackExchange is an exemplary example of this, as it is filled with alot of very fast, very clever solutions to problems, but the time to actually understand how some of them work is quite long.

"Bottlenecks occur in surprising places, so don't try to second guess and put in a speed hack until you have proven that's where the bottleneck is." — Rob Pike

Optimisations in code to improve bytecode performance should only be considered after every other part of the code is profiled to identify potential bottlenecks. If your bytecode optimisation makes a naive O(n!) operation a little faster for each n, finding a O(n^2) solution in code will grant much better results.

Even then, when you start investigating bytecode operation to squeeze extra performance, the cost of adding an extra core to a server, or buying a little extra server time, might be minuscule compared to the time required for code changes and investigations for a bytecode optimal solution - the reason I say this is that if a bytecode optimal solution were trivially easy, it would already be incorporated into the compiler/interpreter.

Body:
I'm going to directly challenge that the first example is more readable. In this code, it is very clear what is happening, you take an int x and return x*x.

int sq(int x) {
    return (x*x);
}

Adding an extra instruction (y=x*x; return y) adds nothing to readability, and in fact makes me wonder what I might be missing (eg. were there lines you've removed), because you are assigning a new variable.

However, in the general "readability vs. speed" argument, I would suggest readability trumps all others. In most cases, programmer time is vastly more expensive than computation or storage. CodeGolf.StackExchange is an exemplary example of this, as it is filled with alot of very fast, very clever solutions to problems, but the time to actually understand how some of them work is quite long.

"Bottlenecks occur in surprising places, so don't try to second guess and put in a speed hack until you have proven that's where the bottleneck is." — Rob Pike

Optimisations in code to improve bytecode performance should only be considered after every other part of the code is profiled to identify potential bottlenecks. If your bytecode optimisation makes a naive O(n!) operation a little faster for each n, finding a O(n^2) solution in code will grant much better results.

Even then, when you start investigating bytecode operation to squeeze extra performance, the cost of adding an extra core to a server, or buying a little extra server time, might be minuscule compared to the time required for code changes and investigations for a bytecode optimal solution - the reason I say this is that if a bytecode optimal solution were trivially easy, it would already be incorporated into the compiler/interpreter.


问:
In C#, performance wise, an object's size does matter when you access one of its members through a reference?
It may be a stupid question but in C#, performance wise, an object's size or complexity does matter when you access one of its members through a reference? Or only that specific member is all that matters?

I know it's premature optimization but I'm curious.

答:
Short answer: no.

Long answer: I assume when you write "size" of an object, you mean size (in bytes) of the member variables, and when you write "complexity", you mean number of members, number of different types used, and so on. Access to an object through a member function will result in IL code which contains

pushing the parameters of the method to the stack

pushing a "this" reference to the stack

calling the function (which will result in a simple call statement at the machine code level, not depending on the object's size)

(This is a simplified model, not taking things like inlining into account, but it is sufficient for answering your question). So as you see, in none of these operations the object size itself has an influence. And neither the number and structure of other member functions.

The size only matters from a performance perspective when you copy objects around, when you store them to disk or a database, or when you are accessing the data of so many different objects that your CPU cache is not sufficiently large to hold all the data accessed. The latter might happen when the "number of objects x size of object" exceeds a certain limit, but it depends also on what other things your program does, which other data is involved. So is an accumulated effect, and I doubt it counts as "performance impact caused by access to one of its members through a reference".


答:
One good approach would be to narrow down the discussion with your colleagues by means of classification. Given a large code base, certainly there is not one single reason but rather multiple, (identifiable) reasons for long living objects.

Examples:

Long living objects which are not referenced by anyone (real leaks). It is a programming logic error. Fix those with lower priority UNLESS they are responsible for your memory footprint to grow over time (and deteriorate your applications quality). If they make your memory footprint grow over time fix them with higher priority.

Long living objects, which are still referenced but not used anymore (due to program logic), but which do not make your memory footprint grow. Code review and try to find the other bugs which lead to that. Add comments to the code base if it is an intentional (performance) optimization.

Long living objects "by design". Singleton pattern for example. They are indeed hard to get rid of, especially if it is a multi- threaded application.

Recycled objects. Long living objects need not always be bad. They can also be beneficial. Instead of having high frequency memory allocations/deallocations, adding currently unused objects to a container to draw from when such a memory block is needed again can help speed up an application and avoid heap fragmentation. They should be easy to free at shutdown time, maybe in a special "instrumentation/checked" build.

"shared objects" - objects which are used (referenced) by multiple other objects and no one knows exactly when it is save to free them. Consider turning them into reference counted objects.

Once you have classified the real reasons for those unfreed objects, it is much easier to enter a case by case discussion and find a resolution.


问:
How to model the dependencies between fields in very complex forms
We have to create a web application that will be used as an application form for multiple insurance products (15 in total). This application form will be similar to a form wizard, it will span across multiple pages, depending on what product between 4 and 10.

The grand total of all different elements (inputs, select boxes) that the form will be rendering is around 250, but even the most complex product will not use more than 170 of them. The least complex one still requires around 80 elements.

We do not want to create 15 different application forms, one per product, we want to have a single application form which will be used by all products.

Now as you can imagine, the elements have a lot of dependencies between them. A value entered in a field can make another field or set of field appear or disappear (on the current page or a following page(s)). Some other dependencies based on entered values:

value of an element is required or not

possible values for select boxes will be changed

the validation constraints will be changed

As you can imagine, modeling this is very complex. The question is, what tool would you recommend for modeling (and documenting) all these elements, the dependencies between them and the validation constraints? How would you do the modeling? Not talking about the data model at all in this case. This model will be part of the specifications of what needs to be done and as a reference after the completion of the project. By changing the model the application forms will not be automatically changed.

Some of the things we would like to be able to do easily:

see what elements a certain element depends on

see all elements included in the form for certain product

see required elements for a certain product

define validation rules for each element

define various attributes for each element

Limitation: our product managers and product owners are the ones who will do the modelling.

答:
For a similar complex project we implemented an interpreter in the business-layerer with formulas for "isValid" and "isVisible" for every form-element

For the interpreter we used UML-s Object Constraint Language which was once designed for that purpose.

Unfortunately nearly nobody speaks "uml-ocl" so finding somebody to maintain the rules is difficuilt.

If we had to do that again we would choose a more common language like js/vb-script for the interpreter


问:
Is every language written in C?
Sometimes while programming in different languages (C/C++, C#), this thought comes to my mind:

Is each and every language written in the C programming language?

Is the C language the mother/father of all languages?

Is each concept (OOP, etc.) all implemented in C?

Am I in right direction?

答: No, some languages pre-date C. And many are implemented independently of C, e.g. see http://en.wikipedia.org/wiki/Lisp_%28programming_language%29</p>

Title: Is every language written in C?


答:
No.

OCaml, Haskell, Lisp dialects like Scheme, and several other languages are often used in the development of hobby languages.

Many languages are implemented in C because it's a ubiquitous language, and compiler-writing tools like lexer-parser generators (such as yacc and bison) are well-understood and almost as ubiquitous.

But C itself couldn't originally be developed in C when it was first created. It was, in fact, originally developed using the B language. Earlier languages (like Fortran) were usually bootstrapped using a native assembly language or even machine code long before C ever existed.

Unrelatedly, language paradigms like OOP are generally language-agnostic. The functional paradigm, for example, was developed (by Alonzo Church) as a foundation of mathematics long before any programming language ever existed. The procedural and structured programming paradigms came out of the mathematical work of theorists like John von Neumann. Object-orientation was developed by several different and unrelated efforts, some out of the lambda calculus (the functional paradigm) and some out of dynamic programming systems like SmallTalk at Xerox PARC by Alan Kay.

C is merely a tiny part of the story, decades after these ideas came into being.

Title: Is every language written in C?

Body:
Sometimes while programming in different languages (C/C++, C#), this thought comes to my mind:

Is each and every language written in the C programming language?

Is the C language the mother/father of all languages?

Is each concept (OOP, etc.) all implemented in C?

Am I in right direction?

ContentLicense: CC BY-SA 4.0


问:
Is there a useful correlation between choice of web-browser/search engine and good quality programmers?
After a round of interviews earlier this year, which included some practical questions with access to a computer, I noticed that, at least for the applicants we were seeing, there was a high inverse correlation between quality of applicant and the explicit choice of Bing/IE as the stack for search/browsing the web. That is, a large number of applicants specifically searched for IE to use as a browser when browsing the web, and specifically used Bing as the search engine (even typing in Bing in the Google search box, before starting a search)

Is this just an outlier, a fluke, or is there some sort of information I can obtain from this observation? So far, my best candidates are:

Yes, there is a high correlation between good programmers and choice of web browser/search engine

There is some training program, or community, which advises using IE/Bing during interviews, and I just happened to run into a poor selection from that group

Something else is going on, that I don't know about, but someone here might know.

So, to repeat, the question is: is there more than coincidence at work here, and, if there is, what's going on?

答:
People who use computers more are more likely to have encountered more than just the default browser, and therefore less likely to settle on IE as their favourite.

Bear in mind as JoshL says below in the comments:

you can't infer from this relationship that anyone with IE is a sucky programmer

ContentLicense: CC BY-SA 2.5


问:
Which 'InputStream' subtype is used by 'Socket' type object here?
In the below server socket program, byte stream object is used to read data from client, as mentioned -  InputStream in = socket.getInputStream();

```<code>public class SingleThreadTCPServer{
    ServerSocket serverSocket;
    int serverPort = 3333;

    public SingleThreadTCPServer(){
        try{
            serverSocket = new ServerSocket(serverPort);
            System.out.println("ServerSocket: " + serverSocket);
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    private void listen(){
        try{
            while(true){  //run until you terminate the program
                //Wait for connection. Block until a connection is made.
                Socket socket = serverSocket.accept();
                System.out.println("Socket: " + socket);
                InputStream in = socket.getInputStream();
                int byteRead;
                //Block until the client closes the connection (i.e., read() returns -1)
                while((byteRead = in.read()) != -1){
                    System.out.println((char)byteRead);
                }
            }
        }catch(IOException ex){
            ex.printStackTrace();
        }

    }

    public static void main(String[] args){
        new SingleThreadTCPServer().listen();
    }
}
</code>```

I had been through the implementation of getInputStream() method but could not understand the actual subtype of InputStream object that is actually returned from getInputStream()

Among the below subtypes,

Which is the actual stream type that is being used by server to read data from client?

答:
That is a native object, it is (probably) implemented in C++. You can't write anything like it in Java since Java do not directly expose its external environment. You can however bind functions written in other languages by using the Java Native Interface.

Doing all of that yourself would be a lot of work, so luckily the Java Runtime Environment has already implemented these interfaces for you. This allows you to treat them as standard Java objects without having to worry about how they work in practice. If you really want to learn about them you need to learn C++.


答:
Most of the core of many important languages is written in C, but things are changing:

the reference implementation of Python (CPython) is written in C (but there are other implementations written in other languages, e.g. Jython / Java, PyPy / Python, IronPython / C#...)

PHP Zend Engine is written in C

very first Java compiler developed by Sun Microsystems was written in C, but now the class libraries are always written in Java (since they are intended to be run using the Java VM itself). Certain libraries using JNI (Java Native Interface) may be partially written in a variety of other languages, as they are intended to be used OUTSIDE the JVM.

The Sun/Oracle VM is written in C++. The BEA/Weblogic/Oracle VM is written in C. But there are JVM written in Java, Lisp, SmallTalk (IBM)...

Perl is implemented as a core interpreter, written in C, together with a large collection of modules, written in Perl and C (but Pugs, a compiler and interpreter for the Perl 6 programming language, is written in Haskell)

the official Ruby interpreter, often referred to as the Matz's Ruby Interpreter or MRI, is written in C and uses its own Ruby-specific virtual machine (but there is JRuby, a Java implementation that runs on the Java virtual machine; Rubinius, a C++ bytecode virtual machine that uses LLVM to compile to machine code at runtime...)

about 50% of R is written in C

and, of course, C is (was) written in C! (but the first C compiler, targeted to the PDP-11, was a mix of B and assembler).

There are many reasons why C was often chosen: performance, portability, experience.

The last probably being the most important: Python was started in 1991, PHP in 1994/1995, Perl in 1988, Ruby in 1995. In those years Java was just released and C++ not yet well standardized.

Somewhat related:

Is functional language without runtime written in C possible?

Title: Is every language written in C?


问:
Commenting Code AS3 - Not being an API
How should I comment a method?

What are the best practices on commenting code?

Example:

```<code>/* Checks if a color is allowed in a given point
* of the bitmapdata of the current floor
* @param value - color to be checked
* @return boolean - if color is allowed returns true, else, return false
*/

private function isAllowed(value:uint):Boolean {

   //code...

}
</code>```

Is that the best way to comment a method?

I´ve heard there´s the use of the tag @see. What should be on this tag?
I wonder if it could be something that has a relation to the method, is that right?

Thanks.

答:
Good code should be descriptive enough that it shouldn't need comments. For example the method should do one thing only and have a name that describes that purpose.

Any parameters passed in should also be properly named so that @param type comments don't need to be used.

Perfect code would be comment-free and would read almost like English.

Title: Commenting Code AS3 - Not being an API


问:
What can slow a developer down?
What things tend to slow a developer down?

Please try to refrain from posting answers that:

are slow now but useful in the feature. (TDD, Refactoring, ...)

list a distraction.

答: Well lately the biggest slow down is because we are developing several things simulatneously that should have been done in a specific order. So I'm waiting until (names changed to protect the innocent) John finishes his component that I need for my SSIS package and Harry is slowed down waiting for me to import records because he needs some data to see to test his export (ever try to write a complex export report when there is no data in any of the tables?) and everybody is slowed down because design isn't done and the database tables we need to do our tasks haven't been created yet and may not even end up being what they said they were going to be, etc.</p>

Title: What can slow a developer down?


答:
It's a matter of availability.

If you don't care about computers, you're going to go to a store that sells computers and buy a Windows box.  Once you've got it, you'll use IE because it's there (when I boot into W7 on my laptop, IE has a favored position on the task bar even though I rarely use it), and Bing because it's what IE uses by default.  Also, you're not going to be interested in alternative ways to do things, and will try to use what you're used to.

If you do care about your computing environment, you will get a computer with your favored OS.  You will experiment with browsers until you find what you like, and the same with search engines.  There's no guarantee that you won't decide you like Windows, IE, and Bing, but the chance is much higher that you'll use Mac or Linux, Firefox or Safari or Opera or Chrome, or Google.

When looking for a programmer, you generally want one who likes computers and is willing to try new things.  You also are likely to interview people who you really wouldn't spend time on if you knew them better, but that's what the interview's for.  They will want to use IE and Bing disproportionately.

It's also possible that good programmers prefer the alternatives to IE and Bing in general, but that's not necessary to explain your observations.

Title: Is there a useful correlation between choice of web-browser/search engine and good quality programmers?

Body:
After a round of interviews earlier this year, which included some practical questions with access to a computer, I noticed that, at least for the applicants we were seeing, there was a high inverse correlation between quality of applicant and the explicit choice of Bing/IE as the stack for search/browsing the web. That is, a large number of applicants specifically searched for IE to use as a browser when browsing the web, and specifically used Bing as the search engine (even typing in Bing in the Google search box, before starting a search)

Is this just an outlier, a fluke, or is there some sort of information I can obtain from this observation? So far, my best candidates are:

Yes, there is a high correlation between good programmers and choice of web browser/search engine

There is some training program, or community, which advises using IE/Bing during interviews, and I just happened to run into a poor selection from that group

Something else is going on, that I don't know about, but someone here might know.

So, to repeat, the question is: is there more than coincidence at work here, and, if there is, what's going on?


问:
Licensing subcomponents
Say I produce system X, which contains some components (A, B and C, say) which are specific to X, but ripe for generalisation. Let's say X is licensed with a viral open source license ([AL]?GPL).

If I decide to break any of A, B or C out as standalone systems, under their own distribution, can they be relicensed, or do they need to keep the same license as X? e.g., Can A be MIT, or BSD, etc.? The code of A, B and C is nearly identical to that as source in X; but even significant changes would still be clear derivatives of X. Does the "virusness" of X's license preclude any use of a more permissive license on after-the-fact components?

答: As long as you are the only programmer of A, you can relicense component A in any way as you like. Otherwise, you have to ask all contributers, if they are OK with relicensing.</p>

Title: Licensing subcomponents


答:
This depends on who contributed to the system X.

Case 1: You did it all by yourself

You are the sole copyright owner of system X. You have decided to distribute that code under a viral open source license. You may at any point stop offering the system under such a license, although you can't cancel existing *GPL licenses or prevent other people from continuing to distribute the system under the original *GPL license. You may also additionally license the system in whole or in part under a different license, and let people choose which license they'd want to use. Dual-licensed software is a fairly frequent occurrence, and you may also transition to a dual-license “after the fact”. Provided again that you are the sole copyright owner.

Case 2: Other people contributed to the system

Let's say you put the *GPL-licensed code on GitHub, and you merged a pull request from someone who fixed a few bugs throughout the code. Since these changes where presumably provided to you under the *GPL license, the complete system is under shared copyright by you and all other contributors. Since everyone licensed their contributions under the *GPL, you are bound by this license, and relicensing the code in an incompatible manner is not permitted.

To change the license or to dual-license the code, you would either have to make all contributors accept a contributor license agreement before their changes are merged into a project, which is usually a copyright assignment to you so that you maintain full control over the code. Or you can contact all contributors after the fact and ask for their written permission to distribute the code under an incompatible license. However, nobody is required to give such permission and without such permission from every single contributor you cannot proceed.

Relicensing only certain components of the system

You are free to split up a system X into components A, B, C, but all those components will retain their original *GPL license. For each of these components you can then try to separately relicense or dual-license them as outlined above. In particular this means that when you are trying to relicense a component C, you don't have to ask contributors that didn't contribute to C for permission.

Title: Licensing subcomponents

Body:
Say I produce system X, which contains some components (A, B and C, say) which are specific to X, but ripe for generalisation. Let's say X is licensed with a viral open source license ([AL]?GPL).

If I decide to break any of A, B or C out as standalone systems, under their own distribution, can they be relicensed, or do they need to keep the same license as X? e.g., Can A be MIT, or BSD, etc.? The code of A, B and C is nearly identical to that as source in X; but even significant changes would still be clear derivatives of X. Does the "virusness" of X's license preclude any use of a more permissive license on after-the-fact components?


问:
Coding convention question about AS3 duplicate variable definition
AS3's got some awkward rules about variable scope, due to its use of hoisting.  I don't like pointlessly leaving a bunch of compiler warnings lying around, but it's more important to me for my code to readable and properly written, regardless.  This produces a couple of duplicate variable definition warnings:

```<code>    private function arrangeElementsLine(pElementSize:Dimensions):void
    {
        if (m_eOrientation == HORIZONTAL)
        {
            for (var i:uint = 0; i < target.numElements; i++)
            {
                var layoutElement:ILayoutElement = target.getElementAt(i);
                layoutElement.setLayoutBoundsSize(pElementSize.x, pElementSize.y);
                layoutElement.setLayoutBoundsPosition(pElementSize.x * i, 0);
            }
        }
        else
        {
            for (var i:uint = 0; i < target.numElements; i++)
            {
                var layoutElement:ILayoutElement = target.getElementAt(i);
                layoutElement.setLayoutBoundsSize(pElementSize.x, pElementSize.y);
                layoutElement.setLayoutBoundsPosition(0, pElementSize.y * i);
            }
        }
    }
</code>```

Is it generally considered to be better and more conventional to remove the redundant var and :<type> syntax for i and layoutElement in the second for loop, or is it more proper to just leave them in there (due to the way their usage is isolated to those two for loops)?  Thanks!

EDIT

This was asked a while back, but when I asked this, part of what I was working on was making something run more efficiently; so I put if outside of any for statements and avoided method calls inside the for statements.

答:
You have a lot of duplicate code here, which defeats the DRY principle. This would be better:

```<code>private function arrangeElementsLine(pElementSize:Dimensions):void {
    for (var i:uint = 0; i < target.numElements; i++) {
        var layoutElement:ILayoutElement = target.getElementAt(i);
        layoutElement.setLayoutBoundsSize(pElementSize.x, pElementSize.y);

        if (m_eOrientation == HORIZONTAL) {
            layoutElement.setLayoutBoundsPosition(pElementSize.x * i, 0);
        } else {
            layoutElement.setLayoutBoundsPosition(0, pElementSize.y * i);
        }
    }
}
</code>```

This also solves your issues with variable duplication.

Body:
You have a lot of duplicate code here, which defeats the DRY principle. This would be better:

private function arrangeElementsLine(pElementSize:Dimensions):void {
    for (var i:uint = 0; i < target.numElements; i++) {
        var layoutElement:ILayoutElement = target.getElementAt(i);
        layoutElement.setLayoutBoundsSize(pElementSize.x, pElementSize.y);

        if (m_eOrientation == HORIZONTAL) {
            layoutElement.setLayoutBoundsPosition(pElementSize.x * i, 0);
        } else {
            layoutElement.setLayoutBoundsPosition(0, pElementSize.y * i);
        }
    }
}

This also solves your issues with variable duplication.


问:
Is embedding data in a executable considered a good practice?
Embedding data (such as images) in a executable seems to have a few advantages, like easier distribution of the executable and easier compatibility with different OSes.

But, is it a good practice? More specifically, how does the OS deals with a big executable? Would it be using much more RAM than needed?

答:
If you mean using Resources, then embedding images and similar data is fine. They are loaded on demand, so the memory footprint won't change a lot.

You may also end up putting this data in an external DLL, which has a benefit: if you need to push a new revision of your software to your clients' machines, you don't need to send the DLL containing the resources, unless they changed too.

Remember that Resources are fine for icons or localized strings or images shown by your app, but there may be easier ways to do what you need to do. For example, I may use Resources for a 2D game which uses a few sprites, but not to store hundreds of textures for a large 3D video game: either storing the textures directly or in a 0% ZIP container would be a more flexible way to do it.

If you mean embedding data directly in source code in constants, I'll rather avoid it for mostly those three reasons:

You may not necessarily need the data to be available directly. If it's stored on disk, you can access it through a stream. If it's a constant, you are forced to get it all at once.

Viewing and editing data would be hell. In general, developers don't have skills to visualize (and modify) images through their binary/hexadecimal representations. What if you copy-pasted the image in the wrong constant? What if you need to change the image? The readability (and maintainability) of your code suffers, and you don't want that.

How do you store binary data in a text file? Hexadecimal form will waste a lot of space. Even Base64 has a 4:3 ratio. Moreover, you would need to find (or write) a converter.

and also because:

You may start getting weird problems, such as the encoding issues.

Compilation may take more memory (depending on your language, framework and compiler),

Compile times may be affected (depending on your language, framework and compiler),

Start time and runtime memory footprint might be affected, although it shouldn't be assumed, but rather measured. Different languages, frameworks and compilers may perform differently.


问:
Use of underscores and earmuffs
I have seen underscores and earmuffs (like _good_ or *good*) frequently used in conversations among programmers. All I know is that underscores are used to denote private variables or methods in languages like C, Python etc. and  earmuffs are the preferred way of indicating that something is a global variable.

Do these have any other punctuational meaning when they are used outside code, in mailing lists etc? Does the highlighted word have any hidden meaning or expression added to it? Or, are they just like air quotes?

答:
It is just formatting for plain-text, very simple markup:

*something* smeans that text should be bold.

_something_ means underlined.

/something/ is italic.

And yes, the stack exchange formatter messes them up and makes bold and underscored italic, and /italic/ is nothing. :)

Title: Use of underscores and earmuffs


问:
Can BDD and Lean methodologies be used together?
I was chatting with my product manager last week and he was bemoaning the lack of progress on our product.  It's a fair criticism, too.  So we got to talking about to describe the writing of requirements.  I'm a big fan of BDD and using something like the Gherkin syntax to describe how the system should behave in terms of a user or actor.

He was pretty dismissive of BDD and said we should be using Lean methodologies like SBCE (set based concurrent engineering) and other stuff which I don't know a massive amount about given I've not read much on Lean practices so far.

Are these two methodologies mutually exclusive? If not BDD then there would need to be some other way of describing what the system should do.  Does Lean have its own language for requirements?

答:
To my understanding, Lean development intends to optimize the development process of your team, with the focus on balancing between quality, costs and time. It is an organizational method, which does not embrace a specific syntax, language or notation. BDD, however, has its focus on "building the right software", and getting the requirements right, by using a specific modeling and a specific form of testing - so BDD is a less an organizational, but more a technical approach. So if you want to take some notations, terms or testing methodology from BDD, this will not contradict Lean - BDD and Lean are somewhat orthogonal.

However, if you try introducing BDD and it turns out it will slow down your processes even more, don't be surprised when your manager in favor of a Lean development process might identify BDD as "waste" (in the Lean sense), and throws the BDD stuff out. So when you suggest BDD, be sure it aims at problems you really have in your team, and it is not just because you "are a big fan of BDD" - fanboyism is a big warning sign for most experienced managers. Since you did not tell us so far the reasons why the speed of progress does not meet your expectations, I cannot tell you if BDD is the right or wrong tool for your problem. But be careful not to attempt to use a technical solution for an organizational problem, that will most probably fail.


问:
Correctly disposing objects upon server termination
I am working on a large C++ project. It consists in a server that exposes a REST API, providing a simple and user-friendly interface for a very broad system comprising many other servers. The codebase is quite large and complex, and evolved through time without a proper design upfront. My task is to implement new features and refactor/fix the old code in order to make it more stable and reliable.

At the moment, the server creates a number of long-living objects that are never terminated nor disposed when the process terminates. This makes Valgrind almost unusable for leak detection, as it is impossible to distinguish between the thousands of (questionably) legitimate leaks from the "dangerous" ones.

My idea is to ensure that all objects are disposed before termination, but when I made this proposal, my colleagues and my boss opposed me pointing out that the OS is going to free that memory anyway (which is obvious to everybody) and disposing the objects will slow down the shutdown of the server (which, at the moment, is basically a call to std::exit). I replied that having a "clean" shutdown procedure does not necessarily imply that one must use it. We can always call std::quick_exit or just kill -9 the process if we feel impatient.

They replied "most Linux daemons and processes don't bother freeing up memory at shutdown". While I can see that, it is also true that our project does need accurate memory debugging, as I already found memory corruption, double frees and uninitialised variables.

What are your thoughts? Am I pursuing a pointless endeavour? If not, how can I convince my colleagues and my boss? If so, why, and what should I do instead?

答:
The key here is this:

While I can see that, it is also true that our project does need
  accurate memory debugging, as I already found memory corruption,
  double frees and uninitialised variables.

This pretty much directly implies that your codebase is cobbled together from nothing more than hope and string. Competent C++ programmers do not have double frees.

You absolutely are pursuing a pointless endeavour- as in, you are addressing one tiny symptom of the actual problem, which is that your code is about as reliable as the Apollo 13 service module.

If you program your server correctly with RAII, these issues will not occur, and the problem in your question will be eliminated. Plus, your code might actually execute correctly from time to time. Thus, it's clearly the best option.


答:
I would make this a comment if I could, but I can't so here goes:

One of the reasons C seems so ubiquitous is because it is one of the earliest languages developed, and an enormous amount of modern languages are based off of its structure (Java, Go, PHP, Perl, etc.) - making it seem like it's more places than it is.

Another oft-forgotten reason is that in 1973 Unix was rewritten in C and many of Unix's system calls are also available as C programs/functions, making the two highly interlinked. Since Unix was a powerful part of the development of modern programming as a whole, C was dragged along into infamy with it.

Having said all that, the answer to your question is "No". C is based off of a language called ALGOL, and there were many competitors both with ALGOL (FORTRAN, Lisp, COBOL) and C (none come to mind). Object-oriented programming, arguably the biggest paradigm-shift in programming design, did not originate with C - despite C++ being a very popular OOP language (it showed up first in Lisp or Simula 67, depending on who you ask). By the time OOP came about, C was such a popular language that it didn't need to be first - it was so popular that the C++ "expansion", so to speak, became one of the primary OOP languages too. It remains in modern use mainly because of its powerful memory control features (you can directly allocate and deallocate the memory your structures create), allowing it to create programs on tight memory budgets (think video games) and its highly optimized compiler (obviously depending on the compiler). Admittedly, even these features are losing ground as Java JIT compilation and in-language memory managers become more advanced.

Title: Is every language written in C?


问:
why "new" keyword is not contextual keyword?
Based on: C# Keywords

Keywords are predefined, reserved identifiers that have special meanings to the compiler.

and Based on: Contextual Keywords

A contextual keyword is used to provide a specific meaning in the code, but it is not a reserved word in C#.

For Keyword new  we have multiple situation for use it, for example:

```<code>//One situation for create an instance of class:
StringBuilder sr=new StringBuilder();

//Another situation for method hiding in polymorphism subject of OOP:
public new void Foo()
{
   //Some Code
}
</code>```

As you can see new keyword has Several meaning Depending on where it's used, then in my openion new must considered as Contextual Keyword and not keyword!

then, the Definition of Contextual keyword is wrong? or considering new as whole keyword? and why?

答:
The question is not how many meanings it has, but whether or not it's reserved.

When Microsoft adds new features to C#, it sometimes need to add new keywords. This can compromise backward compatibility, since it invalidates old code that declares identifiers with the same name. To prevent this, Microsoft makes these new keywords contextual - they only serve as keywords when placed in specific places, places where you can't normally put identifiers.

So - async is a contextual keyword because older code might have declared a variable named async.

new was there from day one, so it doesn't have this problem - if your code declared a variable named new it wouldn't work even in the first version of C#. Therefore, there is no backwards compatibility issue here and new can be a regular keyword.


问:
Reflection performance in this iteration of a (probably) large excel file
I'm wondering the performance of reflection in this situation. I'm iterating a (probably) large excel file (let's say 3000 max) which it's going to be done from time to time, and the implementation that my mate is something like this, iterating each row:

```<code>            while (cells.hasNext()) {
                XSSFCell cell = (XSSFCell) cells.next();
                String cellData = this.getCellData(cell);
                if (cellData.trim().isEmpty()) {
                    break;
                }
                Field field = RowPrestacionVO.class.getField(fields.get(idx));
                field.set(vo, cellData);
                idx++;
            }
</code>```

Is there any probability that I'm going to have some performance issues iterating like that?

答:
While reflection is slow, doing it a handful of thousand times while processing a file will probably not be an issue: the file access is likely to be slower still.

Still, you should be able to improve the performance of the code you posted by moving the initiation of ' field' outside of your loop.


问:
What Are Some Advantages/Disadvantages of Using C over Assembly?
I'm currently studying engineering in Telecommunications and Electronics and we have migrated from assembler to C in microprocessor programming.  I have doubts that this is a good idea.  What are some advantages and disadvantages of C compared to assembly?

The advantages/disadvantages I see are:

Advantages:

I can tell that C syntax is a lot easier to learn
than Assembler syntax.

C is easier to use for making more complex programs.

Learning C is somehow more productive than learning assembler cause there is more developing stuff around C than Assembler.

Disadvantages:

Assembler is a lower level programming language than C,so this makes it a good for programming directly to hardware.

Is a lot more flexible alluding you to work with memory,interrupts,micro-registers,etc.

答:
Relatively good for programming efficiency.

It is easy to program using c language rather than using assembly.

C language can be quite faster than assembly language.

It is possible to write assembly in C code but not C in assembly code.


问:
Are there programming languages that support both static and dynamic typing?
Being either static or dynamic should be something completely supported in the language. Static vs dynamic shouldn't be something that you have to turn on and off, switching between basically 2 languages.

I'm talking full blown mixed typing madness like this thing:

```<code>class MyClass {
  function myMethod(x: int, y: int){        # one parameter is typed, the other not
    return <cast_to_int> y.return_integer(x); #casting to guarantee the contract
  }
}

MyClass static_obj = MyClass();  #statically typed instantiation;
var dynamic_obj = {};   #dynamically typed instantiation
dynamic_obj.return_integer = (function (x) {return x*2}) #dynamic method creation

static_obj.myMethod(3, dynamic_obj)     # This returns 6

dynamic_obj.return_integer = (function (x) {return x+1}); # dynamic member reassignment

static_obj.myMythod(3, dynamic_obj)   # this returns 4

static_obj.myMethod('asdf', dynamic_obj) # This can't compile, because of typing

# and also this crazy thing; Notice that the static interface of the method is respected
if (<user input> == 2){
    static_obj.myMethod = (function (x: int, y){return x + y.yet_some_other_method(x);})
}

# but when the static contract is not respected, it doesn't compile
static_obj.myMethod = (function (a, b, c) {return 'asdf'}) # Compile time error
</code>```

I'm interested in this topic because I really like that API discoverability in static languages is great (thing i liked about Java, C# and ABAP for a while), but I also like testing stuff at run time, monkey patching, REPLs, reassignment, and crazy reflection magic (which I liked about JavaScript and Python).

I'm aware of Dart's static type checker, but that's not enough, because it provides no actual static guarantees.

I'm also not interested in type inferrence. I want true static running next to true dynamic behavior. I also am aware that I can use mapping types like python's dict, or any JS object, or Java's HashMap) to pass around data  (or even functions), but Java's mappings can't carry methods in them, Python's dicts can't (out of the box) have methods in them, and even though JS simply laughs at any kind of static restrictions - adding methods at runtime that DO get access via the this keyword to the context object is something really cool (I know Python does it too, when adding functions on the class object, but NOT on class instances).

My curiosity was also sparked by this paper:
Static typing where possible, dynamic typing where needed

And the API discoverability argument came from my own experience, but this paper seems to support it:
http://personales.dcc.uchile.cl/~rrobbes/p/ICPC2014-idetypes.pdf

答:
Classic Visual Basic and VBA has had this ability from day one.

VB.NET also had this ability from release (1.0) with the option to "switch it off" using Option Strict On statement at the top of the code file or project wide in the project properties. This doesn't actually switch it off as such it just won't compile a late binding statement when this is on.

C# eventually caught up some time later in version 4.0 with the difference that you have to "allow" it by using the dynamic keyword.


问:
Disadvantages of Pointers
I was wondering why pointers are not included in modern languages now-a-days. I already did research on this on internet, and found out few theories/reasons:

Memory leakage is the biggest concern while using pointers.

If not handled properly it may ruin whole project or application.

Understanding and using pointers in best way possible requires a lot of time.

Well there are few problems but if some work is done properly on pointers i.e., exception handling etc. I think pointers can still be very helpful where required. Kindly help me out on this one.

答:
I'm not sure where you get the idea that modern languages don't have pointers. In Ruby, for example, everything is a pointer. It's true that Ruby doesn't have special syntax or special operations for pointers, but that doesn't mean that there are none. Quite the opposite, in fact: because everything is a pointer, there is no need to distinguish between pointers and non-pointers, pointer operations and non-pointer operations. Pointers are so deeply ingrained in the language that you don't even see them.

The same is true for Python, Java, ECMAScript, Smalltalk, and many other languages.

What those languages don't support, is pointer arithmetic or fabricating a pointer out of thin air. But then again, some CPUs don't allow that either.

The original CISC CPU for the AS/400 distinguishes between pointers and integers. You can store pointers and you can dereference pointers, but you cannot create or modify pointers. The only way to get a pointer is if the kernel hands one to you. If you try to do arithmetic on it, you get back an integer, which cannot be converted to or used as a pointer. Even the modern PowerPC  and POWER CPUs have a special tagged address mode specifically for running OS/400 / i5/OS / IBM i.

Go has pointers in the more traditional sense, like C. But it also doesn't allow pointer arithmetic.

Other languages have pointers and pointer arithmetic, but a set of restrictions that ensure that pointers are always valid, always point to initialized memory, and always point to memory that is owned by the entity performing the arithmetic.

Title: Disadvantages of Pointers


问:
How could I avoid singletons in this case?
Using Dart in the client part of a web app where I have an application manager that contains a List of application instances and references to services that are used by each application as in the following diagram

As you can see the application manager is a singleton, so are the services that it contains which are used by all apps, to me it makes sense because

I need to have only one instance of the ApplicationManager and each
service

Easier to access services without the need to pass references

I need to preserve the state of each service

Almost all services have a cache

I found ways to avoid having the services as singletons which is by making them private to the library which is a feature in dart, so I initialize the services only once from the application manager, but I can't make the ApplicationsManager private because its at the top most level of the library, I would appreciate your thoughts for a way to avoid having the application manager as a singelton.

答:
i need to have only one instance of the ApplicationManager and each service

Then create one instance. shrug

easier to access services without the need to pass references

Then provide a global variable to access that one instance you created previously. If you don't like global variables for this, you can't like singletons, because singletons share all the same drawbacks, but are somehow more complex. In that case, just pass things along to whatever needs it.


问:
Retry method for generating unique code
In an app, a user can initiate the generation a six-digit alphanumeric code (actually done via Web API). The code needs to be checked against a remote database to ensure it is unique. Other than for diagnostics or logging, the DB table is only used by the Web API and an Azure web job that cleans out expired codes.

In my tests, collisions occurred on average only one in ~24K times with a high of 85K and a low of 170. It is the latter that concerns me. Although the table is emptied of expired codes daily, at some point there will be a collision. Although unlikely, it could happen with very few records in the table.

It is worth noting that because of exterior requirement, the code is limited to six characters from AEFGHJKLPQRSTUWXYZ123456789.

A simplistic solution would be to keep running the generation/check until a unique code is created. In all likelihood, this would only mean 1-2 iterations. But there's no guarantee. And certainly it can't run unfettered.

The next step would be to put a limit - say 5 tries - through a simple loop. This may be enough of a solution. Despite concern that the user would be frustrated if it ultimately fails, if it does there's probably enough wrong with the overall system to ruin the user experience anyway.

I have good exponential backoff code so although this is not a network issue (also a concern), it may help to incorporate it into the retry scheme. In fact, that might be a nice catch-all solution. Given 5 increasing temporal delays in retrying, it would allow both enough chances for the logical code to exceed the chances of a collision and mitigate introducing more stress on network resources.

Any suggestions/observations would be appreciated.

FYI, this is the code used to generate codes:

```<code>    /// <summary>
/// Generates a randomized alphanumeric code
/// </summary>
/// <param name="strLength">e.g. 6 chars</param>
/// <param name="charSet">e.g. AEFGHJKLPQRSTUWXYZ123456789</param>
/// <returns>string of the specified length</returns>
public static string GenerateCode(int strLength, string charSet)
{
    var chars = charSet.ToCharArray();
    var data = new byte[1];
    var crypto = new RNGCryptoServiceProvider();
    crypto.GetNonZeroBytes(data);
    data = new byte[strLength];
    crypto.GetNonZeroBytes(data);
    var result = new StringBuilder(strLength);
    foreach (var b in data)
    {
        result.Append(chars[b % (chars.Length)]);
    }
    return result.ToString();
}
</code>```

答:
Lets think about your different six-digit codes. You can generate (26 (for alpha) + 10 (for numeric))^6 = 2176782336 different entries. Lets now step into the birthday paradoxon if you have sqrt(2176782336) = 46656 (36^3) elements already in your list, you will have a 50 percent chance to find a duplicate for each new try. Since you are filling the list on the server, it will be harder for the client to find a non-used-code.

If you will not reach 46656 elements within a day, you have very good chances, to use up to 4 tries. But if you come closer to the 46K-barrier, you will have to increase the retry count. If you want lesser probable collisons use more digits or more characters 25 for lower case (omit l) and 24 (Omit O and I) for upper case and 10 for numbers this will increase your 50 Percent barrier to 205379 (59^3).

on the server side you will experience the so called Coupon collectors problem
Analogoue to the problem, that the clients are try to give you (the server) coupons you do not already have...

hth.

Title: Retry method for generating unique code


答:
You can use a table with an auto-incrementing id as the basis for your code.  If need be, start the increments at 100,000 for 6 digits.  Insert a row, get the id, and return it.  It will be guaranteed to be unique.

Depending on your expected usage levels, you might consider tacking on a few random letters to the id.  So that code '1234' becomes '1234AB'.  This makes it more difficult to stumble upon other people's codes.

You can also implement the above as a lookup-table.  Fill a table with suitable codes, and return the corresponding one based on the auto-incremented id.

Title: Retry method for generating unique code

Body:
In an app, a user can initiate the generation a six-digit alphanumeric code (actually done via Web API). The code needs to be checked against a remote database to ensure it is unique. Other than for diagnostics or logging, the DB table is only used by the Web API and an Azure web job that cleans out expired codes.

In my tests, collisions occurred on average only one in ~24K times with a high of 85K and a low of 170. It is the latter that concerns me. Although the table is emptied of expired codes daily, at some point there will be a collision. Although unlikely, it could happen with very few records in the table.

It is worth noting that because of exterior requirement, the code is limited to six characters from AEFGHJKLPQRSTUWXYZ123456789.

A simplistic solution would be to keep running the generation/check until a unique code is created. In all likelihood, this would only mean 1-2 iterations. But there's no guarantee. And certainly it can't run unfettered.

The next step would be to put a limit - say 5 tries - through a simple loop. This may be enough of a solution. Despite concern that the user would be frustrated if it ultimately fails, if it does there's probably enough wrong with the overall system to ruin the user experience anyway.

I have good exponential backoff code so although this is not a network issue (also a concern), it may help to incorporate it into the retry scheme. In fact, that might be a nice catch-all solution. Given 5 increasing temporal delays in retrying, it would allow both enough chances for the logical code to exceed the chances of a collision and mitigate introducing more stress on network resources.

Any suggestions/observations would be appreciated.

FYI, this is the code used to generate codes:

```<code>    /// <summary>
/// Generates a randomized alphanumeric code
/// </summary>
/// <param name="strLength">e.g. 6 chars</param>
/// <param name="charSet">e.g. AEFGHJKLPQRSTUWXYZ123456789</param>
/// <returns>string of the specified length</returns>
public static string GenerateCode(int strLength, string charSet)
{
    var chars = charSet.ToCharArray();
    var data = new byte[1];
    var crypto = new RNGCryptoServiceProvider();
    crypto.GetNonZeroBytes(data);
    data = new byte[strLength];
    crypto.GetNonZeroBytes(data);
    var result = new StringBuilder(strLength);
    foreach (var b in data)
    {
        result.Append(chars[b % (chars.Length)]);
    }
    return result.ToString();
}
</code>```


答:
For assembly there's an unavoidable compromise between code maintainability and performance. You can write easy to read/maintain assembly, or you can write highly optimised code; but you can not do both.

For C, the compromise doesn't quite disappear, but it's far less noticeable - you can write easy to read/maintain C that is reasonably well optimised.

An excellent assembly language programmer will be capable of beating the compiler almost all of the time, but most of the time they will deliberately choose to write easy to read/maintain code instead; and therefore an excellent assembly language programmer will be beaten by a compiler most of the time.

The smart way is to use both assembly and C (instead of only assembly or only C) - e.g. use C for parts of the code where an excellent assembly language programmer would've chosen to write maintainable/slow code, and use assembly for the remainder (where "highly optimised and hard to maintain" is actually justified).

Title: What Are Some Advantages/Disadvantages of Using C over Assembly?

Body:
I'm currently studying engineering in Telecommunications and Electronics and we have migrated from assembler to C in microprocessor programming.  I have doubts that this is a good idea.  What are some advantages and disadvantages of C compared to assembly?

The advantages/disadvantages I see are:

Advantages:

I can tell that C syntax is a lot easier to learn
than Assembler syntax.

C is easier to use for making more complex programs.

Learning C is somehow more productive than learning assembler cause there is more developing stuff around C than Assembler.

Disadvantages:

Assembler is a lower level programming language than C,so this makes it a good for programming directly to hardware.

Is a lot more flexible alluding you to work with memory,interrupts,micro-registers,etc.


问:
Is every language written in C?
Sometimes while programming in different languages (C/C++, C#), this thought comes to my mind:

Is each and every language written in the C programming language?

Is the C language the mother/father of all languages?

Is each concept (OOP, etc.) all implemented in C?

Am I in right direction?

答:
Obviously not. How could the first C compiler be written in C if C wasn't exist before? This isn't the chicken and the egg problem.

There are many ways to write the first compiler of a language which are called bootstrapping

Moreover most compilers try to achieve self-hosting, or compile itself it its language, mainly to promote the language and the compiler itself

Title: Is every language written in C?


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

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

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

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

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

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

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

答:
Consider following the Functional Staff Organization pattern. This would speak towards your second option of splitting the team by software product.

To quote the article in your context:

The greatest strength of a functional organization is that it ties social structures to delivery of business value. In my view software projects succeed as much as they improve the effectiveness of the activity they support - yielding business value. By organizing your teams the same way, you have a team oriented around satisfying their business users.

The actual management/HR structure is irrelevant beyond that.

Title: How to structure a development team


答:
If you can easily identify where the objects that should survive indefinitely are allocated, once possibility would be to allocate them using an alternative allocation mechanism so that either they don't show up in a valgrind leak report or just appear to be a single allocation.

In case you're not familiar with the idea, here's an article on how to impotent custom memory allocation in c++, although note that your solution could well be simpler than the examples in that article as you don't need to handle deletion at all!


问:
What is the value of workflow tools?
I'm new to Workflow developement, and I don't think I'm really getting the "big picture". Or perhaps to put it differently, these tools don't currently "click" in my head.

So it seems that companies like to create business drawings to describe processes, and at some point someone decided that they could use a state machine like program to actually control processes from a line and boxes like diagram. Ten years later, these tools are huge, extremely complicated (my company is currently playing around with WebSphere, and I've attended some of the training, its a monster, even the so called "minimalist" versions of these workflow tools like Activiti are huge and complicated although not nearly as complicated as the beast that is WebSphere afaict).

What is the great benefit in doing it this way? I can kind of understand the simple lines and boxes diagrams being useful, but these things, as far as I can tell, are visual programming languages at this point, complete with conditionals and loops. Programmers here appear to be doing a significant amount of work in the lines and boxes layer, which to me just looks like a really crappy, really basic visual programming language.

If you're going to go that far, why not just use some sort of scripting language? Have people thrown the baby out with the bathwater on this? Has the lines and boxes thing been taken to an absurd level, or am I just not understanding the value in all this?

I'd really like to see arguments in defense of this by people that have worked with this technology and understand why its useful. I don't see the value in it, but I recognize that I'm new to this as well and may not quite get it yet.

答:
Below statements are my personal experience using workflow tools, specifically Oracle BPM Suite(10.3G & 11G). First to specify, your question is focusing on workflow tools which are enabling modeling executable process models, these tools are part of Business Process Management Systems(BPMS). This specific process modeling is definitely developing and you can refer to it as a visual programming language.

The main benefit is the agility of understanding and changing process logic

With business process models you cover a visual explaination of the process logic and at the same time an executable integrative component. This allows faster on-and offboardings of programmers, because less documentation on the transitions, conditionals(Gateways or Business Rules) and process flow in general has to be documented, since its part of the development.

Additionally you have attached reporting/monitoring capabilities, what you would have to develop individually per each application, which is covered by most BPMS.

Moreover in most BPM development environments service adapters are prebuilt(e.g. JMS, Web Services, JDBCs etc.), allowing to develop middleware solutions faster in a step by step interactive integration, reducing human errors in coding.

Following workflow platform does achieve a lot of benefits mentioned above - Platform based approach for automation of workflows

Title: What is the value of workflow tools?


问:
Is there a stronger stress on management than on technical education in recent years?
In my working environment, over the past few years I have observed an increasing stress on developer management and self-management over technical education.

For example, at work I hear lots of discussions about software development processes, about ways to handle software specifications, e.g. through automatic tests, and so on. I hear less discussions about programming concepts / techniques like data structures, lazy evaluation, memoization, and so on.

To give another example, if I asked a colleague how he would manage the complexity of a certain problem, I would expect that he'd indicate me some solution approach (try to solve a subproblem first, identify subtasks) instead of suggesting a programming abstraction (try using pattern X).

Is it just something specific to my working environment or there is a general trend towards management / work organization and away from the more conceptual aspects of programming?

To make my question specific (and answerable), are there any authors or modern schools of thought that consider organizational aspects more important than educational ones for improving developer productivity?

答:
It is part of a general awakening (or maturing) of software engineering.

You can read about this maturing process in No Silver Bullet. Although written several decades ago, its observations still hold true today. At different times in history, various programming paradigms, techniques, methodologies, or management styles were hailed as the "silver bullet" in the sense that it can solve all problems.

A more commercial spin on this "no silver bullet" is known as the Hype Cycle. This is a thesis brought forward by the advisory firm Gartner for explaining the development, maturity and adoption status of some technologies or methodologies, i.e. various things which had been hailed as the silver bullets in the past.

Two examples of where silver bullets don't work:

(1)

A programming paradigm is widely touted as being able to solve a particular type of software requirements, because theoretically source code that is written with this paradigm had certain properties, and these properties will make meeting the said type of software requirements very easy.

It won't work if in reality, no software that makes use of this paradigm to solve that type of software requirements exist. What the theory predicts should have existed, may not exist in the real world, unless one or more companies succeeded in making it happen.

(2)

A software architecture is widely touted as having certain desirable characteristics for a certain industry.

A company tries to use this software architecture for this industry, but faces a problem: this company has a large existing code base, and this existing code base doesn't seem to be compatible or portable to this new software architecture.

A silver bullet that seems to work industry-wide may not be suitable for some particular companies due to individual circumstances.