问:
Is Lisp the first language to adopt structured programming?
I couldn't find any links or books claiming that Lisp is the first programming language to adopt structured programming (actually, most of them don't even mention Lisp at all), but if conditionals were invented by McCarthy and got into Algol later, is it fair to say that Lisp is the first?</p>

答:
BTW, conditionals (and loops, and GOTOs) were invented by Ada Lovelace, 170 years ago.

The structured programming is a style. You can structure your Assembler code. And you can write non-structured mess on any language, too. So we can't say that any language adopted structured programming. The question is incorrect.

But some languages give better opportunities for a programmer to code in structured way. And as the main request of the structured programming is a better readability of the code, Lisp, definitely, is very good in that sense.

Lisp is the second-oldest high-level programming language in widespread use today (wiki). Made in 1958.

The first high-level language was Fortran (1957) and its code is not well read, it is NOT good for structuring, but for these times, in comparison with Assembler, it was VERY readable. And its code CAN be structured.

Other languages, before Lisp and Fortran, were not readable at all, or never realized, or both. RPG and COBOl appeared only in 1959.

But it is not correct to compare nowadays Lisp with the old Fortran. The old Lisp (look here) is even less readable than Fortran. And nobody would name it now the language good for structured programming.

On the other hand, the Lisp uses its own structure, List, to organize its own code, and in this sense, its code IS structured. But it is not in the sense of structured programming as we take it now.

So there is a bit of truth in the sentence that you are asking about. But I can't say it IS true.


问:
Opinions on distribution of software via virtual appliance
I've created a distribution of my open source application framework in a working virtual appliance.  It includes everything to get started with the tutorial.  The distribution is Fedora 14 running Tomcat 5.5 and Oracle 10g Express Edition, plus my framework.  It is completely preconfigured and boots into a working running copy.

Would this be something you might try?

What assurances might you need to get you to try it?

Edit: The VM is just over a 2Gb download.  Alternatively it is also available via 23Mb download for the source and a PDF detailing how to configure the Tomcat and Oracle dependencies.

答:
Yeah, I think this is a terrific thing, especially for systems which require (potentially) complex configuration to get up and running.  If you can ship a working VM image that you just "boot and go" it makes it far easier to get a system up and running for evaluation / analysis ( at a minimum).  I believe that if you want people to evaluate your software and see the value in it, you need to make it as easy as possible for them to get it deployed and working so they can give it a spin.

I wouldn't make it the only means of distribution, but it's something I think many software projects should make available.  I'm planning to (eventually, when I can find time) do a virtual appliance distribution of my own project.  So yeah, I'm definitely on-board with this concept.

That said, I don't think having a VA distribution obviates the need to make it as easy as possible to build, deploy and configure the system via other methods.  Building from source, for example.  I'd still try to do as much as possible to make the source download, build, deploy, configure stuff as easy as possible.

Edit:  also, just to be clear... I'm talking about this in general / conceptual terms only.  Since you didn't say much (if anything) about what your actual project is or what it does, then no, I'm not actually going to download it and try it out.  I'm assuming you were asking this in the context of "Would you recommend that I make this available to people who are already interested in my project and visit the website looking for a download" as opposed to "would you, Stackexchange User $FOO, want to download this appliance and try it out?"

ContentLicense: CC BY-SA 2.5


问:
Code ownership with multiple Scrum teams
If two Scrum teams use the same software component, who is responsible for providing a clear architectural vision of that component and maintain/develop this vision as the code base evolves? In Scrum you are supposed to have a collective code ownership, so how to make sure that development done by Team A doesn't interfere with development done by Team B?</p>

答:
It's a difficult problem to solve, and it's certainly not solved by Scrum, which is a project management methodology, not a development methodology.

The most effective solution I've found is good package management (nuget/gem/etc) and versioning. Never enforce a change on another team until they're ready to consume it. Let them keep using the old build, while you move onto the new.

Make sure that you have a versioning strategy that makes it clear which changes are breaking and which are extensions.

Also, when you make a change, push a code review to someone ON EACH TEAM. Let them look at how it is likely to affect them, long before they're forced to consume it so that they can implement their own changes on top.

And, when things get really messy; when one team needs to make a change and cannot consume another change easily (this SHOULD be a really rare case), branch the code, make it an entirely different package, but make it a priority to get back onto common code as soon as time allows.

ContentLicense: CC BY-SA 3.0


问:
How do I maintain consistency between hard-coded values in different files?
I have a C source file and another (non-code) file in a project which contain the same hard-coded value. Ideally, the value would be specified in only one location and be copied to the other location automatically during the build process. It's not hard to think of hackish ways to accomplish this task, but I want to know if there is a common way of doing it.

What standard method or approach should I use to guarantee that the two values remain consistent?  In other words, how should I maintain consistency in a non-hackish way?

答:
Some high level languages are accustomed to set values in the code - values together with code are named scripts. But C doesn't belong to these languages. So, simply read values from the file.

Of course, there will be some hard set constants - that are identifying by names these values from file. For example, if you read XML or property files, where do you know from the tags/names? It is just your case.

But you should try to move the hard values to files, until this very values export is not too expensive.


问:
how to filter 'must-have' requirements from 'nice-to-have' requirements
In building a software from scratch, there is necessity to conduct detailed needs assessment and find out what the clients/stakeholders really need.

When interviewing the end-users, organizing workshops or directly participating in business process for which the software product is written, there are many requirements which are very important, they are 'must-to-have' requirements .

In the same process, the clients name some functionalities, which are related to software, but they do not seem do solve any problem, so say 'nice-to-have' features., e.g. have the possibility to change the interface color, or be able to manage some processes which the software could do without their interference.

There should be some pattern to manage this kind of requirements.
How to distinguish between these 2 kind of featuures? How to estimate does an additional feature add value to the software or is just augments the scope of the project?

Besides, how to persuade the clients that 'nice-to-have' features are somehow useful, but not really necessary.

答:
They're the client.  They get to decide what they want and what they don't want.  The way you get them to tell you what they don't really need is by attaching time and dollar estimates to the unnecessary features.  They will quickly realize which features are really important to them.

Before signing a contract with a client involving money, you need to know the specific scope of the work and how much the client is going to pay for that work.  Once the contract is signed, it is very difficult to get changes to the amount of money that the client is going to pay, so you either have to build something into the contract that allows them to add features for a price, or constrain the scope in such a way that they cannot add features once the price is agreed upon.

If you don't know the scope of the work, the way you find that out is to gather customer requirements, and then develop a Software Design Specification (or what you call your "needs analysis") so that you can map out how much time it is going to take to fulfill each requirement.  Charge them for preparing the needs analysis, on an hourly basis.  This must be done before a price is agreed upon.

Structure your requirements so that each requirement must pass an acceptance test specified by the client.  If it passes their test, then you declare that requirement completed.  This prevents them from coming back and saying "Well, I know that's what I said I wanted, but what I really wanted is this."


问:
Should the views or front-end server call the RESTful API layer
I need to build a new web application and I am looking for advice on how to manage communication to my API layer.  My goal is to have complete separation between the front-end and back-end code.  Like most, I plan on having a front-end server to serve the views, while the back-end server will expose my API layer.

I am a bit confused on how to approach pulling data from the API.

Should the node server handle all the calls to the API and provide that data to the views?

or Should the views be able to call the API directly and letting the server manage OAuth magic?

I am curious what others have done to approach this.  Let me know what your thoughts are, and I would be really interested if you have any good materials to read.

答:
Short answer:

I don't have enough information about your environment and goals to give a simple and helpful short answer. See my long answer below.

Long answer:

This is a really hard question to answer. There are a lot of specific things to your team and your project that lead to deciding on a best architecture for your system. To answer it well, there needs to be more detail around the goals and requirements for this web app. For example:

Is the API going to be public or only used by the web app? I.e., should it be thought of as an internal service that is behind a firewall and only accessible to the web app, or something else?

How much traffic is expected for this app? (1k users/month? 10k? 100k? 1m?)

How fast do pages need to load? (i.e., how responsive does the application need to fel vs. actually be?)

How much time do you have to build the app?

Do you really need OAuth?

How many people do you have on your team?

Where on the spectrum of "learning experience" to "to support a business" does this project lie?

Where on the spectrum of "practical, get it done" to "it must be perfectly technically correct" does this project lie?

Is this app going to be indexed by search engines or is it going to be mostly private (behind an authentication mechanism)?

My opinion on the "practical" vs. "perfect" question is, make it more practical. If it doesn't ship, the project doesn't matter outside what you learn.

The answers for questions 1, 2 and 3 lead to how big and complex the system needs to be. (If a lot of traffic is expected and page load time is not that important, more layers and more systems could be introduced. If there are areas of data that can be cached, then that can offset other places where it is slower to get data.)

On authentication and account creation. This is a surprisingly complex topic that takes time to really understand. Whether using OAuth (assuming OAuth 2.0) against your own API, regular password authentication, or OAuth authentication against a third-party (facebook, google, etc.), you'll still need a way to create user accounts within your system.

On OAuth: the most common use for OAuth is for allowing a third-party system/service to access data in your system that is owned by one of your users. It does have the flexibility, however, to allow password-based login. This means that, once a user has created an account on your system, you can use the "Resource Owner Password Credentials" grant type in OAuth 2.0 to authenticate that user. Check out the full rfc if you have not yet done so.

Here are a couple common ways to architect web applications (this is not comprehensive and there are tons of variations):

Use a front end framework, in javascript (think ember, angular or similar), to manage all the views and request the appropriate data from the API on a server. This API could then be either a public API or an API only used by that app.

