问:
Switch / select case etc. compared to If ... ElseIf ... Else
I don't understand why the switch or equivalent is so popular in languages. To me, it seems like it had a place back in the days when the alternative was lots of nested if statements in the else part of other if statements. Now that we have else if, why do we need it?

If we take the following:

```<code>switch (expr) {
  case "Oranges":
    document.write("Oranges are $0.59 a pound.<br>");
    break;
  case "Apples":
    document.write("Apples are $0.32 a pound.<br>");
    break;
  case "Bananas":
    document.write("Bananas are $0.48 a pound.<br>");
    break;
  default:
    document.write("Sorry, we are out of " + expr + ".<br>");
}
</code>```

It is clearly more readable than below?

```<code>if (expr == "Oranges") {
    document.write("Oranges are $0.59 a pound.<br>");
} else {
    if (expr == "Apples") {
        document.write("Apples are $0.32 a pound.<br>");
    } else {
        if (expr == "Bananas") {
            document.write("Bananas are $0.48 a pound.<br>");
        } else {
            document.write("Sorry, we are out of " + expr + ".<br>");
        }
    }
}
</code>```

But how is it more readable than:

```<code>if (expr == "Oranges") {
    document.write("Oranges are $0.59 a pound.<br>");
} else if (expr == "Apples") {
    document.write("Apples are $0.32 a pound.<br>");
} else if (expr == "Bananas") {
    document.write("Bananas are $0.48 a pound.<br>");
} else {
    document.write("Sorry, we are out of " + expr + ".<br>");
}
</code>```

答:
Now we have else if

