问:
Why not expose activation records as data types?
Scoped languages tend to store the local variables of a given scope or function together in a data structure known as an activation record. Stack frames are examples of instances of activation records. Not all activation records are part of a stack; for example, in ECMAScript/JavaScript they are garbage collected and you can re-enter a scope through a function object.

Does any strongly-typed language exist with activation records as first-class objects, even with severely limited capabilities? What considerations does this tend to raise? For example, this function:

```<code>void f( int i ) {
    int j = i + 3;
    {
        int * q = & j;
    }
    {
        char r = 'z';
    }
}
</code>```

… could map to this data type:

```<code>struct f_activation {
    int i;
    int j;
    union {
        int * q;
        char r;
    };
};
</code>```

This is just an example; an optimizing compiler wouldn't want to nail down such a restrictive mapping.

Assembly language programmers often declare activation records using the same record directive as other data types. TCL has the uplevel command which is sufficient to treat the scopes of calling functions as objects. (I have seen this done. No joke.)

Context of the question: The C++ community is trying to add coroutines to a future language revision. C++ already has a popular design pattern, "function objects," and many would like paused coroutines to act like objects too, ideally with serialization and clean forced-termination.

I'm not looking for a laundry list, but for past experience with this language design direction. However, I'm happy just to get references so I can do deeper reading myself.

答:
Yes, but not quite in the way you're thinking of. This is an integral part of closures, which many languages make use of.  Closures are implemented by moving part or all of the activation record of the enclosing method into a new object, which is then passed somewhere and a method is called on that object, which can access the data in the closed-over activation record.

In at least one such language, Delphi, it's possible to use RTTI to get at the members of the closure's activation record, which would be useful for the serialization use case noted in the question.  Similar things can probably be done in .NET languages with reflection.


问:
In the spirit of consistency, is it acceptable to comment everything equally?
Consistency is something I value (at an OCD perfectionist level to be honest). I can live with not writing any comments and focus on producing good, refactored, readable code -- or, if I must comment, I would prefer to decide on a very specific comment pattern and comment in that way throughout the entire code consistently, not just to explain certain complicated parts.

Is commenting everything as described or not at all, but not "somewhere in between" an acceptable coding practice?

答:
At my first real job I was hired by a couple of OCDers who wanted me to always write code like this:

```<code>/* comment describing what the next few lines do */
a line of code
a line of code
a line of code

/* comment describing what the next few lines do */
a line of code
a line of code
a line of code
</code>```

etc.

The idea was that it should be possible to gain a relatively good understanding of what the code does by reading through the comments, completely disregarding the actual code.  For this to work there were some additional rules, for example that code comments always had to begin with a verb, etc.

So, I learned to program this way, and I thought it was cool.  Unfortunately, this led to many WTF situations, like the following:

```<code>function int foo( int x )
{
    /* preconditions */
    assert x > 0;

    /* change state */
    this.x = x;

    /* return same value to enable fluent style */
    return x;
}
</code>```

At jobs that I did after that, people either looked at my coding style and did not say anything in order to avoid insulting me, or, if they felt friendly enough to give me advice, they told me that this style of commenting was moronic.

Furthermore, other programmers did not feel obliged at all to follow my style of commenting, so when someone else amended my code, their complete disregard towards my comments was often tantamount to subversion, for example:

```<code>    /* return same value to enable fluent style */
    notifyTheWorldThatXHasChanged();
    return x;
</code>```

So, in my experience, in most workplaces out there, this style of commenting tends to be frowned upon.

My advice would be to write self-documenting code and follow the "minimal comments" rule, which means only add a comment if it is necessary.  Comments in code should only be needed in exceptional circumstances, and their presence should alert the reader that there is something extraordinary going on.

When is a comment necessary? When a reasonably careful reading of the code does not reveal what the code does, or why a certain thing is done in a particular way.

What should be considered a reasonably careful reading of the code? It is when you focus all of your attention to reading the code, with an honest aim to understand what it does, but you trust that the code actually does what it appears to aim to do, so you are not actually going through the pain of executing the code in your mind, trying to figure out what it really does, as if the code has ulterior motives.  You should only have to do that when debugging code.

Of course, the trick is to write that elusive self-documenting code which, when you look at it, its aim becomes readily obvious.  I like to believe that what we do is mostly a science, but this particular little bit seems more like an art to me.  An art well worth mastering.

ContentLicense: CC BY-SA 3.0

Body:
At my first real job I was hired by a couple of OCDers who wanted me to always write code like this:

/* comment describing what the next few lines do */
a line of code
a line of code
a line of code

/* comment describing what the next few lines do */
a line of code
a line of code
a line of code

etc.

The idea was that it should be possible to gain a relatively good understanding of what the code does by reading through the comments, completely disregarding the actual code.  For this to work there were some additional rules, for example that code comments always had to begin with a verb, etc.

So, I learned to program this way, and I thought it was cool.  Unfortunately, this led to many WTF situations, like the following:

function int foo( int x )
{
    /* preconditions */
    assert x > 0;

    /* change state */
    this.x = x;

    /* return same value to enable fluent style */
    return x;
}

At jobs that I did after that, people either looked at my coding style and did not say anything in order to avoid insulting me, or, if they felt friendly enough to give me advice, they told me that this style of commenting was moronic.

Furthermore, other programmers did not feel obliged at all to follow my style of commenting, so when someone else amended my code, their complete disregard towards my comments was often tantamount to subversion, for example:

    /* return same value to enable fluent style */
    notifyTheWorldThatXHasChanged();
    return x;

So, in my experience, in most workplaces out there, this style of commenting tends to be frowned upon.

My advice would be to write self-documenting code and follow the "minimal comments" rule, which means only add a comment if it is necessary.  Comments in code should only be needed in exceptional circumstances, and their presence should alert the reader that there is something extraordinary going on.

When is a comment necessary? When a reasonably careful reading of the code does not reveal what the code does, or why a certain thing is done in a particular way.

What should be considered a reasonably careful reading of the code? It is when you focus all of your attention to reading the code, with an honest aim to understand what it does, but you trust that the code actually does what it appears to aim to do, so you are not actually going through the pain of executing the code in your mind, trying to figure out what it really does, as if the code has ulterior motives.  You should only have to do that when debugging code.

Of course, the trick is to write that elusive self-documenting code which, when you look at it, its aim becomes readily obvious.  I like to believe that what we do is mostly a science, but this particular little bit seems more like an art to me.  An art well worth mastering.


问:
What specifically does expressive power refer to?
Expressive Power is defined by Wikipedia as:

.. the breadth of ideas that can be represented and communicated in
  that language.

Does "ideas" refer to the things (operations, structures, algorithms, etc.?) we can communicate to the machine? Or does it refer to the "human" concepts that can be captured and communicated with the language to other humans?

How is expressive power assessed and measured?

For instance, if we took a language like JavaScript and imposed a weird restriction on variable names, such as variable must be an 8-digit number preceded by an underscore, matching /^_[0-9]{8}$/, would we lose expressive power?

Or would that only be absurd and annoying?

To clarify:

Is expressive power measured by the general ideas inherent to the language:

integers and strings

loops

conditionals

Or the number of specific, unique ideas that the language can represent:

the integers 1, 2 ... 2^32

strings containing "what does the fox say?" and "wha pah pah pah pah pah pow"

for each frog in my collection of frogs

if frog is green or something then do something

答:
There is a simpler and more straight forward way to understand expressive power, but first we need to establish what we mean by languages.  There are two disciplines which study languages: linguistics and automata.  Both would agree on language being sets of words (finite sequences) constructed from some finite alphabet using concatenation.  Typically, interesting languages (by interesting I mean such languages which we can interpret in a useful way) have also a set of rules which govern which words are in the language and which aren't.  Note that expressiveness can only exist when there is interpretation.

By interpretation I mean existence of a function which given a word in a language selects an object from some set of objects (this is obviously debatable for natural languages).

Don't be mislead by the use of "word" though.  A Java program is a word in the Java language (although it may span multiple files containing multiple strings of characters separated by spaces).

It would be counter-productive to use such complicated languages as modern programming languages to deal with this relatively simple concept, this is why I'd rather use mathematical formulas instead.

Let's define language A to be all formulas involving integer addition.

Let's define language B to be the language of all formulas involving integer multiplication.

In both cases we disallow the use of the identity element.  Thus language A contains words "1+1", "1+2", "1+3", "2+3" and so on.  The language B contains words "2*2", "2*3", "2*4", "3*4" and so on.  We also assign usual interpretations to "*" and "+" (integer addition and integer multiplication) to the respective symbols. So, the interpretation of "1+1" is 2, and interpretation of "2*2" is 4.

Observe now that the language A is strictly more expressive than language B, since in integers it is true that multiplication may be cast as repeated addition, but there isn't a way to represent addition as multiplication in general.

To sum this up: language A can be said to be more expressive than language B when their interpretation functions share co-domain, but the image of the interpretation function of B is a proper subset of the image of the interpretation function of A.


问:
Should a Closeable throw an exception if used after being closed, even if it doesn't have to?
Let's say we have this interface:

```<code>public interface OutputChannel extends Closeable {
    public void writeOutput(String output);
}
</code>```

Then there are several classes which implement this interface and generally it is the case that writeOutput() cannot be used after they have been closed.