Create a multi-tier server architecture where there is an external-facing web app layer with internal services (APIs) for each of the services you need. The web app layer has the views and gets all model data from the internal services. All internal services are behind a firewall. For example, see how TripAdvisor does it.

Provide a public API and create a standard, server-based web app where it serves individual html pages generated from views on the server. (i.e., the web app would not use the public API but would access all internal databases and services directly.)

Provide a public API for 3rd-party use and create a semi-private API that only the web app uses. This is a specific variation on #1.

I would follow #1, #3 or #4:

if I were building a system that I know will have < 100k users

if I had to support > 100k users and the number of features in the system is small (i.e., not a hugely complex product)

I would follow a combination of (#2 and (#1, #3 or #4)) (parenthesis for clarity of operational order):

if I had a lot of backend processing going on with a lot of other systems

if I had to support > 100k users and there is a very large feature set / a lot of different types of data to handle

If I had a product that was publicly available and would be indexed by search engines, I would not do #1 nor #4.

My team matters a lot to me. Their preferences, experience and desire to learn would affect what I choose architecturally between #1/#4 and #3.


问:
How do I make a domain model that doesn't violate OOP?
My game reads a number of JSON files, deserializes them, and hands the resulting objects off to the classes that need them. These deserialized objects, which can be thought of as the domain model, are normally very simple:

```<code>public class Settings
{
    public bool FullScreen = false;
    public int WindowWidth = 800;
    public int WindowHeight = 600;
}
</code>```

But one of these objects is not so simple:

```<code>public class Sprite
{
    [JsonProperty]
    private readonly string assetName;

    [JsonProperty]
    private Vector2 position;

    // other properties...

    public Sprite( string assetName, Vector2 position )
    {
        this.assetName = assetName;
        this.position = position;
    }

    public void Move( Vector2 direction )
    {
        // do move
    }

    // other methods...
}
</code>```

The properties of the Sprite class are private because I want to have good encapsulation. This means it has a constructor that accepts many arguments and several other methods for setting its properties. Also, each property needs an attribute so it can be read by the JSON parser. It looks like a POCO, but I read that POCOs should be persistance ignorant. I could create a simpler domain model that acts more like a DTO to satisfy this:

```<code>public class Sprite
{
    public string AssetName = "default.png";
    public Vector2 Position = Vector2.Zero;
}
</code>```

Now my Sprite class is nice and ignorant. I can write another class to handle business logic type of stuff:

```<code>public class SpriteWhatever
{
    private Sprite sprite;

    public SpriteWhatever( Sprite sprite )
    {
        this.sprite = sprite;
    }

    public void Move( Vector2 direction )
    {
        // do move
    }

    // other methods...
}
</code>```

But then I'm worried that my domain model is anemic. In order to avoid that, I could just make all the properties of the Sprite class public, and keep all the business logic in it, but then I have no encapsulation.

What should I do?

答:
This is an answer to the question you posted in the comment on @AlfredoCasado's answer. It's only about the encapsulation aspect of your question.

[tl;dr]: The important thing about encapsulation is getting the functionality in methods/properties, not restricting access to the data.

The Wikipedia Article about encapsulation mentions these two definitions:

A language mechanism for restricting access to some of the object's components.

A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.

Many believe the first one (data hiding and access control) is the most important, and the article alludes to this. Note Robert Harvey's comment about rules: this is one you can be less guilty about breaking. Data Hiding is about 15-20% of the benefit. Using a property to wrap a member, by the way, is not even data hiding (unless it's a value type you're making read-only, or, returning a clone of a reference type or an immutable type; but often those are OOAD hints that you should be returning a value from a method).

Most of the benefit of Encapsulation comes from the 2nd item: bundling data. I would also add, organizing functionality in methods of an object (which also hides implementation, but that's not the point). This is 80-85% of the benefit of encapsulation.

Thus instead of an object's consumer having to worry about the details, you can do (and see) in a few lines of code, using terms from your ubiquitous language, that you've carried over into your method names, exactly what you want.

Then no matter how smart you are, your brain uses less horsepower, and you can do more. That's the 'magic' of OO right there. Data hiding isn't.

Another note about data hiding: It's just a hint to the programmers of the objects you made (50-80% of the time this is you). Devs can (and I see it all the time) check out your class and make private stuff public. Even if you're writing libraries for sale (and who does that?) they can use reflection to hack it. We've done it at my shop and saved tons of money! Who cares if the next version breaks because the implementation was private? We have control over which version we use!!

Bottom line you have to know or notice either way. If you don't know why it's private you won't take the hint. If you do, it won't matter. Yes, data hiding pushes devs in the right direction, and encourages good modelling practices. Here's the Elephant in the room: Encourage all you want. A person who doesn't know OOAD won't learn from encouragement. Better to spend the time teaching them.

Wow, that was long.

edit (See comment by @DavidKennedy85) I completely agree ... however, organizing the implementation into methods of an object (which I bet you do) provides that functionality as well - an accomplishes the lion's share of the benefits of encapsulation. I am not implying the first aspect is worthless - this is just what is taught so much (bulk of article reflects that).   The quote you mention brings up an important point - limiting the size of the interface surface to a cleverly-succinct small subset. (limit interdependencies). Another way to improve objects is to limit that state the object retains - meaning there will be fewer fields to make private. I am sure we agree on this things - I am just pointing out the obvious that for a dev to design her objects right, she has to start by first knowing how, then doing the design, and the private fields and methods will automatically become obvious without her having had to think about their accessibility; however focusing first on the fact that some things should have limited access isn't nearly as useful as the mountain of other 'artwork' that is involved in a proper design, and if proper design is done, what's public and private in the end won't be the thing that  matters.

A crappy design can expose itself in lots of publics - but that could be a good design. You can also have a crappy design with very few publics.

Now I'm just ranting - but I have a right to with every other programmer that came out of uni being told that it would be as easy as data hiding and a couple other concepts that sound good but are too basic to be helpful (like 'is-a/has-a'). It's not, it's much harder, and I was not taught the important things!


问:
How to consider the login function collecting requirements of an application? is it a user requirement?
I am working on an application that expected to the user logs in when the application is started (as for example it is in Skype: the user open the application and appear to him a login mask when he insert the username and password to start work with the application)

Now I am preparing some use case diagram and I am collecting the application requirements (I have to write some documentation)

Can I consider it as a user requirement? Or what is it?

答:
Yes, what else would it be?  Some applications do not require it, the user/customer wants it, it's a user requirement.

Now, that said, I would strongly urge you to push the user towards some kind of federated/openid login -- even if you have to develop a seperate login app.  This will allow your main application to get out of the business of dealing with login information, username, password, user information security, password reset, etc.

As an additional bonus, it will make it clear that, yes, indeed, logging in, is a user requirement.


问:
What is the applicability of CORS?
I have a system which needs to do cross-origin requests and having trouble understanding the relevance of CORS. At first glance it doesn't appear to provide me with any type of security I'd actually want for my service.

Since CORS is honoured only on the client side my server must still make zero assumptions about the request. There is no guarantee a request is coming from a browser at all, thus CORS headers cannot be used as access control.

The target server decides who is allowed to talk to it, and the origin server has no control. My JavaScript is also not secure on the client and subject to alteration. A malicious server could simply accept all CORS requests and thus all data could leak out of my application.

I see only a narrow scope of where CORS is actually helpful. This is the Facebook like scenario. Default cross-origin restrictions prevent a malicious page from making requests to Facebook on behalf of the user. CORS simply allows certain domains to do this. However, I still don't see the value in CORS here because some simple DNS setup would allow the same behaviour.

So what I am missing about CORS? In which scenarios is it relevant and advantageous to use (compared to simple DNS CNAME's)?

答:
Well, the first and most obvious scenario is when you really do want to allow everyone to call your service.  Say you have a public data repository that you want to encourage other people to use and develop interfaces for.  Without CORS, web apps are limited to having the user call the interface server and it making a webservice request and then responding to the user with that information -- the developer of the interface is acting as proxy, which they may not be able to afford/want to do.  With CORS your repository can be accesed by anyone, and thus the interface can be pure javascript.

Secondly, your first objection is irrelevant -- while the COR headers can not be used for acces control other headers and the body of the request certainly can.

As for your second objection -- typically, you aren't sending information to the second server, you are getting information from it.  And if you don't trust the second server your app doesn't have to use it.

Title: What is the applicability of CORS?


问:
How do you handle database security from a desktop application?
For about 10 years I've worked on various in-house desktop client applications with SQL Server data stores.  Rarely did I start these projects - most are takeover work.

One thing that seemed constant everywhere was that there was a single global SQL Server user account that this application used that granted it permission to the common database, and yes in some naive situations it used the sa user account, which I generally tried to fix when possible.

You can't really effectively hide this username and password that the application uses to access the database.  They're usually stored in an ini or config file, or possibly baked into the executable itself.  In all cases, they're visible to the user if they do a little digging.  In one case we actually used a config file but encrypted it, but of course the encryption key had to be stored in the executable (we weren't naive to the limitations of this, but it did effectively stop people from poking around who were savvy enough to look in config files).

All of these systems had a user-authentication system built into the application, but of course they were all managed through the application itself, meaning the user information was stored in the database.  The application restricted what things you could do based on your access level, but it's all kind of moot if you can just connect to the database and run ad-hoc queries.

I'm interested to know what other systems do to get around this problem.  Here are the options I know of:

Use SQL Server's security mechanism to maintain a user and roles list, and make the desktop application add and remove users through T-SQL queries.

Instead of connecting directly to the database, create some kind of web service that runs on the server and put the authentication logic in there.  Make every request do security validation.

The first options is a bit ugly because you're separating users from the database so users are no longer first class entities and you can't reference them with foreign key relationships, etc.

The second just seems like a major performance problem, and a lot of extra work, plus you can't as easily use ORM mappers like NHibernate (I think).

Does anyone have experience with this?  Best practices?

Edit

Thinking a bit more, can SQL Server Authentication actually solve this problem?  For instance, if your user must be able to insert and update timesheet records so you can edit your timesheet, there's no way SQL server can disallow access to other rows in the timesheet details table, meaning you can read and write other people's timesheets too.

答:
Building a new desktop security solution, we opted for the web service solution I´ll try to describe bellow.

We compile the desktop application executables in a separate environment from the developers.
And calculate a HASH from that executable that is recorded to the database.

One web service that provides all the needed information for the application to run, the DB password, connection string information, user permissions, etc...

we use single DB log in per application and record the user details in the database in session variables to be able to audit records.

A DLL handles all the communication from the desktop application to the web-service, that is only accessible with a token build into the DLL.

To be able to get the application DB password from the web service the DLL calculates the DLL callers HASH in runtime and passes as a parameter to the web service that validates the DLL token and the executable runtime calculated HASH to the one recorded when it was deployed (the application is only available in a single network shared installation).

That way we fell it is a good solution to the security problem we where most concerned with and are well aware of a few designs flaws. Are are almost finishing this implementation and so far we are happy with the results.

Edit:
You could replace the hash idea by using digital signatures and X.509 certificates.


问:
Need help modelling a User/Project/Task relationship
So I'm creating a very simple project/task management application in Laravel 4 and I'm not sure how these relationships would work. I have a Project, Task and User model. A User can own a Project or be a member of a Project. A Task belongs to a User and a Project.

What is the best way to define the User/Project relationship? I could have a many to many relationship from User to Project and use a project_user pivot table to associate the two. If I wanted to determine if a User owned the project I could add a field to Project called owner and populate it with the id of the User who created it. This seems kind of wrong though as this relationship would normally be modeled in a belongs to relationship?

Any advice is greatly appreciated :)

答:
As you describe it Project and User have two relations. One for the ownership and one for the membership. The first is a one-to-many relationship, the second a many-to-many relationship.

Adding the owner to the Project and filling it with the user id is simply the way to express that first relationship as a foreign key.

Whether an owner needs to belong to the project as a member as well is a different business rule entirely and would probably need to be modelled as a constraint on the owner field, or by a trigger adding the owner as the first member immediately and adding constraints to ensure that the owner cannot be deleted from the membership pivot table.

You could add an "is_owner" flag to the pivot table, but I would advise against that. Though it makes it easier to enforce an "owner must be member" rule (if applicable), it is less flexible, feels unnatural and that would require logic/triggers to ensure that there is always only one owner. It would also require a join to figure out who the owners of the projects are, whereas with the owner field on the projects table, that is a very straightforward query.


问:
Snapchat clone: How do I secure pre-downloaded notifications so that they cannot be opened outside of the app?
Say I'm making a snapchat clone app for Android and iOS. Let's say that I get a snapchat from Baz. I want to pre-download the audio for this snapchat. However, as the developer, I want to secure this audio from being viewable outside of the app.

I've been thinking of encrypting it using AES with an IV and key that are both generated from a pseudo-random function that takes the user's unique ID as input. However, if an attacker found out that this was the way we encrypt our files, and had access to our PRF, he would easily be able to decrypt it and store it permanently. The thing is, I don't have enough background in cryptography or android programming to tell if that's really a concern or not. The attacker has to learn a lot about our cipher in order to break it, but he could gain pretty much all of that from looking at the unobfuscated source of our app.

Is my suggested approach cryptographically secure? What other, better or simpler approaches could I take to solving this problem?

答:
Securely communicating the key with which a message was encrypted is a solved problem with asymmetric encryption, where each user has a public key for encryption (that can be stored on your servers), and a private key for decryption that only the recipient knows. This private key needs to be protected somehow, e.g. by encrypting it with a user-chosen passphrase.

That is, we have three levels:

The message, which is encrypted by a session key A.

The key A is encrypted itself with a public key B.

The user passphrase C to access the private part of the key B.

Don't reinvent something that already exists – the top paragraph basically describes a PGP implementation (which is used for encrypted emails). You could probably adapt such an implementation to your needs.


问:
Why should I use Iesi.Collections instead of the traditional System.Collection?
Was research on how (for convetion) define a Many Many where table where both fields are primary key and found this post.

So decide to install the Iesi.Collections in my library domain.

But there came a doubt. In the "Iesi.Collections" outperforms "System.Collections" Iesi.Collections?
Why should I use?

It is better in performance?

答: Iesi.Collections was originally released in 2004, when the .NET Framework was at v1.1. As of .NET 3.5, the .NET Framework includes a HashSet collection type, which provides the Set functionality that Iesi.Collections was intended to address. Unless you have a specific reason to use Iesi.Collections (e.g., NHibernate depends on it), it probably makes sense to use the standard .NET classes instead, since they are more likely to be supported and maintained.</p>


问:
Is MongoDB the right choice in my case?
I'm going to build my first real project in Rails that consist in a web app made of 3 main parts:

The static part where no database is used

The User registration part which will require a database and I can use MySQL since each user's row will have the same fields

The "App" where users will be able to create, organize, edit... items in collections and share them with other users

There will be several item types and each one will have different options for example I may have "video" items with the following options:

id

user_id

collection_id

title

platform (if embedded)

url (if embedded)

file name (if hosted on my app)

file size (id hosted on my app)

and "map" items:

id

user_id

collection_id

title

platform (google maps, bing maps...)

location

url

map size

As you can while for users I may use MySQL for items the flexibility of MongoDB may be useful since each item may need different options then another item

Up to now I've always used PHP and MySQL (always on shared hosting for small projects) and scalability is a totally new word for me.

I have time to learn but I would like to be able to do something concrete in something like 1 month.

I've read a lot about MongoDB and NoSQL vs RDMS and MySQL and after trying it I have to say that I like how MongoDB works: no tables, no rows and its documents JSON like so:

In my situation what would you raccomend? why?

About scalability there may be problems with MongoDB? if yes when (in term of DB size) and may these problems slow down my app considerably?

Edit: how the app will work

Since many asked this is how I'd like the app to work:

A user sign up

He's logged in

He create his first collection iside which he can create infinite items

Items are of various type and each type need different data to be saved in the database and type of items may be added or modified

Users may create other collections and items inside it.

So we have CRUD for collections and items inside of them and each collection/item is referred to a specific user

The main problem with MySQL is that it hasn't a flexible schema, there is way to solve this (a workaround?)?

Thinking about NoSQL the only doubt I have is about join, for example given a certain colection I want to retrieve datas related to the User with id = user_id field in the collection

EDIT: Idea to keep using MySQL

Create a field in the "items" table with optional settings, each setting divided by a | or another symbol.

Then I will save somewhere a structure of each item optional settings, for example the "notes" item type need two optional settings "colour" and "strange_setting", when I get the data from MySQL i will split the field for optional settings into an array knowing that the first item in the array is for "colour" and so on.

What do you think? there are problem with that solution? do you have other ideas?

答:
The article below provides good results comparing MySQL and MongoDB in terms of select, fetch and insert, considering the amount of data in the database and the amount of retrieved data. The results shows great perfomance for MongoDB regarding the "inserts", but the other cases MySQL wins. See below:

http://www.moredevs.ro/mysql-vs-mongodb-performance-benchmark/

I had an experience using MongoDB that I think it was a good solution. I used it to insert thousands of collections every day. Combined with Solr solution (cache solution, updated once per day), I can retrieve the MongoDB data by the collection id when needed, so I don't need selects on the fly. So, considering you have to deal with lots of inserts and don't needing to care about to select and fetch, MongoDB could be a great idea, it will depends on each case and to do good analysis.

Title: Is MongoDB the right choice in my case?


答:
Every time I write a RESTful service, I throw in the CORS headers so that I can read it from an arbitrary javascript/browser application.

The reasons are:

1) CORS is all about client-side security, and has NO EFFECT on server side security. (This was the main point that confused me when I first started looking at it.)

