答:
because 0 in the chosen representation (2's complement) is a sequence of 0s, applying the bitwise NOT on it will naturally result in a sequence of 1s

1 is a sequence of 0s followed by a single 1

Remember that a computer will use all bits available to represent a number in a variable. In other words if you have a 64 bit variable then all 64 bits will be in use even if 90% of them are 0.

Title: Why is ~0 a Sequence of 1s

Body:
Why is ~0 a sequence of 1 bits and not just a single bit? Where do the extra 1 bits come from? Does this mean ~1 a sequence of 0 bits or just a single 0 bit?

My understanding was that the ~ operator is applied on the specific bits mentioned.


问:
Is rapid prototyping incompatible with software requirements specification?
From what I've learned last term on SWE courses, a big part of it is writing documents, so it seems that a software requirements specification (SRS) should earn points for my end-of-course project.

However, I will be more comfortable if I use prototyping, i.e., I make a small thing that works for the most trivial of situations and gradually add up features and improvements. LVS 68:1996 doesn't seem to recommend mixing these two things together.

Is it possible to still maintain my preferred approach to development, and have some usable requirement specification document?

答:
If you don't know what you are doing, then the last thing you should do is write a requirements spec, as all that will give you is a requirements spec written by someone who doesn't know what they are doing.

Maybe someone else knows what they are doing - if so, they should write the spec. If not, you have to learn what needs to be done. And for this it makes little difference whether its a new activity that literally noone knows how to do, or there theoretically is someone who could tell you, but you don't have the budget to pay them to spend time doing so.

The problem with requirements specification as as a learning activity is that it doesn't give any feedback as to whether what you have specified is right or wrong. There is no such thing as a requirements compiler or test tool that comes back and says 'this is wrong, it makes no sense, doesn't solve the problem, or noone will like it'.

Exploratory prototyping is one technique that suits some people as a means of learning enough about a domain to write a useful requirements spec. But you shouldn't assume it will be the best in any particular case without considering alternatives. And you certainly shouldn't be expecting to get much use out of any software produced as a byproduct of that learning process, any more than you should expect to be able to sell the notes you made in class for some fraction of the price of a university education.

ContentLicense: CC BY-SA 3.0


问:
How to learn to make better estimates?
I suck at estimates. When someone asks me how long something will take, I don't even dare to make a guess since I will be completely off the mark. Usually I'm way too optimistic, and should probably multiply my guess with some large X factor...

How can I learn to make better estimates? It's not taught at my uni, and even though we have deadlines for all laborations I never think about how long something will actually take. Which I should. For everyone's sake (especially mine).

答:
The formula that works when working for myself :

do a break down of todo's to a 1 - 4 hour granularity. I find that i'm usually accurate with these

the 'unknowns factor': Multiply by a factor of 2 raised to number of unknowns. I.e. if you are to develop a couchdb applicaiton, but do now know anything about javascript and http .. add 2 ^ 2 as mult factor.

context-switch-factor : multiple by 1.5 if you will work in perfect environment( at home in study corner etc ) , or 2.5 if you will work in imprefect environment ( office / crowded place etc )

I find this to be within +/- 20% of actual time taken !!

ContentLicense: CC BY-SA 2.5

Title: How to learn to make better estimates?


问:
How should my AngularJS "wizard" be structured?
For brevity's sake, consider the following scenario:

Part of my application is a wizard for bringing on new clients and it's a dynamic page. One step contains billing information, another step is setup information, etc. Because it's one page, in my mind I have one controller for the entire wizard, but that also means I have models and functions for each step in one controllername.js file in addition to using a bunch of ng-show directives to "show" steps. This doesn't feel quite right..have I overlooked something in the docs?

Edit:

To exapnd a bit, I feel like I'm violating the SRP and I feel dirty.

答:
You can have a controller for each step, but then you would need a way to share state between your controllers. You could use different strategies for this, like

an stateful angular service

angular $cacheFactory

angular session $cookies/$cookieStore.

Your first step do its work and put its data in this shared structure (session) and then you forward the user to the next step, which in turn, checks the existence of the data in the session or otherwise takes the user back to step 1. Then every step updates the data in the session object and at the end you simply destroy/remove the data from the session when no longer needed.

OwnerDisplayName: sean

OwnerDisplayName: edalorzo


问:
Fail-fast design
I recently tend to design my methods in the following way:

```<code>if ( 'A' === $a ) {
    if ( 'B' === $b ) {
        return 'some thing';
    } else if ( 'C' === $c ) {
        return 'some other things';
    }
}

/* If you made it up to here, then something has gone wrong */
return false;
</code>```

So basically the idea is to check if the first condition is correct, if it is then continue until you reach the first return statement to return the expected result, if not, move on to the next condition and so on.

The key is that all the method's functionality has already shrunken down and wrapped up in a conditional statement piece by piece, so you should meet at least one condition to take a useful action or if you reach the very last line, then it will return false, that means none of the expected conditions were met, that in my design it means the input wasn't in a proper or expected format, data-type, range, etc. so the method were not able to continue processing that.

I can achieve the same goal in a couple of different ways, but this one seems to be cleaner as I generally need to write code only for positive conditions (I actually don't know how should I call it) -- unless I need to take a specific action if a certain condition haven't met. And in the end I will get false if the method wasn't able to accomplish its job -- with real conditions in place most of the time it's almost like a jump to the end of method when you can't pass through an if statement. It's actually designed in a way that you will either pass this if and will heading to the either next if or a return statement or you are very unlikely to match any other if statements and will jump directly to the last return false statement.

Now, my questions are:

Is it a (true) fail-fast design, which in this case is only looking for the proper condition to continue and is willing to fail as soon as one fails. Is that correct or am I mixing up things here? If not, is there any specific term for that?

Also as I recently generalized this approach for all the new methods I create, I wish to know if there is any drawback or design flaw here that might bite me back later.

答:
A Fail-fast design is really the same structure but with reverse order to avoid the arrowhead code.

A fail fast design would be:

```<code>if ( 'A' !== $a )
    return false;

if ( 'B' === $b ) {
    return 'some thing';
}
if ( 'C' === $c ) {
    return 'some other things';
}
return false;
</code>```

Less indentation is a good thing.

Title: Fail-fast design

Body:
A Fail-fast design is really the same structure but with reverse order to avoid the arrowhead code.

A fail fast design would be:

if ( 'A' !== $a )
    return false;

if ( 'B' === $b ) {
    return 'some thing';
}
if ( 'C' === $c ) {
    return 'some other things';
}
return false;

Less indentation is a good thing.


答: Regarding your second question, my 2 cents are that your methods should not return anything if the input was not in the correct/expected format. Don't be afraid to use exceptions for expressing something like 'i cannot work with this input'.</p>

Title: Fail-fast design

Body:
I recently tend to design my methods in the following way:

```<code>if ( 'A' === $a ) {
    if ( 'B' === $b ) {
        return 'some thing';
    } else if ( 'C' === $c ) {
        return 'some other things';
    }
}

/* If you made it up to here, then something has gone wrong */
return false;
</code>```

So basically the idea is to check if the first condition is correct, if it is then continue until you reach the first return statement to return the expected result, if not, move on to the next condition and so on.

The key is that all the method's functionality has already shrunken down and wrapped up in a conditional statement piece by piece, so you should meet at least one condition to take a useful action or if you reach the very last line, then it will return false, that means none of the expected conditions were met, that in my design it means the input wasn't in a proper or expected format, data-type, range, etc. so the method were not able to continue processing that.

I can achieve the same goal in a couple of different ways, but this one seems to be cleaner as I generally need to write code only for positive conditions (I actually don't know how should I call it) -- unless I need to take a specific action if a certain condition haven't met. And in the end I will get false if the method wasn't able to accomplish its job -- with real conditions in place most of the time it's almost like a jump to the end of method when you can't pass through an if statement. It's actually designed in a way that you will either pass this if and will heading to the either next if or a return statement or you are very unlikely to match any other if statements and will jump directly to the last return false statement.

Now, my questions are:

Is it a (true) fail-fast design, which in this case is only looking for the proper condition to continue and is willing to fail as soon as one fails. Is that correct or am I mixing up things here? If not, is there any specific term for that?

Also as I recently generalized this approach for all the new methods I create, I wish to know if there is any drawback or design flaw here that might bite me back later.


问:
Ruby on Rails database using static lookup tables or constant strings
In some ruby on rails projects, I have seen instances where strings are used instead of a foreign key reference to a lookup table.

I usually code in C#/SQL Server and use lookup tables, but am not particularly experienced in ruby on rails.

So my question is, should I be using strings instead of lookup tables in my ruby on rails web project (mysql and active record)? Is this something specific to ruby on rails, or to dynamically typed languages? Or for some particular circumstances? Or is it just bad database design?

By lookup tables I mean, like the following

UserStatus

```
Id    Name
1     Active
2     Disabled
```

User

```
Id    Username               UserStatusId
1     john.smith@gmail.com   1
1     jane.smith@gmail.com   2
```

Whereas with just strings

User

```
Id    Username               UserStatus
1     john.smith@gmail.com   active
1     jane.smith@gmail.com   disabled
```

答:
[EDIT] Ruby on Rails 4 enums

Rails 4 supports enums, so you can declare an enum attribute where the values map to integers in the database, but can be queried by name.

```<code>class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
end

conversation.archived!
conversation.active? # => false
conversation.status  # => "archived"

Conversation.archived # => Relation for all archived Conversations

Conversation.statuses # => { "active" => 0, "archived" => 1 }
</code>```

Rails 3 and older

You could implement something like this:

```<code>USER_STATUS_VALUES = { 1 => :active, 2 => :disabled }

class UserStatus
  attr_reader :status_id

  def status
    USER_STATUS_VALUES[@status_id]
  end

  def status=(new_value)
    @status_id = USER_STATUS_VALUES.invert[new_value]
    new_value
  end
end
</code>```

You would use it like this:

```<code>my_status = UserStatus.new

my_status.status = :new
puts "status: #{my_status.status}"
puts "status_id: #{my_status.status_id}"
</code>```

Will return:

status: new

status_id: 1

Note:
I could have used 'active' instead of :active but in this case, use of symbols is more appropriate.

Body:
[EDIT] Ruby on Rails 4 enums

Rails 4 supports enums, so you can declare an enum attribute where the values map to integers in the database, but can be queried by name.

class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
end

conversation.archived!
conversation.active? # => false
conversation.status  # => "archived"

Conversation.archived # => Relation for all archived Conversations

Conversation.statuses # => { "active" => 0, "archived" => 1 }

Rails 3 and older

You could implement something like this:

USER_STATUS_VALUES = { 1 => :active, 2 => :disabled }

class UserStatus
  attr_reader :status_id

  def status
    USER_STATUS_VALUES[@status_id]
  end

  def status=(new_value)
    @status_id = USER_STATUS_VALUES.invert[new_value]
    new_value
  end
end

You would use it like this:

my_status = UserStatus.new

my_status.status = :new
puts "status: #{my_status.status}"
puts "status_id: #{my_status.status_id}"

Will return:

status: new

status_id: 1

Note:
I could have used 'active' instead of :active but in this case, use of symbols is more appropriate.


问:
Branch twice for unique condition
Consider an application that displays only Foobars belonging to themselves to normal users, and all Foobars to admins:

```<code>-- Normal users:
SELECT * FROM Foobar WHERE user_id=:user_id;

-- Admins:
SELECT * FROM Foobar;
</code>```

Currently, this how the queries are represented in the codebase:

```<code>$sql = "SELECT * FROM Foobar";

if ( $user['type']!='admin' ) {
    $sql.= ' WHERE user_id=:user_id';
}

$stmt = $pdo->prepare($sql);

if ( $user['type']!='admin' ) {
    $stmt->bindValue(':user_id', $user['id']);
}
</code>```

I do not like this dual-branching approach from a maintainability standpoint. For instance, a bug like typing $user['type']=='admin' instead of $user['type']!='admin' would have to be found and fixed in two places instead of one. However, I also don't like the idea of separate functions for each case: admins and regular users.

A third approach would be to branch once and there create the SQL to add and the values to bind:

```<code>$sql_to_add = '';
$array_to_bind = array();

if ( $user['type']!='admin' ) {
    $sql_to_add = ' WHERE user_id=:user_id';
    $array_to_bind = array( ':user_id'=>$user['id'] );
}

$sql = "SELECT * FROM Foobar {$sql_to_add}";
$stmt = $pdo->prepare($sql);

foreach ( $array_to_bind as $k=>$v ) {
    $stmt->bindValue($k, $v);
}
</code>```

However I find this approach cumbersome. Is there a design pattern for this situation? What is the canonical way to handle situations where the code must branch in two separate locations on the same if condition?

答:
This may sound trivial, but I would simply create a variable holding the condition to be tested twice

```<code>$is_normal_user = $user['type'] != 'admin';
</code>```

and then use that variable in the if checks. This not only makes the code more readable and easier to maintain (the variable name describes what the check is supposed to do, avoiding confusion about == vs !=), but can also improve performance in case the check is more complex.

Title: Branch twice for unique condition

Body:
This may sound trivial, but I would simply create a variable holding the condition to be tested twice

$is_normal_user = $user['type'] != 'admin';

and then use that variable in the if checks. This not only makes the code more readable and easier to maintain (the variable name describes what the check is supposed to do, avoiding confusion about == vs !=), but can also improve performance in case the check is more complex.


问:
What is the general tech news website every programmer should read?
A link and a quick explanation why would be very helpful.

General tech news, I mean not like InfoQ which is too technical. Probably much more like P.SE than SO.

EDIT: site should help developers gain general knowledge about the industry, technologies, inventions, etc. Much like when we listen to the news every morning in our car to know what is happening in our world. But target audience must be either programmmers, geeks or any other persons interested in technology.

答:
Much like when we listen to the news every morning in our car to know what is happening in our world.

Sometimes when presented with a newspaper, I like to skip to the funnies.  On those days, the clear choice is thedailywtf.com


问:
How to integrate a second programmer to a startup
I'm the technical founder of a startup and I'm currently looking to hire a second developer for our product.

Since I've been the sole developer, there is no formal organization for the project and I wanted to know what would be the minimum organization required to incorporate this second developer.

Right now the code only under source control (a kind of chaotic git repo) but it lacks unit tests and other things that are required for serious development.

I was willing to go without those for a while for the sake of speed, but now that the company is growing, we feel that delaying those might be problematic.

How to incorporate this second person to work with the code?

答:
First, congratulations on your expansion and thank you for hiring another developer.

Focus on hiring the best programmer you can find as soon as possible. There is an exhaustive list of things you could do to help incorporate this new developer, but I think you risk delaying the hire. This person will need to spend time getting familiar with things, so why not involve him or her in the process? When you're part of the cleanup process, you know where you put things.

When you finally hire someone, try to keep track, organize and document everything you do to get this new dev up and running. This is the perfect time to discover what the new person needs to know. Examples.

Getting a development machine configured.

Diagram basic structure of the app

Coding Standards (There's got to be something you do consistently.).

Source Control

Tests

Planning and Estimation

You'll come up with more as the new programmer gets close to writing production code.

This way you don't waste too much time on things that aren't needed. It's tough to predict at first and we all know something will be left out.

Getting your second dev up to speed, may not be as smooth as you like, but don't sacrifice the hiring of the 3rd, 4th and 5th. If you need more programmers, you know your business is getting to a critical success point, so you want to make sure your team is ready to grow.


答: I recommend that the new developer actually write the unit tests that the code currently lacks. This will help him get up to speed about what the extant parts of the code do, and it will keep you on development in the meantime.

Title: How to integrate a second programmer to a startup

Body:
I'm the technical founder of a startup and I'm currently looking to hire a second developer for our product.

Since I've been the sole developer, there is no formal organization for the project and I wanted to know what would be the minimum organization required to incorporate this second developer.

Right now the code only under source control (a kind of chaotic git repo) but it lacks unit tests and other things that are required for serious development.

I was willing to go without those for a while for the sake of speed, but now that the company is growing, we feel that delaying those might be problematic.

How to incorporate this second person to work with the code?


问:
At what stage of an Open Source project should you invite contributions from the community?
I've been wondering about getting contributions to a new open source product my team will be developing.  There's encouragement for us to get as much support from the wider community as we're able, but I can also see this absorbing a lot of time making sure that 3rd parties located outside our office are on track regards things like code quality.  Also at the start of the project we're likely to have a lot of informal discussions within the core team regarding design of the system, spikes etc. and taking these online to allow community involvement will be time consuming and I can imagine could make the discussion less effective.

There is a more human side to this which probably needs to be considered: allowing community involvement in the design process may also have its benefits regards perceived ownership of the project, and there's always a chance that early involvement could pick up on problems that the core team haven't noticed.

So the question: at what stage of an Open Source project should you invite contributions from the community?

答:
I agree with Martijn Verburg. You should start soliciting contributions right from the start. I wrote a little about this before.

The summary of that post is that software rots. If you want to keep it fresh, you have to do maintenance. And the more popular a project gets, the more bugs are going to be found, the more features are going to be added, and the more this maintenance task is going to bog you down.

In fact, this is a very common problem. There's a great talk by Fat called What Is Open Source & Why Do I Feel So Guilty? In this talk (which I highly recommend you watch) he tells the story of one of his OSS projects, and how over time, he found himself spending most of his free time doing ticket triage and management tasks. And he talks about how damaging this was. Which is something I can completely empathise with.

The solution, of course, is to add people to the project early and often. Your time is limited, and valuable. Invest it in growing your contributor base, and the rest of your problems start to take care of themselves.

As I say at the end of my post: "What is more important for your project: features or a future? Pick one, and prioritise your efforts accordingly."


问:
Did the gradual shift in methodology of writing code affect system performance? And Should I care?
TD;DR:

There was some confusion as to what I was asking, so here is the driving idea behind the question:

I always intended the question to be what it is. I may not have articulated it well originally. But intent have always been "is modular, separated, loose coupled, decoupled, refactored code" markedly slower by its own nature than "monolithic single-unit, do-everything in one place, one file, tightly coupled" code. The rest is just details and various manifestations of this that I came across then or now or will later. It is slower for sure on some scale. Like a non-defragged disk, you have to pick up the pieces from everywhere. It's slower. For sure. But should I care?

And the question is not about...

not about micro-optimization, premature optimization, etc.  It is not about "optimize this or that part to death".

What is it then?

It is about the overall methodology and techniques and ways of thinking about writing code that emerged over time:

"inject this code into your class as a dependency"

"write one file per class"

"separate your view from your database, controller, domain".

don't write spaghetti homogenious single codeblock, but write many separate modular components that work together

It is about the way and the style of code that is currently - within this decade - seen and advocated in most frameworks, advocated at conventions, passed on via the community.  It is a shift in thinking from 'monolithic blocks' to 'microservices'.  And with that comes the price in terms of machine-level performance and overhead, and some programmer-level overhead as well.

Original Question follows:

In Computer Science field, I have noticed a notable shift in thinking when it comes to programming.  I come across the advice quite often that goes like this:

write smaller function-wise code (more testable and maintainable this way)

refactor existing code into smaller and smaller chunks of code until most of your methods/functions are just a few lines long and it is clear what is their purpose (which creates more functions, compared to a larger monolithic block)

write functions that only do one thing - separation of concerns, etc (which usually creates more functions and more frames on a stack)

create more files (one class per file, more classes for decomposition purposes, for layer purposes such as MVC, domain architecture, design patterns, OO, etc, which creates more file system calls)

This is a change compared to the "old" or "outdated" or "spaghetti" coding practices where you have methods spanning 2500 lines, and big classes and god objects doing everything.

My question is this:

when it call comes down to machine code, to 1s and 0s, to assembly instructions, to HDD platters, should I be at all concerned that my perfectly class-separated OO code with variety of refactored small-to-tiny functions and methods generates too much extra overhead?

Details

While I am not intimately familiar with how OO code and its method calls are handled in ASM in the end, and how DB calls and compiler calls translate to moving actuator arm on a HDD platter, I do have some idea.  I assume that each extra function call, object call, or "#include" call (in some languages), generate an extra set of instructions, thereby increasing code's volume and adding various "code wiring" overheads, without adding actual "useful" code.  I also imagine that good optimizations can be done to ASM before it is actually ran on the hardware, but that optimization can only do so much too.

Hence, my question -- how much overhead (in space and speed) does well-separated code (code that is split up across hundreds of files, classes, and design patterns, etc) actually introduce compared to having "one big method that contains everything in one monolithic file", due to this overhead?

UPDATE for clarity:

I am assuming that taking the same code and splitting it, refactoring it out, decoupling it into more and more functions and objects and methods and classes will result in more and more parameter passing between smaller code pieces.  Because for sure, refactoring code has to keep the thread going, and that requires parameter passing.  More methods or more classes or more Factory Methods design patterns, results in more overhead of passing various bits of information more than it is the case in a single monolithic class or method.

It was said somewhere (quote TBD) that up to 70% of all code is made up of ASM's MOV instruction - loading CPU registers with proper variables, not the actual computation being done.  In my case, you load up CPU's time with PUSH/POP instructions to provide linkage and parameter passing between various pieces of code.  The smaller you make your pieces of code, the more overhead "linkage" is required.  I am concerned that this linkage adds to software bloat and slow-down and I am wondering if I should be concerned about this, and how much, if any at all, because current and future generations of programmers who are building software for the next century, will have to live with and consume software built using these practices.

UPDATE:  Multiple files

I am writing new code now that is slowly replacing old code.  In particular I've noted that one of the old classes was a ~3000 line file (as mentioned earlier).  Now it is becoming a set of 15-20 files located across various directories, including test files and not including PHP framework I am using to bind some things together. More files are coming as well. When it comes to disk I/O, loading multiple files is slower than loading one large file.  Of course not all files are loaded, they are loaded as needed, and disk caching and memory caching options exist, and yet still I believe that loading multiple files takes more processing than loading a single file into memory.  I am adding that to my concern.

UPDATE: Dependency Inject everything

Coming back to this after a while.. I think my question was misunderstood.  Or maybe I chose to misunderstand some answers.  I am not talking about micro-optimizing as some answers have singled out, (at least I think calling what I am talking about micro-optimization is a misnomer) but about the movement of "Refactor code to loosen tight coupling", as a whole, at every level of the code.  I came from Zend Con just recently where this style of code has been one of the core points and centerpieces of the convention.  Decouple logic from view, view from model, model from database, and if you can, decouple data from the database.  Dependency-Inject everything, which sometimes means just adding wiring code (functions, classes, boilerplate) that does nothing, but serves as a seam/hook point, easily doubling code size in most cases.

UPDATE 2:  Does "separating code into more files" significantly affect performance (at all levels of computing)

How does philosophy of compartmentalize your code into multiple files impact today's computing (performance, disk utilization, memory management, CPU processing tasks)?

I am talking about

Before...

In a hypothetical yet quite real not so distant past, you could easily write one mono-block of a file that does has model and view and controller spaghetti or not-spaghetti-coded, but that runs everything once it is already loaded.  Doing some benchmarks in the past using C code I found out that it is MUCH faster to load a single 900Mb file into memory and process it in large chunks than it is to load a bunch of smaller files and process them in a smaller peace-meal chunks doing the same work in the end.

.. And Now*

Today I find myself looking at code that shows a ledger, that has features like .. if an item is an "order", show order HTML block.  If a line item can be copied, print HTML block that displays an icon and HTML parameters behind it allowing you to make the copy.  If the item can be moved up or down, display the appropriate HTML arrows.  Etc.  I can, through Zend Framework create partial() calls, which essentially means "call a function that takes your parameters and inserts them into a separate HTML file that it also calls".  Depending on how detailed I want to get, I can create separate HTML functions for the tiniest parts of the ledger.  One for arrow up, arrow down, one for "can I copy this item", etc.  Easily creating several files just to display a small part of the webpage.  Taking my code and behind-the-scenes Zend Framework code, the system/stack probably calls close to 20-30 different files.

What?

I am interested in aspects, the wear and tear on the machine that is created by compartmentalizing code into many smaller separate files.

For example, loading more files means having them located in various places of the file system, and in various places of physical HDD, which means more HDD seek and read time.

For CPU it probably means more context switching and loading various registers.

In this sub-block (update #2) I am interested more strictly in how using multiple files to do the same tasks that could be done in a single file, affect system performance.

Using Zend Form API vs simple HTML

I used Zend Form API with latest and greatest modern OO practices, to build an HTML form with validation, transforming POST into domain objects.

It took me 35 files to make it.

```<code>35 files =
    = 10 fieldsets x {programmatic fieldset + fieldset manager + view template}
    + a few supporting files
</code>```

All of which could be replaced with a a few simple HTML + PHP + JS + CSS files, perhaps total of 4 light-weight files.

Is it better? Is it worth? ... Imagine loading 35 files + numerous Zend Zramework library files that make them work, vs 4 simple files.

答:
You need to be careful to listen to experienced programmers as well as current thinking.
People who have dealt for years with massive software have something to contribute.

In my experience, here is what leads to slowdowns, and they are not small.
They are orders of magnitude:

The assumption that any line of code takes roughly as much time as any other.
For example cout << endl versus a = b + c. The former takes thousands of times longer than the latter.
Stackexchange has a lot of questions of the form "I've tried different ways of optimizing this code, but it doesn't seem to make a difference, why not?" when there's a big-old function call in the middle of it.

The assumption that any function or method call, once written, is of course necessary.
Functions and methods are easy to call, and the calling is usually pretty efficient.
The problem is they are like credit cards. They tempt you to spend more than you really want to, and they tend to hide what you spent.
On top of that, large software has layers upon layers of abstraction, so even if there is only 15% waste at each layer, over 5 layers that compounds to a slowdown factor of 2.
The answer to this is not to remove functionality or write bigger functions, it is to discipline yourself to be on guard for this problem and be willing and able to root it out.

Galloping generality.
The value of abstraction is it can let you do more with less code - at least that's the hope.
This idea can be pushed to extremes.
The problem with too much generality is that every problem is specific, and when you solve it with general abstractions, those abstractions are not necessarily able to exploit the specific properties of your problem.
For example, I've seen a situation where a fancy priority queue class, which could be efficient at large sizes, was used when the length never exceeded 3!

Galloping data structure.
OOP is a very useful paradigm, but it does not encourage one to minimize data structure - rather it encourages one to try to hide the complexity of it.
For example, there is the concept of "notification" where if datum A is modified in some way, A issues a notification event so that B and C can also modify themselves so as to keep the whole ensemble consistent. This can propagate over many layers, and magnify the cost of the modification enormously.
Then it is entirely possible that the change to A could soon after be undone or changed to yet another modification, meaning that the effort spent on trying to keep the ensemble consistent has to be done yet again.
Confounding that is the probability of bugs in all these notification handlers, and circularity, etc.
It is far better to try to keep the data structure normalized, so that any change needs to be made in one place only.
If non-normalized data cannot be avoided, it is better to have periodic passes to repair the inconsistency, rather than pretending it can be kept consistent with a short leash.

... when I think of more I'll add it.


问:
How to address the concerns of the software architect but still maintain collective code ownership?
The quality of the code in our software is indeed lacking. When you change a line of code in one component it usually breaks code in other components.

Our software architect blames this on collective code ownership. He believes that if every developer was responsible for his own piece of code then he would tidy it up all the time because he would feel ownership over the component.

In the current situation, developers change code in multiple components and they break other components either because they don't understand how the component works (because they work with so many components) or because they don't care about how their changes will affect the other clients of the component (as long as they are not affected).

How can I address the concerns of the software architect but still maintain collective code ownership?

答:
It's a shared responsability.

Each programmer should be responsable for their own code, and, at the same time, the architect should check every programmer's code.

In order to implement that "shared responsability", your company should also have some policies about code. They should be "close" enough to avoid bugs, and, "open" enough to allow programmers to apply their skills, without feeling too much restricted.

An example of a policy could be to install version control software, and every developer should store their last changes to the code every day before leaving.

Another example of a policy could be how to write an "if-else" sentence, using a "C"-like language. In a company I worked in, we always use brackets, even if we only use a single instruction.

So, this:

```<code>if ()
    DoSomething();
else
    DoSomethingElse();
</code>```

Became this:

```<code>if ()
{
    DoSomething();
}
else
{
    DoSomethingElse();
}
</code>```

When a programmer is hired, he should be informed about the coding policies. And, sign a contract. But, the policies should be explained as something that helps do the job, with examples or training.

You may allow a developer to skip the rules sometimes, too much workload, or an unexpected scenario. Sometimes the broken rule becomes the one rule.

But, if a developer breaks them, frequently, with a non-significant reason, you should fire him, because he may spoil the other coworkers.

If your company doesn't have formal policies, or those policies require to be updated, check them together with the programmers, not just the architect or project manager.

Body:
It's a shared responsability.

Each programmer should be responsable for their own code, and, at the same time, the architect should check every programmer's code.

In order to implement that "shared responsability", your company should also have some policies about code. They should be "close" enough to avoid bugs, and, "open" enough to allow programmers to apply their skills, without feeling too much restricted.

An example of a policy could be to install version control software, and every developer should store their last changes to the code every day before leaving.

Another example of a policy could be how to write an "if-else" sentence, using a "C"-like language. In a company I worked in, we always use brackets, even if we only use a single instruction.

So, this:

if ()
    DoSomething();
else
    DoSomethingElse();

Became this:

if ()
{
    DoSomething();
}
else
{
    DoSomethingElse();
}

When a programmer is hired, he should be informed about the coding policies. And, sign a contract. But, the policies should be explained as something that helps do the job, with examples or training.

You may allow a developer to skip the rules sometimes, too much workload, or an unexpected scenario. Sometimes the broken rule becomes the one rule.

But, if a developer breaks them, frequently, with a non-significant reason, you should fire him, because he may spoil the other coworkers.

If your company doesn't have formal policies, or those policies require to be updated, check them together with the programmers, not just the architect or project manager.


答:
I don't think there is a general pattern to this, although there are a limited number of solutions.  One solution is to recognize that you have two conditions which determine how many rows you get back, and then allow both of those conditions to be tested on sql backend.</p>

```<code>-- Normal users:
SELECT * FROM Foobar WHERE user_id=:user_id;

-- Admins:
SELECT * FROM Foobar;

-- actual query
SELECT * FROM Foobar WHERE user_id=:user_id Or is_admin=1;
</code>```

Title: Branch twice for unique condition

Body:
Consider an application that displays only Foobars belonging to themselves to normal users, and all Foobars to admins:

```<code>-- Normal users:
SELECT * FROM Foobar WHERE user_id=:user_id;

-- Admins:
SELECT * FROM Foobar;
</code>```

Currently, this how the queries are represented in the codebase:

```<code>$sql = "SELECT * FROM Foobar";

if ( $user['type']!='admin' ) {
    $sql.= ' WHERE user_id=:user_id';
}

$stmt = $pdo->prepare($sql);

if ( $user['type']!='admin' ) {
    $stmt->bindValue(':user_id', $user['id']);
}
</code>```

I do not like this dual-branching approach from a maintainability standpoint. For instance, a bug like typing $user['type']=='admin' instead of $user['type']!='admin' would have to be found and fixed in two places instead of one. However, I also don't like the idea of separate functions for each case: admins and regular users.

A third approach would be to branch once and there create the SQL to add and the values to bind:

```<code>$sql_to_add = '';
$array_to_bind = array();

if ( $user['type']!='admin' ) {
    $sql_to_add = ' WHERE user_id=:user_id';
    $array_to_bind = array( ':user_id'=>$user['id'] );
}

$sql = "SELECT * FROM Foobar {$sql_to_add}";
$stmt = $pdo->prepare($sql);

foreach ( $array_to_bind as $k=>$v ) {
    $stmt->bindValue($k, $v);
}
</code>```

However I find this approach cumbersome. Is there a design pattern for this situation? What is the canonical way to handle situations where the code must branch in two separate locations on the same if condition?

Body:
I don't think there is a general pattern to this, although there are a limited number of solutions.  One solution is to recognize that you have two conditions which determine how many rows you get back, and then allow both of those conditions to be tested on sql backend.

-- Normal users:
SELECT * FROM Foobar WHERE user_id=:user_id;

-- Admins:
SELECT * FROM Foobar;

-- actual query
SELECT * FROM Foobar WHERE user_id=:user_id Or is_admin=1;


问:
How to organise intermodule integration in a modular project?
I'm currently writing my own PHP Framework (yes, another one) for studying purposes. I'll actually try to use it as my graduation dissertation.

After two failed attempts, I've finally found a way to develop it in a modular architecture, like Zend and Symfony.

I have some loosely coupled modules that can work apart from each other, but their usability would be better if I stick them together.

Now I'm wondering the best way of integrate them. I'm not willing to put a module as requirement for the other, because this breaks the modular design.

My first idea was to create a different module that requires the other two and put them to work together. This would work fine when I have just two modules, but when I have a module that can be integrated with two or more modules I get lost.

Should I create one module for each possible integration? Or should I create just one module and put all integrations I could have there?

Am I clear? If not, I'll try to explain it better.

Edit:

A practical example.

My Data Access Layer implements the Table Row Gateway pattern. I have a TableGatewayInterface and a default implementation TableGateway.

Imagine now that I want a table with a cache for the last queries. I can achive this with the Decorator pattern, creating a CachedTableGateway that depends on TableGateway and a cache component, let's say CacheInterface.

I don't need the cache, but it could be useful.

Should I embed this decorated implementation into the original package, creating a requirement to the cache component? Or should I create an "integration package" that requires both cache and table gateway?

答:
If you are using the Decorator pattern, the CachedTableGateway package would implement the TableGatewayInterface and accept another TableGatewayInterface to forward the requests to that couldn't be found in the cache.

If you have a generic caching package, then the CachedTableGateway package could be implemented using that caching package and that naturally implies a 'requires' relationship between the packages.

Other than that they both implement the same interface, there is no relation between CachedTableGateway and TableGateway. It is up to the client code (which could include integration tests) to decorate a TableGateway with a CachedTableGateway.


问:
Giving team members more decision-making power led to very long arguments, blocking progress since there is no one with the final say
Currently we use Scrum with the exception that our Scrum Masters sometimes act as project managers rather than facilitators of the Scrum process. About half of the time team members pull tasks on their own, but half of the time the Scrum Master assigns the tasks to team members.

I would like us to fully adopt self-organizing teams. However when we tried giving team members more decision-making power, it led to very long arguments between team members, and since there would be no one with the final say, these arguments would block progress.

Do you think there is a way to minimize arguments with self-organizing Scrum teams?

答:
For many, giving a programmer control over task assignment is a privilege, so you have to make sure you operate under the business restrictions. In your case, it's the amount of time to decide.

Hopefully, everyone gets better at this with more practice. You could set a time limit and then the PM just steps in with an immediate ruling.

Also, your company has to decide if allowing the programmers to take a lot more time than the PM to assign tasks is better because they are more accurate, improves team morale and possibly holds everyone more accountable.

With some measurement, you can determine who actually does better assignments, estimates etc.

EDIT: Make sure team members aren't using this time to vent or possibly getting into technical/philosophical discussions. Arrange other meetings formal or informal to help them get this out of their system.


问:
Unit Testing with an Optimization Problem
Suppose I'm making an algorithm that identifies the subject of a picture. It could be anything that a computer doesn't do that well, but I'm not expecting to get the right answer every time - 80% is fine. Suppose further, that the accuracy of the intermediate steps was also somewhat fuzzy. Is there a way to incorporate unit tests?

The option that immediately comes to mind is to add 1 to a tally and every time a 'test' passes, increment the tally. When that finishes, divide by the total and test 'passes/tests > 0.8', but that seems kludgey.

EDIT: Thank you all for your kind words and well-reasoned responses. My particular problem, while fuzzy, has nothing to do with pictures, and I'm currently getting about 80% pass. The short term value for me in a testing scheme would be knowing whether small adjustments were more globally beneficial or catastrophic. Long term testing value should be obvious.

答:
As others have noted, TDD primarily focuses on unit-testing.  However, that doesn't mean that black-box integration testing shouldn't be covered.  Nor should it necessarily cover the same deterministic nature of a unit-test.

In terms of unit-testing

Assuming that nothing in your algorithm is random, it should be possible to write unit-tests for the components of your software that pass 100%.  There should be no reason why you would need to reach an 80% mark.

However, these tests are specific to the implementation of the algorithm, by their very nature.  With a given input you would always expect the same output.  You describe the situation in which things will lead towards a match, and the situations in which they would move away from a match.

If the algorithm changes, you would expect at least some of the unit tests to change too.

In terms of black-box integration testing

It seems that there may be a requirement for a test along the lines of:

Given this set of x pictures I expect a positive match rate of 80%

I don't care which have a positive match, just that the threshold is reached.

You would run each picture through, check if your algorithm gave you a match with the expected result or not.  Keep a tally and score, as per your suggestion.

This test would describe the minimum functional requirements of the algorithm and would be entirely independent of the implementation.

So yes, this sounds like an entirely appropriate test and a measure of how successful the whole of the software was.


答:
Start timeboxing your discussions.  At the end, take a vote.  Tie?  Bring someone else in who can provide an unbiased vote. Although, it's not really recommended to involve "chickens" in decisions of magnitude.

At the heart of it, it seems like there is some toxicity within the team. Why? That may be a better question to start with.  Bring it up to your Scrum Master.  Maybe somebody is confusing ideality with reality.

You may also want to give your PM / PO (idealy) or SM final say.  It's their responsibility to weigh the opinions and facts that others have presented.

Title: Giving team members more decision-making power led to very long arguments, blocking progress since there is no one with the final say

Body:
Currently we use Scrum with the exception that our Scrum Masters sometimes act as project managers rather than facilitators of the Scrum process. About half of the time team members pull tasks on their own, but half of the time the Scrum Master assigns the tasks to team members.

I would like us to fully adopt self-organizing teams. However when we tried giving team members more decision-making power, it led to very long arguments between team members, and since there would be no one with the final say, these arguments would block progress.

Do you think there is a way to minimize arguments with self-organizing Scrum teams?


答:
since there would be no one with the final say, these arguments would block progress.

There's your problem, right there.  Someone needs to have final decision-making authority.  Figure out a way to make that happen.

You also might want to look into adopting a bit of informal parliamentary procedure.  Folks highjacking a meeting is not a new problem, and there are already known solutions.


答:
I actually work using Scrum too.

We self-organize the tasks and whenever needed the Scrum Master have the final say.
It's easy like that!

Just try to follow some directives:

Team must agree when assigning tasks

If they can't agree, don't waste time with endless discussion (never argue!). Take it to Scrum Master.

Trust the Scrum Master's decision, everybody is on the same boat.

Hope these tips help.


答:
Do you think there is a way to minimize arguments with self-organizing Scrum teams?

That's part of the scrum master job: get the team to take decisions efficiently and timely.

The blunt approach is to let someone (scrum master or other) to have the final say. But it's (imho) an abuse of power. A better approach is help the team to get a decision, for instance:

Get the team to agree when a decision is needed (now, in 30 minutes, tomorrow, in a month). This needs to be reasonable, don't force an artificial deadline (agile: take decisions at the last possible reasonable moment).

Get the team to agree on the importance of the issue and how much time it's worth spending debating it. I call that the bike shed limit. It's not a strict limit, but have them realize that spending a day arguing about something that in the end doesn't really matter is not the best use of their time. (Debate for the fun of it is another story, don't kill that!)

Tell them to work on an answer by the deadline, otherwise you're going to take the decision (don't tell them what your decision is going to be)

Actually do it. And stick to that contract.

Realize that's a scrummaster vs the team play, so tread carefully. You might end up taking more decisions than you're comfortable with, but any team worth its weight is going to figure out that they'd rather own at least some of the decisions and will work at it before you're forced to take them.


问:
How do I properly add a reference from my Github project to someone elses in VS2013 on Windows 8?
I need to reference the latest version of Bouncy Castle in a project I intend to publish to Github.

In my first posting of the code to Github, someone complained that I downloaded the entire Bouncy Castle library, added it as a project, and uploaded it.

What is the correct way to link to the latest version of this Bouncy Castle DLL so that my references are properly maintained?

答:
It looks like Bouncy Castle has a NuGet package. You could set up your VS2013 solution for package restore, and then reference Bouncy Castle through NuGet.

By doing so, you don't actually store the referenced files in your repository at all, just the NuGet reference. Then, when somebody else builds your project, the package restore process will download the files from the (NuGet) source for them.


答:
Someone on each team needs to learn some mediation skills.  The scrum master is a logical choice, but it doesn't have to be him.  You can hire people to teach a class to your company.  Someone doesn't have to have the deciding say in order to effectively lead a group to consensus.  Incidentally, even when someone has the authority to effectively dictate a decision, the team works much more smoothly when that person uses that authority sparingly, and instead uses mediation skills to come to a consensus as often as possible.

The topic is much too big for a post here, and also involves a certain degree of natural talent and a lot of practice, but here are some basic tips:

As other answers have mentioned, agree beforehand to timebox your decision.

Figure out how you will make a decision before trying to come to a decision.  Possible methods for deciding who has the final say are:

Majority vote.

Take turns.

The person with the most to lose.

The person who touched the code most recently.

The person who touches that code most frequently.

The person who spent the most time researching that particular problem.

The person who has the best grasp of the customer requirements.

A manager or technical lead.

Suggest compromises.

Suggest competing ideas each submit a proof of concept for review before doing the final product.

Often a decision is contentious due to lack of information.  Figure out precisely what information you lack and suggest methods of finding it out before you come to a decision.

Meet in smaller groups, or with both sides individually to hash out the concerns and get to the heart of the matter before trying to do it in a large group.

Steer the team away from bikeshedding on trivial details.  Suggest focusing on only the large decisions, then leave the details up to individuals doing the implementation.

Point out areas where you agree, and see if you can proceed on only that basis.

Realize sometimes you just need a ranting session when undertaking a large new project, to get the complaints out of everyone's system.  Make sure everyone's concerns are heard and validated, ask for volunteers to investigate the uncertainties, then hold a second meeting.  Almost always, fewer people come to the second meeting, and they're more in a mood to get things accomplished.


问:
Understanding the difference between mutable and immutable classes
I faced this question in one interview. I explained that String is immutable and StringBuffer is mutable class. I don't know very much about mutable and immutable and also don't know the exact answer. What are the key concepts to be able to distinguish the two ideas?  Is there a performance impact when chosing one over the other?

答:
To properly define mutable and immutable classes, one must first define what it means for an object instance to be mutable.  An object instance is mutable if there is any possible(*) means via which the state encapsulated thereby might be modified.  An object instance is immutable if its state cannot possibly be changed.  An class is immutable if all instances of that class are guaranteed to be immutable, regardless of who might hold references to them.

(*) There are certain approaches like Reflection where malicious code could modify just about anything; most discussions of immutability focus on things code may "legitimately" do, and regard such Reflection tricks as illegitimate.  Outside of security applications, the normal goal is to have objects work correctly for well-behaved clients; if a class behaves oddly when clients do illegitimate things, that's the clients' problem.

Many discussions of immutability ignore the fact that while all instances of an immutable class are immutable, instances of a mutable class can also be immutable.  Some discussions of mutability suggest that for a class to "really" be immutable, all fields thereof must also be immutable types.  Not only is that not true, but in many cases it would represent an almost-impossible goal given the absence of immutable array types.  What is necessary is that an immutable object must always be certain that no reference to any mutable object in which it holds state will ever be exposed to any code that might mutate it.  Anything that outside code might legitimately want to do with the encapsulated object must be done through methods implemented by or on behalf of the immutable containing object.

It would be helpful if .NET or Java had declarative means of specifying that certain objects, despite being of mutable type, should never be modified.  Unfortunately, no such feature exists.  Despite that, a major key to writing correct and efficient code is knowing which references identify things which are known to be of immutable classes, which ones identify (what must be) immutable instances of possibly-mutable classes, which ones identify unshared mutable instances of mutable classes, and which ones fit none of those patterns (generally because they identify "entities").  Many kinds of bugs, some of which may be very obscure, can result from using one of the above kinds of reference as though it was another.

PS--A framework may achieve the efficiency and robustness of const validation without the hassles of C++-style "const correctness" if

Distinct storage types exist for "references to entity", "unrestricted reference to potentially-mutable value", "read-only reference to potentially-mutable value", and "reference to immutable value"

Values are cloneable [cloning could be largely automated if the types of contained references are distinguished]

Members can be marked based upon whether they should be invokable upon read-only or immutable references

Each object instance includes a flag saying whether unrestricted references to it may exist

Any reference can be implicitly converted to a read-only reference; an unrestricted reference can also be implicitly converted to an immutable reference by making a new immutable clone.  A read-only reference can be implicitly converted to immutable, making a new immutable clone if needed.  A new mutable object may be cloned from any reference.

An essential aspect of the "entity" versus "value" distinction would be that an object is a "value" only if either (1) it is immutable, or (2) it has a single owner, and no reference of any sort exists to the object which is not under the control of that owner.  Trying to regain control over all references that might exist to an object which has ever been freely exposed to outside code would be impossible, and a strictly-compiler-enforced mechanism would probably be too restrictive to be useful, but even if things worked like C++ "const-correctness" where code could promise to behave with proper semantics even when it looked "suspicious", but any problems which resulted would be the fault of the programmer breaking his promise, that would be a significant advantage over the status quo.


问:
Why is Encapsulation considered a primary principle in OOP?
I am currently trying to understand more deeply the 4 principles of OOP: Abstraction, Encapsulation, Inheritance, and Polymorphism.

After studying the four principles, I don't fully understand why Encapsulation is considered one of the four primary principles of OOP.

Encapsulation is extremely common and useful in OOP, but it seems to me as more of a technique or strategy to use as part of Abstraction.

A good definition for Abstraction:

'Abstraction is the concept of moving the focus from the details and concrete implementation of things, to the types (i.e. classes), the operations available (i.e. methods), etc, thus making the programming simpler, more general, and more abstract.'

Encapsulation, on the other hand, is this:

'Hiding the internal implementation details of a class from the outside software world, and prividing an interface for other software entities to communicate and manipulate that class.`

If so, it seems to me that Encapsulation is mostly a technique to make things more abstract in the software system. Thus, it acts more of a strategy that implements the concept of Abstraction, rather than a primary principle by itself. It could be considered a 'principle' and not only a technique, but it still would be a part of the more general Abstraction principle, and not a major principle by itself.

Does anybody agree? If I'm wrong, please explain why.

答:
I agree, those descriptions are really similar. But Abstraction is the idea of consolidating state and functionality into meaningful bundles. Encapsulation is about protecting that bundle so that an outsider can't come in, break the rules, and mess with your state.

The abstraction has exclusive domain over the state, and encapsulation is how we guarantee that.

Another side of encapsulation is that the implementation may be more complicated than the abstraction. So you might have a method (pseudocode):

List<Thing> getRelatedThings()

but internally, the list of Things isn't represented as a List at all. Maybe it's a complicated mess of data structures, from which you abstract a List.

Or maybe it is just a list of Things, but you want to be able to change your mind later. The abstraction stays the same, but encapsulation protects the implementation.

So another difference would be: abstraction strives to simplify, but encapsulation hides complication.

EDIT: one more thing... Encapsulation is an important aspect of decoupling. So let's say that I have two classes that are really similar. Without encapsulation, those abstractions might start to overlap and become more and more inter-twined over time. Encapsulation says, no, this abstraction is distinct from that abstraction.

If there is a common abstraction, factor it out & abstract a base class.

(although now you have two problems ;) ) (...sorry, thats a "favor composition over inheritance" joke. If that doesn't make sense, you'll get there.)

encapsulation keeps the boundaries of an abstraction distinct


答:
I agree, encapsulation is more of a mechanism than a principle. The same could be said about implementation inheritance, which is an (arguably dangerous) mechanism for achieving subtyping, which is in turn just one kind of Polymorphism. Honestly, I wouldn't consider inheritance a fundamental principle of OOP at all - objects are about interfaces, not inheritance trees.

On that note, you say "the four principles" as if there were an authoritative source for them; I don't believe there is one. OOP means many things to many people. Personally, I find the SOLID principles to be useful, but understand that regardless of which ones you subscribe to, they're just a means to an end. I'd argue nothing matters more than correctness, modularity, and clarity, in that order.

Title: Why is Encapsulation considered a primary principle in OOP?

Body:
I am currently trying to understand more deeply the 4 principles of OOP: Abstraction, Encapsulation, Inheritance, and Polymorphism.

After studying the four principles, I don't fully understand why Encapsulation is considered one of the four primary principles of OOP.

Encapsulation is extremely common and useful in OOP, but it seems to me as more of a technique or strategy to use as part of Abstraction.

A good definition for Abstraction:

'Abstraction is the concept of moving the focus from the details and concrete implementation of things, to the types (i.e. classes), the operations available (i.e. methods), etc, thus making the programming simpler, more general, and more abstract.'

Encapsulation, on the other hand, is this:

'Hiding the internal implementation details of a class from the outside software world, and prividing an interface for other software entities to communicate and manipulate that class.`

If so, it seems to me that Encapsulation is mostly a technique to make things more abstract in the software system. Thus, it acts more of a strategy that implements the concept of Abstraction, rather than a primary principle by itself. It could be considered a 'principle' and not only a technique, but it still would be a part of the more general Abstraction principle, and not a major principle by itself.

Does anybody agree? If I'm wrong, please explain why.


答:
ACM TechNews - "[P]roviding timely information for IT professionals three times a week."

I get TechNews through the email subscription and it is very well edited. Department Chairs read it religiously to stay abreast of all of the recent findings in the various IT and CS fields.

Also related is:

ACM Queue, which has original content (as opposed to links to news stories or press releases). Here's a sample of the stories: "Virtualization: Blessing or Curse?", "Sir, Please Step Away from the ASR-33!", and "Realtime Garbage Collection". The articles are from researchers, practitioners, and scientists, as opposed to journalists, so you get much more of a straight-from-the-horse's-mouth experience.

Title: What is the general tech news website every programmer should read?

Body:
A link and a quick explanation why would be very helpful.

General tech news, I mean not like InfoQ which is too technical. Probably much more like P.SE than SO.

EDIT: site should help developers gain general knowledge about the industry, technologies, inventions, etc. Much like when we listen to the news every morning in our car to know what is happening in our world. But target audience must be either programmmers, geeks or any other persons interested in technology.


问:
Do you have to rename the software when you fork a repo?
I forked a repo some time ago and created a few pull requests which went unanswered.

Now, the software is MIT-licensed, and I kept the copyright notice there.

Do I have to rename the software, or whoever forks a repo can keep referring to it by the same name?

Thanks!

答:
From the comments:

if you create a fork that uses the same original codebase but diverges in another direction that competes with the original project, even if legally speaking the license doesn't require you to do that, ethically speaking you should change the name of the software.


问:
Why doesn't monad take `(M a -> M b)`?
All apologies -- I'm still very much on the outside of Haskell looking in.

Why does the bind for a monad have this signature:

M a -> (a -> M b) -> M b

and not

M a -> (M a -> M b) -> M b

i.e. a function that takes M a instead of just a

a is available to the function in both, but the context that M provides is not available to the function in the 1st. Just the lifted value itself.

(If that's a silly question, just downvote me a lot & I'll delete it... like I say, still very much on the outside looking in)

答:
Let’s call functions that return a monadic value “actions”.

The type signature for >>= in p >>= q says that:

Given a nullary action p that returns something of type a

And given a unary action q that takes an a and returns something of type b

You can chain them to get a nullary action that returns something of type b

It is worth remembering that >>= has a flipped version: =<<, that might be easier to understand visually—it corresponds to function application in a monad:

```<code>($)   :: (a ->   b) ->   a ->   b
(=<<) :: (a -> m b) -> m a -> m b
</code>```

Whereas $ is application of a pure function to a pure argument:

```<code>succ $ 2 + 2
</code>```

=<< is application of a side-effectful function to a side-effectful argument:

```<code>putStrLn =<< readLine
</code>```

And you may have seen the Applicative operator <$> (an alias for fmap), which is for the other common case of pure functions with side-effecting arguments:

```<code>lines <$> readFile "input.txt"
</code>```

Title: Why doesn't monad take `(M a -> M b)`?

Body:
Let’s call functions that return a monadic value “actions”.

The type signature for >>= in p >>= q says that:

Given a nullary action p that returns something of type a

And given a unary action q that takes an a and returns something of type b

You can chain them to get a nullary action that returns something of type b

It is worth remembering that >>= has a flipped version: =<<, that might be easier to understand visually—it corresponds to function application in a monad:

($)   :: (a ->   b) ->   a ->   b
(=<<) :: (a -> m b) -> m a -> m b

Whereas $ is application of a pure function to a pure argument:

succ $ 2 + 2

=<< is application of a side-effectful function to a side-effectful argument:

putStrLn =<< readLine

And you may have seen the Applicative operator <$> (an alias for fmap), which is for the other common case of pure functions with side-effecting arguments:

lines <$> readFile "input.txt"


问:
How to handle not-quite-legacy code?
This is a frequently asked topic... And I have read through many posts, articles and am about to read the book Working Effectively with Legacy Code, but before that and mainly because it will take more than a couple days for book to arrive, and I would like to keep my sanity in check, here's the question:

I am looking at not-that-old (1-2 years) code by a company I recently joined, and I have found so many bad practices in there that it's almost heart breaking...

Massive code duplication, global variables (which are inconsistently used), and things like using a factory class to instantiate various objects that extend a parent object... and then calling methods that don't exist in the parent, but are defined in all the subclasses...

The code works... It's rigorously QAed and bugs are at a minimum, which is fine... but I cringe so much looking at the code...

I recently asked my boss if I could refactor the entire codebase, he asked how I would be able to guarantee the changes will not break anything, I asked we could invest some time to create real unit tests, as their so called unit tests are actually end-to-end tests, so we have to trace the debug log very time something breaks. He said we don't have enough time to create the unit tests (actually the code isn't very unit testable, since there is so much tightly couple code... and I would've had to pretty much re-write most of the classes), so in effect I couldn't even do minor changes to code if it isn't listed as a bug in the issue tracker...

What I'm doing right now is alot of copy and pasting... then fine tuning that since the logic isn't exactly the same...

What can I do? :/

Sorry I think I'm just venting here, and there is nothing I can do in the short/medium term... sigh

答:
Do NOT, under any circumstances, change fragile code that you do not have to.  While it's fine to proactively add tests so you can refactor bad practices, doing so is at best an as-time-allows activity which should not detract from whatever is is they hired you to do.

If the code is a mammoth ugly behemoth of GOTOs and broken encapsulation and copy-pasted craziness, and it works, then you should leave it alone as much as possible for as long as possible.  Your time is better spent on scaffolding a test-driven framework for an eventual replacement,  into which you can then migrate and refactor the useful component of said ugly behemoth.

(Not that even doing that is a worthwhile expenditure of time, unless there's some looming Y2K-like deadline that may destroy the behemoth.  Or your co-workers are continuing development on said monstrosity.)

Title: How to handle not-quite-legacy code?


问:
Using interfaces as part of encapsulation
I'm creating interfaces for a number of our existing classes for mocking reasons.  Many of these classes also have package scope methods as an attempt to give some level of encapsulation by ensuring only the controller can modify some of their state.  I had thought I could use this change to try to get cleaner encapsulation as well.

My question is two fold.  First, is it considered viable to use interfaces for encapsulation?  I could make certain methods not in my interface that are available in the class.  or I could have my IBar method have a getFoo method that returns an IFoo, but my bar class overrides getFoo to return a Bar.  The problem is that anyone could easily cast my Ixxx to the actual class, so is it really considered a worthwhile encapsulation?

My second question has to do with my model.  I would want my model to have some getAllFoo sort of methods that return IFoo objects.  however, I want my controller to have a way to fetch the actuall Foo implementation (ie, know that my IFoo is of type Foo) so that it has access to methods not in the interface.  What is considered the cleanest way to ensure my controller has access to the full class but other classes only see the interface?  I asume just casting the interface to it's concrete class would be considered rather sloppy?

答:
The interface provides no encapsulation advantage if you need to cast to the class to be able to use an object, or if the class is public, rather than internal or privately nested in another class.

To give your controller access to members that are not available to other classes, you must either make Foo a private nested class within the controller class, making it invisible even within the same assembly, or make Foo an internal class, making it invisible outside the assembly.

My advice is to avoid interfaces as much as possible, and use them only in cases where you need the advantages of multiple inheritance, as it is the only form of multiple inheritance allowed (yes it is not true inheritance, but the idea is the same). Use base classes as much as possible. This will make it easier for others to read and navigate your code. For encapsulation, try to put related classes in the same assembly, so some of them can be internal, and some members can also be internal.

Choosing between Class and Interface in the Framework Design Guidelines book has more information.


答:
For the possibility that someone might be helped by this, and even though sometimes he can be a douche, and at the risk of being torn apart by the non-Mac majority...

daringfireball.net by John Gruber

Now let explain why I like it.

The news is not overly technical.

The amount of news is usually just about right. (I find Slashdot simply too overwhelming).

Most of the posts are links to interesting articles around the web, with a small blurb about why it was interesting.

The topics are very wide-ranging and usually looked at from a high-level point of view:

Phones/tablets (Apple, Google, Blackberry)

Mobile apps, iOS/Android/WebOS, App Store philosophies, mobile web

Developer stories and philosophies

Closed vs. Open

Apple/Google/Microsoft/other product and tech strategies

Other tech stories (Google TV, Netflix, Wikileaks, to name a few)

Big tech acquisitions

Internet community philosophies

I think it fits your guidelines really well:

Site should help developers gain general knowledge about the industry √, technologies √, inventions √

Target audience must be either programmmers √, geeks √ or any other persons interested in technology √


问:
Do software developers write SQL?
Do software developers write SQL or database developers provide the SQL and the software developers use it? I am a novice to software development. I am just trying to understand the software development process because I have to do an internship this summer. I apologize in advance if this is a basic question. </p>

答:
Software developers do write SQL.  How much they write depends on how the company is structured.

Some companies have a strong emphasis on controlling access to databases via a Database Administrator (DBA).  In those companies, the DBA will often write Stored Procedures (a form of SQL) and provide views for the software developers to use, but the software developers can still write SQL against those views.

In other companies where the responsibilities are more spread out, the application developers can be responsible for the entire software product, including writing all of the necessary SQL .

Some companies use Object-Relational Mapping software or rely on "NoSQL" databases such as MongoDB, and do very little SQL work.  So, as with many things in software development, it depends.

Title: Do software developers write SQL?


答:
There's nothing stopping you from creating "real" unit tests whenever you fix an existing bug or add a new enhancement, and there are some good techniques in Working Effectively with Legacy Code on just how to do that.

If the code's as brittle as it sounds, you're likely going to get plenty of opportunities to fix bugs; just make sure you put good tests in to support your bugfixes and enhancements as they arise. Over time, either you'll eventually grow a substantial test suite or the application will go away (at which point the lack of test coverage is no longer a problem :-)

Title: How to handle not-quite-legacy code?

Body:
This is a frequently asked topic... And I have read through many posts, articles and am about to read the book Working Effectively with Legacy Code, but before that and mainly because it will take more than a couple days for book to arrive, and I would like to keep my sanity in check, here's the question:

I am looking at not-that-old (1-2 years) code by a company I recently joined, and I have found so many bad practices in there that it's almost heart breaking...

Massive code duplication, global variables (which are inconsistently used), and things like using a factory class to instantiate various objects that extend a parent object... and then calling methods that don't exist in the parent, but are defined in all the subclasses...

The code works... It's rigorously QAed and bugs are at a minimum, which is fine... but I cringe so much looking at the code...

I recently asked my boss if I could refactor the entire codebase, he asked how I would be able to guarantee the changes will not break anything, I asked we could invest some time to create real unit tests, as their so called unit tests are actually end-to-end tests, so we have to trace the debug log very time something breaks. He said we don't have enough time to create the unit tests (actually the code isn't very unit testable, since there is so much tightly couple code... and I would've had to pretty much re-write most of the classes), so in effect I couldn't even do minor changes to code if it isn't listed as a bug in the issue tracker...

What I'm doing right now is alot of copy and pasting... then fine tuning that since the logic isn't exactly the same...

What can I do? :/

Sorry I think I'm just venting here, and there is nothing I can do in the short/medium term... sigh


问:
Able to read Code but struggling majorly to write it
I had my first programming exam recently...and well I pretty much flopped it. Did not do great at all. I have only myself to blame as outside of college time, I pretty much did nothing.

Now I have another coming up near summer time and I'm not allowing this to happen again. For a couple of weeks now I've been reading, reading and reading some more. I keep going over the older things I missed and the newer things we're doing. So, obviously I can notice a huge difference in my understanding of the language. However, that's about it. I can read the code and I now have an idea of what's going on in the code... but when it comes to me writing the code myself I'm just clueless. It's like I never know what approach to take and can never really fully comprehend the questions.

I have done a fair amount of reading (been doing around 5-6 hours for the past month or so) each day... But when opening my IDE I always feel doomed it's really demotivating. Especially because I have knowledge of nodes, lists, arraylists, interfaces ect ect but besides from reading them on a page that's about it. I can point out exactly everything that's going on in a program so annotating a presample code I find fine... but writing my own code is another story..

答:
I know this isn't the answer you're going to want to hear but:  Write more code!

More specifically dissect the code that you do understand.  It often helps me to "translate" it into regular English (as I'm a relative beginner).

Don't be afraid to brainstorm your idea for writing a piece of code first (ie "I want to declare a variable here, iterate through this segment etc"), and THEN look up piece by piece how to do these various segments.

Remember that coding is less like an exercise in memorization and like figuring out a way to construct something out of building blocks.  Much like learning an actual foreign language, comprehension comes first, this is a good sign that you are well on your way.

Just have faith that the more you write and read code, the more it will make sense.


答:
You learn how to write programs by writing programs.

But you gotta start small, man.

```<code>public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
</code>```

From there, begin building...

```<code>public class HelloWorld {
    static String test = "This is a test";

    public static void main(String[] args) {
        System.out.println(test);
    }
}
</code>```

and then...

```<code>public class HelloClass {
    String test;

    public void setTest(String str)
    {
        test = str;
    }

    public String getTest()
    {
        return test;
    }
}

public class HelloWorld {
    HelloClass myHelloInstance;

    public static void main(String[] args) {
        myHelloInstance = new HelloClass();
        myHelloInstance.SetTest("Hello World.")
        String myResult = myHelloInstance.getTest();
        System.out.println(myResult);
    }
}
</code>```

... and so on.  Once you understand the basics of how objects work, it will be much easier to write larger programs.

Title: Able to read Code but struggling majorly to write it

Body:
I had my first programming exam recently...and well I pretty much flopped it. Did not do great at all. I have only myself to blame as outside of college time, I pretty much did nothing.

Now I have another coming up near summer time and I'm not allowing this to happen again. For a couple of weeks now I've been reading, reading and reading some more. I keep going over the older things I missed and the newer things we're doing. So, obviously I can notice a huge difference in my understanding of the language. However, that's about it. I can read the code and I now have an idea of what's going on in the code... but when it comes to me writing the code myself I'm just clueless. It's like I never know what approach to take and can never really fully comprehend the questions.

I have done a fair amount of reading (been doing around 5-6 hours for the past month or so) each day... But when opening my IDE I always feel doomed it's really demotivating. Especially because I have knowledge of nodes, lists, arraylists, interfaces ect ect but besides from reading them on a page that's about it. I can point out exactly everything that's going on in a program so annotating a presample code I find fine... but writing my own code is another story..

Body:
You learn how to write programs by writing programs.

But you gotta start small, man.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

From there, begin building...

public class HelloWorld {
    static String test = "This is a test";

    public static void main(String[] args) {
        System.out.println(test);
    }
}

and then...

public class HelloClass {
    String test;

    public void setTest(String str)
    {
        test = str;
    }

    public String getTest()
    {
        return test;
    }
}

public class HelloWorld {
    HelloClass myHelloInstance;

    public static void main(String[] args) {
        myHelloInstance = new HelloClass();
        myHelloInstance.SetTest("Hello World.")
        String myResult = myHelloInstance.getTest();
        System.out.println(myResult);
    }
}

... and so on.  Once you understand the basics of how objects work, it will be much easier to write larger programs.


问:
Why do we study Java at university?
Java is often found in academia. What is the reason behind that? </p>

答:
I've heard professors say they use java to teach because:

uses the newer paradigm(s) (OOP, some generics)

syntactically very simple, although quite verbose

no advanced concepts such as higher order functions, closures, currying or continuations that may confuse people still learning basic concepts

a lot of libraries written for it

students don't get as bogged down in debugging memory leaks since there is a gc

Personally I'm glad I took CS at Berkeley when they used Scheme to teach.  Although I didn't realize how elegant of a language it really was until a few years later.

Title: Why do we study Java at university?


问:
What is the absolute minimum set of instructions required to build a Turing complete processor
I have a general idea of how the processor handles instructions but spend my time working in mostly high level languages. Maybe somebody who works closer to the iron can provide some valuable insight.

Assuming that programming languages are basically very high level abstractions of a processor's instruction set, what is the most basic set of instructions necessary to create a turing complete machine?

Note: I don't know anything about the diversity of hardware architectures but -- for the sake of simplicity -- lets assume it's a typical processor with an ALU (if necessary) and instruction stack.*

答:
There are many ways to implement something that one can implement a turing machine in.

As you are looking at processors, the one that is most applicable is probably the register machine model.  The simplest of these (in terms of symbols) is the mulit-tape two symbol (mark and blank).  If you go for something not quite as esoteric, the inc(r), dec(r) and jz(r,z) (jump if register r is zero to instruction z) or the clr(r) (clear r), inc, je(i,j,z) (jump if register i and j are equal to instruction z).

I have seen mention of a register machine that is:

inc(i, m) - increment register i and go to line m

jzdec(i, m1, m2) - if register i is 0 go to line m, else decrement i, and go to line m2

which is turing complete too - its a Minsky register machine though it has other constraints on the data in the tape (it has to be a Gödel number storing the state rather than individual registers)

Thats it.  Nothing more.

So, why aren't these ultra risc processors used instead?  Its a real pain to write a compiler for them and you give up a lot of other things that the processor can do.  Its really nice to have a bitwise and, and an add rather than trying to do everything with incrementing registers and looping.  Thats the basis of a favorite programming language titled Brainfuck which has 8 instructions.

> increment the data pointer

< decrement the data pointer

+ increment the data at the data pointer

- decrement the data at the data pointer

. output the data at the data pointer

, read input, storing the data at the data pointer

[ if the data at the pointer is zero, instead of moving the instruction pointer forward one, jump it forward to the command after the matching ] command

] if the data at the pointer is nonzero, instead of moving the instruction pointer forward, jump it back to the command after the matching ] command

One can find compilers to Brainfuck, though its really not fun to do even simple things in it.  Unless you enjoy the frustration, which is the purpose of the language.

Related reading:

(esolangs) Turing tarpit

What makes a language Turing-complete? (for a programming language)

Why is FRACTRAN turing complete? (on Gödel number based register machines)


答:
OOP was commonly defined as encapsulation, inheritance, and polymorphism.  I've seen this definition around a lot, and I've only seen abstraction, encapsulation, inheritance, and polymorphism, a few times.  Matt Weisfeld's 'The Object-Oriented Thought Process' acknowledges the 3 part definition and goes on to add composition to the end of the list.

Although nobody agrees on what OO is, there are a lot of definitions.

I think what happened is that encapsulation/inheritance/polymorphism was originally set up as a definition for what OO is, then later people referred to the individual points as principles, then people stopped referring to the whole thing as a definition, and instead referred to them as a set of principles, then people noticed that while inheritance is how the principle of polymorphism was implemented in OOP, there was no principle listed to correspond to encapsulation as an implementation, so they added it.  Then you noticed that not all of these principles are on the same level of abstraction.  I don't have any proof that it happened in that order, but we do know what the start and endpoints were.

If you take the 4 "principles" as a definition, but then throw out encapsulation and inheritance as implementations, you get abstraction+polymorphism as a definition of OOP, which is ridiculous, since many languages that have no objects in them at all have both of those.


问:
Why do expressions print variable value using System.out.print?
Why does java print the value of the variable that is assigned it in the code below? I want understand what is happening here.

My thought is that the expression inside println() method is evaluated first. For the first example, 5 is assigned to int x. At that point, does x become available for the println() method to print its value?

This code confuses me. I wouldn't have thought expression like x=5 could return a value. Thank you.

Examples:

```<code>int x;
System.out.println(x=5); //prints 5

boolean isValid;
System.out.println(isValid = true); //prints true

String fruit;
System.out.println(fruit="Orange"); //prints orange
</code>```

答:
Java is fairly liberal about where you can do an assignment.  It is printing the value of the variable after the assignment.  What you are really writing is code like:

```<code>int x;
x = 5;
System.out.println(x);
</code>```

or

```<code>int x = 5;
System.out.println(x);
</code>```

Most coding standards will prefer code written as shown above.

Body:
Java is fairly liberal about where you can do an assignment.  It is printing the value of the variable after the assignment.  What you are really writing is code like:

int x;
x = 5;
System.out.println(x);

or

int x = 5;
System.out.println(x);

Most coding standards will prefer code written as shown above.


答:
Great question! It's important to realise that you have multiple learning curves to climb. Just so that you don't think that you are only learning a programming language. You are doing quite a bit more than that.

You are learning about ...

The tools that you use to write code. Your development environment, the editor, the debugger, your compiler. There are manuals and help files for all these tools, check them out. The more you know the tools the easier it is to create code.

The syntax of the programming language under study, from your post it sounds like you are putting a lot of focus here and you certainly need to.

Solution Design Skills. How to put together a useful, maintainable piece of code. This is the muscle that you need to build up. Like other posters have pointed, you learn by doing.

I suspect that it's point three where you are struggling. You are learning how to say things in code (syntax) but really you are asking us what should I be saying in code. Is there a right way and a wrong way to do things?

I would suggest that you take on a challenge. Have a look at the following as an exercise.

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

Now this is a tough challenge. You have to place eight Queens on a chess board so that each of the Queens are safe from each other.

So as a learner this may be an over-reach, however you can look at this problem and use it to learn how to write code.

Here's a strategy to try out ...

Restate the problem to be far simpler that the stated problem to be solved.
Forget the eight queens. Focus on just one. Learn how to write the code to represent a chess board in memory, place a single queen on that board and then display it to the user on screen in just text.

Once you have made a stab at Step 1. Place two queens on such that they are both safe.

Finally, have a go at placing more than 2 queens on the board so that they are all safe.

The above steps are a twist on a design strategy called Step-wise Refinement. It's a little bit old-school in terms of design but it will take you from a blank screen to some interesting code in no time.

There are other design and implementation strategies: Test Driven Design, Object Oriented Design and Design Patterns to name a few.

In time you will add these strategies to the arsenal and use them as and when required. The more design strategies you study and practise the easier it will become.

May the source be with you.


问:
Estimating time remaining in a queue with multiple workers
I've been trying to figure out a way of calculating the estimated time remaining for an item in a queue when there are multiple workers processing items from the single queue.

A client submits a job to the queue, but since processing can take some time I wanted to give an estimate of feedback.

I know

Number of items in the queue

Position in queue

Length of time an item takes to process*

How many workers are running

When each worker last completed a job

I don't know

How far along processing the worker is, only when it starts and ends**

*Processing time is the 90th percentile processing time of past jobs within a reasonable time range. Not completely accurate but tends to overestimate slightly and is accurate enough for my needs.

**Workers are calling an external service so the best estimate of progress is time taken

With a single worker I can use a function such as

```<code>estimated_seconds_remaining = (
    (position_in_queue + 1) * average_processing_time_seconds
) - (
    average_processing_time_seconds - time_since_worker_last_finished_seconds
)
</code>```

(position_in_queue + 1) * average_processing_time_seconds gives me the time it will take to process all the items in the queue plus the one that is currently being processed, then taking away average_processing_time_seconds - time_since_worker_last_finished_seconds gives me the estimated time remaining to process the current queue item.

This works fairly well, and is accurate enough for reporting back since the variation in processing times is quite small.

But, in production I'll be running multiple workers, so multiple workers will be processing items from the same queue. There will most likely be 3 or 4 workers running, but could be upwards of 10 at times.

The simplest option is just modifying my formula so

```<code>estimated_seconds_remaining = (
    (position_in_queue + 1)/number_of_workers * average_processing_time_seconds
) - (
    average_processing_time_seconds/number_of_workers - time_since_worker_last_finished_seconds
)
</code>```

But this gives inaccurate and erratic predictions, since the estimates are being re-calculated every second to update the display the times jump up and down depending on when the workers all finish their jobs.

Is there a simple way, with the information I have, to calculate a reasonably accurate prediction of the time remaining before an item from the queue is processed?

答:
Sure, what you can do is adapt your second equation. I think it's basically right, but the problem is that workers might all end at about the same time, so that second term can jump about a little bit.

What I'd suggest would be to track the termination time of each worker individually. You could also track their individual average processing time, but for simplicity I'll keep assuming it's constant.

So now the function becomes:

```<code>(position_in_queue) / (avg_worker_processing_time / workers_count)
+ time_until_most_advanced_worker_completes_processing
</code>```

that holds until your position is 0, at which point of course you want to report time_until_worker_that_has_my_task_completes_processing .

This should be far smoother, as time_until_most_advanced_worker_completes_processing will go to about zero smoothly and then you'll go forward one spot (reducing the time) and at the same time the next time_until_most_advanced_worker_completes_processing will rise a bit (keeping the smooth descent).

Hope that helps!

Body:
Sure, what you can do is adapt your second equation. I think it's basically right, but the problem is that workers might all end at about the same time, so that second term can jump about a little bit.

What I'd suggest would be to track the termination time of each worker individually. You could also track their individual average processing time, but for simplicity I'll keep assuming it's constant.

So now the function becomes:

(position_in_queue) / (avg_worker_processing_time / workers_count)
+ time_until_most_advanced_worker_completes_processing

that holds until your position is 0, at which point of course you want to report time_until_worker_that_has_my_task_completes_processing .

This should be far smoother, as time_until_most_advanced_worker_completes_processing will go to about zero smoothly and then you'll go forward one spot (reducing the time) and at the same time the next time_until_most_advanced_worker_completes_processing will rise a bit (keeping the smooth descent).

Hope that helps!


答:
I suspect that Post machine is about the simplest form of a Turing-complete device. You need a supply of bit-addressable memory, an address register that points to the current data location, and five instructions:

Set the bit at the current location;

Reset the bit at the current location;

Move to the next address (increment data address register);

Move to the previous address (decrement data address register);

Check the bit at the current data location.

I don't think it's easy to invent something much simpler hardware-wise, though something even more reduced probably exists.

Title: What is the absolute minimum set of instructions required to build a Turing complete processor

Body:
I have a general idea of how the processor handles instructions but spend my time working in mostly high level languages. Maybe somebody who works closer to the iron can provide some valuable insight.

Assuming that programming languages are basically very high level abstractions of a processor's instruction set, what is the most basic set of instructions necessary to create a turing complete machine?

Note: I don't know anything about the diversity of hardware architectures but -- for the sake of simplicity -- lets assume it's a typical processor with an ALU (if necessary) and instruction stack.*