However, among them there are classes like NullOutputChannel (which never does anything, so it doesn't care if it was closed), or classes that only delegate the output to other Closeables (so they don't care either - they don't do any IO themselves).

I'm not sure if every OutputChannel should always throw IllegalStateException if writeOutput() was called after close(), or if it should silently tolerate it unless it encounters an actual IO problem.

So far I have come up with some conflicting views:

THROW:

Calling writeOutput() after close() is an error and it should not be tolerated. Even if it doesn't matter in case of NullOutputChannel etc., it could matter if NullOutputChannel was replaced by some other OutputChannel implementation.

The interface will behave more consistently if the exception throwing is decided by the general logic that you can't write after closing, rather than by the implementation details of a particular class.

If a class doesn't throw an exception in this case, it is only hiding a bug. It would be better if the bug manifested regardless of the chosen implementation.

IGNORE:

If a particular class doesn't have a problem with something, it should not throw an exception.

Checking for closed state in a class that doesn't care anyway is an unnecessary complication.

I would be grateful for some arguments for either approach, or some recommended best practice in these situations.

答:
The "ignore" approach does not really have any grounds to stand on.

"If a particular class doesn't have a problem with something, it should not throw an exception": no, a class is supposed, among other things, to honor an interface, therefore it ought to have a big problem with anything that violates the rules laid out by the interface.  Whether the violation of the interface has anything to do with the inner workings of the class implementing the interface, is irrelevant.

"Checking for closed state in a class that doesn't care anyway is an unnecessary complication": no, it is not an unnecessary complication, it is an absolutely indispensable part of making sure that the interface is being used correctly.

The ease of programming should not be considered as being equal to the ease of making undetected mistakes.  (This is something that Edsger W. Dijkstra said, source is here.)

Generally, the habit of always making sure that everything is happening precisely as expected, and that nothing is being left to chance, leads to systems that are more stable, more predictable, less buggy, less chaotic. In contrast, writing code that allows mistakes to go undetected is a sure way to forever keep busy fixing bugs all over the place.


问:
Why shouldn't pure functions always be static and public?
What are the reasons, technical or otherwise, that pure functions (functions which do not rely on external state and have no side effects) should not always be public and static?

When a static and pure function is very general, such as Math.floor() or something, then it makes total sense to have it be public and static. Why shouldn't we have global access to basic math functions? But when you do the same with functions specific to the application domain, specific even to JUST the class they are implemented in, then I begin to feel like I'm doing something wrong.

For example, let's say a we have a class User, and it has a super specific attribute called happiness, which can be changed by eating food.   Generally I would have a public function acting as an interface, getting the outside information, then call a protected helper function which is purely implemented, passing in any stateful data as arguments. The implementation might look like this:

```<code>class User {
    private FoodPreference foodPreference;
    private float age;
    // ...
    // constructors initializing the users food preferences and
    // changing the Users preferences as they get older
    // ...

    // Impure interface relying on users state to get their preferences
    public void EatFood(Food food) {
        this.happiness = this.ComputeHappiness(this.foodPreference, food);
    }

    // Pure, does not rely on Users state to compute this info, it's passed in as an argument.
    protected Happiness ComputeHappiness(FoodPreference preference, Food food) {
      Happiness newHappiness = /* some user-specific logic computing their happiness due to eating food */
      return newHappiness;
    }
</code>```

}

If ComputeHappiness() was public and static, would that be bad? My knee-jerk reaction is "Yes it would be", I think because it seems that the usage of the keyword static in OOP is something generally avoided since it is so easy to shoot yourself in the foot.

I can see a lot of benefits to having pure functions be static and public, even if they are not very general:

Pure functions are easier to test. Static functions are easy to access. Your unit tests will need to do less setup to produce the means to test the function. Now you just need the data, which usually isn't the hard part of testing functions.

You public functions can be interfaces which access the stateful data (from the object, database, or any other source) and leave the business logic to their purely implemented helper functions.

Pure functions can be reused much more easily. Perhaps other parts of the application would like to ComputeHappiness()!

What are the reasons this is a terrible idea? It certainly seems to violate the principle of least astonishment.

答:
Every public function is part of component's interface. Interfaces are restricted in their changes, they need to be backward compatible most of the time, and when they aren't, their clients should adapt to changes.
Interfaces therefore tend to be as narrow, as effectively possible. Leaking implementation detail into interface destroys modularity, and introduces additional maintenance cost.</p>


问:
Programming Language vs Markup Language vs Scripting Language
Up until now I don't know the KEY differences between these three. When someone asks me about this, I only tell them that C# is a programming language, HTML and XML are Markup Languages, and JavaScript and VBScript are scripting languages. But what are the key differences that distinguish them from one another?

答:
To produce any kind of taxonomy, you'd need to first ask yourself some questions:

Are objects I'm going to put into whatever relationships defined properly?

If so, do they actually exist?

Am I limiting myself to only a specific kind of relationships between objects, or is there a set requirement for the system to use only legitimate relations?

Typically, when one hears a question like the one you asked, the expected answer makes several assumptions. For instance, it is natural to assume that since all of these are languages they must form a hierarchy under a more general concept of language, or that they partition the space of all languages, or that they are subsets of each other.

Programming languages

Unfortunately, none of the above seems to be true. Perhaps only the programming languages have a definition most agree on. Programming languages are languages which encode programs. Encoding means that a word in the language can be interpreted as a program (a sequence of actions). Computer programming languages are a subset of these. Examples of non-computer programming languages: a grocery list, interpreted as directions for a buyer in a supermarket, DNA interpreted by transcribing peptides, an analogue musical record serving as a program for a tape recorder.

Computer programming languages are thusly the ones which program computers.

Scripting languages

Aren't well-defined. It is open to interpretation what this term means. Historically, it would seem that programming languages which did not have a compiler to produce machine code had been called this way. By today's standards this would put every popular programming language sans Assemblers into this category. Even the so-called low-level languages like C require a runtime with pre-existing procedures, thus the binaries obtained by compiling a C program aren't entirely machine code, but also call to the runtime every now and then.

Markup languages

Aren't well-defined. Whenever the term is used, the intention seems to be to describe a programming language with very limited lexicon, primarily used to generate visual or audio image. It may be difficult to see XML as programming something, but if you look at Man or TexInfo markup, you'll see that the "special" characters are actually instructions of the interpreter.

It is also possible to give a "programming" interpretation for XML language, something that could go like this:

```<code>< := put interpreter in the reading node mode
! := if reading node, start CData/Comment mode
     else if not in read text mode, signal error
-- := if in start CData/Comment mode, start comment
      else if in comment, put in end comment mode
      else if in end comment mode, signal error
...
</code>```

Bottom line: this division as of today, doesn't seem very meaningful, it can only give you some intuition as to what kind of language you are faced with, but it will not provide you with rigorous definition.

Body:
To produce any kind of taxonomy, you'd need to first ask yourself some questions:

Are objects I'm going to put into whatever relationships defined properly?

If so, do they actually exist?

Am I limiting myself to only a specific kind of relationships between objects, or is there a set requirement for the system to use only legitimate relations?

Typically, when one hears a question like the one you asked, the expected answer makes several assumptions. For instance, it is natural to assume that since all of these are languages they must form a hierarchy under a more general concept of language, or that they partition the space of all languages, or that they are subsets of each other.

Programming languages

Unfortunately, none of the above seems to be true. Perhaps only the programming languages have a definition most agree on. Programming languages are languages which encode programs. Encoding means that a word in the language can be interpreted as a program (a sequence of actions). Computer programming languages are a subset of these. Examples of non-computer programming languages: a grocery list, interpreted as directions for a buyer in a supermarket, DNA interpreted by transcribing peptides, an analogue musical record serving as a program for a tape recorder.

Computer programming languages are thusly the ones which program computers.

Scripting languages

Aren't well-defined. It is open to interpretation what this term means. Historically, it would seem that programming languages which did not have a compiler to produce machine code had been called this way. By today's standards this would put every popular programming language sans Assemblers into this category. Even the so-called low-level languages like C require a runtime with pre-existing procedures, thus the binaries obtained by compiling a C program aren't entirely machine code, but also call to the runtime every now and then.

Markup languages

Aren't well-defined. Whenever the term is used, the intention seems to be to describe a programming language with very limited lexicon, primarily used to generate visual or audio image. It may be difficult to see XML as programming something, but if you look at Man or TexInfo markup, you'll see that the "special" characters are actually instructions of the interpreter.

It is also possible to give a "programming" interpretation for XML language, something that could go like this:

< := put interpreter in the reading node mode
! := if reading node, start CData/Comment mode
     else if not in read text mode, signal error
-- := if in start CData/Comment mode, start comment
      else if in comment, put in end comment mode
      else if in end comment mode, signal error
...

Bottom line: this division as of today, doesn't seem very meaningful, it can only give you some intuition as to what kind of language you are faced with, but it will not provide you with rigorous definition.


问:
Writing your test assertions in your function comments (just before the code)?
I'm using PHP and PHPUnit.  Something bothers me: the fact that the assertions are in another class (too easy to forget or to ignore, for any new programmer in the project).

If the test assertions can be written just above the code, it will be easier to maintain, or difficult to ignore, I guess.

How useful can it be?