2) I always provide some security mechanism like OAuth anyway, so that the browser's cross-origin restriction is weak and redundant.

3) A malicious user can trivially stand up a proxy service that takes requests and routes them to your service. The proxy doesn't care about the same-origin restriction, which defeats the restriction in the browser.

But for me, the short answer is, either my data is protected with some authorization scheme like OAuth, or else it's not protected and I don't care if (or actively want) an arbitrary browser comes in and gets it.

BTW standing up a proxy on the same server that serves the pages is the "other" official way to defeat the same-origin restriction. ;) I have to do that for the RESTful services I integrate with but I don't own. ...If you're doing that, just provide some limits so the proxy doesn't become a wide-open portal to your internal infrastructure.

More information on CORS headers here: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

Title: What is the applicability of CORS?

Body:
I have a system which needs to do cross-origin requests and having trouble understanding the relevance of CORS. At first glance it doesn't appear to provide me with any type of security I'd actually want for my service.

Since CORS is honoured only on the client side my server must still make zero assumptions about the request. There is no guarantee a request is coming from a browser at all, thus CORS headers cannot be used as access control.

The target server decides who is allowed to talk to it, and the origin server has no control. My JavaScript is also not secure on the client and subject to alteration. A malicious server could simply accept all CORS requests and thus all data could leak out of my application.

I see only a narrow scope of where CORS is actually helpful. This is the Facebook like scenario. Default cross-origin restrictions prevent a malicious page from making requests to Facebook on behalf of the user. CORS simply allows certain domains to do this. However, I still don't see the value in CORS here because some simple DNS setup would allow the same behaviour.