In many language specifications, Java certainly being among them (I'd have to look up Java*script*), else if isn't a thing. You have if (expr) {block} [else statement] where an if statement is itself a statement. I'm not sure there are many languages in which the idea of an "else if" has been impossible.

Switch/case statements originated because they allowed the compiler to create a jump table, allowing one to create a large number of different "paths" without necessarily having to pay for n comparisons. A jump table can save a fair number of instructions, and once that really mattered. You can view a case statement as a goto label even now.

These days the differences are less relevant, but some think that switch/case better shows intent.

Personally I'm more inclined to agree with your conclusion, that it isn't necessarily any more readable and introduces conceptual wobbles with a case label being logically a "block" but not actually scoped as one.


问:
Multiple var statements in JavaScript
Writing a single var declaration per function is considered to be good for readability and maintainability.

But, when I went through some of standard libraries, their dev version doesn't strictly follow this. For example, Underscore code has multiple var statements in many function which are spread randomly and declared as required.

Is there any reason to not to follow the single-var-rule?

答:
JavaScript allows both the single and multiple var declarations in any given scope. However, behind the scenes it actually converts them into a single declaration by hoisting variables to the top of the scope.

The flexibility of the language in this sense allows for different styles. You can choose whatever you like, and many developers do so.

For example, if you use jsdoc and would like to write per-variable comments, then I personnaly think that multiple var statements are a way to go, otherwise lengthy comments would make it look like you're declaring global variables:

```<code>/**
 * something about a
 */
var a = 'a',

    /**
     * something about b
     */
    b = 'b'; // <-- it looks like b is in global scope here
</code>```

But to enforce discipline and make code more understandable and readable - use single var statement and lint code with JSLint or JSHint.

ContentLicense: CC BY-SA 3.0

Title: Multiple var statements in JavaScript

Body:
JavaScript allows both the single and multiple var declarations in any given scope. However, behind the scenes it actually converts them into a single declaration by hoisting variables to the top of the scope.

The flexibility of the language in this sense allows for different styles. You can choose whatever you like, and many developers do so.

For example, if you use jsdoc and would like to write per-variable comments, then I personnaly think that multiple var statements are a way to go, otherwise lengthy comments would make it look like you're declaring global variables:

/**
 * something about a
 */
var a = 'a',

    /**
     * something about b
     */
    b = 'b'; // <-- it looks like b is in global scope here

But to enforce discipline and make code more understandable and readable - use single var statement and lint code with JSLint or JSHint.


问:
Where to put comments, class declaration or constructor?
For a given class, where should the comments about the purpose of the class go?

```<code>/// <summary>
///       <----------------- describe the class here (1)?
/// </summary>
public class Message
{
  ...
  //class members here
  ...
  /// <summary>
  ///      <--------------- or here (2)?
  /// </summary>
  public Message()
  {
  }
}
</code>```

If I go with the first option, the purpose of the class is very easy to find when I open the file, it's in the same place, on approximately the same line. When you have lots of classes, this is easier for the eyes. You don't have to scroll down past the members to find the constructor

If I go with the second option, I get Intellisense when creating an object of the class, stating it's purpose and explaining the parameters, which is very nice.

From what I can tell, I can't get both advantages by using just one method. The only solution I can think of is putting the same comment in both places, but that's just duplicate information and I don't like it.

答:
The purpose of the class should be described above the class name.

A documentation above the constructor is to document differences between the different constructors of the class and what the parameters passed to the constructor(s) do.


问:
Is it possible to use the framework behind Metro UI to make Exposé?
Is it possible to use the framework behind the Windows 8 Metro UI to make Exposé-like application for Windows? I tried Mac and I really like this feature, on another side i like that I can drag the screen from the top of the screen into the Metro UI, but that is completely useless. So imagine if it is possible to use this functionality in a Exposé-like application for windows.

Is it even feasible? If not, maybe at a later stage? I am a programming rookie, but it could be a fun project.

Thanks in advance for any answers, suggestions and information.

答:
No it is not possible.

All WinRT applications are completely isolated from other applications and OS. Only specific APIs are available for them and neither of those allow what you would like to do. It could be possible, but we are talking about low-level OS hacking. Not something rookie could handle.


问:
Good Programming Practice for similar child classes
I am developing an iOS application, in which I have to draw some patterns on a view based on option selected by user. Let me explain you more clearly.

User will be shown number of images as options to choose from.

On selecting an option, a view will be drawn. This view is inheriting from a class say ParentClass where I have set up common properties for child classes.

ParentClass

```<code>@interface ParentClass : UIView

-(ImagePlaceHolder *) imageHolderTouched:(CGPoint) position;

//common properties declared

@end
</code>```

Right now, my approach is use of separate classes for each pattern. I override drawRect: for different patterns. So that's why I am creating separate child classes for each.

ChildDesign

```<code>@interface ChildDesign : ParentClass

@end

@implementation CollageDesign

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self drawViews];
    }
    return self;
}

-(void) drawRect:(CGRect)rect
{
//different implementation for different classes
}

@end
</code>```

There are many similar child classes just having different drawRect implementation. In main controller, I initialize pattern child class based on selection using switch case.

```<code>ParentClass collView;

switch (selectedOptionIndex) {
            case 1:
                collView = [[ChildDesign alloc] initWithFrame:newframe];
                break;
            case 2:
                collView = [[ChildDesign2 alloc] initWithFrame:newframe]; //similar other classes
                break;
            case 3:
                collView = [[ChildDesign3 alloc] initWithFrame:newframe];
                break;
}
</code>```

Problem is that I have got alot of options, say 50 - 100. Creating separate inherited classes (50 - 100 .h and .m files) would be really bad approach in my opinion and is bad programming practice.

So What pattern should I follow here to optimize my code? How should I create my child classes/ patterns? What will be best approach? An idea in my mind is to pass selected index to   I hope my Question is clear.. Thanks.

An idea in my mind is to create single child pattern class having selected index as a property. Based on selected index, I will implement drawRect: method. But there will be lot of if-else or switch cases.

答:
In order to answer this, you must first understand at the level of drawRect.  Strictly speaking, if you genuinely have cause to differentiate classes according to drawRect, then having 50-100 child classes is what you should do.  However, it is a little hard to believe that something can't be salvaged between implementations.

For instance, say the only difference between these classes is the icon that gets drawn in the space indicated by drawRect.  At this point, it isn't drawRect that changes between one child class and another but the icon itself.  Therefore, in that case, you could simply create a property "icon" which, when drawRect is called, will draw that icon in the indicated space.

It is difficult to imagine a circumstance in which each child class would genuinely need to have its own implementation of drawRect, however I'm explicitly not discounting the possibility because it could be the case.  Suppose in one child class, you draw a triangle while in another you draw a circle, and in another still, you draw a rectangle.  If you cannot generalize this behavior, then you'd be correct to implement a child class for each one.  However, even if you could generalize by drawing an icon of a triangle or an icon of a circle, then that is already reason enough to have one class which does this for you.

More than likely in your circumstance, you could probably generalize it into a single parent class, or lacking that, no more than a handful of child classes for each option type.  Try to remember that when the code differs, you need a new class, but if the data differs, you only need a new instance.


问:
What's the simplest example out there to explain the difference between Parse Trees and Abstract Syntax Trees?
To my understanding, a parser creates a parse tree, and then discards it thereafter. However, it can also pop out an abstract syntax tree, which the compiler supposedly makes use of.

I'm under the impression that both the parse tree and the abstract syntax tree are created under the parsing stage. Then could someone explain why these are different?

答:
The first thing you need to understand is that nobody forces you to write a parser or compiler in a certain way. Specifically, it is not necessarily the case that the result of a parser must be a tree. It can be any data structure that is suitable to represent the input.

For example, the following language:

```<code>prog:
      definition
    | definition ';' prog
    ;

definition: .....
</code>```

can be represented as a list of definitions. (Nitpickers will point out that a list is a degenerate tree, but anyway.)

Second, there is no need to hold onto the parse tree (or whatever data structure the parser returned). To the contrary, compilers are usually constructed as a sequence of passes, that transform the results of the previous pass. Hence the overall layout of a compiler could be thus:

```<code>parser :: String             -> Maybe [Definitions]      -- parser
pass1  :: [Definitions]      -> Maybe DesugaredProg      -- desugarer
pass2  :: DesugaredProg      -> Maybe TypedProg          -- type checker
pass3  :: TypedProg          -> Maybe AbstractTargetLang -- code generation
pass4  :: AbstractTargetLang -> Maybe String             -- pretty printer

compiler :: String           -> Maybe String    -- transform source code to target code
compiler source = do
   defs  <- parser source
   desug <- pass1 defs
   typed <- pass2 desug
   targt <- pass3 typed
   pass4 targt
</code>```

Bottom Line: If you hear people talk about parse trees, abstract syntac trees, concrete syntax trees etc., always substitute by data structure suitable for the given purpose, and you're fine.

Body:
The first thing you need to understand is that nobody forces you to write a parser or compiler in a certain way. Specifically, it is not necessarily the case that the result of a parser must be a tree. It can be any data structure that is suitable to represent the input.

For example, the following language:

prog:
      definition
    | definition ';' prog
    ;

definition: .....

can be represented as a list of definitions. (Nitpickers will point out that a list is a degenerate tree, but anyway.)

Second, there is no need to hold onto the parse tree (or whatever data structure the parser returned). To the contrary, compilers are usually constructed as a sequence of passes, that transform the results of the previous pass. Hence the overall layout of a compiler could be thus:

parser :: String             -> Maybe [Definitions]      -- parser
pass1  :: [Definitions]      -> Maybe DesugaredProg      -- desugarer
pass2  :: DesugaredProg      -> Maybe TypedProg          -- type checker
pass3  :: TypedProg          -> Maybe AbstractTargetLang -- code generation
pass4  :: AbstractTargetLang -> Maybe String             -- pretty printer

compiler :: String           -> Maybe String    -- transform source code to target code
compiler source = do
   defs  <- parser source
   desug <- pass1 defs
   typed <- pass2 desug
   targt <- pass3 typed
   pass4 targt

Bottom Line: If you hear people talk about parse trees, abstract syntac trees, concrete syntax trees etc., always substitute by data structure suitable for the given purpose, and you're fine.


问:
How can I improve quality on SQL reports?
I've recently ran into some issues where some reports were not generating the proper results. We already have a QA department that reviews the reports and then our business owners review them as well; this hasn't prevented the issue.

I'm trying to figure out a decent way to have a test harness to ensure reports are giving me the desired result.

So far, I've thought about having a static snapshot of the database (point-in-time), I would then

run the report sprocs (stored procedures) against my data with defined parameters

save off the output

write testing sprocs that call the reporting sprocs with my define parameters

Verify the results matched using the EXCEPT keyword.

Can you please offer some suggestions and alternatives?

答:
It seems to me like you need an automated test.

You need a test data-set which covers all possible data constellations which might or might not be problematic and the desired output which is supposed to be generated from that dataset.

Then you just need a program which automatically runs the test, compares the results against the desired results and reports any discrepancies.


答:
A slightly devil's advocate position:

Neither position.

The name of the class should tell the reader its purpose. If it doesn't, find a better name.

Title: Where to put comments, class declaration or constructor?

Body:
For a given class, where should the comments about the purpose of the class go?

```<code>/// <summary>
///       <----------------- describe the class here (1)?
/// </summary>
public class Message
{
  ...
  //class members here
  ...
  /// <summary>
  ///      <--------------- or here (2)?
  /// </summary>
  public Message()
  {
  }
}
</code>```

If I go with the first option, the purpose of the class is very easy to find when I open the file, it's in the same place, on approximately the same line. When you have lots of classes, this is easier for the eyes. You don't have to scroll down past the members to find the constructor

If I go with the second option, I get Intellisense when creating an object of the class, stating it's purpose and explaining the parameters, which is very nice.

From what I can tell, I can't get both advantages by using just one method. The only solution I can think of is putting the same comment in both places, but that's just duplicate information and I don't like it.


问:
In functional programming how does one achieve modularity through mathematical laws?
I read in this question that functional programmers tend to use mathematical proofs to ensure that their program is working correctly.  This sounds alot easier and faster than unit testing, but coming from an OOP / Unit Testing background I've never seen it done.

Can you explain it to me and give me an example?

答:
"Beware of bugs in the above code; I have only proved it correct, not tried it."
- Donald Knuth

In a perfect world, programmers are perfect and don't do mistakes, so there are no bugs.

In a perfect world, computer scientists and mathematicians are also perfect, and don't do mistakes either.

But we don't live in a perfect world. So we can't rely on programmers to make no mistakes. But we can't assume that any computer scientist who delivers a mathematical proof that a program is correct didn't make any mistakes in that proof. So I wouldn't pay any attention to anyone trying to proof that his code works. Write unit-tests and show me that the code behaves according to specifications. Anything else won't convince me of anything.


问:
Using Scrum on small projects where Owner doesn't want to be involved
Recently I've been reading and learning quite a lot about scrum and I like it a lot. However, I do have a couple of likely scenarios in my head to which I don't know the solution. So let's say that I might want to organize an agile team of (for instance) four web developers (one of them UI/UX designer). This team would operate on scrum principles.

Initially we would probably be working on projects like landing pages for ordinary people's small businesses, like renting apartments, selling cookies... Such customers simply can't be set with Product Owner role (IMHO), because they usually expect to hire a company, give them the overall project goal with some details, and then expect the job to be done (including a lot of decision making) with as little of their involvement as possible (in their opinion, they have more important things to do). Let's say I'd like to engage myself in a developer/scrum master role (I know that even that is debatable, being a team member and scrum master at once), so I simply shouldn't take the role of the product owner as well.

So as for my questions: If I'm my company's business owner, do I simply need to be a product owner as well (do these roles include each other)? Can I employ a sales person which might have the product owner role? Would it be better if it is an experienced developer instead of a sales person? Is this even a smart move? Lastly, is there another agile approach that might better suit my position?

EDIT: Thank you everyone for good inputs. I added some comments, any aditional info will be greatly appreciated.

答:
I think that your situation its in fact very common, a lot clients don't to be involved with the level of dedication that a PO role needs.

Its very usual the approach of the "PO proxy", this is someone of your company that talks with the client and translates the requirements of the client into user histories for the scrum team. Off course you need to, little by little, involve more a more your real client into your process, but this is not always possible and depends a lot in your type of clients, the "PO proxy" can be a reasonable solution in most scenarios.

For this position the best fit its probably not a developer, and probably not a sales people, the best fit its a domain expert in the business of your client (at the same time can be a developer or sales, but his main skill its to be a domain expert).

Other thing to consider its if you really need a person full-time with this role, or if this role can be shared with other task, this again depends a lot on your particular context, you can begin with a shared or full-time role and "inspect and adapt" to your particular needs.


问:
When is it reasonable to create my own programming language?
Are there types of killer applications, classes of algorithmic problems, etc., where it is better, in the long run, to create my own language?

PS: Just to be sure, I mean a new programming language and a compiler, not a new compiler for an existing language.

EDIT: Thank you for the answers. Can you provide some examples, where it is absolutly unnecessary to create a DSL or cases in which a DSL might be a good idea?

答:
Your 'edit' seems to be a substantially different question ("when should I build a DSL?" rather than the original question which people understood as "when should I build a new, general purpose programming language").  It seems people have thoroughly answered the 'original' question but there are few answers giving specific criteria for when to use a DSL.  So I propose a checklist :

Your userbase is larger than a few people, generally non-technical and / or with restricted system access (hence it's unreasonable to expect them to learn / use an existing general purpose language).  If it is within your dev team or software organisation you could instead say "just write a script".

Your users need to use it sufficiently often, with sufficiently varied and changing behaviours needed (i.e. you can't just provide a fixed library of functions maintained by you)

The behaviour that users can specify is too complicated to specify as data (e.g. you can't achieve it using a database table, or a user-input matrix, or a list of tasks, or a key-value collection...think carefully because you can achieve a lot of complexity with these).  If you can achieve the behaviour using data input or configuration instead of DSL then you probably should because it will be much less work.  Some kind of conditionality, or composability / chaining together, or modelling a few different abstractions may be signs that the behaviour you need is too complex for plain data / configuration

But the behaviour is still restricted enough that you can specify it in a concise DSL.  A big danger is 'platform bloat' e.g. if users start to request "can you just add...?".  If they need to connect to the internet, or read and write from the file system, or open and close processes - then this is no longer a DSL. (I have seen this happen for real...users allowed to embed small python calls, gradually growing to python scripts, and eventually destroying any limits / modularity / performance)

If all of these are true then a DSL may be appropriate.

ContentLicense: CC BY-SA 2.5


答: In my experience, if you tell the client they're the 'product owner', they tend to revolt at the extra responsibility.  But if you say you're going to show them your progress every couple weeks so they can direct the team, they're cool with it.  For the most part, that's what the product owner does anyway.</p>

Title: Using Scrum on small projects where Owner doesn't want to be involved

Body:
Recently I've been reading and learning quite a lot about scrum and I like it a lot. However, I do have a couple of likely scenarios in my head to which I don't know the solution. So let's say that I might want to organize an agile team of (for instance) four web developers (one of them UI/UX designer). This team would operate on scrum principles.

Initially we would probably be working on projects like landing pages for ordinary people's small businesses, like renting apartments, selling cookies... Such customers simply can't be set with Product Owner role (IMHO), because they usually expect to hire a company, give them the overall project goal with some details, and then expect the job to be done (including a lot of decision making) with as little of their involvement as possible (in their opinion, they have more important things to do). Let's say I'd like to engage myself in a developer/scrum master role (I know that even that is debatable, being a team member and scrum master at once), so I simply shouldn't take the role of the product owner as well.

So as for my questions: If I'm my company's business owner, do I simply need to be a product owner as well (do these roles include each other)? Can I employ a sales person which might have the product owner role? Would it be better if it is an experienced developer instead of a sales person? Is this even a smart move? Lastly, is there another agile approach that might better suit my position?

EDIT: Thank you everyone for good inputs. I added some comments, any aditional info will be greatly appreciated.


答:
Are there types of killer applications, classes of algorithmic
  problems, etc., where it is better, in the long run, to create my own
  language?

It depends.

Let's take our brain. It seems to be such a complex mess that we encounter borders with ANY programming language (at least now). So maybe in order to actually virtualize our brain we need other approaches and therefor other semantics and syntaxes.

Generally speaking, there are yet such complex topics which might lead to other strategies which would also include a 'better' language for a given scenario.

Title: When is it reasonable to create my own programming language?

Body:
Are there types of killer applications, classes of algorithmic problems, etc., where it is better, in the long run, to create my own language?

PS: Just to be sure, I mean a new programming language and a compiler, not a new compiler for an existing language.

EDIT: Thank you for the answers. Can you provide some examples, where it is absolutly unnecessary to create a DSL or cases in which a DSL might be a good idea?


问:
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.

答:
What the "101 Computer Games" BASIC does

The dialect of BASIC used in the Microcomputer edition of "101 Computer Games" will execute the body of a FOR...NEXT loop at least once.  This does differ from BASIC-80 v. 5.

From p. i12, listing exceptions to "normal" BASIC:

FOR...TO...STEP

As in standard BASIC, except that the test for ending the loop is made
  after it h as been executed.  That is, when this program is run:

```<code>10 FOR X=2 TO 1
20 PRINT "HI"
30 NEXT X
40 END
</code>```

"HI" will be printed...

Because of that, this dialect of BASIC has no trouble locating the NEXT statement, or sharing the same next statement with multiple FOR statements.  No static analysis is required.  Simply execute every statement as it occurs, and you'll eventually get to the NEXT statement, wherever it is.

Is it possible for BASIC-80 to handle an out-of-order NEXT?

It is possible for a FOR statement to skip the loop body, as BASIC-80 v.5 allows, and still allow out-of-order NEXT statements in most cases.  Here's how:

The interpreter gets two states, "running," and "skipping to NEXT"

When in the "running" state, the interpreter executes every statement normally.

When evaluating a FOR statement, if the loop body is to be skipped, the state is changed to "skipping to NEXT"

When in the "skipping to next" state, the interpreter skips every statement except NEXT and unconditional GOTO.

An unconditional GOTO statement is followed

A NEXT statement, if its variable matches that of the FOR statement (or if the variable is not specified), switches back to the "running" state.  If the variable does not match, the interpreter remains in the "skipping to NEXT" state.

This would handle simple pathological sequences such as that in the question.  It would not handle cases where the NEXT was reached by an IF...GOTO statement, or a GOSUB.  Code that does that is so much worse than the already bad code in the question that it's not unreasonable to simple declare that the interpreter will not support such cases.  It might even be permissible for the interpreter to set such code on fire.

Body:
What the "101 Computer Games" BASIC does

The dialect of BASIC used in the Microcomputer edition of "101 Computer Games" will execute the body of a FOR...NEXT loop at least once.  This does differ from BASIC-80 v. 5.

From p. i12, listing exceptions to "normal" BASIC:

FOR...TO...STEP

As in standard BASIC, except that the test for ending the loop is made
  after it h as been executed.  That is, when this program is run:

10 FOR X=2 TO 1
20 PRINT "HI"
30 NEXT X
40 END

"HI" will be printed...

Because of that, this dialect of BASIC has no trouble locating the NEXT statement, or sharing the same next statement with multiple FOR statements.  No static analysis is required.  Simply execute every statement as it occurs, and you'll eventually get to the NEXT statement, wherever it is.

Is it possible for BASIC-80 to handle an out-of-order NEXT?

It is possible for a FOR statement to skip the loop body, as BASIC-80 v.5 allows, and still allow out-of-order NEXT statements in most cases.  Here's how:

The interpreter gets two states, "running," and "skipping to NEXT"

When in the "running" state, the interpreter executes every statement normally.

When evaluating a FOR statement, if the loop body is to be skipped, the state is changed to "skipping to NEXT"

When in the "skipping to next" state, the interpreter skips every statement except NEXT and unconditional GOTO.

An unconditional GOTO statement is followed

A NEXT statement, if its variable matches that of the FOR statement (or if the variable is not specified), switches back to the "running" state.  If the variable does not match, the interpreter remains in the "skipping to NEXT" state.

This would handle simple pathological sequences such as that in the question.  It would not handle cases where the NEXT was reached by an IF...GOTO statement, or a GOSUB.  Code that does that is so much worse than the already bad code in the question that it's not unreasonable to simple declare that the interpreter will not support such cases.  It might even be permissible for the interpreter to set such code on fire.


问:
What did Alan Perlis mean regarding the ways to write error-free programs?
There's a quotation by Alan J. Perlis that says:

There are two ways to write error-free programs; only the third one works.

I recently heard this quote from my friend, and was unable to understand the deeper meaning behind it.

What is Perlis talking about here?

答:
As additional insight, the "two ways" might be a reference to this quote by Tony Hoare:

There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult. It demands the same skill, devotion, insight, and even inspiration as the discovery of the simple physical laws which underlie the complex phenomena of nature.

Meditate on that a little and you'll see he's saying the same thing: if your piece of software is non-trivial, it has bugs (but complicate it enough and they won't be obvious bugs).


问:
Stored Procedures a bad practice at one of worlds largest IT software consulting firms?
I'm working at a project in one of the world's top 3 IT consulting firms, and was told by a DBA that company best practice's state stored procedures are not a "best practice".  This is so contrary to everything I've learned.

Stored procedures give you code reuse, and encapsulation (two pillars of software development), security (you can grant/revoke permissions on an individual stored proc), protect you from SQL injection attacks, and also help with speed (although that DBA said that starting with SQL Server 2008 that even regular SQL queries are compiled if they are run enough times).

We're developing a complex app using Agile software development methodology.  Can anyone think of good reasons why they wouldn't want to use stored procs?  My guess was that the DBAs didn't want to maintain those stored procs, but there seem to be way too many negatives to justify such a design decision.

答:
I just wanted to make a concise overview of how I would recommend using stored procedures. I do not think they are a bad practice at all, and like others have said they should be used in the proper situations.

I can see problems where writing procedures for different applications can become confusing in functionality and separate the business logic of the application and result in the database becoming more disorganized and restrictive as well.

Therefore, I would use a stored procedure in relational data-oriented tasks specific to the database. In other words, if there is logic used for database operations that is consistent with the data for any application, a stored procedure could be used to keep the data stored consistently (makes sense). I think good examples of this are: consistent logging, consistent maintenance, working with sensitive information, etc.

Other tasks the manipulate the data to fit the needs of the application that follow the strong data model of the database, I think, should then be stored in another layer containing the business logic. In short, database specific data manipulation for consistency could use stored procedures, where the consistency extends past the database integrity schema model.


问:
Coarse-grained views on server vs fine-grained views assembled on client vs fine-grained views with batching
I've currently got a browser talking via an "API" to the server. API is scare quoted because the API really wouldn't support another user interface very well, because it consists of every call our UI happens to need, in the form it happens to need it, and nothing else. Which could be fine. However, we are starting to have calls along the lines of "GetUserSummaryData", "GetUserHisFriendsAndHisPurchases", "GetUserAndHisPurchases", etc.

Note that on the server a more reasonable fine-grained API is written, (and the current API calls just cause the server to wire those together) it's just that what is exposed to the UI matches exactly what it needs at that particular moment.

The justification for the current approach is that going from "I need those 6 things at the moment" to "I need to make 6 calls and put the data together" has to happen somewhere, and if you do it on the server then the browser can make 1 course-grained call, vs. the alternative of either making 6 calls and taking a (significant) performance hit, or else figuring out some system of batching the 6 calls (including dealing with the issue of dependencies, possibly by having the call batching mechanism smart enough to say "the 3rd parameter of call 2 should be this part of the JSON response object from call 1" and having the server understand that).

Doing things on the server as we are does make it pretty much impossible to write another UI without making more customized views on the server to support it. But we have no reasonable current expectation that someone without access to the server would want to write another UI.

Is continuing to make really customized views on the server as the only "API" the right approach, and if not what would be better?

答:
If you're following REST principles, then the definition of resources is pretty loose. So you can define granular resources, and collections of granular resources. But, over time, it might make sense to start exposing course resources that bundle the granular resources.

IMHO it's fantastic that you've tailored your API closely to the client's requirements. But if the client requirements are consistently met by bundled data, then that's fair game too. Sounds like you're getting into an optimization phase.

It's a design / implementation decision if you want to generalize the bundling logic, or just have code to bundle specific resources.

EDIT: After reading @Aaronaught 's answer I re-read the description. I agree with him, with api resources like "GetUserHisFriendsAndHisPurchases", "GetUserAndHisPurchases", you're kind of going off in the weeds. More on that in a second.

Also, the resources shouldn't involve the verb: "GetUserSummaryData" should just be "UserSummary" (I hope it's data!) and you use GET to get it.

Sounds to me like you need to step back and redefine your broad resources. Also, remember you can use the query string to broaden or narrow the resource. So "GetUserHisFriendsAndHisPurchases" would be much better as "user/{id}?includefriends=true&includepurchases=true" and the User resource can include the bundled dependent resources if requested.


问:
Scope vs Visiblity vs Lifetime vs Accessibility vs etc
I have been trying to understand what it means to say "scope of a named entity". In reading about scope, there are terms like visibility, lifetime, accessibility and more that are used.  What is confusing is the fact that the terms are at
times used distinctly and at times interchangeably.

Quoting from this IBM article:

scope is... the largest region in which the name potentially is valid.

Fair enough. But then what does this mean -

The visibility of an identifier is the region of program text from which the object associated with the identifier can be legally accessed.

Is visibility related to accessibility?

Further it goes on to say

Scope exceeds visibility when a duplicate identifier is used in an inner declarative region, thereby hiding the object declared in the outer declarative region. The original identifier cannot be used to access the first object until the scope of the duplicate identifier (the lifetime of the second object) has ended.

Does this mean scope and lifetime are the same things?

Do these terms like scope fundamentally mean the same thing in C++ as it does in say PHP or Python or even Java. Or they could mean different things conceptually depending on the language you are working in. The article I have quoted is C/C++ related, but I want to understand the terms in the general sense.

答:
I believe those terms are the same for all the languages, since it's how the Compiler (or Interpreter) will save internally the variables, and access them.

[Edit] The C example is better for this purpose.

```<code>#include <stdio.h>

int i = 4;

void myMethod(void) {
  int j = 3;
  printf("I can see var i from the outside: %d\n", i);
}

void anotherMethod(void) {
  int i = 2;
  printf("Scope of 'i' declared outside of the method is valid, but it's not visible.\n");
  printf("You'll see the 'i' variable declared inside the method: %d\n", i);
}

int main(void) {
  myMethod();
  printf("Asking for j will give an error, because it's outside the scope\n");
  anotherMethod();
}
</code>```

Body:
I believe those terms are the same for all the languages, since it's how the Compiler (or Interpreter) will save internally the variables, and access them.

[Edit] The C example is better for this purpose.

#include <stdio.h>

int i = 4;

void myMethod(void) {
  int j = 3;
  printf("I can see var i from the outside: %d\n", i);
}

void anotherMethod(void) {
  int i = 2;
  printf("Scope of 'i' declared outside of the method is valid, but it's not visible.\n");
  printf("You'll see the 'i' variable declared inside the method: %d\n", i);
}

int main(void) {
  myMethod();
  printf("Asking for j will give an error, because it's outside the scope\n");
  anotherMethod();
}


答:
Scope, visibility and accessibility are all really talking about the same thing; given a particular declaration when can that declaration be referenced. Scope is the most general term and encompasses both visibility and accessibility and the referenced quote is adequate. Visibility and accessibility are usually applied to the members of a class as it is easier to think of them as being "hidden" or "not visible" as opposed to out of scope; that is, myMember is either private, protected or public controlling the visibility of the member in a class and its decedents. When inside a method of a class, all members are accessible or visible but only public members are from outside the class. protected members are only accessible or visible from the class itself or one of its derived classes. All of these contribute to the scope of myMember, that is the smallest region of text that can access myMember.

The parenthetical about lifetime is technically accurate for local variables but is really mixing a runtime concept, lifetime, with a compile-time or lexical concept, scope. You should ignore it. It is more confusing than helpful when trying to understand scope. Understanding lifetime is important to understand when a destructor is run and is related to scope but not important in understanding scope.

Title: Scope vs Visiblity vs Lifetime vs Accessibility vs etc

Body:
I have been trying to understand what it means to say "scope of a named entity". In reading about scope, there are terms like visibility, lifetime, accessibility and more that are used.  What is confusing is the fact that the terms are at
times used distinctly and at times interchangeably.

Quoting from this IBM article:

scope is... the largest region in which the name potentially is valid.

Fair enough. But then what does this mean -

The visibility of an identifier is the region of program text from which the object associated with the identifier can be legally accessed.

Is visibility related to accessibility?

Further it goes on to say

Scope exceeds visibility when a duplicate identifier is used in an inner declarative region, thereby hiding the object declared in the outer declarative region. The original identifier cannot be used to access the first object until the scope of the duplicate identifier (the lifetime of the second object) has ended.

Does this mean scope and lifetime are the same things?

Do these terms like scope fundamentally mean the same thing in C++ as it does in say PHP or Python or even Java. Or they could mean different things conceptually depending on the language you are working in. The article I have quoted is C/C++ related, but I want to understand the terms in the general sense.


问:
Finding most Important Node(s) in a Directed Graph
I have a large (≈ 20 million nodes) directed Graph with in-edges & out-edges. I want to figure out which parts of of the graph deserve the most attention. Often most of the graph is boring, or at least it is already well understood. The way I am defining "attention" is by the concept of "connectedness" i.e. How can i find the most connected node(s) in the graph?

In what follows, One can assume that nodes by themselves have no score, the edges have no weight & they are either connected or not.

This website suggest some pretty complicated procedures like n-dimensional space, Eigen Vectors, graph centrality concepts, pageRank etc. Is this problem that complex?

Can I not do a simple Breadth-First Traversal of the entire graph where at each node I figure out a way to find the number of in-edges. The node with most in-edges is the most important node in the graph. Am I missing something here?

答: If it is not important which nodes connect to which, use a simple 2x2 matrix, which has a column for every node and a row that represent one node. each node that is connected get a value of 1 for the column. then add an extra column at the end of each row that counts the number of connections for that node. this does have huge over head up front but will get the most connected node and make node insertion and deletion easy if you know the size up front. If the size of the graph is dynamic then this will not work, works only for static graphs. Memory will also be an issue since you will have to use an array. But if finding the most connect node is the big issue this is a simple way to do it.</p>


答:
Way-too-specific "query APIs" are typically what you get when your application architecture and sometimes the development process itself fails to keep up with expansion of requirements scope.

Well-designed APIs aren't specific to a client. Those aren't really APIs at all, they're basically a "business layer" or middleware application tier. APIs should either encapsulate business operations or, in the ever-more-popular REST style, application resources.

Building highly-maintainable, high-performance applications is hard, and bloated not-really-APIs evolve because - and I'm speaking from experience here - development teams lack the experience, mandate, and/or skills to do everything that is necessary to achieve that goal. In a system where you actually want to have an API, one that is meant for external as well as internal consumption, you should expect to see several qualities:

Clear separation of responsibilities. As in, X API deals with X resource, Y API deals with Y resource. Note that I say "resource" and not "data"; resources are not tables, you could maybe consider them to be similar to an aggregate root.

Versatility. Names like GetOrdersByCustomer imply an extremely myopic API design. What you want to see is a GetOrders API (or an /orders/ resource) that lets you query by example, or specify several different search/filter/paging criteria in one go. Really great APIs will have the foresight to allow plurals in filter criteria, especially when the ID is a potential criterion but even for other criteria (like, say, orders owned by any of 5 or 10 different customers). You're not trying to go nuts here and reinvent SQL; the de facto standard (in my experience) is that "fields" are combined with AND, field values are combined with OR. This completely natural to do in an HTTP URL: /orders?date=today&customerIds=6,7,8.

Asynchrony. This goes hand in hand with #2. The key here is to understand how users actually use your app. Users want a fast response time but don't process all of the information on the screen instantaneously. Say you're looking at a search results page; it's OK if the filters load a second or two earlier or later, and if there are annotations (like say, products you've already ordered, or reviews from other users, etc.) then those annotations can finish loading a few seconds later, as long as the most important information loads quickly. Or, on a dashboard page, you don't need each fragment to appear at exactly the same time. Note that this does not mean you make every request in sequence, because that would be insanely slow; typically a "page load" happens in 2 or 3 stages (first to get the data, second to decorate the data and load first-level relationships, subsequent steps to decorate relationships or load second-level relationships, such as information about the members who wrote the product reviews). During each step you make several parallel requests, because your API is clean and they are all independent.

A powerful composition and data-binding system on the client side. My areas of specialization are .NET and JavaScript, so I think of rich-client frameworks with observable support (WPF, Silverlight, etc.) or MV-* web frameworks (AngularJS, KnockoutJS, etc.). The reason for this is, let's say you're trying to populate something like a grid or table but aren't going to have all columns available on the first pass. These types of frameworks will automatically update the grid when the information does become available, which makes the "put all the data together" step largely unnecessary. On the other hand, Forms-style frameworks, while very convenient for slamming together quick-and-dirty apps, are absolutely miserable at composition, and you have to do a lot of extra work in order to maintain loose coupling, not to mention synchronization with the GUI thread.

Tests, tests, and more tests. APIs demand not only unit tests but also integration/acceptance tests, because they encapsulate both data and business rules. I'd be extremely surprised if an operation like GetUserHisFriendsAndHisPurchases actually has tests. When you have hundreds of these ultra-specific operations, the cost of maintaining such tests becomes prohibitively high. It's far better to have many different small and simple services then one or two mammoth services with no clearly defined scope.

Like I said, this approach is hard. It pays dividends in the end, especially on a largish dev team where different developers need to be able work on the different APIs and functional areas in general without stepping on each others' toes. But it takes experience and time to do well. That's why many if not most teams don't do it, especially not teams in a corporate setting where software is treated as a cost center and everybody would rather have fast and cheap than good.

I don't know if this is the right solution for you. But I do know that bloated APIs which try to do all the composition for you are a design smell and should generally be avoided when possible.

Title: Coarse-grained views on server vs fine-grained views assembled on client vs fine-grained views with batching

Body:
I've currently got a browser talking via an "API" to the server. API is scare quoted because the API really wouldn't support another user interface very well, because it consists of every call our UI happens to need, in the form it happens to need it, and nothing else. Which could be fine. However, we are starting to have calls along the lines of "GetUserSummaryData", "GetUserHisFriendsAndHisPurchases", "GetUserAndHisPurchases", etc.

Note that on the server a more reasonable fine-grained API is written, (and the current API calls just cause the server to wire those together) it's just that what is exposed to the UI matches exactly what it needs at that particular moment.

The justification for the current approach is that going from "I need those 6 things at the moment" to "I need to make 6 calls and put the data together" has to happen somewhere, and if you do it on the server then the browser can make 1 course-grained call, vs. the alternative of either making 6 calls and taking a (significant) performance hit, or else figuring out some system of batching the 6 calls (including dealing with the issue of dependencies, possibly by having the call batching mechanism smart enough to say "the 3rd parameter of call 2 should be this part of the JSON response object from call 1" and having the server understand that).

Doing things on the server as we are does make it pretty much impossible to write another UI without making more customized views on the server to support it. But we have no reasonable current expectation that someone without access to the server would want to write another UI.

Is continuing to make really customized views on the server as the only "API" the right approach, and if not what would be better?


答: This sounds like you're confusing classes with objects.  A class is a template, with the code included to implement the actual object, while an object is the actual value.  For instance you would create a Letter class, but wouldn't create a separate class for every letter of the alphabet.  You need to simplify drawRect enough so that it can be calculated from the smallest amount of data and code.  That data and code would go into your ChildDesign.

Title: Good Programming Practice for similar child classes

Body:
I am developing an iOS application, in which I have to draw some patterns on a view based on option selected by user. Let me explain you more clearly.

User will be shown number of images as options to choose from.

On selecting an option, a view will be drawn. This view is inheriting from a class say ParentClass where I have set up common properties for child classes.

ParentClass

```<code>@interface ParentClass : UIView

-(ImagePlaceHolder *) imageHolderTouched:(CGPoint) position;

//common properties declared

@end
</code>```

Right now, my approach is use of separate classes for each pattern. I override drawRect: for different patterns. So that's why I am creating separate child classes for each.

ChildDesign

```<code>@interface ChildDesign : ParentClass

@end

@implementation CollageDesign

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self drawViews];
    }
    return self;
}

-(void) drawRect:(CGRect)rect
{
//different implementation for different classes
}

@end
</code>```

There are many similar child classes just having different drawRect implementation. In main controller, I initialize pattern child class based on selection using switch case.

```<code>ParentClass collView;

switch (selectedOptionIndex) {
            case 1:
                collView = [[ChildDesign alloc] initWithFrame:newframe];
                break;
            case 2:
                collView = [[ChildDesign2 alloc] initWithFrame:newframe]; //similar other classes
                break;
            case 3:
                collView = [[ChildDesign3 alloc] initWithFrame:newframe];
                break;
}
</code>```

Problem is that I have got alot of options, say 50 - 100. Creating separate inherited classes (50 - 100 .h and .m files) would be really bad approach in my opinion and is bad programming practice.

So What pattern should I follow here to optimize my code? How should I create my child classes/ patterns? What will be best approach? An idea in my mind is to pass selected index to   I hope my Question is clear.. Thanks.

An idea in my mind is to create single child pattern class having selected index as a property. Based on selected index, I will implement drawRect: method. But there will be lot of if-else or switch cases.


问:
How does assembly relate to machine/binary code
How does assembly relate to machine/binary code.

For example here is how to print to the screen in mikeOS(a small pure assembly OS), mikeOS it uses NASM to assemble.

```<code>BITS 16
    ORG 32768
    %INCLUDE 'mikedev.inc'

start:
    mov si, mystring
    call os_print_string

    call os_wait_for_key

    ret

    mystring db 'My first MikeOS program!', 0
</code>```

Where os_print_string and os_wait_for_key are defined as

```<code>os_print_string     equ 0003h   ; SI = zero-terminated string
</code>```

and

```<code>os_wait_for_key     equ 0012h   ; Returns AL = key pressed
</code>```

in mikedev.inc respectively and defined as

```<code>os_call_vectors:
    jmp os_print_string     ; 0003h
</code>```

in kernal.asm

Now nasm must do a lot more work under the scene when assembling, I have no idea what.

In other words assembly language is a wrapper to some degree to machine code just as say C is a wrapper to assembly. If I said cout >> "Hello World" for example in C++, this is then compiled into it's assembly equivalent and them assembled into machine code.

So I am trying to understand out how 0003h and 0012h seem to dictate everything that is going on when printing to the screen. How do these two values,

a) Tell the CPU/PC system which bus to send the corresponding bytes that represent the required string to the monitor bus and not say to the sound card.

b) In this case the string is sent to the monitor, obviously, now my understanding is that you have a frame buffer that can store a maximum number of bytes. So say the resolution of your screen is set at 1024 x 768 which is 786432 pixels and a refresh rate of 60hz on the screen, therefore the FB will contain this number of byte values and hence will be sending this many bytes to the monitor every 1/60 sec. The first byte in the FB corresponding to the first pixel on the screen and the last to the last on the screen etc.

So how does the CPU/GPU know which byte to put in which position in the FB. It's like saying to the GPU 'ok I need this pixel at coord (245,232) green so I will leave it to you to put this pixels value in the correct position in the FB' etc.

How does this work.

答:
So ideally assembly language has a one to one relationship with machine code.  One line or mnemonic (add, sub, xor...) goes with one machine instruction (add, sub, xor...).

Then to make programming easier, they add macros, so just like macros in other languages you can save some typing.

Likewise the instruction set lets you make function calls, the syntax is of course specific to your architecture and assembler, so you can save some typing there just like in any other language.

Then you have system calls, and unfortunately there is too much reliance on system calls when learning "assembly language".  Learning system calls is I would argue something you do after you learn assembly language.  The C equivalent is learning C then learning the C library functions, rather than learning "some" C while learning the C library functions.  System calls, which on x86 boil down into int this or int that (10h, 21h, etc).  Basically trigger some other code written typically by someone else which is the operating system or bios or whatever you want to call it.  And there is more code there programmed in some language, compiled and/or assembled.  For example there is likely piles of code behind your simple print string call.  However you call a system call function is defined by that operating system you are living on top of, in this case it appears you have the magic numbers you are asking about that are specific to and defined by that operating system/environment you are running on top of.  You would need to get the documentation for that environment/system and then learn what registers, etc need to be set to what and how to make the call.  This would be true for any assembler.  If the assembler has its own environment then you use the assemblers definitions for its system calls and simply do what it says.  Just like memset in C, it is well defined somewhere you need to create a function call that has the right parameters in the right place as defined by the documentation for that function, compile and link it right, run it in the right place and that function will happen as documented and return as documented.


问:
Method to store some site content data, allowing reusability
(Don't believe this is a "best practice" question as I believe there will be a single better choice).

I need to choose a data storage option to store specific site data to allow easy management and re-usability: array; class; DB; Other; but am not sure which one would be adequate.

The data in question is my Services, which is a list of titles and descriptions.

Example of the text:

On-site SEO

  We provide On and Off site SEO, by careful keyword assignment and placement,
  blah etc, etc blah etc, etc blah etc, etc blah etc, etc blah etc, etc.

Logo Design

  We can provide clean and elegant logos suited to your current company
  branding... blah etc, etc blah etc, etc blah etc, etc blah etc, etc
  blah etc, etc blah etc, etc blah etc, etc blah etc, etc blah etc, etc
  blah etc, etc.

Each title is no more than 5 words, and descriptions are about 70 words/350 chars, and I have about 20 titles and descriptions.

As services can be changed, retracted, and new added, I want control over the data - more than just editing a view/template file where the raw output/HTML is done, because I:

Require the data to be reusable on different templates

Want the option to use only a part of each data, eg just the title(s) so a
specific array index, or class method, DB table row, etc

I'm reluctant use an array, given the size of the Description text and number of services (20). And it might end up fiddly accessing a specific array value, having to know the exact key (the title), and the key being long.

I could use a multidimensional array, with the top level key being a simple reference, but it seems well overkill for the requirements.

It seems a waste of a class as the data itself is static, and feel I'd be abusing the point of OOP a bit.

I could use a DB, but the site doesn't require a DB for anything else currently, though am happy to implement one if worthwhile for this.

The site is on a framework, loosely on MVC/P, so can implement anything easily.

So, out of the options: array; class; database; (other?) which would be the most suitable for this scenario?

The overhead difference is not an issue, as it'll be marginal enough between all three for my requirements (small site, good hosting etc).

Access to said data will only be on a couple of pages, so having it in memory isn't a large requirement (AFAIK).

答: Based on what you've defined - you want something thats more than variables in an included() file, but less than a database server - I'd look at keeping the information in an SQLite database.  Thats a single file, server-less database system.  I believe its built into PHP, so you wouldn't have to install anything.  And then if you ever need to scale up to something like MySQL, it shouldn't require many changes.


问:
What are invariants, how can they be used, and have you ever used it in your program?
I'm reading Coders at Work, and in it there's a lot of talk about invariants. As far as I've understood it, an invariant is a condition which holds both before and after an expression. They're, among other things, useful in proving that loop is correct, if I remember my Logic course correctly.

Is my description correct, or have I missed something? Have you ever used them in your program? And if so, how did they benefit?

答:
Based on the following quote from Coders At Work...

But once you know the invariant that it's maintaining, you can see,
  ah, if we maintain that invariant then we'll get log lookup time.

...I guess "invariant" = "condition you want to maintain to ensure a desired effect".

It seems that invariant has two senses that differ in a subtle way:

Something that stays the same.

Something that you're trying to keep the same, in order to achieve goal X (such as a "log lookup time" above).

So 1 is like an assertion; 2 is like a tool for proving correctness, performance, or other properties - I think. See the Wikipedia article for an example of 2 (proving the correctness of the solution to the MU puzzle).

Actually a 3rd sense of invariant is:

.3. What the program (or module or function) is supposed to do; in other words, its purpose.

From the same Coders At Work interview:

But what makes big software manageable is having some global invariants or big-picture statements about what it's supposed to do and what things are supposed to be true.


问:
Is this mini-DSL for hiding URI passwords compatible with the URI spec?

Passwords exposed in URIs

An application stores URIs to be used for file transfers via SFTP, FTP, FTPS and SCP.  Many of these URIs contain passwords, for example:

```<code>sftp://someuser:sekrit@host.example.com/
</code>```

These URIs are visible to too many people.  We cannot hide email addresses from these people.

A mini-language to get passwords out of URIs

Using a mini-DSL, we can specify the parts of the email address we don't want to show:

```<code>sftp://someuser:<<CONFIG:customers/widgitco/password>>@host.example.com/
</code>```

The program that does the file transfer would look for instances of this mini-DSL in the URI, parse them, look up the appropriate strings from restricted sources, and substitute those strings into the URI.  For example, supposing that restricted source contains this key/value pair:

```<code>customers/widgitco/password: moresekrit
</code>```

Then, after replacement, the URI should be:

```<code>sftp://someuser:moresekrit@host.example.com/
</code>```

Each instance of the mini-DSL within the URI would be delimited with << and >>.  Details of the mini-DSL between the << and >> would be free to vary in order to meet future requirements; the only requirement would be that it contain no >>.

This would achieve my goal of reducing the exposure of these passwords.

Is this mini-language fragile?

Are there valid FTP/FTPS/SFTP/SCP URIs which will break this scheme?

Are they at all likely?

What mini-DSL is less likely to be broken by valid URIs?

答:
Are there valid FTP/FTPS/SFTP/SCP URIs which will break this scheme? Yes.  Any user that has a password containing "<" or "> is likely to cause problems.

Are they at all likely? Absolutely, since you don't have any control over the passwords used by the users (presumably).

What mini-DSL is less likely to be broken by valid URIs?  None.  Any un-escaped string substitution model, which is all this really is, is going to have problems.


问:
C++ project organization to reduce unit testing build time
I want to organize tests for a project large enough that build time matters (especially for the CI server).

Say I have this code that I would like to test :

```<code>//foo/greet.cpp
#include <stdio.h>
#include "foo/greet.h"
int greet() { return printf("Hello, World!\n"); }
</code>```

And I have this main program that is boilerplate that I will not test.

```<code>//main.cpp
#include "foo/greet.h"
int main() { return greet(); }
</code>```

I will use this code to generate a unittest program

```<code>//testgreet.cpp
#include <some_test_framework.h>
SOME_TEST_FRAMEWORK("Testing greet")
    SOME_TEST_FRAMEWORK_ASSERT(greet() > 0)
SOME_TEST_FRAMEWORK_END()
</code>```

I thought of the following

Skipping the build of greet.cpp for the unittest target, and linking with the objects

Create a separate project structure for the tests, but share the output folder

Pile everything in one place, maybe with a new folder named test

Make a greeting library and link both main and unittests targets to it

How can I organize my project so that I can build greet.cpp only once, yet reduce confusion caused by having two targets that share a lot of code ?

This question is related, but not duplicate (IMHO).

(+I tried making my question generic, reusable and future proof. If you think that this is too opinion based, vote to close and I will not repost)

答:
Some testing frameworks allow you to organise tests into categories, so use this and then set the main tests to be run on every commit, and all to be run on a nightly build that builds and tests everything.

Some others have you create unit test projects - create 2 sets, one with a minimal set of tests included.

Boost::Test allows you to run test suites by name.

So it all depends which test framework you use, but my answer is still basically: run some regularly, the full suite less regularly.


问:
Implementing bussiness logic with a large number of business rules and processes
We are currently working on a project that heavily relies on a database.
Among many tables the main focus is on table "data" which is linked to another table "data_type" as many-to-one, which is then linked to table "data_operation" as one-to-many.

The last table defines specific set of operations that has to be processed for each row in table "data" based on specific data type. The operation is processed against specific fields in table "data" and partially data from other tables, not mentioned in this example. The actual operation is mostly a complex calculation or specific formula. The result of a specific operation will be stored in yet another table.

So in general we have:

Projection for table "data" is approximately one million rows per year, while other tables should not change drastically on a yearly basis, but it will initially hold a few thousand rows, that is, each data type will define roughly 10-15 operations.

Each operation should be reversible (revert changes).

Processing speed is a very important factor.

The application will most likely process 2500 new table "data" rows per day.

My question is concerning the best approach to implement operations.
Do you think it is wiser to move business logic and rules to a database (procedures, triggers for each operation) or implement and process each operation in the application/business layer? What would be the ideal generic structure?

Also I am open for other approaches as well.

答:
I'm not sure why euphoric didn't post his comment as an answer but he's correct.  The same data might show up in many use cases and that will impact your rules.  You should design your business classes for each use case based in the expected behavior.   Then you can look at what data you have and figure out how to store it.

For example you might be able to save a partial quote.  You may require more data though before the system allows a quote to be sent to a customer.  Yet different rules for the quote to be converted to an order, etc.


答:
Your goal is simply to avoid compiling greet.cpp twice (once for the application and once for the tests).  Correct?

Like you said, there are lots of ways of doing this.  It's really a question of what build system you're using, how your code is organized, and how you want to organize your code.

 Use a library

This is your last suggestion: Make a greeting library and link both main and unittests targets to it.

This is the cleanest solution:

It makes it obvious what you're doing and it should work well with any build system or IDE out there.

Having the application and test suite share the same library ensures that you're testing production-ready code (instead of, for example, accidentally using different compiler options for application versus test suite and failing to catch problems).

Putting your unit testable code in a library can help encourage good design (by keeping you from slipping dependencies on UI code or other non-unit-testable code into your library).

On the other hand, it may be more hassle to set up initially, or your project design may make it hard to cleanly split into libraries.

 Share the object files

Your first three suggestions are variations on this.  Some build systems make this easy.  For example, the following Makefile would work:

```<code>%.o: %.cpp
  $(CXX) -c $<
main_program: greet.o main.o
  $(CXX) -o $@ $+
unit_tests: greet.o testgreet.o
  $(CXX) -o $@ $+
</code>```

If you're using something like Make, this should be very easy to set up and get going.  (Simply for the sake of organizing your source files, you may want to put the test sources in a separate directory, as you mentioned.)

Other build systems make this harder.  For example, using IDE-managed project files and configuring the two IDE projects to share an output directory, so they happen to see each other's output, should work, but it's a bit hackish, and it can invite problems if one project's settings diverge at all from the other (since a project build may think that an object file is suitable for its own use, even if it was built using incompatible settings by the other project).

Title: C++ project organization to reduce unit testing build time

Body:
I want to organize tests for a project large enough that build time matters (especially for the CI server).

Say I have this code that I would like to test :

```<code>//foo/greet.cpp
#include <stdio.h>
#include "foo/greet.h"
int greet() { return printf("Hello, World!\n"); }
</code>```

And I have this main program that is boilerplate that I will not test.

```<code>//main.cpp
#include "foo/greet.h"
int main() { return greet(); }
</code>```

I will use this code to generate a unittest program

```<code>//testgreet.cpp
#include <some_test_framework.h>
SOME_TEST_FRAMEWORK("Testing greet")
    SOME_TEST_FRAMEWORK_ASSERT(greet() > 0)
SOME_TEST_FRAMEWORK_END()
</code>```

I thought of the following

Skipping the build of greet.cpp for the unittest target, and linking with the objects

Create a separate project structure for the tests, but share the output folder

Pile everything in one place, maybe with a new folder named test

Make a greeting library and link both main and unittests targets to it

How can I organize my project so that I can build greet.cpp only once, yet reduce confusion caused by having two targets that share a lot of code ?

This question is related, but not duplicate (IMHO).

(+I tried making my question generic, reusable and future proof. If you think that this is too opinion based, vote to close and I will not repost)

Body:
Your goal is simply to avoid compiling greet.cpp twice (once for the application and once for the tests).  Correct?

Like you said, there are lots of ways of doing this.  It's really a question of what build system you're using, how your code is organized, and how you want to organize your code.

 Use a library

This is your last suggestion: Make a greeting library and link both main and unittests targets to it.

This is the cleanest solution:

It makes it obvious what you're doing and it should work well with any build system or IDE out there.

Having the application and test suite share the same library ensures that you're testing production-ready code (instead of, for example, accidentally using different compiler options for application versus test suite and failing to catch problems).

Putting your unit testable code in a library can help encourage good design (by keeping you from slipping dependencies on UI code or other non-unit-testable code into your library).

On the other hand, it may be more hassle to set up initially, or your project design may make it hard to cleanly split into libraries.

 Share the object files

Your first three suggestions are variations on this.  Some build systems make this easy.  For example, the following Makefile would work:

%.o: %.cpp
  $(CXX) -c $<
main_program: greet.o main.o
  $(CXX) -o $@ $+
unit_tests: greet.o testgreet.o
  $(CXX) -o $@ $+

If you're using something like Make, this should be very easy to set up and get going.  (Simply for the sake of organizing your source files, you may want to put the test sources in a separate directory, as you mentioned.)

Other build systems make this harder.  For example, using IDE-managed project files and configuring the two IDE projects to share an output directory, so they happen to see each other's output, should work, but it's a bit hackish, and it can invite problems if one project's settings diverge at all from the other (since a project build may think that an object file is suitable for its own use, even if it was built using incompatible settings by the other project).


答:
A suite of unit tests is just a project depending on the tested code.

Given a project that reaches a certain, not-really-that-big size, the need arises to arrange the code on a number of separate modules (a.k.a. libraries). It seems to me the most straightforward approach to have a testing project for each of those modules, and so I do in practice. In this way, changes in the implementation of a class require the affected module to be rebuild, and no more; the related test project is only needed to be linked again, and then rerun.

It's possible for a test suite to grow in excess, and this fact probably hints to the very same problem in its corresponding module. If that's the case, further subdivision shows necessary.


问:
Why can't native machine code be easily decompiled?
With bytecode-based virtual machine languages like Java, VB.NET, C#, ActionScript 3.0, etc., you hear sometimes about how easy it is to just go download some decompiler off the Internet, run the bytecode through it one good time, and oftentimes, come up with something not too far from the original source code in a matter of seconds.  Supposedly this sort of language is particularly vulnerable to that.

I've recently started wondering why you don't hear more about this concerning native binary code, when you at least know which language it was written in originally (and thus, which language to try to decompile into).  For a long time, I figured it was just because native machine language is so much crazier and more complex than typical bytecode.

But what does bytecode look like?  It looks like this:

```<code>1000: 2A 40 F0 14
1001: 2A 50 F1 27
1002: 4F 00 F0 F1
1003: C9 00 00 F2
</code>```

And what does native machine code look like (in hex)?  It, of course, looks like this:

```<code>1000: 2A 40 F0 14
1001: 2A 50 F1 27
1002: 4F 00 F0 F1
1003: C9 00 00 F2
</code>```

And the instructions come from a somewhat similar frame of mind:

```<code>1000: mov EAX, 20
1001: mov EBX, loc1
1002: mul EAX, EBX
1003: push ECX
</code>```

So, given the language to try to decompile some native binary into, say C++, what's so hard about it?  The only two ideas that immediately come to mind are 1) it really is that much more intricate than bytecode, or 2) something about the fact that operating systems tend to paginate programs and scatter their pieces causes too many problems.  If one of those possibilities is correct, please explain.  But either way, why do you never hear of this basically?

NOTE

I'm about to accept one of the answers, but I want to kind of mention something first.  Almost everybody is referring back to the fact that different pieces of original source code might map to the same machine code; local variable names are lost, you don't know what type of loop was originally used, etc.

However examples like the two that were just mentioned are kind of trivial in my eyes.  Some of the answers though tend to state that the difference between machine code and the original source is drastically much more than something this trivial.

But for example, when it comes down to things like local variable names and loop types, bytecode loses this information as well (at least for ActionScript 3.0).  I've pulled that stuff back through a decompiler before, and I didn't really care whether a variable was called strMyLocalString:String or loc1.  I could still look in that small, local scope and see how it's being used without much trouble.  And a for loop is pretty much the same exact thing as a while loop, if you think about it.  Also even when I would run the source through irrFuscator (which, unlike secureSWF, doesn't do much more than just randomize member variable and function names), it still looked like you could just start isolating certain variables and functions in smaller classes, figure out how they're used, assign your own names to them, and work from there.

In order for this to be a big deal, the machine code would need to lose a lot more information than that, and some of the answers do go into this.

答:
At every step of compilation you lose information that is irrecoverable. The more information you lose from the original source, the harder it is to decompile.

You can create a useful de-compiler for byte-code because a lot more information is preserved from the original source than is preserved when producing the final target machine code.

The first step of a compiler is to turn the source into some for of intermediate representation often represented as a tree. Traditionally this tree does not contain non-semantic information such as comments, white-space, etc. Once this is thrown away you cannot recover the original source from that tree.

The next step is to render the tree into some form of intermediate language that makes optimizations easier. There are quite a few choices here and each compiler infrastructure has there own. Typically, however, information like local variable names, large control flow structures (such as whether you used a for or while loop) are lost. Some important optimizations typically happen here, constant propagation, invariant code motion, function inlining, etc. Each of which transform the representation into a representation that has equivalent functionality but looks substantially different.

A step after that is to generate the actual machine instructions which might involve what are called "peep-hole" optimization that produce optimized version of common instruction patterns.

At each step you lose more and more information until, at the end, you lose so much it become impossible to recover anything resembling the original code.

Byte-code, on the other hand, typically saves the interesting and transformative optimizations until the JIT phase (the just-in-time compiler) when the target machine code is produced. Byte-code contains a lot of meta-data such as local variable types, class structure, to allow the same byte-code to be compiled to multiple target machine code. All this information is not necessary in a C++ program and is discarded in the compilation process.

There are decompilers for various target machine codes but they often do not produce useful results (something you can modify and then recompile) as too much of the original source is lost. If you have debug information for the executable you can do an even better job; but, if you have debug information, you probably have the original source too.


答:
The reason why machine code cannot be easily convertible back to the original source code is that a lot of information is lost during compilation.  Methods and non-exported classes can be inlined, local variable names are lost, file names and structures are lost entirely, compilers can make non-obvious optimizations.  Another reason is that multiple different source files could produce the exact same assembly.

For example:

```<code>int DoSomething()
{
    return Add(5, 2);
}

int Add(int x, int y)
{
    return x + y;
}

int main()
{
    return DoSomething();
}
</code>```

May be compiled to:

```<code>main:
mov eax, 7;
ret;
</code>```

My assembly is pretty rusty, but if the compiler can verify that an optimization can be done accurately, it will do so.  This is due to the compiled binary not needing to know the names DoSomething and Add, as well as the fact that the Add method has two named parameters, the compiler also knows that the DoSomething method essentially returns a constant, and it could inline both the method call and the method itself.

The compiler's purpose is to create an assembly, not a way to bundle up source files.

Title: Why can't native machine code be easily decompiled?

Body:
With bytecode-based virtual machine languages like Java, VB.NET, C#, ActionScript 3.0, etc., you hear sometimes about how easy it is to just go download some decompiler off the Internet, run the bytecode through it one good time, and oftentimes, come up with something not too far from the original source code in a matter of seconds.  Supposedly this sort of language is particularly vulnerable to that.

I've recently started wondering why you don't hear more about this concerning native binary code, when you at least know which language it was written in originally (and thus, which language to try to decompile into).  For a long time, I figured it was just because native machine language is so much crazier and more complex than typical bytecode.

But what does bytecode look like?  It looks like this:

```<code>1000: 2A 40 F0 14
1001: 2A 50 F1 27
1002: 4F 00 F0 F1
1003: C9 00 00 F2
</code>```

And what does native machine code look like (in hex)?  It, of course, looks like this:

```<code>1000: 2A 40 F0 14
1001: 2A 50 F1 27
1002: 4F 00 F0 F1
1003: C9 00 00 F2
</code>```

And the instructions come from a somewhat similar frame of mind:

```<code>1000: mov EAX, 20
1001: mov EBX, loc1
1002: mul EAX, EBX
1003: push ECX
</code>```

So, given the language to try to decompile some native binary into, say C++, what's so hard about it?  The only two ideas that immediately come to mind are 1) it really is that much more intricate than bytecode, or 2) something about the fact that operating systems tend to paginate programs and scatter their pieces causes too many problems.  If one of those possibilities is correct, please explain.  But either way, why do you never hear of this basically?

NOTE

I'm about to accept one of the answers, but I want to kind of mention something first.  Almost everybody is referring back to the fact that different pieces of original source code might map to the same machine code; local variable names are lost, you don't know what type of loop was originally used, etc.

However examples like the two that were just mentioned are kind of trivial in my eyes.  Some of the answers though tend to state that the difference between machine code and the original source is drastically much more than something this trivial.

But for example, when it comes down to things like local variable names and loop types, bytecode loses this information as well (at least for ActionScript 3.0).  I've pulled that stuff back through a decompiler before, and I didn't really care whether a variable was called strMyLocalString:String or loc1.  I could still look in that small, local scope and see how it's being used without much trouble.  And a for loop is pretty much the same exact thing as a while loop, if you think about it.  Also even when I would run the source through irrFuscator (which, unlike secureSWF, doesn't do much more than just randomize member variable and function names), it still looked like you could just start isolating certain variables and functions in smaller classes, figure out how they're used, assign your own names to them, and work from there.

In order for this to be a big deal, the machine code would need to lose a lot more information than that, and some of the answers do go into this.

Body:
The reason why machine code cannot be easily convertible back to the original source code is that a lot of information is lost during compilation.  Methods and non-exported classes can be inlined, local variable names are lost, file names and structures are lost entirely, compilers can make non-obvious optimizations.  Another reason is that multiple different source files could produce the exact same assembly.

For example:

int DoSomething()
{
    return Add(5, 2);
}

int Add(int x, int y)
{
    return x + y;
}

int main()
{
    return DoSomething();
}

May be compiled to:

main:
mov eax, 7;
ret;

My assembly is pretty rusty, but if the compiler can verify that an optimization can be done accurately, it will do so.  This is due to the compiled binary not needing to know the names DoSomething and Add, as well as the fact that the Add method has two named parameters, the compiler also knows that the DoSomething method essentially returns a constant, and it could inline both the method call and the method itself.

The compiler's purpose is to create an assembly, not a way to bundle up source files.


答:
I have been in similar situations and we never gave the the responsibility of the product owner to the client. As you said the client will not want to undertake this responsibility. It requires to much effort from their side, and it is not considered best practice.

You should have a product owner that is part of your team and makes sure that the team delivers what the client asks for. And more important, acts in the interest of your team. She should have enough expertise to understand the client and judge the priorities and the importance of the features asked from the client.


问:
How much help should I give during technical interviews?
I'm asked to perform or sit in during many technical interviews. We ask logic questions and simple programming problems that the interviewee is expected to be able to solve on paper. (I would rather they have access to a keyboard, but that is a problem for another time.) Sometimes I sense that people do know how to approach a problem, but they are hung up by nervousness or some second-guessing of the question (they aren't intended to be trick questions).

I've never heard my boss give any help or hints. He just thanks the interviewee for the response (no matter how good or bad it is) and moves on to the next question or problem. But I know something about the rabbit hole that defeat and nerves can lead you down, and how it disables your mind, and I can't help wondering if providing a little help now and then would ultimately help us end up with more capable programmers instead of more failed interviews.

Should I provide hints and assistance for befuddled interviewees (and if so, how far should I go while still being fair to the more prepared candidates)?

答:
The way I see it, an interview is a trial coworking session, not a test. I'm primarily trying to answer the question "what's it feel like to work with this person?" I sometimes even pretend I have forgotten the answer to the question, to make the exercise feel more collaborative.

Have you ever worked with someone who you just could not get on the same page with whenever you talked through a problem? Or someone who asked too many questions instead of jumping in and solving problems? In an interview I'm mostly making sure the person I'm talking with isn't one of those. There's a strong element of chemistry there.

In the process I'll of course also learn things like, "does she write clean code," "is she familiar with the requisite concepts," and "can she cleverly poke a problem to arrive at insights?" The candidate will still be the one "driving" and writing code. But along the way hopefully she'll be more relaxed and I'll see a version of her that's closer to what I would actually see day to day as a coworker.