```<code>/**
 * @assertions for mycode goes here
 */
 public function mycode() {}
</code>```

答:
Gypsy included specifications and assertions in the language itself.  Part of the Gypsy programming system and methodology was generation of verification conditions (theorems to be proved) that proved the correctness of the code.

The Gypsy program demonstrated, among other things, that, contrary to popular belief, it IS possible to deliver entirely bug-free code.  The Message Flow Modulator was a small program, that sat on a serial line and filtered messages passing through.  The MFM was developed at UT Austin.  The acceptance test suite was developed independently, by a team on the West Coast.  The MFM saw the acceptance test suite for the first time at the customer acceptance test at PAX River, and it passed, on the first try, no deviations, no waivers, no yeabuts, no NOTHING.  It PASSED.  (Don Good, the principal investigator on the project, told me that it was a long time before his phone stopped ringing after that news got out.)


答:
The Java Modeling Language (JML) might be close to what you mean.  It provides a formalized way to express the contract of a function or class in special comments and there exist tools to convert these into run-time assertions or unit tests but by default these will just be comments and have zero overhead.

The following example is taken from the Arc class in the digraph example on the JML website.  The comment with the @s defines the contract.

/** Invert the direction of this arc. */
/*@ public normal_behavior
  @   assignable source, target;
  @   ensures source == \old(target) && target == \old(source);
  @*/
public void flip() {
    NodeType temp = source;
    source = target;
    target = temp;
}
```

Title: Writing your test assertions in your function comments (just before the code)?

Body:
I'm using PHP and PHPUnit.  Something bothers me: the fact that the assertions are in another class (too easy to forget or to ignore, for any new programmer in the project).

If the test assertions can be written just above the code, it will be easier to maintain, or difficult to ignore, I guess.

How useful can it be?

```<code>/**
 * @assertions for mycode goes here
 */
 public function mycode() {}
</code>```


答:
Interesting question (which I studied in my 1990 PhD thesis, BTW). I'll rather speak of call frames (on the call stack) instead of activation records (which IIRC are relevant for nested functions displays).

It is quite related to continuations, and there are several languages reifying somehow continuations (notably Scheme). Most of the time continuations are considered abstract (e.g. in relation to CPS or call/cc); sometimes there are inspectable (or even mutable). Read also about dynamic software updating, persistence, application checkpointing, Lisp machines.

Read also old A.Appel's book Compiling With Continuations & his old paper Garbage Collection Can Be Faster than Stack Allocation. Read the Flanagan & al paper Essence of Compiling With Continuations.

Read C.Queinnec Lisp In Small Pieces book which explain various strategies and tradeoffs related to your questions.

Notice that closures (used for function abstractions and anonymous functions) are often heap allocated (and they usually want an efficient garbage collection implementation). Look into Ocaml.

Several implementations of languages are able to introspect the call stack, at least for debugging purposes, a minima like the GNU libc backtrace functions. Look for instance into the JVM (see this question) and the JPDA. IIRC, Smalltalk has explicitly reified call stacks.

A practical issue is efficiency (in particular when you have genuine machine code, e.g. produced by JIT techniques), since most calling conventions do not require that all arguments go thru the processor stack, and a few of them go only thru registers (and might not even be spilled on the stack). Efficiency consideration and compatibility with existing ABIs and calling conventions could explain lack of standard call-stack introspection techniques (since efficient register allocation is hostile to full stack introspection).

BTW, a precise garbage collector is in need of call stack introspection (since it needs to trace local variables pointing to GC-ed values or objects). So look also into some implementations of Scheme entirely or mostly written in Scheme (e.g. Bones, S48, Chicken).

The SBCL implementation of Common Lisp is also able to introspect call stacks (and both its debugger and its compiler is written in SBCL).

Look also into Lua & Neko &  Parrot. IIRC, their bytecode VM is introspectable (including the stack[s]).

Look also into Lisaac project.

See also the nearly obsolete setcontext(3) (on Linux and some other Unixes) & longjmp(3). Notice that C++ destructors and exceptions (and threads) are related to the call stack.

Read the technical appendix of J.Pitrat's book Artificial Beings, the Conscience of a Conscious Machine and his blog which have several explanations about why introspecting the call stack can be practically useful.

BTW, my MELT stuff (a Lispy domain specific language to customize GCC) nearly has introspectable call stack (the internal implementation has it, but I might not yet have exposed it).

Title: Why not expose activation records as data types?

Body:
Scoped languages tend to store the local variables of a given scope or function together in a data structure known as an activation record. Stack frames are examples of instances of activation records. Not all activation records are part of a stack; for example, in ECMAScript/JavaScript they are garbage collected and you can re-enter a scope through a function object.

Does any strongly-typed language exist with activation records as first-class objects, even with severely limited capabilities? What considerations does this tend to raise? For example, this function:

```<code>void f( int i ) {
    int j = i + 3;
    {
        int * q = & j;
    }
    {
        char r = 'z';
    }
}
</code>```

… could map to this data type:

```<code>struct f_activation {
    int i;
    int j;
    union {
        int * q;
        char r;
    };
};
</code>```

This is just an example; an optimizing compiler wouldn't want to nail down such a restrictive mapping.

Assembly language programmers often declare activation records using the same record directive as other data types. TCL has the uplevel command which is sufficient to treat the scopes of calling functions as objects. (I have seen this done. No joke.)

Context of the question: The C++ community is trying to add coroutines to a future language revision. C++ already has a popular design pattern, "function objects," and many would like paused coroutines to act like objects too, ideally with serialization and clean forced-termination.

I'm not looking for a laundry list, but for past experience with this language design direction. However, I'm happy just to get references so I can do deeper reading myself.


答:
All three concepts overlap somewhat, so you can get endless arguments whether XSLT is a programming language or whether Python is a scripting language or not.

A markup language is a language which represent structured data in a textual format, HTML is the most well-known, but there are numerous formats for various purposes, like SVG for graphics, WSDL for describing web service interfaces, resx for resouce files in .net and so on. A rule of thumb is that a markup language does not describe a process or algorithm (like a programming language does) but is pure data. But it is also a fundamental CS insight that there is no fundamental difference between code and data. Some markup languages like XSLT has loops and conditionals like a "real" programming language, and some programming languages like Prolog are almost pure data with no process specified in the code. And Lisp blurs the line so much it treats its own code as a structured data format.

As for the distinction between programming language and scripting language, this is a historical distinction which is almost obsolete today. In the olden days we had compiled stand-alone programs written in say C, and then we had scripting languages like say shell scripts or Word Basic, which were interpreted and designed to manipulate other programs and tool. Today the line is quite blurred with a lot of middle ground, since we have various levels of compilation and interpretation (bytecode compilation, JIT-compilation etc.), and various language-independent API's. So the distinction is not that useful.

Title: Programming Language vs Markup Language vs Scripting Language

Body: Up until now I don't know the KEY differences between these three. When someone asks me about this, I only tell them that C# is a programming language, HTML and XML are Markup Languages, and JavaScript and VBScript are scripting languages. But what are the key differences that distinguish them from one another?


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答:
Be Master of Something, but
Be Aware of Everything !!!!

ContentLicense: CC BY-SA 2.5


问:
Multi inheritance in Java
Let's say I've got a generic java class Filter<InputType, OutputType> which receives an input object and transforms it to an output object.

Now I've got two other classes (NoInputFilter<OutputType>, NoOutputFilter<InputType>) which should do the same except they haven't an InputType respectively an OutputType.

Now the three classes have some functionality in common. The Filter class should handle the input object the same way like the NoOutputFilter does, and it should handle the output object the same way like the NoInputFilter does.

So I've got something like this in terms of functionality, where B is Filter:

Now, Java doesn't allow to inherit from multiple classes. Is there a design pattern to do something like this?

My first approach was to have two interfaces. One interface for the input, one interface for the output. The Filter class implements both. But this way I have to implement the interfaces two times each.

Then I thought about to give the Filter class (which implements the two interfaces) instances of NoOutputFilter and NoInputFilter and just call the right method instead of have duplicated code. But this breaks the semantics, has a lot of boilerplate code, and isn't a very clean approach in my opinion. Here a little demonstration:

```<code>class Filter<InputType, OutputType> implements INoOutputFilter<InputType>, INoInputFilter<OutputType> {
  private final INoOutputFilter<InputType> noOutputFilter;
  private final INoInputFilter<OutputType> noInputFilter;

  public void InputType setInput(InputType input) {
     noOutputFilter.setInput(input);
  }

  public OutputType getOutput() {
     noInputFilter.getOutput();
  }

  [...]
}
</code>```

The last idea was to turn the class hierarchy up site down:

```<code>public class Filter<InputType, OutputType>
public class NoInputFilter<OutputType> extends Filter <Void, OutputType>
public class NoOutputFilter<InputType> extends Filter <InputType, Void>
</code>```

This way, the classes behaves the right way, no duplicated code, but e.g. the NoOutputFilter has a public Void getOutput() method. Even though you can not instantiate something from Void, the API of those two classes are wrong. This would be something like this:

So this isn't a nice approach as well.

Do you have any hint how I could solve this in Java? Is there a design pattern for this?

答:
First of all, Java 8 introduced Default Methods, which is in fact multi-inheritance in Java.

History showed that complicated inheritance structure is cancer. You should favor composition over inheritance. In this case you are mixing input filter with output filter to create artificial bi-directional filter parent. Not clean for me at all.

I don't have your full picture, but from what you described, I would consider two interfaces: InputFilter and OutputFilter. Eventual Bi-directional filter implementation would implement both interfaces.

And if there would be some common functionality, I would extract that common logic into separate class and use it as dependency.

Title: Multi inheritance in Java


答:
I think your approach is wrong.
You are looking at it in terms of classes instead of results.
What you - in my opinion - should do is something like this:

Define an input interface

Define an output interface

Define a base class implementing both, with nullable protected properties

Define a concrete class for NoInput that exposes the output stuff

Define a concrete class for Filter that exposes both.

That's it.

A

Title: Multi inheritance in Java

Body:
Let's say I've got a generic java class Filter<InputType, OutputType> which receives an input object and transforms it to an output object.

Now I've got two other classes (NoInputFilter<OutputType>, NoOutputFilter<InputType>) which should do the same except they haven't an InputType respectively an OutputType.

Now the three classes have some functionality in common. The Filter class should handle the input object the same way like the NoOutputFilter does, and it should handle the output object the same way like the NoInputFilter does.

So I've got something like this in terms of functionality, where B is Filter:

Now, Java doesn't allow to inherit from multiple classes. Is there a design pattern to do something like this?

My first approach was to have two interfaces. One interface for the input, one interface for the output. The Filter class implements both. But this way I have to implement the interfaces two times each.

Then I thought about to give the Filter class (which implements the two interfaces) instances of NoOutputFilter and NoInputFilter and just call the right method instead of have duplicated code. But this breaks the semantics, has a lot of boilerplate code, and isn't a very clean approach in my opinion. Here a little demonstration:

```<code>class Filter<InputType, OutputType> implements INoOutputFilter<InputType>, INoInputFilter<OutputType> {
  private final INoOutputFilter<InputType> noOutputFilter;
  private final INoInputFilter<OutputType> noInputFilter;

  public void InputType setInput(InputType input) {
     noOutputFilter.setInput(input);
  }

  public OutputType getOutput() {
     noInputFilter.getOutput();
  }

  [...]
}
</code>```

The last idea was to turn the class hierarchy up site down:

```<code>public class Filter<InputType, OutputType>
public class NoInputFilter<OutputType> extends Filter <Void, OutputType>
public class NoOutputFilter<InputType> extends Filter <InputType, Void>
</code>```

This way, the classes behaves the right way, no duplicated code, but e.g. the NoOutputFilter has a public Void getOutput() method. Even though you can not instantiate something from Void, the API of those two classes are wrong. This would be something like this:

So this isn't a nice approach as well.

Do you have any hint how I could solve this in Java? Is there a design pattern for this?


问:
How do distributed applications verify that the data was processed correctly?
There are a lot of projects out there that rely on the public sphere to process data for them, but I do wonder how they ensure that every computer participating has processed the data properly.

The first one that comes to mind is Bitcoin mining. I know that the Bitcoin network has a mathematical way of verifying that the data has been processed correctly (I'm not going to go into that here).

But, when I think about other projects, such as the SETI@home project, I often wonder how they know that every participant is behaving correctly; how is it that they know the data was actually processed, or that the results being returned are accurate. The only validation I can think of would require them to also process the same data, meaning that the distributed model is moot.

The game of connect four has already been solved, but let's say that someone wanted to develop a project that solved the game of connect four using a distributed public network (the internet). The server would send down a large chunk of data to one machine to process, for example it would send down a starting point and the machine would have to process all possible boards with a depth of 5 and use a predetermined formula for scoring, then return the best move to the server.

How does the server know that this was the best move using the algorithm?

How do we guarantee that there isn't a rogue actor that is consuming the service and replacing the predetermined scoring algorithm with a junk one that yields the incorrect best move?

答:
You are asking about two different problems, result verification and byzantine failure.

For result verification, the general idea is to find a way to verify the answer more quickly than it can be computed. There are two approaches, which I will call strong verification and weak verification. Strong verification involves a proof that the result is (in)correct. For example, this is a defining characteristic of NP-complete problems: an answer takes exponential time to compute but can be verified in polynomial time.

Weak verification can be used in situations where it is impossible to prove the correctness of a result, and only attempts to verify the result to within some acceptable confidence interval. This is typically a heuristic-based approach, such as SETI@Home's result verification method (as mentioned by MichaelT).

Byzantine systems are those where processes can fail in arbitrary (including malicious) ways. There are a number of methods for achieving Byzantine fault tolerance. The most common is perhaps state machine replication, where the critical step is ordering inputs to ensure that the replicas have a consistent view of the world.

Input ordering is commonly achieved via consensus algorithms. Consensus algorithms are pretty much what they sound like: a way to ensure that there is sufficient agreement about a data value within the system before it is used.

Byzantine failure is a complex problem and this is a very brief and necessarily incomplete summary. For more information, please use the included links and especially the references that they provide.


答:
Have you considered this?

```<code>public interface Input<InputType>   { ... }