So what I am missing about CORS? In which scenarios is it relevant and advantageous to use (compared to simple DNS CNAME's)?


问:
Unit testing multiple conditions in an IF statement
I have a chunk of code that looks something like this:

```<code>function bool PassesBusinessRules()
{
    bool meetsBusinessRules = false;

    if (PassesBusinessRule1
         && PassesBusinessRule2
         && PassesBusinessRule3)
    {
         meetsBusinessRules= true;
    }

    return meetsBusinessRules;
}
</code>```

I believe there should be four unit tests for this particular function.  Three to test each of the conditions in the if statement and ensure it returns false.  And another test that makes sure the function returns true.

Question: Should there actually be ten unit tests instead?  Nine that checks each of the possible failure paths.  IE:

False False False

False False True

False True False

And so on for each possible combination.

I think that is overkill, but some of the other members on my team do not.  The way I look at it is if BusinessRule1 fails then it should always return false, it doesn't matter if it was checked first or last.

答:
This is one of those cases where Something like quickcheck (http://en.wikipedia.org/wiki/QuickCheck) will be your friend. Instead of writing out all N cases by hand have the computer generate all (or at least a large number) of possible test cases and validate that all return a sensible result. </p>

<p>We program computers for a living here, why not program the computer to generate your test cases for you? </p>

Body:
This is one of those cases where Something like quickcheck (http://en.wikipedia.org/wiki/QuickCheck) will be your friend. Instead of writing out all N cases by hand have the computer generate all (or at least a large number) of possible test cases and validate that all return a sensible result.

We program computers for a living here, why not program the computer to generate your test cases for you?


答:
You could refactor the conditions into guard conditions:

```<code>if (! PassesBusinessRule1) {
    return false;
}

if (! PassesBusinessRule2) {
    return false;
}

if (! PassesBusinessRule3) {
    return false;
}
</code>```

I don't think that reduces the number of cases, but my experience is that it's easier to break them out this way.

(Note that I'm a big "single point of exit" fan, but I do make an exception for guard conditions. But there are other ways to structure the code so you don't have separate returns.)

Title: Unit testing multiple conditions in an IF statement

Body:
I have a chunk of code that looks something like this:

```<code>function bool PassesBusinessRules()
{
    bool meetsBusinessRules = false;

    if (PassesBusinessRule1
         && PassesBusinessRule2
         && PassesBusinessRule3)
    {
         meetsBusinessRules= true;
    }

    return meetsBusinessRules;
}
</code>```

I believe there should be four unit tests for this particular function.  Three to test each of the conditions in the if statement and ensure it returns false.  And another test that makes sure the function returns true.

Question: Should there actually be ten unit tests instead?  Nine that checks each of the possible failure paths.  IE:

False False False

False False True

False True False

And so on for each possible combination.

I think that is overkill, but some of the other members on my team do not.  The way I look at it is if BusinessRule1 fails then it should always return false, it doesn't matter if it was checked first or last.

Body:
You could refactor the conditions into guard conditions:

if (! PassesBusinessRule1) {
    return false;
}

if (! PassesBusinessRule2) {
    return false;
}

if (! PassesBusinessRule3) {
    return false;
}

I don't think that reduces the number of cases, but my experience is that it's easier to break them out this way.

(Note that I'm a big "single point of exit" fan, but I do make an exception for guard conditions. But there are other ways to structure the code so you don't have separate returns.)


问:
As a practitioner, why should I care about Haskell? What is a monad and why do I need it?
I just do not get what problem they solve.</p>

答:
If you're familiar with the GoF patterns, monads are like the Decorator pattern and Builder pattern put together, on steroids, bitten by a radioactive badger.

There are better answers up above, but some of the specific benefits I see are:

monads decorate some core type with additional properties without changing the core type. For example, a monad might "lift" String and add values like "isWellFormed", "isProfanity" or "isPalindrome" etc.

similarly, monads allow conglomerating a simple type into a collection type

monads allow late binding of functions into this higher-order space

monads allow mixing arbitrary functions and arguments with an arbitrary data type, in the higher-order space

monads allow blending pure, stateless functions with an impure, stateful base, so you can keep track of where the trouble is

A familiar example of a monad in Java is List. It takes some core class, like String, and "lifts" it into the monad space of List, adding information about the list. Then it binds new functions into that space like get(), getFirst(), add(), empty(), etc.

On the large scale, imagine that instead of writing a program, you just wrote a big Builder (as the GoF pattern), and the build() method at the end spat out whatever answer the program was supposed to produce. And that you could add new methods to your ProgramBuilder without recompiling the original code. That's why monads are a powerful design model.


问:
Maybe monad vs exceptions
I wonder what are the advantages of Maybe monad over exceptions? It looks like Maybe is just explicit (and rather space-consuming) way of try..catch syntax.

update Please note that I'm intentionally not mentioning Haskell.

答:
Exception handling can be a real pain for factoring and testing. I know python provides nice "with" syntax that allows you to trap exceptions without the rigid "try ... catch" block. But in Java, for example, try catch blocks are big, boilerplate, either verbose or extremely verbose, and hard to break up. On top of that, Java adds all the noise around checked vs. unchecked exceptions.

If, instead, your monad catches exceptions and treats them as a property of the monadic space (instead of some processing anomaly), then you're free to mix and match functions you bind into that space regardless of what they throw or catch.

If, better yet, your monad prevents conditions where exceptions could happen (like pushing a null check into Maybe), then even better. if...then is much, much easier to factor and test than try...catch.

From what I've seen Go is taking a similar approach by specifying that each function returns (answer, error). That's sort of the same as "lifting" the function into a monad space where the core answer type is decorated with an error indication, and effectively side-stepping throwing & catching exceptions.

Title: Maybe monad vs exceptions


问:
Can I license a program under Apache License 2.0, if it is using/including Eclipse Link (EPL or EDL)?
Can I license a program under Apache License 2.0, if it is using/including EclipseLink?
(EclipseLink under Eclipse Public License or Eclipse Distribution License)

I did not change anything in EclipseLink.
I would realy like to distribute a Version that includes the needed EclipseLink jars, so that it is working "out of the box".

答:
For most things you might want to do, yes.

There are differences in the terms so that some situations could result in problems. As always, before you do anything like commercial use or annoying someone big and nasty get competent legal advice. The advice will probably be: don't do it.

Make sure you read the licences and do what they say you have to. EPL seems to require their copyright notice on your distribution, so do that. Full disclosure of what components you used and including copies of everyone's licence in your distribution should keep everyone happy.

OwnerDisplayName: scherlock


问:
Upgrading old ASP classic to newer standards
For the past year I have been working in a Classic ASP \ ASP.net hybrid. The website has 1M+ hits daily.
The code, as you can imagine, is very hard to navigate. There are 200+ files.
Dozens of includes...

```<code><!--#INCLUDE virtual="sub/head.aspx"-->
</code>```

I need to make a function that would be used throughout the website and I don't even know where to put it. There is no Visual Studio project file.

My questions is... how can I upgrade it to a full ASP.net website. MVC is not an option since the owner is concerned there will be a performance decrease.
I would be happy if I could load it up in VS and have a app_data folder, plus all the goodies of ASP.net (when compared to classic asp)

答:
I don't think there is a tool or something to just magically upgrade a classic ASP site to ASP.NET. I think you will need to write the code. The good news is you already have the markup and changing it to RAZOR should be pretty trivial, tedious mostly.

As for the performance concerns about MVC, that is without merit. MVC should be faster than WebForms. For the record 80-95% of web performance issues are in how the markup, css and JavaScript are structured to work in the browser and transport across the wire. While WebForms has gotten better in recent years there are many artifacts that make it less than optimal. My advice, if you cant use MVC and are forced to use the WebForms engine, do not use any of the controls and disable the viewstate. I did that few years back when I transitioned off WebForms and into modern web development. It worked well.


问:
DDD Proper aggregates division and getting rid of too many references
I am designing an application, which will aid designing electric installations. I went for Domain Driven Design, as the topic is complex and the application will be growing with gained knowledge. However, I am newbie to this concept. For now, I have a problem to properly model the domain, especially to divide entities into aggregates.

I have defined wiring - Installation as a set of ConnectionPoints and Cables, which connect them. One ConnectionPoint has one or more Cables. Each Cable has a set of wires. I consider end of a wire as a Terminal, which we can connect to another Terminal creating a Junction. Terminals differ one from another, as wires have different colours and purpose. Junctions are made of two or more Terminals and can be done only inside a ConnectionPoint. I have illustrated it for a better understanding:

Besides Cables there are also Devices, which also have Terminals. They are also connected in a ConnectionPoint and their Terminals are treated the same way as Cable's  Terminals. For each Device I must be able to track, where the Terminal is connected to (it might be a list of end points).

The problem, with the design, is the need of having references to Terminals outside of a Cable and Device entities to create Junctions and track connections. I could consider a Cable and a Device as aggregates of Terminals, as Terminals cannot exist without them and as a knowledge of Terminal's parent is important. However, each Terminal has also an identity outside of a Cable / Device and I have no idea how later in code and database I could keep knowledge of the connections made.

Do you have any ideas how could I model it? What questions should I ask myself to define a correct model and avoid keeping references everywhere?

答:
The point of DDD is to allow express complex behavior in domain model and not just complex structure. And what you are describing is just a static structure. I believe DDD is not going to help you here. If you do have such behavior, then best way is to use TDD and slowly evolve the whole design. If you don't then you should look back at standard modeling techniques and don't use DDD.

Aggregates are great if you want to keep specific invariants on multiple different entities that are related, but they can be problematic when modeling complex relationships, just like you are experiencing.


问:
Domain Name Lookup
I'm trying to automate the process of sending many domain name lookup requests.

I tried to do this by sending for example http request to domain registry site like Whois.net, but I notice they block you after several attempts.

others like networksolutions adds token to the page to avoid automated requests.

Is there any ideas please?

I'm using Java.

答:
You are currently going through middlemen (remote web servers) instead of querying the information more directly.

There's a program on your host system called whois (which is what that whois.net site is named after!) which you can call as a subprocess, and the information out of it isn't usually too hard to parse. Theoretically, you could write the client in Java directly, but why would you bother to duplicate all that effort?

Title: Domain Name Lookup


问:
Scrum: requirements clarification vs changing scope
So we estimate the story and put tasks on the board. Then during the Sprint the UX guy comes up with a user experience for the story that is more complicated than what we originally thought. So on one hand we want to implement the right feature for the user, on the other hand if we had known about the complexity of the UX during Sprint planning, we probably wouldn't have committed to the story.

So what to do in cases such as this?

The same question applies to cases where a usability test or user feedback during the Sprint shows us that we should change the feature.

In general, where do you draw the line between clarification of requirements or adaptations and the changing of scope?

答:
Well, the first thing that stands out is that UX effort should be part of your story point estimate.

But that point aside, when I've been faced with a story that wasn't what it originally seemed I usually ask the following questions:

Does the new version of the story invalidate the complexity estimate?

If yes, pull the story from the sprint.

If not, you may still be able to deliver the new version.

Can it be broken down into smaller stories (at least one of which will be delivered in this sprint)?

If yes, you can attempt to deliver the same number of story points without delivering the entire set of stories.

If not, pull the story from the sprint.

Does the new version of the story invalidate the sprint?

By this I mean "has the sprint goal changed?"  If so, cancel the sprint.

This is usually a decent compromise as the PO will still receive some of the promised business value and you're not actually introducing scope creep in your sprint.


答:
At the end of the day, UX is part of the story and, as MetaFight points out, your UX person should be involved in the estimation.

That said, don't worry about it TOO much. If these kind of surprises are a regular occurrence, your velocity will automatically account for it.

If this is unusual, your business owner should be made aware and should be OK with dropping lower-priority stories (which may or may not include this one) from this sprint. If they're not, you have a different problem.

Title: Scrum: requirements clarification vs changing scope

Body:
So we estimate the story and put tasks on the board. Then during the Sprint the UX guy comes up with a user experience for the story that is more complicated than what we originally thought. So on one hand we want to implement the right feature for the user, on the other hand if we had known about the complexity of the UX during Sprint planning, we probably wouldn't have committed to the story.

So what to do in cases such as this?

The same question applies to cases where a usability test or user feedback during the Sprint shows us that we should change the feature.

In general, where do you draw the line between clarification of requirements or adaptations and the changing of scope?


问:
Does an iterator have a non-destructive implied contract?
Let's say I'm designing a custom data structure like a stack or a queue (for example - could be some other arbitrary ordered collection that has the logical equivalent of push and pop methods - ie destructive accessor methods).

If you were implementing an iterator (in .NET, specifically IEnumerable<T>) over this collection that popped on each iteration, would that be breaking IEnumerable<T>'s implied contract?

Does IEnumerable<T> have this implied contract?

eg:

```<code>public IEnumerator<T> GetEnumerator()
{
    if (this.list.Count > 0)
        yield return this.Pop();
    else
        yield break;
}
</code>```

答:
In an attempt to keep things "simple", .NET only has one generic/non-generic pair of interfaces for things which are enumerated by calling GetEnumerator() and then using MoveNext and Current on the object received therefrom, even though there are at least four kinds of objects which should support only those methods:

Things which can be enumerated at least once, but not necessarily more than that.

Things which can be enumerated an arbitrary number of times in free-threaded contexts, but may arbitrarily yield different content each time

Things which can be enumerated an arbitrary number of times in free-threaded contexts, but can guarantee that if code which enumerates them repeatedly doesn't call any mutating methods, all enumerations will return the same content.

Things which can be enumerated an arbitrary number of times, and are guaranteed to return the same content every time as long as they exist.

Any instance which satisfies one of the higher-numbered definitions will also satisfy all the lower ones, but code which requires an object satisfying one of the higher definitions may break if given one of the lower ones.

It appears that Microsoft has decided that classes which implement IEnumerable<T> should satisfy the second definition, but are under no obligation to satisfy anything higher.  Arguably, there's not much reason that something which could only meet the first definition should implement IEnumerable<T> rather than IEnumerator<T>; if foreach loops could accept IEnumerator<T>, it would make sense for things that can only be enumerated once to simply implement the latter interface.  Unfortunately, types which only implement IEnumerator<T> are less convenient to use in C# and VB.NET than types which have a GetEnumerator method.

In any case, even though it would be useful if there were different enumerable types for things that could make different guarantees, and/or a standard way to ask an instance that implements IEnumerable<T> what guarantees it can make, no such types as yet exist.


问:
How to put lessons learned, good practices, etc into the "work flow"
As the title states it, I would like to get some suggestions about putting knowledge into action.

We have many additional requirements that concern: coding practices feature development (all of them or only a subset), process, etc. The problem is that we have problems with introducing those practices into new projects and I want to help developers and reviewers to remember about it, but I don't want them to have everything just in theirs heads, but rather in some kind of a database that they can use easily.

The list of practices is already defined in Excel. I would like all team members to apply these practices in their work but I don't know how make those information easy to find. When developer starts working on a feature he should be able to easily find all practices that he should use in these feature.

To be clear with what I mean, I'm showing some examples of information we have to apply:

(new design request) every feature must output logs (and it must not contain any sensitive data);

(new design request) every feature has to have a flag in the configuration that allows to disable it;

(good practice) always update docs when feature is ready;

(retrospective feedback) QA must test only on release package (not in debug mode);

(retrospective feedback) make stress tests for every new feature implemented;

(lead's task) write release notes after each sprint that includes tasks completed and open bugs;

(design usage) every event from "ABCStoreManager" must be disconnected after being invoked;

(design usage) try-catch every event.Invoke() call;

I thought for a while about a wiki, but it's no good, because it doesn't support tagging/categories or querying and I'm afraid that everybody would ignore it (people must know exactly where to look).

My question can be summed up as how can I improve communication to our developers about the required development methodologies and practices listed above in an easy way?

Remarks:

this question is not about security issues or code smells per-se;

I'm not looking for any heavy process (like RUP) or any process for that matter, which forces you to go step by step. Preferably I am looking for an agile approach

Daniel Figueroa has suggested adding additional requirements to the "definition of done". And it seems like a good way. But the problem is that some features have, for instance, 20 additional requirements ("all GUI features"), some 10 ("all server requests"), etc. I would like to have this stuff aggregated in a one place and just use links ("see: 'GUI feature' ");

答:
Okay so here is what I believe.

When it comes to your example with the logs I think you actually have the answer in your list. What it boils down to is in the definition of done. If the devs are printing sensitive data to the logs and the testers are supposed to check that no sensitive data makes it to the logs, then clearly that feature isn't done, which means that the tester should put that feature back to In progress or whatever you guys are doing to keep track of development.

The same goes for everything that has to do with the actual code, now I'm not promoting a view that the testers should teach the developers. But they should work as a guard that the implementation is up to par with your standards. Any developer worth his/her salt should quickly take it to heart if every time they create a new feature it gets sent back because they didn't properly adhere to some of your rules.

Another thing I think is really important is what @Robert Harvey put in the comments field, code reviewing. That could be anything from pair-programming to something more formal. If a piece of code has only touched one pair of eyes I strongly believe something must be done. Such a simple thing as a high level description of what the code does while showing the actual code has made me blush several times because I've found problems or things I've missed several times. And usually it's just dumb mistakes.

So to recap:

One responsibility of the testers are to check that the devs are following rules.

Don't let devs act as lone-wolfs, should be a social activity (I don't always like it but it's true).

Have a clear definition of done, and don't let the implementer be the only one that says it's done.

I think this is a question about culture not about tools.


答:
I think this would be a violation of the Liskov substitution principle which states,

objects in a program should be replaceable with instances of their
  subtypes without altering the correctness of that program.

If I had a method like the following which is called more than once in my program,

```<code>PrintCollection<T>(IEnumerable<T> collection)
{
    foreach (T item in collection)
    {
        Console.WriteLine(item);
    }
}
</code>```

I should be able to swap out any IEnumerable without altering the correctness of the program, but using the destructive queue would alter the programs behavior extensively.

Title: Does an iterator have a non-destructive implied contract?

Body:
Let's say I'm designing a custom data structure like a stack or a queue (for example - could be some other arbitrary ordered collection that has the logical equivalent of push and pop methods - ie destructive accessor methods).

If you were implementing an iterator (in .NET, specifically IEnumerable<T>) over this collection that popped on each iteration, would that be breaking IEnumerable<T>'s implied contract?

Does IEnumerable<T> have this implied contract?

eg:

```<code>public IEnumerator<T> GetEnumerator()
{
    if (this.list.Count > 0)
        yield return this.Pop();
    else
        yield break;
}
</code>```

Body:
I think this would be a violation of the Liskov substitution principle which states,

objects in a program should be replaceable with instances of their
  subtypes without altering the correctness of that program.

If I had a method like the following which is called more than once in my program,

PrintCollection<T>(IEnumerable<T> collection)
{
    foreach (T item in collection)
    {
        Console.WriteLine(item);
    }
}

I should be able to swap out any IEnumerable without altering the correctness of the program, but using the destructive queue would alter the programs behavior extensively.


问:
Is there anyone who has used Python/Ruby and PHP for a long time and still prefer PHP?
I am usually fascinated by articles defending PHP and the arguments being used. Quite often authors of these types of articles don't mention what experience they have with other languages. Personally I find it hard to imagine that somebody would know either Python or Ruby, and PHP at a high level and still prefer PHP.

So if anyone fits this description, I would be interested in hearing why you prefer PHP to either of these languages.

答:
Our company still prefers PHP for a few simple reasons:

Easy to scale to medium sized deployments. No need for proxy servers, caches, etc., PHP is fairly efficient with very little effort. Also trivial to set up for most developers.

Developers are cheap and abundant. This is especially handy for enterprise shops like ours where we're solving relatively narrow problems.  This makes PHP profitable for vertical style products.

Easy to train the average developer. We've converted Java, C, and C++ programmers to PHP with minimal effort.  Python and Ruby are excellent languages, but they take a bit more thinking for average developers to grok (in our experience).

Now for me personally (versus my employer), I prefer Ruby + Rails for web development and Python for back-end tools (like mini servers, etc.). These two languages are interchangeably great, but I've traditionally used them for those two purposes.

And looking to the future, JavaScript on the server is gaining mojo, especially in places where I've traditionally used Python (mini servers, etc.).


问:
How does BASIC locate an out-of-order NEXT statement when the loop body is skipped
Set the WABAC machine, Sherman.  This question is about BASIC in general, and Microsoft's BASIC-80 in particular.  Old school basic.  With line numbers.

How do (or, rather, did) old-school BASIC interpreters handle FOR...NEXT loops when the loop body was not executed, and the NEXT statement appeared out of order?

An out-of-order NEXT statement from the before time:

Here's a subroutine from the game Awari out of David H. Ahl's "101 Basic Computer Games":

```<code>200 K=M:GOSUB 600
205 E=0:IF K>6 THEN K=K-7
210 C=C+1:IF C<9 THEN F(N)=F(N)*6+K
215 FOR I=0 TO 5:IF B(I)<>0 THEN 230
220 NEXT I
225 RETURN
230 FOR I=7 TO 12:IF B(I)<>0 THEN E=1:RETURN
235 GOTO 220
</code>```

and here it is with everything except the flow control redacted:

```<code>200 GOSUB 600
215 FOR I=0 TO 5:IF ... THEN 230
220 NEXT I
225 RETURN
230 FOR I=7 TO 12:IF ... THEN RETURN
235 GOTO 220
</code>```

Does that bring back not-so-fond memories?  Can you hear Dijkstra  rolling over in his grave?

Here are the interesting part of what's happening in this fragment:

The second FOR loop, since it uses the same loop variable, replaces the first FOR loop

The two FOR loops share the same NEXT statement

The second FOR loop's NEXT statement comes before it, in source order, but after it, in execution order

You might suppose, then, that the interpreter, having started a FOR loop, simply runs statements until it happens across the NEXT loop.  The order of the statement in the source does not matter in this case.  But let's see what the basic80 manual has to say about FOR loops:

The basic-80 manual says "moo..."

The body of the loop is skipped if the initial value of the loop times
  the sign of the step exceeds the final value times the sign of the
  step.

So, the loop body can be skipped entirely.

We have evidence, in the form of published programs, that at least some versions of BASIC were dynamically locating their NEXT statements.  This is easy enough to do when the loop body is being executed.  However, in the case where the body of the FOR statement should be skipped, as BASIC-80 permits, how did BASIC locate the NEXT statement, given that it might be before the FOR statement in source order?

Did the version of BASIC used in "101 Basic Computer Games" always execute the loop body at least once?

Did BASIC-80 require a FOR loop's NEXT statement to occur after the FOR statement, in source order?

PS: Yes, I'm writing a BASIC interpreter for old school BASIC.  It's a sickness.

答:
I don't have a copy of the specification for one of these ancient BASIC interpreters in front of me (it may not even exist), but I'm going to go out on a limb and say that the BASIC interpreter will not execute a NEXT on a FOR loop that doesn't belong to it, even if the loop variable has the same name.

So, in other words, in your example

```<code>200 K=M:GOSUB 600
205 E=0:IF K>6 THEN K=K-7
210 C=C+1:IF C<9 THEN F(N)=F(N)*6+K
215 FOR I=0 TO 5:IF B(I)<>0 THEN 230
220 NEXT I
225 RETURN
230 FOR I=7 TO 12:IF B(I)<>0 THEN E=1:RETURN
235 GOTO 220
</code>```

when line 235 executes and goes to line 220, line 220 will NEXT the top FOR loop, not the bottom.

This is evident in the "NEXT without FOR" error message; the BASIC interpreter rejects any NEXT for which it did not find a corresponding FOR.  This typically happens when you get your NEXT's out of order, as in

```<code>100 FOR I = 1 to 10
110 FOR J = 1 to 10
120 ...
130 NEXT I
140 NEXT J
</code>```

So to answer your bulleted questions:

Yes, if the loop variable is within range of the FOR.

Yes, to my knowledge, that is the case.

Body:
I don't have a copy of the specification for one of these ancient BASIC interpreters in front of me (it may not even exist), but I'm going to go out on a limb and say that the BASIC interpreter will not execute a NEXT on a FOR loop that doesn't belong to it, even if the loop variable has the same name.

So, in other words, in your example

200 K=M:GOSUB 600
205 E=0:IF K>6 THEN K=K-7
210 C=C+1:IF C<9 THEN F(N)=F(N)*6+K
215 FOR I=0 TO 5:IF B(I)<>0 THEN 230
220 NEXT I
225 RETURN
230 FOR I=7 TO 12:IF B(I)<>0 THEN E=1:RETURN
235 GOTO 220

when line 235 executes and goes to line 220, line 220 will NEXT the top FOR loop, not the bottom.

This is evident in the "NEXT without FOR" error message; the BASIC interpreter rejects any NEXT for which it did not find a corresponding FOR.  This typically happens when you get your NEXT's out of order, as in

100 FOR I = 1 to 10
110 FOR J = 1 to 10
120 ...
130 NEXT I
140 NEXT J

So to answer your bulleted questions:

Yes, if the loop variable is within range of the FOR.

Yes, to my knowledge, that is the case.


答:
While whois is often used as a method to determine domain name availability, it is not always real-time or accurate.

The best and proper way to do this would be to become an accredited registrar for the TLDs in question and use the registry's APIs (which usually work with the extensible Provisioning Protocol (EPP)) to determine availability.

How easy and cheap this is would depend on how many TLDs need to be supported. Another cheaper option with some limits would be to become a reseller that has has an API and supports the TLDs in question.

Title: Domain Name Lookup

Body:
I'm trying to automate the process of sending many domain name lookup requests.

I tried to do this by sending for example http request to domain registry site like Whois.net, but I notice they block you after several attempts.

others like networksolutions adds token to the page to avoid automated requests.

Is there any ideas please?

I'm using Java.


问:
Is it necessary to science of DSP for a c++ programmer?
I am a C++ programmer.  I would like to use DSP algorithms in C++.

Is understanding the science behind Digital Signal Processing a prerequisite to implementing DSP algorithms?

答:
A lot depends on the algorithm you're trying to implement.  Some of them require a LOT more knowledge of what's going on than others.  Almost all of them require at least the basics.

A basic AGC (automatic gain control) is simple.  Basic filters are fairly simple.  Mixers start to require more knowledge.

Active echo cancellation using least mean squares, and especially normalized least mean squares, just about requires that you know what you're doing, especially if you're doing it in fixed point math (as opposed to floating point).  Trust me on this.

Certain kinds of image processing can bite you in the ass if you don't know the secret insider knowledge.  I have the toothmarks to prove this one, too.

Hamming's book on "Digital Filters" is a good place to start, if you need an overview.


问:
What is a byte stream actually?
Can anyone explain me what byte stream actually contains? Does it contain bytes (hex data) or binary data or english letters only? I am also confused about the term "raw data". If someone asked me to "reverse the 4 byte data", then what should I assume the data is hex code or binary code?</p>

答:
A byte is 8 bits. A bit is 0 or 1. The "raw data" is just a flow of one byte after another. A byte stream can come from a file, a network connection, a serialized object, a random number generator, etc.

There are several ways to display a byte: binary (01110110), hex = hexidecimal (7C), octal (0271), or decimal (215). In all cases, the maximum value is 255 (base 10).

Sometimes bytes are assigned to characters, like ascii. Type "ascii" on a unix command line, and you'll get a big table that maps the byte vales 0-255 or (0-FF hex) to the associated character. For example, space is x20 and "A" is x40. Note that some byte values map to control characters and aren't printable. But the bytes themselves aren't characters -- they'e just a bundle of bits. A number.

"reverse 4 bytes" would be to take some bytes 123 42 231 0 and flip the order -- 0 231 42 123. Applied to a byte steam, I'd probably read 4 bytes, reverse them, read the next 4 bytes, etc.

(BTW that problem is relevant, because if you want to represent a number bigger than 255 as byes, you need to use more than one byte. But then the question is, does the "biggest" byte come first, or last? That's called big endian or little endian -- look those up for more background on why it's useful to shuffle around the bytes in a raw byte stream.)

Title: What is a byte stream actually?


问:
What is a stream, and how does it work?
Like a data stream in general, this can be an I/O stream or memory stream or a file stream or what not.

I understand that it's some sort of stream of bytes, that you can read to parse very large amounts of data if needed, what I don't understand however, is how it works.

Is it possible to 'miss' data from a stream if you start reading it too late? or does it wait for you?

A lot of tutorials I find online just tell how to use a stream, but it doesn't actually get out of the way to explain how it works, one tutorial explained it like a river, but that just confuses me more; the water running in the river doesn't wait, which again brings me back to; what if I read it too late?

Can someone explain this concept to me?

答:
whether it is possible to miss some data depends on the source of the data;

if you start streaming a file then it will always start at the beginning of the file wait for you and you can rewind as needed.

if you are streaming an internet livestream then you will start getting data from the point you connect. and it won't wait

you can compare it to listening to audio, you can start/pause/rewind at any point you want on a LP record/cassette/CD but you can't with radio broadcasts

Title: What is a stream, and how does it work?


答:
The defining trait of a stream is that you can consume it part by part. Typically, a stream API has methods that offer the next chunk, the next byte etc. of content, and you call them in a loop, interleaving processing with the reading of data. The opposite would be a component that only lets you access the entire content at once, e.g. a primitive File API that only has a method that looks like

```<code>  byte[] getContent()
</code>```

The disadvantage of non-streamed data access is that you have to store the entire data in memory at one time or other, which may be prohibitively expensive if there is a lot of it.

As ratchet freak explained, streaming access doesn't mean you won't miss something if you start reading too late. It only promises that it's okay in principle to read the data in increments rather than all at once.

Title: What is a stream, and how does it work?

Body:
Like a data stream in general, this can be an I/O stream or memory stream or a file stream or what not.

I understand that it's some sort of stream of bytes, that you can read to parse very large amounts of data if needed, what I don't understand however, is how it works.

Is it possible to 'miss' data from a stream if you start reading it too late? or does it wait for you?

A lot of tutorials I find online just tell how to use a stream, but it doesn't actually get out of the way to explain how it works, one tutorial explained it like a river, but that just confuses me more; the water running in the river doesn't wait, which again brings me back to; what if I read it too late?

Can someone explain this concept to me?

Body:
The defining trait of a stream is that you can consume it part by part. Typically, a stream API has methods that offer the next chunk, the next byte etc. of content, and you call them in a loop, interleaving processing with the reading of data. The opposite would be a component that only lets you access the entire content at once, e.g. a primitive File API that only has a method that looks like

  byte[] getContent()

The disadvantage of non-streamed data access is that you have to store the entire data in memory at one time or other, which may be prohibitively expensive if there is a lot of it.

As ratchet freak explained, streaming access doesn't mean you won't miss something if you start reading too late. It only promises that it's okay in principle to read the data in increments rather than all at once.


问:
Will You Use an Online Technical Skills Test to Hire a Senior Developer?
There are online services such as IKM that offer skills tests in many areas, including programming.

Would you use these kind of tests when hiring for a senior developer position?

What about just for objectively benchmarking candidates before calling them for an interview? Would you use it as a step after short-listing candidates after interviews?

Is this approach more suitable in some situations compared to others? Have you personally used this kind of service or know someone who has?

答:
Would you use this kind of tests while hiring senior developer positions?

Yes.

What about just for objectively benchmarking candidates before calling them for interview?

No.  Benchmarking implies you compare candidates based on score.  The tests are better used to determine a baseline, not perform benchmarking between candidates.

Would you use it as a step after short-listing candidates after interview?

No.  You should have done the test before the interview.  The interview is the basis for future consideration.

Is this approach more suitable in some situations compared to others?

If proof of programming knowledge is most of what a candidate would bring (e.g. junior developer) then it is proportionally more useful.

Have you personally used this kind of services or know someone using it?

I was subject to one at a recruiting company I used.  I found it helpful in understanding which concepts I needed to brush up on.


问:
what is difference between protected static method and protected method?
What is difference between protected static method and protected method? For example demo and demo2 in Data2 respectively

Data.java:

```<code>package pack1;

import pack2.*;

public class Data extends Data2 {

    public static void main(String args[]){
        System.out.println("From main class");
        Data d=new Data();
        d.first();
    }

    void first(){
        Data2 d2=new Data2();

        d2.demo();
        d2.demo2();
    }
}
</code>```

Data2.java:

```<code>package pack2;

public class Data2 {
    protected static void demo(){
        System.out.println("In method demo");
    }

    protected void demo2(){
        System.out.println("In method demo2");
    }
}
</code>```

答:
A static method is a method which doesn't belong to a particular instance of a class. It belongs  to the class itself.

You could write Demo2.demo() to call the static method directly on the class without creating an instance. But you couldn't call Demo2.demo2() because demo2 isn't static and thus can only be called on an instance you created with the new keyword.

Because a static method is not (necessarily) bound to a specific instance of a class, it can only access static variables (the value of static variables is shared between all instances of a class while the value of a non-static variable is different for each instance you create with the new keyword).

You might wonder "what's the reason for a static protected method, considering that it's impossible to call it from anywhere except from an instance of that class?". Usually there isn't much reason to declare a private or protected method as static. Static methods are usually public. But when the behavior of a method does not affect or is affected by the state of the current instance, declaring it static can be a way to document this fact.


问:
Would Python be too slow for client-side use in Browsers?
I've heard the statement that Python would be too slow to be of any use in browsers.

I reckon Javascript is only superior in this aspect because of companies like Google who need it fast (and made it fast) because they need it to survive, but I could be wrong.

Are there any differences in how Python and Javascript are designed that have an impact on how they (would) perform in browsers?

Since as of now there isn't a client side Python implementation, my question comes from the statement someone made, so maybe it has something to do with the languages itself (although I don’t believe that).

答:
Even when you asked this question, there were already a number of python implementations available in javascript that can be used on web pages today.

Have a look at http://www.skulpt.org/ or http://www.brython.info/ for starters.

The performance doesn't seem to be too bad, but you should test them yourself and find out.


问:
How to manage accidental complexity in software projects
When Murray Gell-Mann was asked how Richard Feynman managed to solve so many hard problems Gell-Mann responded that Feynman had an algorithm:

Write down the problem.

Think real hard.

Write down the solution.

Gell-Mann was trying to explain that Feynman was a different kind of problem solver and there were no insights to be gained from studying his methods. I kinda feel the same way about managing complexity in medium/large software projects. The people that are good are just inherently good at it and somehow manage to layer and stack various abstractions to make the whole thing manageable without introducing any extraneous cruft.

So is the Feynman algorithm the only way to manage accidental complexity or are there actual methods that software engineers can consistently apply to tame accidental complexity?

答:
"Software architecture skill cannot be taught" is a widespread fallacy.

It is easy to understand why many people believe it (those who are good at it want to believe they're mystically special, and those who aren't want to believe that it's not their fault that they're aren't.) It is nevertheless wrong; the skill is just somewhat more practice-intensive than other software skills (e.g. understanding loops, dealing with pointers etc.)

I firmly believe that constructing large systems is susceptible to repeated practice and learning from experience in the same way that becoming a great musician or public speaker is: a minimum amount of talent is a precondition, but it's not a depressingly huge minimum that is out of reach of most practitioners.

Dealing with complexity is a skill you acquire largely by trying and failing a few times. It's just that the many general guidelines that the community has discovered for programming in the large (use layers, fight duplication wherever it rears its head, adhere religiously to 0/1/infinity...) are not as obviously correct and necessary to a beginner until they actually do program something that is large. Until you have actually been bitten by duplication that caused problems only months later, you simply cannot 'get' the importance of such principles.


答:
Pragmatic thinking by Andy Hunt addresses this issue. It refers to the Dreyfus model, according to which there are 5 stages of proficiency in various skills. The novices (stage 1) need precise instructions to be able to do something correctly. Experts (stage 5), on the contrary, can apply general patterns to a given problem. Citing the book,

It’s often difficult for experts to explain their actions to a fine level of detail; many
  of their responses are so well practiced that they become preconscious actions. Their vast experience is mined by nonverbal, preconscious areas of the brain, which makes it hard for us to observe and hard for them to articulate.

When experts do their thing, it appears almost magical to the rest of us—strange incantations, insight that seems to appear out of nowhere, and a seemingly uncanny ability to know the right answer when the rest of us aren’t even all that sure about the question.
  It’s not magic, of course, but the way that experts perceive the world, how they problem solve, the mental models they use, and so on, are all markedly different from nonexperts.

This general rule of seeing (and as a result avoiding) different issues can be applied to specifically the issue of accidental complexity. Having a given set of rules isn't enough to avoid this problem. There will always be a situation which isn't covered by those rules. We need to gain experience to be able to foresee problems or identify solutions. Experience is something that cannot be taught, it can only be gained by constant trying, failing or succeeding and learning from mistakes.

This question from Workplace is relevant and IMHO would be interesting to read in this context.

Title: How to manage accidental complexity in software projects

Body:
When Murray Gell-Mann was asked how Richard Feynman managed to solve so many hard problems Gell-Mann responded that Feynman had an algorithm:

Write down the problem.

Think real hard.

Write down the solution.

Gell-Mann was trying to explain that Feynman was a different kind of problem solver and there were no insights to be gained from studying his methods. I kinda feel the same way about managing complexity in medium/large software projects. The people that are good are just inherently good at it and somehow manage to layer and stack various abstractions to make the whole thing manageable without introducing any extraneous cruft.

So is the Feynman algorithm the only way to manage accidental complexity or are there actual methods that software engineers can consistently apply to tame accidental complexity?


问:
modelling a restaurant availability search
I am looking into finding an efficient way which can scale up to thousands of restaurants, for doing a reservation search.  Ideally, it would be efficient to answer queries like find a restaurant which has availability for 6 people at 19:00.  Time slots are based on 15-minute interval, e.g 19:00, 19:15, 19:30, ...

I am using a document database (RavenDB), but the issue is more conceptual and I don't think it is dependent on the underlying datasource.

Each restaurant can have a different amount of capacity, for example restaurant A might fit 40 people, while restaurant B might fit 60.

My first instinct was to have a Restaurant collection, and a Reservations collection.  However, I cannot think of a way how an efficient query can be made on the restaurant/reservations collections to actually get a result for a restaurant only if it has enough space at that particular time for a booking.   Sample data objects below:

```<code>Restaurant
----------
Id
Name
Capacity

Reservation
-----------
Id
DateTime
RestaurantId
NoOfPeople
</code>```

The other option that came in mind was to actually keep a track of each day and all the timeslots in a day (each 15 min interval).  Then, with each booking, each respective timeslot is updated.  Hence, the query would be a simple search on the timeslots.  This would work (haven't tried it yet), but it involves more 'maintenance'.  Is this the best way to go for such a problem, or is there maybe a side of it which I'm not seeing?

Computing availability on bookings

My idea for the second option, to compute availability for bookings is that I would add another data object, as below

```<code>RestaurantTimeSlot
------------------
RestaurantId
DateTime (e.g 18/02/2014 17:00)
AvailableBookings
MaxBookings
</code>```

A background task would create new time slots for restaurants for subsequent days, example creating up to 90 days in advance so that users can book a maximum of 90 days from today.  Each day would have all the different timeslots, example 00:00, 00:15, 00:30, so on so forth.  Initially, the RestaurantTimeSlot would be set as AvailableBookings = 0, MaxBookings = maximum bookings of that restaurant (e.g 60).  The reason for MaxBookings is because a restaurant availability might be based on time, and in 2012 it might have availability for 60, while in 2013 it might expand to 80.  Then, when a booking for say 4 people is made at 18/02/2014 17:00, that respective timeslot's AvailableBookings would be added by 4.  Then, when a search needs to be done, one would search easily in RestaurantTimeSlot.

Does this make sense?  My issue that having to constantly create these new data objects so that they are available for search, and keeping them in sync when a new booking is made.  This looks like it can lead to the system being more error-prone.

答:
I would advise you to indeed keep projections of free/taken timeslots of those restaurants. If not, the more restaurants you'll want to query, the longer your query will take.

Keeping a projection of which slots are taken and which are free will also make it a lot easier for you to fetch free slots, because the data will be in the format you'll need it to be.

As to how: you'll need some sort of stream of events that signal that a reservation was made (or cancelled, modified), for which you need individual handlers. Those handlers encapsulate the logic to update your projections.

One thing to keep in mind though is that creating/updating/deleting projection records can be a strain for NoSQL systems, if you need to retrieve documents through an other way than via Id.

P.S.: I'm assuming you can easily access reservation data of restaurants; I don't know anything about this.


问:
What are my options for using a C++11 library in a C# WPF application?
I am writing a cross-platform (OS X and Windows) desktop application in C++11. I intend to use the same C++11 core on both platforms, utilizing native frameworks for the UI (Cocoa and Objective-C on OS X and WPF and C# on Windows) as I believe the best UX experience is a native one.

Currently the application runs as a console app on both platforms. The application performs some CPU-intensive work and provides callbacks for progress reporting and, when complete, instantiates a collection of Items (std::vector<std::unique_ptr<Item>>) representing the results of the processing.

My goal is for the C++11 library to act as a model for the UI in a manner compatible with the MVC and MVVM patterns.

The UI must:

Allow the user to choose a file to process (open a file dialog and send the file path to the C++ library)

Display progress (handle callbacks from the C++ library to update a progress bar)

Display the results in a WPF form (access the Item class and display information it provides)

I've looked at WinRT and it seems there isn't a lot of information out there for use in desktop applications.  I'm also not fond of the idea of creating the UI itself in C++.  My goal is to get data in and out of the C++ app and use C# to handle the UI as I believe that's a more efficient way of working with WPF.

I'm aware of P/Invoke but my understanding is that it only works with a C interface. Creating such an interface around the C++11 seems cumbersome.

I'm also aware of C++/CLI but I'm not sure if that will meet my needs or if it is compatible with C++11.

I took a look at CppSharp but it seems to be a work-in-progress and I doubt I'd know how to work around any issues that may arise.

I have a lot of experience with C++ and a little with C# but I'm not sure if I'm missing better options or which of the above is a sound approach.

答:
SWIG can generate C# wrappers for C++ code.  I have no experience using it for this, so I don't know how well it works.

I believe the current release of SWIG (version 2.x) has at least some C++11 support, but you may need to use the development version for full support.


答:
This brings back the old times...

I have a copy of the book, 3rd printing, 1975. I checked your listing and it's non-original. In the original source code the statements have no spaces and assignments have the keyword LET. For example

```<code>200 LETK=M:GOSUB600
</code>```

The dialect is DIGITAL PDP-11 BASIC (not Basic-plus or BASIC-80). From experience, not all of these games worked on all dialects of BASIC. I have a vague recollection of having to recode several of these games to get them to work on other dialects. This kind of horrible loop structure was definitely a problem.

I had experience with over 20 different dialects of BASIC and I can tell you that this was a vexed question at the time. There were 2 main camps.

In one camp there were the full interpreters, which parsed each line afresh each time it was seen. They handled a FOR loop by pushing it on a stack, identified by its variable, and then scanning the stack for a match with each NEXT. If they skipped a loop, they would have to scan the source for the NEXT. Some did, some didn't.

The other camp was the tokenizers or semi-compilers. They would scan all the lines before execution and convert them to some kind of internal format. They also matched up FOR/NEXT loops and checked for missing GOTO and GOSUB targets. DEC and BASIC-80 were in this camp, as I recall, but it is a long time ago.

In answer to your questions,

Yes, the dialect of BASIC does skip a loop if initially satisfied

No, sequencing of FOR NEXT was not a documented requirement, but the behaviour was undefined. As a professional, obviously I never did it. :)

Hope this helps. These are horrible languages, but if you gotta do it...

Title: How does BASIC locate an out-of-order NEXT statement when the loop body is skipped

Body:
Set the WABAC machine, Sherman.  This question is about BASIC in general, and Microsoft's BASIC-80 in particular.  Old school basic.  With line numbers.

How do (or, rather, did) old-school BASIC interpreters handle FOR...NEXT loops when the loop body was not executed, and the NEXT statement appeared out of order?

An out-of-order NEXT statement from the before time:

Here's a subroutine from the game Awari out of David H. Ahl's "101 Basic Computer Games":

```<code>200 K=M:GOSUB 600
205 E=0:IF K>6 THEN K=K-7
210 C=C+1:IF C<9 THEN F(N)=F(N)*6+K
215 FOR I=0 TO 5:IF B(I)<>0 THEN 230
220 NEXT I
225 RETURN
230 FOR I=7 TO 12:IF B(I)<>0 THEN E=1:RETURN
235 GOTO 220
</code>```

and here it is with everything except the flow control redacted:

```<code>200 GOSUB 600
215 FOR I=0 TO 5:IF ... THEN 230
220 NEXT I
225 RETURN
230 FOR I=7 TO 12:IF ... THEN RETURN
235 GOTO 220
</code>```

Does that bring back not-so-fond memories?  Can you hear Dijkstra  rolling over in his grave?

Here are the interesting part of what's happening in this fragment:

The second FOR loop, since it uses the same loop variable, replaces the first FOR loop

The two FOR loops share the same NEXT statement

The second FOR loop's NEXT statement comes before it, in source order, but after it, in execution order

You might suppose, then, that the interpreter, having started a FOR loop, simply runs statements until it happens across the NEXT loop.  The order of the statement in the source does not matter in this case.  But let's see what the basic80 manual has to say about FOR loops:

The basic-80 manual says "moo..."

The body of the loop is skipped if the initial value of the loop times
  the sign of the step exceeds the final value times the sign of the
  step.

So, the loop body can be skipped entirely.

We have evidence, in the form of published programs, that at least some versions of BASIC were dynamically locating their NEXT statements.  This is easy enough to do when the loop body is being executed.  However, in the case where the body of the FOR statement should be skipped, as BASIC-80 permits, how did BASIC locate the NEXT statement, given that it might be before the FOR statement in source order?

Did the version of BASIC used in "101 Basic Computer Games" always execute the loop body at least once?

Did BASIC-80 require a FOR loop's NEXT statement to occur after the FOR statement, in source order?

PS: Yes, I'm writing a BASIC interpreter for old school BASIC.  It's a sickness.

Body:
This brings back the old times...

I have a copy of the book, 3rd printing, 1975. I checked your listing and it's non-original. In the original source code the statements have no spaces and assignments have the keyword LET. For example

200 LETK=M:GOSUB600

The dialect is DIGITAL PDP-11 BASIC (not Basic-plus or BASIC-80). From experience, not all of these games worked on all dialects of BASIC. I have a vague recollection of having to recode several of these games to get them to work on other dialects. This kind of horrible loop structure was definitely a problem.

I had experience with over 20 different dialects of BASIC and I can tell you that this was a vexed question at the time. There were 2 main camps.

In one camp there were the full interpreters, which parsed each line afresh each time it was seen. They handled a FOR loop by pushing it on a stack, identified by its variable, and then scanning the stack for a match with each NEXT. If they skipped a loop, they would have to scan the source for the NEXT. Some did, some didn't.

The other camp was the tokenizers or semi-compilers. They would scan all the lines before execution and convert them to some kind of internal format. They also matched up FOR/NEXT loops and checked for missing GOTO and GOSUB targets. DEC and BASIC-80 were in this camp, as I recall, but it is a long time ago.

In answer to your questions,

Yes, the dialect of BASIC does skip a loop if initially satisfied

No, sequencing of FOR NEXT was not a documented requirement, but the behaviour was undefined. As a professional, obviously I never did it. :)

Hope this helps. These are horrible languages, but if you gotta do it...