public interface Output<OutputType> { ... }

public interface Filter<InputType,OutputType>
    extends Input<InputType>, Output<OutputType> { }
</code>```

To give a more general-purpose answer to your question:

Multi-inheritance in Java

(Please note that this is somewhat experimental, and I have not ran it by other experienced java developers to see what they think about it. Perhaps I will receive some feedback here.)

The way to achieve multi-inheritance in Java is by means of interfaces.  If you have class A extending classes X and Y then you need to begin by defining interfaces for X and Y, so that A can implement both interfaces. The question now becomes, once you have all this in place, how can you avoid code duplication.  Prior to Java 8, this was a mess. With Java 8, this becomes considerably easier and cleaner.  (Still not as clean as I would like it to be, but at least manageable.)

Whenever I create an interface in Java 8 which is bound to be implemented in various different ways, I add Decorator and Defaults sub-interfaces to it.  So, I build something like this:

```<code>public interface Zork
{
    boolean foo();
    boolean bar( int a );

    interface Defaults extends Zork
    {
        @Override
        default boolean foo()
        {
            return bar( 0 );
        }
    }

    interface Decorator extends Defaults
    {
        Zork getDecoratedZork();

        @Override
        default boolean bar( int a )
        {
            Zork decoree = getDecoratedZork();
            return decoree.bar( a );
        }
    }
}
</code>```

This way:

A class wishing to provide an implementation of Zork can be declared with implements Zork.Defaults and refrain from having to implement methods for which defaults have been provided.

A class wishing to act as a decorator of Zork can be declared with implements Zork.Decorator, supply an implementation for the getDecoratedZork(), and implement whatever subset of Zork is necessary, allowing the rest of the methods to be delegated to the decorated Zork.

A class wishing to multiply inherit Zork can be declared as follows:

(Note that since Zork is an interface, the MultipleInheritor class can implement many other interfaces like Zork.)

```<code>public class MultipleInheritor implements Zork.Decorator
{
    private final Zork myZork = new Zork.Defaults()
    {
        @Override
        public boolean bar( int a )
        {
            return a % 2 == 0;
        }
    }

    @Override
    public Zork getDecoratedZork()
    {
        return myZork;
    }
}
</code>```

Title: Multi inheritance in Java

Body:
Have you considered this?

public interface Input<InputType>   { ... }

public interface Output<OutputType> { ... }

public interface Filter<InputType,OutputType>
    extends Input<InputType>, Output<OutputType> { }

To give a more general-purpose answer to your question:

Multi-inheritance in Java

(Please note that this is somewhat experimental, and I have not ran it by other experienced java developers to see what they think about it. Perhaps I will receive some feedback here.)

The way to achieve multi-inheritance in Java is by means of interfaces.  If you have class A extending classes X and Y then you need to begin by defining interfaces for X and Y, so that A can implement both interfaces. The question now becomes, once you have all this in place, how can you avoid code duplication.  Prior to Java 8, this was a mess. With Java 8, this becomes considerably easier and cleaner.  (Still not as clean as I would like it to be, but at least manageable.)

Whenever I create an interface in Java 8 which is bound to be implemented in various different ways, I add Decorator and Defaults sub-interfaces to it.  So, I build something like this:

public interface Zork
{
    boolean foo();
    boolean bar( int a );

    interface Defaults extends Zork
    {
        @Override
        default boolean foo()
        {
            return bar( 0 );
        }
    }

    interface Decorator extends Defaults
    {
        Zork getDecoratedZork();

        @Override
        default boolean bar( int a )
        {
            Zork decoree = getDecoratedZork();
            return decoree.bar( a );
        }
    }
}

This way:

A class wishing to provide an implementation of Zork can be declared with implements Zork.Defaults and refrain from having to implement methods for which defaults have been provided.

A class wishing to act as a decorator of Zork can be declared with implements Zork.Decorator, supply an implementation for the getDecoratedZork(), and implement whatever subset of Zork is necessary, allowing the rest of the methods to be delegated to the decorated Zork.

A class wishing to multiply inherit Zork can be declared as follows:

(Note that since Zork is an interface, the MultipleInheritor class can implement many other interfaces like Zork.)

public class MultipleInheritor implements Zork.Decorator
{
    private final Zork myZork = new Zork.Defaults()
    {
        @Override
        public boolean bar( int a )
        {
            return a % 2 == 0;
        }
    }

    @Override
    public Zork getDecoratedZork()
    {
        return myZork;
    }
}


问:
Storing great amounts of data
I was brainstorming and I found quite an interesting topic I couldn't come up with a solution for myself.

How does storing excessively large amounts of data work? I mean physically, no matter how big the drive is, there will always be more data than there is space on a single disk. And I'm guessing this is more of a fundamental question, because I can see how it works with caching, since it is essentially the same problem, except it's RAM that you run out of. When a server runs out of RAM you start a second server and then query both servers to find the key you need, it's OK because RAM is fast, but how does that work with relational databases? You can't split a table between two drives, or can you? Even if you could, this still wouldn't work because querying multiple databases would be slow? Apparently there is some kind of a solution to this problem, since Google, Facebook and others are functioning and they surely possess insane amounts of data.

答:
The most generalized term for this is "distributed index", and it is indeed a quite complex topic where a lot of active research is done.

The first step is a dedicated index server, i.e. one that contains no data itself but for every key it knows which server has the data for that key and forwards the request there.

When even the index becomes too big for one server, you can split up the index, most naively by making each index server responsible for an equal range of the key space, e.g. with string keys one is responsible for A-M and the other for N-Z. But data could be unevenly distributed, and the distribution can change, so you need a way for the ranges to be dynamic.

The next step is then a hierarchy of index servers, where the top one only determines which other server is responsible for the range in which the requested key is, possibly with multiple such "hops".

The really tricky thing about this is how to coordinate changes in the index (additions, deletions) between the servers, especially when you replicate parts of the index on multiple servers to handle a large amount of requests. You run into all sorts of very tricky concurrency problems - deadlocks, lock contention, distributed locks being unacceptably slow, dealing with network delays and outages... As I wrote, active research topic!

Title: Storing great amounts of data


问:
What does weak static typing/strong dynamic typing mean?
For most of my career, I've been working with strong static typed languaged such as Java. For this reason, probably I've mixed up these two typing dimension (strongness and staticness). I came upon this link, which says that they are actually orthogonal dimension. I read it, but still can't understand this distinction. 'weak static' sounds oxymoron to me, because static sounds like they will check stuff at compile time, while weak is the opposite.

The page uses Pascal and C as examples of weak static, and CommonLisp and Python as examples of strong dynamic, but unfortunately I don't know enough of these language to help.

What does weak static typing/strong dynamic typing mean? How can a language like C and Python be like Java in one aspect, but like Perl in others?

答:
Static and dynamic is the easy axis to explain, because it refers to when your types are checked:  at compile time or runtime respectively.

In the most simplistic terms, on the weak-strong axis, the stronger your types, the more likely the programmer is to get a type error instead of some other kind of error when he screws up.  You try to compare a number with a boolean in C, no problem.  Try it in python, you'll get a type error at runtime.  That's why python is said to be more strongly typed.

However, that's not the entire picture, because many of the more advanced type system features are designed to help you avoid type errors.  As your types get stronger you get more and more frequent type errors, so people invented ways to help you take them away again, such as generics, inference, and implicit conversion.  This makes the type system more expressive, but it's a matter of intense debate whether those features strengthens or weakens the type system.


问:
Web Framework for Education Management System
Please note that I'm moving my original question from StackOverflow to here, because I think it's more on-topic here

So, I'm working on an idea and I'll go into a brief overview of that but my question is, What are some good web frameworks for this situation? I have some experience in the following languages:

C#

Python

I have considerably more experience in C# than Python, however I am expecting to learn new things.

My idea is this, a completely web-based community-oriented Education Management System that focuses on making students and teachers day-to-day lives easier. For students it will provide a centralized place for them to do homework, study for tests, and reinforce concepts learned previously in class. For teachers it will give them a centralized place to handle assignments, attendance, homework, tests, and all other major parts of classroom management. All of that, but in a community-oriented fashion. Everything a teacher does is shared and open to constructive criticism, allowing other teachers to use their assignments/tests and for students or other teachers to comment, rate and criticize their assignments. This encourages an environment of openness that will allow teacher's to focus on teaching and student's to focus on learning. And that community wouldn't be limited to one school or school-district, this system would be completely school-independent.

Also note that I have no problem with hearing constructive criticism on this idea, however I would prefer if this post was more focused on my question.

I have somewhat explored about the following options:

Django

ASP.NET

Ruby on Rails

Silverlight

(1) I have Django installed and I played with it for a little bit, I really like how easy setting up databases are and how it handles the database completely for you. I don't really know how to use it very well and I don't quite understand the Model-View-Controller paradigm(?) for it yet but I haven't thought about it much. I also like the fact that it uses Python.

(2) I don't really like Visual Studio for developing in ASP.NET, I hate the way the web-designer works and it just feels clunky and old. I like the server-side development part though. I don't like how expensive ASP.NET and overall Visual Studio is, even if I do get it for free for now using DreamSpark

(3) I haven't been able to explore much with this, I could not get Rails (or maybe Ruby) properly installed. I first installed it within RadRails and that didn't work so I uninstalled RadRails and then installed the latest version of Ruby off the official Windows Installer and then installed Ruby on Rails through gem and even after all that it still didn't work, so I installed Netbeans and attempted to use it there but it still did not work

(4) I like Silverlight in some extents, I've played with this one the most, it's very similar to WPF (which I've used the most) in a lot of ways but I don't like how database connectivity works, at least in comparison to Django. I also dislike how expensive everything with Microsoft is, even if I get it for free for now with DreamSpark.

I would like to hear some suggestions from experienced web-developers as to what I should use and why, or at least what some good options are for my scenario

答:
Coding too soon?

When you're just starting out with an idea, it is best to not spend much time coding. @Bitoff is absolutely right in his comments guiding you towards just putting together a prototype that shows how the different user stories work. How do students pick up new work? How does a teacher get rewarded for their contributions? How do I manage password resets? How do I manage online payments? And so on.

This kind of design can be done using pencil and paper sketches that show how a user (either a teacher, student or admin) works their way through the system. You don't need a line of code. You don't need a framework. You just need to convince your significant other that you're not wasting your time.

How much control do you want?

Now comes the decision point. You need to decide how much control over the web application you want:

Complete control. You and your team wrote it all (apart from the open source libraries - Spring, Hibernate etc).

Configuration control. You and your team obtained a framework (Django, Joomla, Silverlight, Flex, etc) and configured it to meet your needs, mostly, with some clunkiness but, hey?

No control. You've outsourced the whole technical development side to a software house and they did all the technical stuff leaving you to concentrate on the business side.

Given that this is a programmers forum, I'll assume you go for option 1. I know I would, but that's because I have a lot of experience with web application development and I can put something together very rapidly. However, there are compelling business arguments to go for options 2 or 3 depending on how you see your business plan developing and your own desire for technical ability.

Create the business and persistence layers first

At the point where you are happy that you have a design that works, then you should be able to knock up a simple prototype quickly because you've already thought through the difficulties. This implies that you are coding in a language with which you are familiar.

At their core, most languages allow for very rapid development, and it's only when the web tier is introduced that a great dump of complexity occurs. So keep it simple: create an integration test (a unit test that interacts with many entities) that demonstrates a simple user story and build out from there. Your code will follow your integration test and you will see how the different entities start to interact.

Design it all to be stateless.

This means that you don't hold anything over to use next time a function is called. Each time you call a function it only knows about what you have passed into it and nothing else.

Over time you will build up a suite of integration tests and will have a complete business domain and perhaps as far as a persistence domain as well. You will have a database model that works efficiently for you.

You will also have sharpened your skills in your chosen language enough so that you are prepared for the onslaught that is the web tier.

Build the web tier

When you start building up the web tier, you will thank your lucky stars that you designed for stateless operation, because it should all just click together nicely.

Your web tier will probably work under a Model-View-Controller pattern so that your Controller receives the web request, processes it by handing over to your business domain in some manner, and then receives back a Model containing data that is then presented as XHTML, JSON, XML or something by the View in the response.

At this point you are in the realms of user experience design, and so you need to make sure that you have some input from a professional graphic designer. They will help you to rapidly overcome front end design issues that could put people off from trying your site.

Summary

Work with a language you like and have experience in

Choose free and open source frameworks and development tools to avoid a) large costs later should you scale up and b) re-inventing the wheel

Build your business and persistence tiers first

Sketch out your web front end and get a professional to do it right

Best of luck with your project.


问:
Hard time understanding structure of web apps w JS frameworks?
I'm having a difficult time understanding how web applications work. Please help me understand without giving me google definitions. Baby steps/words would be appreciated =) From what I understand so far:

Okay so say we use Flask or Django ( python frameworks) for the backend.- This would be used as a base for our web app.Provides restful requests and some templating(?)

Then we would use HTML and CSS for the basic structure and styling needs?

Why do we need to use Javascript then. Does JS make the page dynamic,interactive,etc?, Like click of a button or something ( give me simple examples).

And then I see people using JS frameworks like Angular,react,ember, etc as a client-side framework. Can someone explain how the backend with python works with front-end with these kind of frameworks?

Like don't tell me what these frameworks are, tell me in simple words/examples what they actually do.

Flask VS Flask+JS VS flask+angular ??

Can i still build an application that does simple things without using Javascript or (angular,react,etc)?

So in conclusion, please give me the ingrediants needed for a web app and what each piece does. So maybe examples of simple apps built JUST with flask, JUST with angular, and one with BOTH.

答:
I am not going to comment on the specific frameworks that you have mentioned, but I will try to explain the concept .

The first thing you need to understand that there are two players her :

The Server side ( Python, Php, Java )

..and the Client side ( javascript, jQuery, Angular etc .. )

The second thing is to know and distinguish between languages , framework and libraries ( even though in my answer I might ignore that )

After you will understand that , everything else is easy to explain .
( with the introduction of HTML5 - that border between client and server was blurred a bit - but for the sake of the answer I will ignore that )

With a web app, first, the client side acquire and process some data , it can be many things depending on the app itself ( like database queries , data manipulation etc ) - but then , the result is HTML markup and some other code like Javascript and images - and it send this data in the form of HTML over some protocol ( lets say  HTTP )  to the client ( Let´s say a Browser ) resulting in the three-tier architecture ( data-logic-presentation) .

When it reaches your browser, the code is rendered into a UI that you ( the user ) can really see and interact with . This is where the HTML and Javascript comes to play in the form of the DOM tree.

You see, some calculations regarding the app ( UI related ) Can be only made on client side for example showing and hiding elements (like error messages at login ) , changing element values, special effects , form submission buttons, dynamic situations and general input related actions etc ... in other words, DOM manipulation.

So why the frameworks ?  Well, even if the definition is a bit different , you might want to look at frameworks like some kind of a library that someone wrote with generic functionality , that will help you write the code faster by reusing functions ( or structure ) they have already made available.

( and yes, there is a difference between library and framework, but you asked for a simple layman answer )

Regarding your question

" Can i still build an application that does simple things without
  using Javascript or (angular,react,etc)?"

Sure you can . But the real answer is it will depend on what you want your web app to do and how it will look . No problem writing a simple web app without javascript . Simple .

But here you have to distinguish between "javascript " and "javascript libraries" or "javascript frameworks" .

Without javascript as a whole , it would be much more difficult , and probably your app would be very limited . without the frameworks, well - yes, it can be done - but it would mean though ,depending on the goal ,  that you will probably have to write much more code and will probably need higher skills .

Now, back to HTML5 - it could shake a bit the foundations of the above answer, because HTML5 allows for some actions that were formally in the realm of the server side - to be done on client side . But that does not change the concept that some actions must and can be done only on server side , and some , only on client side .

Weather you use frameworks or not and on which side of the app ( or both ) is totally up to you - but with today's standards, it is very hard to ignore them completely - and remember that they are just tools , and tools must be chosen according to the job at hand so for every webapp the answer would be different.


问:
Why do DVCSes seem to all have an irrational phobia of uncommitted changes?
Coming from a SVN background, one of the hardest things to get used to when working with DVCS systems is the way they all seem to regard any uncommitted change whatsoever like a ticking time bomb.

In Mercurial, if you try to fetch changes and you have any uncommitted changes in your working copy, you have to jump through hoops to get it to just merge the incoming changes in.  Try to switch branches?  It'll force you to shelve everything and then you have to immediately un-shelve it all on the other end.  (SVN has no trouble with either of these scenarios.)

Git is about the same way.  I'm working side-by-side with another developer on a project, and I just tried to cherry-pick one of his commits into my fork.  It refused to let me because I have uncommitted changes in my working copy, on completely different files than the ones changed in his commit.  There's not even a merge option; apparently I have to stash my changes first!

If a person were to treat something completely harmless with such extreme caution, I would call it a "phobia," an irrational fear that should be regarded as a mental disorder.  But Git and Mercurial were designed by two different teams of intelligent, rational developers, so I have to wonder if they know something I'm not aware of.

Is there a technical reason that justifies this attitude towards uncommitted changes?  And if so, why does the problem in question only seem to exist on DVCSes?

答:
In DVCS-world commits are cheap and history is mutable. WIP can be as "dirty", as you want: and I can't see any reasons against "drop my current state in changeset for storing"

SVN history is linear, thus - you must to merge you drafts with changes from new revisions. DVCS use (natually) DAG, and additional head (commit+pull+up) for diverged history is safer, than merging on the fly modified working dir with fetch'ed external changes

When you switch (to some node) modified WC in Subversion, you get rid of one potential additional merge (contrary to "commit to old"-"switch"-"merge 1 rev. range")... and we know: merges in SVN are not the perfect side of tool, while it isn't a problem at all for DVCSes

Resume

It's not a phobia, it's (sometimes harsh) enforcement to following of good manners "commit often" (SVN-users sometimes are afraid of this style)

And, at last, hg qnew|qpop|qpush is small fair price for neatness and order


问:
Selenium Testing w/ dynamically generated element id's: XPATH or CSS selectors?
Background: I'm an intern tasked with learning Selenium; my organization plans on having QA/Testing use it to simplify testing. We use JSF and WebSphere Application Server.

One of the persistent issues I (and other users) have had with using Selenium is identifying input elements that have dynamically generated ID attributes. Simply put, I don't know how the ID's are generated or when they change, so hard-coding the ID's into the test case is right out.

Fortunately, I figured out two solutions to the problem. I'm not sure which is better, and as a result I'm not sure which I should recommend.

1) I could use XPATH to locate the element. The devs almost always use the ID attribute when they write up the html, and while JSF will re-assign it on the rendered page, the dev-assigned substring is always (AFAIK) a part of the JSF-generated id. For example:

```<code><input id="name"...>
</code>```

will be rendered as something like:

```<code><input id="j_id1234567:name"...>
</code>```

However, a search using XPATH can yield false positives. It also might not stay stable if a dev changes the ID, or if the id-generation algorithm changes.

2.(Recommended by friend who actually works with Selenium) Create empty CSS classes for the input elements, as CSS selectors can be used to locate an element in Selenium., e.g.

```<code><input id = "name"... class="... qa_name">
</code>```

where .qa_name is empty, and then use driver.findElement.(By.cssSelector(".qa_name")) to locate.

If you create one class per tested element, you have a deterministic way to identify the desired element. What concerns me about this is that

I don't know if this will create any overhead while loading the page.

The webapp this would be used for has a LOT of input fields.

Dev will probably not be thrilled about having to create a bunch of custom CSS for each page.

This doesn't seem like a proper use of CSS. I was under the impression that CSS was purely for styling, not giving information about an element.

Are one of these methods more valid than the other, or are these both valid? Also, are my concerns about these methods valid?

答:
I would focus on looking for the stable portion of the ID. You can use CSS selectors to do this.

```<code>driver.findElement(By.cssSelector("input[id^='j_id']");
</code>```

This is read find an INPUT tag that has an ID that starts with (^) j_id. You can also look for ends with ($) or contains (*).

Read more on CSS Selectors

Body:
I would focus on looking for the stable portion of the ID. You can use CSS selectors to do this.

driver.findElement(By.cssSelector("input[id^='j_id']");

This is read find an INPUT tag that has an ID that starts with (^) j_id. You can also look for ends with ($) or contains (*).

Read more on CSS Selectors


答:
When you merge or cherry-pick in git, you are creating a commit immediately. The operation is not complete until that commit is finished and part of the history.

Now, what would happen if git allowed you to gloss over your uncommitted changes in your working directory? You would have a (more or less) hard time to differentiate between the changes/merge conflicts that you need to take care of for the merge/cherry-pick, and the changes that you introduced yourself. Also, it would be near impossible for you to test what you are actually committing.

Thus, forcing a clean working directory for merge situations helps to keep things simple and manageable. After all, all you need to do is to stash your uncommitted changes before the merge, and unstash them afterwards. Note, that in the workflow

```<code>git stash
git pull
git stash pop
</code>```

you have two(!) merge operations. One that merges your last commit with the incoming changes, and one that merges your uncommitted changes with the resulting merge commit. In this way, you only ever need to merge two things into one, avoiding the confusion that would result from trying to merge three things into one in a single operation while trying to ignore of these three things. The git stash/git stash pop makes it easy and explicit that you are ignoring your uncommitted changes for the merge.

Title: Why do DVCSes seem to all have an irrational phobia of uncommitted changes?

Body:
Coming from a SVN background, one of the hardest things to get used to when working with DVCS systems is the way they all seem to regard any uncommitted change whatsoever like a ticking time bomb.

In Mercurial, if you try to fetch changes and you have any uncommitted changes in your working copy, you have to jump through hoops to get it to just merge the incoming changes in.  Try to switch branches?  It'll force you to shelve everything and then you have to immediately un-shelve it all on the other end.  (SVN has no trouble with either of these scenarios.)

Git is about the same way.  I'm working side-by-side with another developer on a project, and I just tried to cherry-pick one of his commits into my fork.  It refused to let me because I have uncommitted changes in my working copy, on completely different files than the ones changed in his commit.  There's not even a merge option; apparently I have to stash my changes first!

If a person were to treat something completely harmless with such extreme caution, I would call it a "phobia," an irrational fear that should be regarded as a mental disorder.  But Git and Mercurial were designed by two different teams of intelligent, rational developers, so I have to wonder if they know something I'm not aware of.

Is there a technical reason that justifies this attitude towards uncommitted changes?  And if so, why does the problem in question only seem to exist on DVCSes?

Body:
When you merge or cherry-pick in git, you are creating a commit immediately. The operation is not complete until that commit is finished and part of the history.

Now, what would happen if git allowed you to gloss over your uncommitted changes in your working directory? You would have a (more or less) hard time to differentiate between the changes/merge conflicts that you need to take care of for the merge/cherry-pick, and the changes that you introduced yourself. Also, it would be near impossible for you to test what you are actually committing.

Thus, forcing a clean working directory for merge situations helps to keep things simple and manageable. After all, all you need to do is to stash your uncommitted changes before the merge, and unstash them afterwards. Note, that in the workflow

git stash
git pull
git stash pop

you have two(!) merge operations. One that merges your last commit with the incoming changes, and one that merges your uncommitted changes with the resulting merge commit. In this way, you only ever need to merge two things into one, avoiding the confusion that would result from trying to merge three things into one in a single operation while trying to ignore of these three things. The git stash/git stash pop makes it easy and explicit that you are ignoring your uncommitted changes for the merge.


问:
Why update client model before sever model?
In tutorials I've seen, when data changes on the client (maybe a TODO is added to the TODOs list) the client side model (and often UI) is updated first, then the server is called to persist that change. This puzzles me as there's the potential for error and failure (in which case you would have to notify the client and revert the change on the data model/UI).

Is it best to update the server first, then the client data model/UI or the other way around?

答:
It's generally easiest to update the server first and then update the UI when the server responds with success.

This allows you to avoid handling cases where you updated the UI but the server update fails.

But it also makes your users wait for the server request to complete before seeing the results in UI.

Which way is best depends on your priorities, and on your application. For some applications it's also easy (just a little more work) to handle cases where server updates fail by updating the UI again. For some applications this becomes quite complex and can lead users to make incorrect decisions with frustrating or even dangerous consequences.

For example, show a doctor on his/her iPad that a medication has been ordered before the server confirms it, and you just might have harmed the patient, if the medication was actually not ordered, due to a brief network outage or other problem, the doctor may put down the iPad and walk away thinking the job is done.

In this case, either a delay or a pending status seems in order in the UI. Although a pending status sounds nicer, sometimes e.g. for safety reasons, a delay and a formal confirmation is better. That's a question of user experience design.

Securities trading, another area from my experience, is one where you ought not to tell a user something is done when it's not. Traders are used to watching complex ui's with status indicators and they mostly hate delay. However, in this case the required status indicators and dynamic UI can add a lot more scope vs. simply waiting for the server to confirm.

Overall the answer is not a technical one. It's really user experience that should drive in this case, along with your budget for development.


问:
ASP.NET vs ASP.NET MVC
I just started learning the ASP.NET MVC framework and it's very different in architecture from regular ASP.NET development. Transitioning from windows forms to WPF was nice, and seemed a way forward in technology. But, while learning ASP.NET MVC, I don't feel the same, I am unable to convince myself that MVC is better than WebForms. It just seems that they made some tweaks to the already available web framework and adopted the MVC architecture from some other language.

Is ASP.NET MVC the step ahead in development?  Should I learn and develop my future projects based on this platform and architecture? To me, it just seems like Microsoft is throwing a new architecture just along with WPF or copying Ruby on Rails. WPF seems promising and great while ASP.NET MVC just makes you crumb-some [sic]. They have removed the controls, thrown a new control system and data-packaging, and it's all together an extreme change to WebForms.

I realize that with MVC you have great freedom in the testing aspect, but I don't believe that this makes a lot of difference in small website or projects. If you ignore the value of testing, What are your takes on this?

答:
ASP.NET MVC makes it easier to manage complexity by dividing an application into the model, the view, and the controller.

ASP.NET MVC does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.

ASP.NET MVC uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure.

ASP.NET MVC provides better support for test-driven development (TDD).

ASP.NET MVC works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.

Source: Advantages of an ASP.NET MVC vs Web Forms

Title: ASP.NET vs ASP.NET MVC


答:
File systems can span multiple physical disks. You may be familiar with the concept of “partitions”, where one physical medium is split into multiple logical volumes, e.g. a hard disk in a typical Windows installation might have a C: and D: partition. However, this doesn't have to be a 1:n mapping and some file systems can handle n:m mappings between drives and volumes/file systems.

The main motivation for an abstraction level between logical volumes and physical disks is not the potential larger storage capacity, but more flexibility and better fault tolerance, especially in a server setting: when a hard drive fails, I want the server to continue running without interruption or downtime, even when I replace the failed disk. This fault tolerance implies that the same data is replicated on multiple hard disks (e.g. in a RAID-6 setup); the ability to hot-swap a drive requires the applications to be unaware of physical disks (i.e. only use the file system, not access the device directly).

This functionality can be provided by hardware disk controllers that present themselves to the OS as a single disk, but actually contain multiple drives. However, there are software approaches as well. On Linux, you can use the Logical Volume Manager to implement multi-drive partitions, move partitions between drives, or to hot-swap drives. The ZFS file system was created to support massively big amounts of data, and includes sophisticated management of large pools of physical drives. A ZFS file system is spread over all disks in its pool, and can support hot-swapping if in a suitable RAID configuration.

For example, I have configured a server with a ~1TB ZFS pool out of 10 × 150GB disks. The RAID level chosen can withstand two disk failures, and one of the disks is a hot spare that will be used to restore the pool until the faulted disks can be swapped out. Obviously, this could be scaled up with larger disks. E.g. with 20 2TB disks, I would configure them into a 30TB pool.

The RAID level chosen does have performance implications. Since a file is typically spread over multiple disks, reading it can use the combined bandwidth of all drives. However, write performance is reduced when the same file is written to multiple drives for fault tolerance.

With techniques such as RAID or Storage Area Networks, there is a lot you can do to expand the storage capacity of a system. However, at some point data can get too big to be managed on a single system, e.g. if you have too much throughput or need system-level rather than disk-level fault tolerance. In such a scenario, a different, distributed software architecture is needed to scale up further, though hard issues around data consistency arise once you have more than one system that are responsible for the same data.

Title: Storing great amounts of data

Body:
I was brainstorming and I found quite an interesting topic I couldn't come up with a solution for myself.

How does storing excessively large amounts of data work? I mean physically, no matter how big the drive is, there will always be more data than there is space on a single disk. And I'm guessing this is more of a fundamental question, because I can see how it works with caching, since it is essentially the same problem, except it's RAM that you run out of. When a server runs out of RAM you start a second server and then query both servers to find the key you need, it's OK because RAM is fast, but how does that work with relational databases? You can't split a table between two drives, or can you? Even if you could, this still wouldn't work because querying multiple databases would be slow? Apparently there is some kind of a solution to this problem, since Google, Facebook and others are functioning and they surely possess insane amounts of data.


问:
why adding a vertex in a graph represented using an adjacency matrix takes O(|v|^2) time complexity?
Adding a vertex in a graph that is represented using an adjacency matrix takes O(|v|^2) time complexity according to http://bigocheatsheet.com/ (graph operation > adjacency matrix > add vertex).

But I couldn't find a reason why? Since all we need is to add a row and a column, which of course takes O(|v|), what is the reasoning behind this?

答:
Matrixes are typically stored in contiguous memory, and the content must have a defined mapping from the sequential memory layout to matrix cell (x,y) (a typical mapping is described in this former "Programmers" post). Now, if there is to add a new vertex, one has to increase the storage for a |V|² matrix to (|V|+1)². That means you will have to copy the whole content of the former smaller matrix to the newly allocated memory for the bigger matrix, because the mapping won't fit anymore. And that is obviously an O(|V|²) operation.

One can mitigate this problem by providing a better memory allocation strategy, for example, by not increasing the matrix size one-by-one, but in bigger steps.


答:
The largest storage systems use specialized parallel file systems like Lustre, GPFS, BeeGFS, etc. The worlds largest supercomputers all rely on one of these, typical installations reach well into the petabyte range, i. e. they contain literally thousands of hard drives (1 petabyte = 1000 terabytes). These drives are connected to a number of dedicated front end servers (often called I/O-nodes), which provide a unified view of the file system to the rest of the supercomputers.

The use of these filesystems is just as with any other filesystem that's mounted via NFS, the semantics are POSIX-like (POSIX-"like" because many of these parallel file systems deviate subtly from strict POSIX semantics for performance reasons). You do not see, which file is placed on which disk, not even which server manages its data. This is abstracted away by the file system. Files may even be striped across several servers to achieve a higher throughput.

Of course, file systems like these have higher latencies than a local disk, so they perform best when data accesses are large and sequential. Thus, putting a database on them is generally not the best idea, however, it can be done. As I said, the use of a parallel file system is not much different from the use of any other file system mounted via NFS.

Title: Storing great amounts of data


问:
How can I target both Windows 10 UWP and Windows Phone 8.1 in the same app?

Background

From a developer's viewpoint, the main selling point of Windows 10 is its new Universal* Windows Platform (UWP).

* Where "Universal" really means "universal to all devices that run Windows 10", and not "universal to devices that run not only Windows 10, but also Windows 8.1 and maybe Windows 7". So if you're building a UWP app, you're really just building a "Windows 10 app". UWP apps will not run even on Windows 8.1 and Windows Phone 8.1 devices, i.e. they're not backward-compatible at all.

As of Q3 2015, Windows 10 is available for PCs and IoT devices. It'll be at least another few months before Windows 10 Mobile is released to the public, but probably no more than a year. This means that Windows Phone 8.1 will remain around for a while yet.

Question

I'm about to start developing a Windows Phone app, and I plan to publish it within the next month or so as it's a fairly simple app. Since Windows 10 Mobile won't be arriving anytime soon, let alone devices the world over getting upgraded, I have to target Windows Phone 8.1 for now. However, since it won't be that long before Windows 10 Mobile rolls out, I'm wondering if it'd be wise to prepare my solution for deployment to Windows 10 UWP as well as Windows Phone 8.1 (which will also allow me to continue supporting 8.1 for as long as I need).

I see that I can group a UWP project and an 8.1 project in the same solution, and share source files and assets via a Shared project as done with the Windows 8.1 Universal template in Visual Studio. Am I on the right track? If so, are there any additional guidelines I should follow to ensure everything (including XAML, as ideally I'd like to have the same or at least similar UI on both platforms) actually works correctly on both platforms accounting for any incongruities?

Alternatively, I could just not worry about Windows 10 Mobile for now and start with an 8.1 project, and migrate it to UWP later on, but I'd still have to maintain both versions of my app since I don't plan on ditching 8.1 users immediately. I'd still have to worry about feature/XAML parity in this case.

答: Depending on how Windows feature specific your app needs to be, you could go with a platform like Xamarin which would allow you to write not only for Windows, but also iOS and Android in the same codebase.</p>


问:
How an add vertex operation could be performed in constant time for a graph represented using adjacency list?
Adding a vertex in a graph that is represented using an adjacency list takes O(1) time complexity according to http://bigocheatsheet.com/ (graph operation > adjacency list > add vertex).

It is said that adjacency list holds all the vertex in an array, and maintains a linked list of adjacent vertex, if we are to add a vertex then we need to copy the entire array to new array with extra space so the operation would take O(|v|) time but they say O(1) how is that possible ?

答:
It's possible because the "lists" in an adjacency list representation are not necessarily raw arrays.

In particular, adding a new node to a linked list is an O(1) operation, so if you make the adjacency list out of linked lists then adding a new node or edge is O(1).

As the chart you've linked points out, stacks and hash tables also have O(1) insertion so you could use them as well, but stacks would probably make many other operations highly inconvenient, and hash tables are only O(1) given some strong assumptions about the hashing function that are tricky to justify, so I usually assume adjacency lists are made out of linked lists if they want constant-time node/edge insertion.

It's also worth noting that even if you did use arrays, you would still have amortized constant-time complexity for node insertion, because the worst case of O(|v|) should be a rare occurrence. It's unclear whether the chart you linked is including any amortized complexities.


问:
Issues deciding on approach to create object
I'm trying to decide what's the best approach to instantiate a particular class. Basically there are two use cases for it: instantiate it in order to save a new entry to the database and fetch an existing entry from the database (and maybe edit the fetched entry and save it back to the database).

The issue I'm having right now is that I can't decide which mechanism for instantiating that class and populating its fields to choose. Say I have this class

```<code>public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }
}
</code>```

And here are the usecases. If you want to fetch a student for the database, the code looks something like:

```<code>Student student = MyLibrary.GetStudent(id);
</code>```

And if you want to create a new student and add it to the database:

```<code>Student student = new Student();
student.FirstName = "James";
student.LastName = "Jackson";
// etc
MyLibrary.CreateStudent(student);
</code>```

The massive issue with this approach is that all the setters are public and I absolutely do not want this. But at the same time I want the user to be able to populate most of the Student fields freely (maybe with the exception of Id.

I'm thinking the builder pattern could be employed in here. This way I can keep the setters private and force the user to create read-only students via the builders. However it then becomes really awkward if the user wants to update a field and save it to the database:

```<code>var student = MyLibrary.GetStudent(id);
var newStudent = new Student.Builder(id).FirstName("NewFirstName").LastName(student.LastName)...etc...Build();
MyLibrary.CreateStudent(newStudent);
</code>```

Basically my only issue with the builder approach is that the code can get quite awkward and tedious if you want to update an existing entry. Some of the classes I have can have around 10 fields and it's not great having to copy 9 of the fields and update one. But it may be much nicer than having a class with public setters.

What other options do I have?

答:
If you want to keep the setter private then you have to use construction arguments to set the properties.

ie

```<code>public class Student
{
    public Student(string firstName, string lastName....
</code>```

Even if you use an additional builder class it will still need to do this underneath. I wouldn't bother with one, unless you are publishing the class or need to enforce some complicated setup logic.

When you come to update an existing object, in the OOP world you would expect to be calling a method on your object which would modify the private properties in accordance with some business logic, rather than simply setting a data value.

ie

```<code>myStudent.MoveIntoAccomadation(myCollege);
</code>```

rather than

```<code>myStudent.Address = myCollege.Address;
</code>```

if you are just doing the latter then it suggests that you object is really just a data struct. There's nothing wrong with this, you could be apssing it to services as  DTO, or just moving it around databases etc

Body:
If you want to keep the setter private then you have to use construction arguments to set the properties.

ie

public class Student
{
    public Student(string firstName, string lastName....

Even if you use an additional builder class it will still need to do this underneath. I wouldn't bother with one, unless you are publishing the class or need to enforce some complicated setup logic.

When you come to update an existing object, in the OOP world you would expect to be calling a method on your object which would modify the private properties in accordance with some business logic, rather than simply setting a data value.

ie

myStudent.MoveIntoAccomadation(myCollege);

rather than

myStudent.Address = myCollege.Address;

if you are just doing the latter then it suggests that you object is really just a data struct. There's nothing wrong with this, you could be apssing it to services as  DTO, or just moving it around databases etc


问:
How can I write a flexible messaging structure for sending TCP messages to clients and server
The general question: how can I write a flexible, but not property heavy, messaging structure for sending TCP messages to clients and server?

Example:

I have a TCP Server for a game that sends some messages through TCP sockets to clients:

Chat messages, including chat text, chat room, and speaker.

Game messages, including game actions and events

Client messages, including clients connecting, logging in, and disconnecting

To achieve this, when one of these actions occurs within the program, an event handler is called generating some specific event type.

```<code>ChatEvent with ChatEventArgs
GameEvent with GameEventArgs
ClientEvent with ClientEventArgs
</code>```

These all extend the EventArgs class.

Now to my question. As things get more complex, I begin to cram more pieces of info into these EventArgs. My GameEventArgs start as

```<code>GameEventArgs gameArgs = new GameEventArgs(GameAction.Start);
gameArgs.gameId = "gameId123";
gameArgs.turn = "thisPlayersTurn";
JSON json = GameEventArgs.ToJson(gameArgs);
SendMessageToClient(json);
</code>```

From this you can gather that GameEventArgs has some public properties such as gameId and turn. But a game is more than IDs and Turns. The client will need to receive game actions, which can be very complex. Suddenly the GameEventArgs needs more and more properties. This is fine, except, that only a few of these properties will be sent at a time. There could be 20-40 unused properties of GameEventArgs. Should I make more classes that inherit GameEventArgs, and only contain certain properties? I will be sending messages often, and I want to take the GC into consideration, as these messages are one time uses. (Should they then be IDisposable?).

Is there a better method to go about creating a messaging structure, where only a few of the defined properties of the message will be used at one time?

答:
In your situation I would not use inheritance, except for a small amount of types maybe, where each type contains a set of properties that are usually used together.

I suggest using a single ID to encode your type of data. I prefer an Enum for that (Syntax is C++.net):

```<code>enum class EnumMessage
{
  MASK_Group = 1000000,
  Group_Chat   = 1000000,
  Group_Game   = 2000000,
  Group_Client = 3000000,
  ...
  Game_GameID = Group_Game + 1,
  Game_Turn   = Group_Game + 2,
  ...
};
</code>```

Given an ID, you could find out the group by dividing by MASK_Group.

Alternative solution:

One Enum per class (GameEventArgs, ...), that encodes the data types.

The message itself would consist of multiple pairs of ID and actual data, e.g.

ID=1 data="content" ID=2 ...

If the data could contain the " character, I would omit it and add a length info instead, which in any case is safer.

Based on the existence of an ID in the received message you know which data you get. To decide which data you need to send, I would create static lists, that contain the IDs of the data you want to send.

Body:
In your situation I would not use inheritance, except for a small amount of types maybe, where each type contains a set of properties that are usually used together.

I suggest using a single ID to encode your type of data. I prefer an Enum for that (Syntax is C++.net):

enum class EnumMessage
{
  MASK_Group = 1000000,
  Group_Chat   = 1000000,
  Group_Game   = 2000000,
  Group_Client = 3000000,
  ...
  Game_GameID = Group_Game + 1,
  Game_Turn   = Group_Game + 2,
  ...
};

Given an ID, you could find out the group by dividing by MASK_Group.

Alternative solution:

One Enum per class (GameEventArgs, ...), that encodes the data types.

The message itself would consist of multiple pairs of ID and actual data, e.g.

ID=1 data="content" ID=2 ...

If the data could contain the " character, I would omit it and add a length info instead, which in any case is safer.

Based on the existence of an ID in the received message you know which data you get. To decide which data you need to send, I would create static lists, that contain the IDs of the data you want to send.