问:
Don't Use "Static" in C#?
I submitted an application I wrote to some other architects for code review. One of them almost immediately wrote me back and said "Don't use static. You can't write automated tests with static classes and methods. static is to be avoided."

I checked and fully 1/4 of my classes are marked static. I use static when I am not going to create an instance of a class because the class is a single global class used throughout the code.

He went on to mention something involving mocking, IOC/DI techniques that can't be used with static code. He says it is unfortunate when 3rd party libraries are static because of their un-testability.

Is this other architect correct?

update: here is an example:

APIManager - this class keeps dictionaries of 3rd party APIs I am calling along with the next allowed time. It enforces API usage limits that a lot of 3rd parties have in their terms of service. I use it anywhere I am calling a 3rd party service by calling Thread.Sleep(APIManager.GetWait("ProviderXYZ")); before making the call. Everything in here is thread safe and it works great with the TPL in C#.

答: Static methods are fine to use and have a rightful place in programming.  It sounds like your architect has a testing framework that does not fully support static methods.  If your code is part of a bigger project, then it is important to meet the architects guidelines.  However, don't let this project deter you from using static methods when it is appropriate to do so.</p>

OwnerDisplayName: Josh Brown

ContentLicense: CC BY-SA 4.0

Title: Don't Use "Static" in C#?


问:
If null is bad, why do modern languages implement it?
I'm sure designers of languages like Java or C# knew issues related to existence of null references (see Are null references really a bad thing?). Also implementing an option type isn't really much more complex than null references.

Why did they decide to include it anyway? I'm sure lack of null references would encourage (or even force) better quality code (especially better library design) both from language creators and users.

Is it simply because of conservatism - "other languages have it, we have to have it too..."?

答:
There are clear, practical uses of the NULL (or nil, or Nil, or null, or Nothing or whatever it is called in your preferred language) pointer.

For those languages that does not have an exception system (e.g. C) a null pointer can be used as a mark of error when a pointer should be returned. For example:

```<code>char *buf = malloc(20);
if (!buf)
{
    perror("memory allocation failed");
    exit(1);
}
</code>```

Here a NULL returned from malloc(3) is used as a marker of failure.

When used in method/function arguments, it can indicate use default for the argument or ignore the output argument. Example below.

Even for those languages with exception mechanism, a null pointer can be used as indication of soft error (that is, errors that is recoverable) especially when the exception handling is expensive (e.g. Objective-C):

```<code>NSError *err = nil;
NSString *content = [NSString stringWithContentsOfURL:sourceFile
                                         usedEncoding:NULL // This output is ignored
                                                error:&err];
if (!content) // If the object is null, we have a soft error to recover from
{
    fprintf(stderr, "error: %s\n", [[err localizedDescription] UTF8String]);
    if (!error) // Check if the parent method ignored the error argument
        *error = err;
    return nil; // Go back to parent layer, with another soft error.
}
</code>```

Here, the soft error does not cause the program to crash if not caught. This eliminates the crazy try-catch like Java have and have a better control in program flow as soft errors are not interrupting (and the few remaining hard exceptions are usually not recoverable and left uncaught)

ContentLicense: CC BY-SA 3.0

Body:
There are clear, practical uses of the NULL (or nil, or Nil, or null, or Nothing or whatever it is called in your preferred language) pointer.

For those languages that does not have an exception system (e.g. C) a null pointer can be used as a mark of error when a pointer should be returned. For example:

char *buf = malloc(20);
if (!buf)
{
    perror("memory allocation failed");
    exit(1);
}

Here a NULL returned from malloc(3) is used as a marker of failure.

When used in method/function arguments, it can indicate use default for the argument or ignore the output argument. Example below.

Even for those languages with exception mechanism, a null pointer can be used as indication of soft error (that is, errors that is recoverable) especially when the exception handling is expensive (e.g. Objective-C):

NSError *err = nil;
NSString *content = [NSString stringWithContentsOfURL:sourceFile
                                         usedEncoding:NULL // This output is ignored
                                                error:&err];
if (!content) // If the object is null, we have a soft error to recover from
{
    fprintf(stderr, "error: %s\n", [[err localizedDescription] UTF8String]);
    if (!error) // Check if the parent method ignored the error argument
        *error = err;
    return nil; // Go back to parent layer, with another soft error.
}

Here, the soft error does not cause the program to crash if not caught. This eliminates the crazy try-catch like Java have and have a better control in program flow as soft errors are not interrupting (and the few remaining hard exceptions are usually not recoverable and left uncaught)


问:
Should I really need to implement event sourcing is this case?
An example of use case when event sourcing is applicable here whose excerpt is:

Say, something went wrong in your app and as a result, a user gets
  blocked for abuse but that user claims to not have done anything to
  break rules. Now you can go back to your staging environment and play
  the events leading up to the block in that system and see what happens
  first hand.

What’s needed for this is a comprehensive log of events for basically
  any interaction that happens around your app and a staging system to
  replay events to. Based on the sensitivity of your data you may want
  to anonymize some details before hand but that’s about it.

IMO, event sourcing has a real benefit when we are asking for "why" was there this state rather than "what" was the state.

My application is designed following CQRS principle, but I don't use Event Sourcing yet.

If my application is really focus on the "what" rather than the "why" (since operations are really simple, meaning there are no different ways to end up the same result), is it similar to use the Temporal Pattern as introduced here (persisting object's versions/revisions in database) rather than implementing event sourcing?

Especially for tracking user abuses (like posting some insults) that were temporary (so hidden), a simple query asking for the version where the abuse was commit could be enough and quickly made, rather than having a "script" in staging environment replaying the events to get the right snapshot showing the abuse.

答:
If you only want to be able to understand what happened in your application (i.e. what the state of your application was at a specific point in time and, potentially, who initiated a state change), an Audit Log may well be all you need. An Audit Log does not make any assumptions as to how you store the currently valid state of your application, i.e. it is fairly independent of the core of your application. It also does not make any assumptions as to how state changes are initiated and controlled, i.e. Audit Log does not require that there is any notion of an event in the system.

From my perspective, Event Sourcing pursues objectives far beyond Audit Log. For example, Audit Log by itself does not provide the event replay capabilities that Event Sourcing can provide.


问:
Alternatives to null values and option-like types
Related to this question i want to know if there is a concise way to eleminate null values out of code in general or if there is not.

E.g. imagine a class that represents a user with birthday as attribute which can be set but does not have to, which then means it's null. In scala and similar languages one could use the Option type to describe this and i see why this is better then just having a regular null value as one would code it in java.

However i wonder if this is the right concept or if we can do it better in this case and even in general.

I came to the idea that we could replace the users birthday (and other optional or possibly unknown/unset attributes) with a list of possible optional attributes. So we could have like

```<code>ourUser.getOptionalAttributes()
// could return a list [Date Birthday, Float Height, Color Eyecolor]
// or just [Color Eyecolor]
// or even an empty list
</code>```

However using a regular list would mean that we could store multiple birthdays e.g.
So we needed a way to tell the compiler that the list may only contain one Birthday type.

Am i totally on the wrong track here and are option types the (philosophical) correct way to express optional attributes?
Also, are there additional concepts for handling the logic of optional attributes other than nullable types and option-like types?

答:
What is a type?

A type is meta data that can be used, at compile time or run time, to describe the shape of our data.

```<code>trait A { val b: X; def c(y: Y): Z}
</code>```

So we know in our program that when ever we see an a: A, we know that a has the shape of A so we can call a.b safely.

So what shape does null have?

null has no data. null does not have a shape. String s = null is allowed as null has no shape, so it can fit any where. MikeFHay above says that an  empty collection can be thought of as a null object. This is wrong, an empty collection has exactly the same shape as any other collection.

If a field can be null, then we can no longer rely on a.b to be safe. The shape of the data in this field is not truly A, only potentially A. The other shape it can be is null. That is the shape of this field is a union of A and null.

Most languages allow unions to be implemented as a tagged union. Scala's Option type is a tagged union of None | Some(a:A). Like wise Ceylon adds a ? postfix for types that say that the type may be null as in String? s = null.

Body:
What is a type?

A type is meta data that can be used, at compile time or run time, to describe the shape of our data.

trait A { val b: X; def c(y: Y): Z}

So we know in our program that when ever we see an a: A, we know that a has the shape of A so we can call a.b safely.

So what shape does null have?

null has no data. null does not have a shape. String s = null is allowed as null has no shape, so it can fit any where. MikeFHay above says that an  empty collection can be thought of as a null object. This is wrong, an empty collection has exactly the same shape as any other collection.

If a field can be null, then we can no longer rely on a.b to be safe. The shape of the data in this field is not truly A, only potentially A. The other shape it can be is null. That is the shape of this field is a union of A and null.

Most languages allow unions to be implemented as a tagged union. Scala's Option type is a tagged union of None | Some(a:A). Like wise Ceylon adds a ? postfix for types that say that the type may be null as in String? s = null.


问:
Lexing: One token per operator, or one universal operator token?
When lexing, what would be the best way to tokenize operators? Would one just create a BinaryOperator token, or a separate token for every single binary operator? Examples: PlusOperator, MinusOperator, DivisionOperator ...

I am tended towards having a universal one, but going from the documentations and project sources I've read the vast majority of lexers are using one token per operator. Is there a particular reason for this? Does it even matter? Does it give you any advantages?

答:
If you have some language support that can leverage, bigger tokens can help improvong efficiency.

From my personal experience from writing a lexer in Objective-C, I leveraged the feature that an Objective-C object can change its class. I defined all binary tokens as one token, but in AST I used one class for each binary operator, sharing one base class. When lexing the lexer emits an object of the base class, BinaryOperator, which later changes itself to object of operator-specific class using simpler table lookup.


答:
There are two related, but slightly different issues:

Should null exist at all? Or should you always use Maybe<T> where null is useful?

Should all references be nullable? If not, which should be the default?

Having to explicitly declare nullable reference types as string? or similar would avoid most (but not all) of the problems null causes, without being too different from what programmers are used to.

I at least agree with you that not all references should be nullable. But avoiding null is not without its complexities:

.NET initializes all fields to default<T> before they can first be accessed by managed code. This means that for reference types you need null or something equivalent and that value types can be initialized to some kind of zero without running code. While both of these have severe downsides, the simplicity of default initialization may have outweighed those downsides.

For instance fields you can work around this by requiring initialization of fields before exposing the this pointer to managed code. Spec# went this route, using different syntax from constructor chaining compared with C#.

For static fields ensuring this is harder, unless you pose strong restrictions on what kind of code may run in a field initializer since you can't simply hide the this pointer.

How to initialize arrays of reference types? Consider a List<T> which is backed by an array with a capacity larger than the length. The remaining elements need to have some value.

Another problem is that it doesn't allow methods like bool TryGetValue<T>(key, out T value) which return default(T) as value if they don't find anything. Though in this case it's easy to argue that the out parameter is bad design in the first place and this method should return a discriminating union or a maybe instead.

All of these problems can be solved, but it's not as easy as "forbid null and all is well".

Title: If null is bad, why do modern languages implement it?

Body:
I'm sure designers of languages like Java or C# knew issues related to existence of null references (see Are null references really a bad thing?). Also implementing an option type isn't really much more complex than null references.

Why did they decide to include it anyway? I'm sure lack of null references would encourage (or even force) better quality code (especially better library design) both from language creators and users.

Is it simply because of conservatism - "other languages have it, we have to have it too..."?


答:
Null serves a very valid purpose of representing a lack of value.

I will say I'm the most vocal person I know about the abuses of null and all the headaches and suffering they can cause especially when used liberally.

My personal stance is people may use nulls only when they can justify it's necessary and appropriate.

Example justifying nulls:

Date of Death is typically a nullable field. There are three possible situations with date of death. Either the person has died and the date is known, the person has died and the date is unknown, or the person is not dead and therefore a date of death does not exist.

Date of Death is also a DateTime field and doesn't have an "unknown" or "empty" value. It does have the default date that comes up when you make a new datetime which varies based on language utilized, but there is technically a chance that person did in fact die at that time and would flag as your "empty value" if you were to use the default date.

The data would need to represent the situation properly.

Person is dead date of death is known (3/9/1984)

Simple, '3/9/1984'

Person is dead date of death is unknown

So what's best? Null, '0/0/0000', or '01/01/1869' (or whatever your default value is?)

Person is not dead date of death is not applicable

So what's best? Null, '0/0/0000', or '01/01/1869' (or whatever your default value is?)

So lets think each value over...

Null, it has implications and concerns you need to be wary of, accidently trying to manipulate it without confirming it's not null first for example would throw an exception, but it also best represents the actual situation... If the person isn't dead the date of death doesn't exist... it's nothing... it's null...

0/0/0000, This could be okay in some languages, and could even be an appropriate representation of no date. Unfortunately some languages and validation will reject this as an invalid datetime which makes it a no go in many cases.

1/1/1869 (or whatever your default datetime value is), the problem here is it gets tricky to handle. You could use that as your lack of value value, except what happens if I want to filter out all my records I don't have a date of death for? I could easily filter out people who actually died on that date which could cause data integrity issues.

The fact is sometimes you Do need to represent nothing and sure sometimes a variable type works well for that, but often variable types need to be able to represent nothing.

If I have no apples I have 0 apples, but what if I don't know how many apples I have?

By all means null is abused and potentially dangerous, but it's necessary at times. It's only the default in many cases because until I provide a value the lack of a value and something needs to represent it. (Null)


问:
Should failing unit tests that we're not going to fix be removed?
My coworker likes to see all of our unit tests pass (as would anyone) and he argues that some of the failing tests of a system he wrote are unnecessary "noise" since they all involve the validity of the data and a separate system in our stack is supposed to be responsible for validation.

Personally, I think keeping the tests allows you to at least understand/acknowledge some of the failing points even if you consciously choose not to fix them.

Is he right in wanting them removed since they are "noise" compared to the other tested functionality and will probably never be fixed?

Just for context. Here are some concrete examples. They all involve code paths that are used, but passing non-validated data into the routines causes unexpected behaviors.:

passing in NaN results in a false positive.

passing in a value that overflows a double's significant figures results in false when true should have been returned. Rounding should not occur.

"139.9999999999999" -> Double.TryParse() -> 139.9999999999999

"139.99999999999999" -> Double.TryParse() -> 140

答:
I would say: no!
If such a failing unit test is not necessery and shows only small bugs you should not remove it, because such units test are essential for future plannig and for bug tracking of your application.

In the current version the bug may not influence your application but can you guarantee that for future versions where requirements are changing?

greetings
Nico


问:
Global variables in javascript
I don't consider myself a highly skilled javascript developer, but I thought I got one thing right for sure: don't create global variables unless you really have to.

I've been learning angularjs lately and discovered one strange thing, almost everywhere in code samples for angular you can find constructions like the following.

```<code>'use strict';

/* Controllers */

var phonecatControllers = angular.module('phonecatControllers', []);

phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone',
  function($scope, Phone) {
    $scope.phones = Phone.query();
    $scope.orderProp = 'age';
  }]);
</code>```

Source: official example app https://github.com/angular/angular-phonecat/blob/master/app/js/controllers.js

So I assumed I might be missing/misunderstanding something. Any thoughts except "since it's demo code, they don't care"?

答:
It's demo code. If you want to read it from the Angular developers, go here and scroll down until you see

In practice, you will not want to have your controller functions in the global namespace.

Title: Global variables in javascript


答:
Not going to be fixed - why?

Is it something that is planned to be fixed later? Keep tests.

Is the whole functionality no longer relevant (tests are checking something that is no longer true)? See if you can fix the tests to check the correct functionality or just remove the tests if new tests for that new functionality already exist.

Title: Should failing unit tests that we're not going to fix be removed?

Body:
My coworker likes to see all of our unit tests pass (as would anyone) and he argues that some of the failing tests of a system he wrote are unnecessary "noise" since they all involve the validity of the data and a separate system in our stack is supposed to be responsible for validation.

Personally, I think keeping the tests allows you to at least understand/acknowledge some of the failing points even if you consciously choose not to fix them.

Is he right in wanting them removed since they are "noise" compared to the other tested functionality and will probably never be fixed?

Just for context. Here are some concrete examples. They all involve code paths that are used, but passing non-validated data into the routines causes unexpected behaviors.:

passing in NaN results in a false positive.

passing in a value that overflows a double's significant figures results in false when true should have been returned. Rounding should not occur.

"139.9999999999999" -> Double.TryParse() -> 139.9999999999999

"139.99999999999999" -> Double.TryParse() -> 140


答:
Let me start off with a few assertions:

Tests are used to show you where your code fails.

Tests should cover all scenarios for each unit that you want to test.

The testresults should give a clear overview of what went wrong.

Now on to your scenario: you acknowledge that these tests are written in a location where they don't belong. I assume from your story that you have a separate project that tests all the validation, so why don't you just move these tests to that project?

The downsides from keeping these tests where they don't belong:

Tests are fractured throughout projects even though they have a designated place to keep them together.

The overview over what failing tests are relevant and what ones are consciously ignored becomes harder and you might miss a few new breaking tests.

That being said: removing tests just because you want to see them all pass is not the answer. The preferred solution is obviously to fix them but when this is not possible then you might want to look into classifying them inside a separate project.

It should also be noted that duplicate tests aren't good either. If you have two tests in two different projects that test the exact same thing then you have to do upkeep for two while only getting benefit from one. If you test your validation in the ValidationTest project and you do the very same in your other project, then you should remove those in your other project and keep things contained to where they are supposed to be.

Lastly, you might also want to make use of the testing framework's possibilities. For example MSTest will allow you to add an [Ignore] attribute to tests that should be ignored. This will result in a nice green bar with an additional category of ignored tests, thus keeping them prevalent.


答:
It depends...

If the failing tests belong to functionality that is not being scrapped then they should not be removed.

As you probably are aware the entire point of unit tests are to be able to quickly and promptly test all the little bits and pieces of your code on a micro level to determine every tiny component is doing what it's supposed to. If a component is still in use, it should still have a test...

The next question is why are they failing? Should the tests be moved to a more appropriate location for testing? was there a change in the system design that broke them? Tests weren't designed properly and are failing because of it?

Regardless of the issue. If the functionality still exists they stay AND should be fixed to properly test again, even if that has to wait until later. (soon enough this noise will piss someone off enough they'll do something about it, hopefully that something is to start fixing them.)

Now if that functionality is temporarily moth balled, you might disable the tests until such a time you revisit it.

If the functionality is being removed (and not expected to ever come back) only then would I remove the tests.


问:
Why can static methods only use static data?
I don't understand why a static method can't use non-static data. Can anybody explain what the problems are and why we can't do it?</p>

答:
I think the issue here is one of understanding.

From a technical standpoint a static method called from within an object would be quite capable of seeing the instance fields.  I strongly suspect this is what caused the question in the first place.

The issue is that methods can be called from outside the object.  At that point there's no instance data to provide them--and thus no way for the compiler to resolve the code.  Since allowing instance data caused a contradiction we must not allow instance data.


答:
I'm sure designers of languages like Java or C# knew issues related to existence of null references

Of course.

Also implementing an option type isn't really much more complex than null references.

I beg to differ! The design considerations that went into nullable value types in C# 2 were complex, controversial and difficult. They took the design teams of both the languages and the runtime many months of debate, implementation of prototypes, and so on, and in fact the semantics of nullable boxing were changed very very close to shipping C# 2.0, which was very controversial.

Why did they decide to include it anyway?

All design is a process of choosing amongst many subtly and grossly incompatible goals; I can only give a brief sketch of just a few of the factors that would be considered:

Orthogonality of language features is generally considered a good thing. C# has nullable value types, non-nullable value types, and nullable reference types. Non-nullable reference types don't exist, which makes the type system non-orthogonal.

Familiarity to existing users of C, C++ and Java is important.

Easy interoperability with COM is important.

Easy interoperability with all other .NET languages is important.

Easy interoperability with databases is important.

Consistency of semantics is important; if we have reference TheKingOfFrance equal to null does that always mean "there is no King of France right now", or can it also mean "There definitely is a King of France; I just don't know who it is right now"? or can it mean "the very notion of having a King in France is nonsensical, so don't even ask the question!"?  Null can mean all of these things and more in C#, and all these concepts are useful.

Performance cost is important.

Being amenable to static analysis is important.

Consistency of the type system is important; can we always know that a non-nullable reference is never under any circumstances observed to be invalid?  What about in the constructor of an object with a non-nullable field of reference type?  What about in the finalizer of such an object, where the object is finalized because the code that was supposed to fill in the reference threw an exception?  A type system that lies to you about its guarantees is dangerous.

And what about consistency of semantics?  Null values propagate when used, but null references throw exceptions when used. That's inconsistent; is that inconsistency justified by some benefit?

Can we implement the feature without breaking other features? What other possible future features does the feature preclude?

You go to war with the army you have, not the one you'd like. Remember, C# 1.0 did not have generics, so talking about Maybe<T> as an alternative is a complete non-starter. Should .NET have slipped for two years while the runtime team added generics, solely to eliminate null references?

What about consistency of the type system? You can say Nullable<T> for any value type -- no, wait, that's a lie. You can't say Nullable<Nullable<T>>. Should you be able to? If so, what are its desired semantics? Is it worthwhile making the entire type system have a special case in it just for this feature?

And so on. These decisions are complex.


问:
How do languages with Maybe types instead of nulls handle edge conditions?
Eric Lippert made a very interesting point in his discussion of why C# uses a null rather than a Maybe<T> type:

Consistency of the type system is important; can we always know that a non-nullable reference is never under any circumstances observed to be invalid? What about in the constructor of an object with a non-nullable field of reference type? What about in the finalizer of such an object, where the object is finalized because the code that was supposed to fill in the reference threw an exception? A type system that lies to you about its guarantees is dangerous.

That was a bit of an eye-opener.  The concepts involved interest me, and I've done some playing around with compilers and type systems, but I never thought about that scenario.  How do languages that have a Maybe type instead of a null handle edge cases such as initialization and error recovery, in which a supposedly guaranteed non-null reference is not, in fact, in a valid state?

答:
The same ways you guarantee any other data is in a valid state.

One can structure semantics and control flow such that you can't have a variable/field of some type without fully creating a value for it. Instead of creating an object and letting a constructor assign "initial" values to its fields, you can only create an object by specifying values for all its fields at once. Instead of declaring a variable and then assigning an initial value, you can only introduce a variable with an initialization.

For example, in Rust you create an object of struct type via Point { x: 1, y: 2 } instead of writing a constructor that does self.x = 1; self.y = 2;. Of course, this may clash with the style of language you have in mind.

Another, complementary approach is using liveness analysis to prevent access to storage before its initialization. This allows declaring a variable without immediately initializing it, as long as it's provably assigned to before the first read. It can also catch some failure-related cases like

```<code>Object o;
try {
    call_can_throw();
    o = new Object();
} catch {}
use(o);
</code>```

Technically, you could also define an arbitrary default initialization for objects, e.g. zero all numeric fields, create empty arrays for array fields, etc. but this is rather arbitrary, less efficient than other options, and can mask bugs.

Body:
The same ways you guarantee any other data is in a valid state.

One can structure semantics and control flow such that you can't have a variable/field of some type without fully creating a value for it. Instead of creating an object and letting a constructor assign "initial" values to its fields, you can only create an object by specifying values for all its fields at once. Instead of declaring a variable and then assigning an initial value, you can only introduce a variable with an initialization.

For example, in Rust you create an object of struct type via Point { x: 1, y: 2 } instead of writing a constructor that does self.x = 1; self.y = 2;. Of course, this may clash with the style of language you have in mind.

Another, complementary approach is using liveness analysis to prevent access to storage before its initialization. This allows declaring a variable without immediately initializing it, as long as it's provably assigned to before the first read. It can also catch some failure-related cases like

Object o;
try {
    call_can_throw();
    o = new Object();
} catch {}
use(o);

Technically, you could also define an arbitrary default initialization for objects, e.g. zero all numeric fields, create empty arrays for array fields, etc. but this is rather arbitrary, less efficient than other options, and can mask bugs.


答:
That quote points to a problem that occurs if the declaration and assignment of identifiers (here: instance members) are separate from each other. As a quick pseudocode sketch:

class Broken {
    val foo: Foo  // where Foo and Bar are non-nullable reference types
    val bar: Bar

    Broken() {
        foo = new Foo()
        throw new Exception()
        // this code is never reached, so "bar" is not assigned
        bar = new Bar()
    }

    ~Broken() {
        foo.cleanup()
        bar.cleanup()
    }
}
```

<p>The scenario is now that during construction of an instance, an error will be thrown, so construction will be aborted before the instance has been fully constructed. This language offers a destructor method which will run before the memory is deallocated, e.g. to manually free non-memory resources. It must also be run on partially constructed objects, because manually managed resources might already have been allocated before construction was aborted.</p>

<p>With nulls, the destructor could test whether a variable had been assigned like <code>if (foo != null) foo.cleanup()</code>. Without nulls, the object is now in an undefined state – what is the value of <code>bar</code>?</p>

<p>However, this problem exists due to the <em>combination</em> of three aspects:</p>

<ul>
<li>The absence of default values like <code>null</code> or guaranteed initialization for the member variables.</li>
<li>The difference between declaration and assignment. Forcing variables to be assigned immediately (e.g. with a <code>let</code> statement as seen in functional languages) is an easy was to force guaranteed initialization – but restricts the language in other ways.</li>
<li>The specific flavor of destructors as a method that gets called by the language runtime.</li>
</ul>

<p>It is easy to choose another design that does not exhibit these problems, for example by always combining declaration with assignment and having the language offer multiple finalizer blocks instead of a single finalization method:</p>

<pre class="lang-scala prettyprint-override"><code>// the body of the class *is* the constructor
class Working() {
    val foo: Foo = new Foo()
    FINALIZE { foo.cleanup() }  // block is registered to run when object is destroyed

    throw new Exception()

    // the below code is never reached, so
    //  1. the "bar" variable never enters the scope
    //  2. the second finalizer block is never registered.
    val bar: Bar = new Bar()
    FINALIZE { bar.cleanup() }  // block is registered to run when object is destroyed
}
</code>```

So there is not an issue with the absence of null, but with the combination a set of other features with an absence of null.

The interesting question is now why C# chose one design but not the other. Here, the context of the quote lists many other arguments for a null in the C# language, which can be mostly summarized as “familiarity and compatibility” – and those are good reasons.

Title: How do languages with Maybe types instead of nulls handle edge conditions?

Body:
Eric Lippert made a very interesting point in his discussion of why C# uses a null rather than a Maybe<T> type:

Consistency of the type system is important; can we always know that a non-nullable reference is never under any circumstances observed to be invalid? What about in the constructor of an object with a non-nullable field of reference type? What about in the finalizer of such an object, where the object is finalized because the code that was supposed to fill in the reference threw an exception? A type system that lies to you about its guarantees is dangerous.

That was a bit of an eye-opener.  The concepts involved interest me, and I've done some playing around with compilers and type systems, but I never thought about that scenario.  How do languages that have a Maybe type instead of a null handle edge cases such as initialization and error recovery, in which a supposedly guaranteed non-null reference is not, in fact, in a valid state?

Body:
That quote points to a problem that occurs if the declaration and assignment of identifiers (here: instance members) are separate from each other. As a quick pseudocode sketch:

class Broken {
    val foo: Foo  // where Foo and Bar are non-nullable reference types
    val bar: Bar

    Broken() {
        foo = new Foo()
        throw new Exception()
        // this code is never reached, so "bar" is not assigned
        bar = new Bar()
    }

    ~Broken() {
        foo.cleanup()
        bar.cleanup()
    }
}

The scenario is now that during construction of an instance, an error will be thrown, so construction will be aborted before the instance has been fully constructed. This language offers a destructor method which will run before the memory is deallocated, e.g. to manually free non-memory resources. It must also be run on partially constructed objects, because manually managed resources might already have been allocated before construction was aborted.

With nulls, the destructor could test whether a variable had been assigned like if (foo != null) foo.cleanup(). Without nulls, the object is now in an undefined state – what is the value of bar?

However, this problem exists due to the combination of three aspects:

The absence of default values like null or guaranteed initialization for the member variables.

The difference between declaration and assignment. Forcing variables to be assigned immediately (e.g. with a let statement as seen in functional languages) is an easy was to force guaranteed initialization – but restricts the language in other ways.

The specific flavor of destructors as a method that gets called by the language runtime.

It is easy to choose another design that does not exhibit these problems, for example by always combining declaration with assignment and having the language offer multiple finalizer blocks instead of a single finalization method:

// the body of the class *is* the constructor
class Working() {
    val foo: Foo = new Foo()
    FINALIZE { foo.cleanup() }  // block is registered to run when object is destroyed

    throw new Exception()

    // the below code is never reached, so
    //  1. the "bar" variable never enters the scope
    //  2. the second finalizer block is never registered.
    val bar: Bar = new Bar()
    FINALIZE { bar.cleanup() }  // block is registered to run when object is destroyed
}

So there is not an issue with the absence of null, but with the combination a set of other features with an absence of null.

The interesting question is now why C# chose one design but not the other. Here, the context of the quote lists many other arguments for a null in the C# language, which can be mostly summarized as “familiarity and compatibility” – and those are good reasons.


问:
Why does the regular expression metacharacter \w include underscores?
In most, if not all implementations of regular expressions, the \w metacharacter matches all alphanumeric characters plus the underscore.

Historically speaking, why was the underscore character included in this character class?  And why not include dashes too?

答: Because underscores are second-nature for identifiers in almost all computer languages that matter.  Dashes are not; they're typically used as an operator for subtraction, and are specifically excluded from identifiers.


问:
Why are background-colors not or rarely used for syntax highlighting?
I wonder why I rarely see any IDEs or other developers that use background colors for syntaxhighlighting.

One of the first things when installing and configuring a new IDE is adjusting the colors so that for example comments have a decent light-grey background. This really helps me seeing where documentation is and where code is when scrolling down fast.

The only time i saw something like that was in the Greenfoot Editor but that didn't look so well at least if you are doing some more complex work and there are more nested conditions and stuff.

So why is it that background colors are rarely used; or does anyone have some good examples where they are used and how?

答:
Text color is enough for that purpose. In most editors I've used, I can clearly see the comments, the keywords, the strings, etc. There is simply no need to visually complicate stuff with background color.

Another element is that backgrounds are used, but for the purposes other than syntax highlighting. For example, in Visual Studio:

Background colors are used to highlight the current line (not the configuration by default) as well as the matching brackets or every use within the file of a currently selected variable.

This alone is a good reason not to use backgrounds for syntax highlighting. Changing background to highlight the occurrences is a very powerful visual way to show information if and only if the background stays uniform elsewhere.

Yellow background is used for quick search.

This is another good example. You can see in practice how difficult such search becomes in a browser when the webpage uses too much background colors. You simply can't see where the search occurrences are.

Dark red background and yellow background are used when debugging.

Light yellow, light blue and light red are used to show the results of code coverage.

Other colors are used during a diff in TFS to highlight added and removed text.

Not using background colors for syntax highlighting makes it possible to keep background colors for something special. If you already use backgrounds for syntax highlighting, you'll end up with a visual mess.

Your example of Greenfoot Editor is a different illustration. They use background for nesting, so using it also for syntax highlighting would create a mess too. Note that their case is problematic too; not, like you said, "if you are doing some more complex work and there are more nested conditions"—if your code has five nested levels, you're screwed anyway and your first concern should not be the IDE, but the code itself, but rather because if the code is formatted correctly, nesting is visually clear, and there is no need to add colors.


答:
It should be obvious that you don't fix your code because a unit test fails, but because your code does the wrong things - the unit test is only an indicator, and unit tests are not by definition always correct. If you say "our code is wrong but we can't be bothered to fix it", leave the unit tests and suffer the shame. If you say "our code is correct, you can't expect it to be called that way", remove the unit test.

If you write a function, define the legal inputs, and define the correct outputs for each input, then a unit test that doesn't give legal inputs and fails should be removed. If your code is limited by the precision of floating-point arithmetic, then a test that fails because it expects higher precision should be removed. That's what seems is happening here.

When I said "legal inputs", that could of course be misunderstood. I can write a function that expects a valid email address as an input; that function may fail if you pass something that isn't a valid email address. I can write another function that expects a non-NULL zero terminated C string that could contain any bytes but is supposed to contain a valid email address in UTF-8 encoding. A unit test that calls it with a null pointer or a non-terminated string is wrong and should be removed. But a unit test that passes a valid string with rubbish data should lead to a correct detection of the rubbish data, because with the function definition any rubbish data is "legal input" that must be handled correctly (most likely identified and an error returned or an exception thrown). And test cases that go into absolute corner cases of the spec and expect them to be handled correctly are correct as well.


问:
Pros and Cons of Facebook's React vs. Web Components (Polymer)
What are the main benefits of Facebook's React over the upcoming Web Components spec and vice versa (or perhaps a more apples-to-apples comparison would be to Google's Polymer library)?

According to this JSConf EU talk and the React homepage, the main benefits of React are:

Decoupling and increased cohesion using a component model

Abstraction, Composition and Expressivity

Virtual DOM & Synthetic events (which basically means they completely re-implemented the DOM and its event system)

Enables modern HTML5 event stuff on IE 8

Server-side rendering

Testability

Bindings to SVG, VML, and <canvas>

Almost everything mentioned is being integrated into browsers natively through Web Components except this virtual DOM concept (obviously). I can see how the virtual DOM and synthetic events can be beneficial today to support old browsers, but isn't throwing away a huge chunk of native browser code kind of like shooting yourself in the foot in the long term? As far as modern browsers are concerned, isn't that a lot of unnecessary overhead/reinventing of the wheel?

Here are some things I think React is missing that Web Components will take care of for you. Correct me if I'm wrong.

Native browser support (read "guaranteed to be faster")

Write script in a scripting language, write styles in a styling language, write markup in a markup language.

Style encapsulation using Shadow DOM

React instead has this, which requires writing CSS in JavaScript. Not pretty.

Two-way binding

答:
Update: this answer seems to be pretty popular so I took some time to clean it up a little bit, add some new info and clarify few things that I thought were not clear enough. Please comment if you think anything else needs clarification or updates.

Most of your concerns are really a matter of opinion and personal preference but I'll try to answer as objectively as I can:

Native vs. Compiled

Write JavaScript in vanilla JavaScript, write CSS in CSS, write HTML
  in HTML.

Back in the day there were hot debates whether one should write native Assembly by hand or use a higher level language like C to make the compiler generate Assembly code for you. Even before that people refused to trust assemblers and preferred to write native machine code by hand (and I'm not joking).

Meanwhile, today there are a lot of people who write HTML in Haml or Jade, CSS in Sass or Less and JavaScript in CoffeeScript or TypeScript. It's there. It works. Some people prefer it, some don't.

The point is that there is nothing fundamentally wrong in not writing JavaScript in vanilla JavaScript, CSS in CSS and HTML in HTML. It's really a matter of preference.

Internal vs. External DSLs

 Style encapsulation using Shadow DOM
   React instead has this, which requires writing CSS in JavaScript. Not pretty.

Pretty or not, it is certainly expressive. JavaScript is a very powerful language, much more powerful than CSS (even including any of CSS preprocessors). It kind of depends on whether you prefer internal or external DSLs for those sorts of things. Again, a matter of preference.

(Note: I was talking about the inline styles in React that was referenced in the original question.)

Types of DSLs - explanation

Update: Reading my answer some time after writing it I think that I need to explain what I mean here. DSL is a domain-specific language and it can be either internal (using syntax of the host language like JavaScript - like for example React without JSX, or like the inline styles in React mentioned above) or it can be external (using a different syntax than the host language - like in this example would be inlining CSS (an external DSL) inside JavaScript).

It can be confusing because some literature uses different terms than "internal" and "external" to describe those kinds of DSLs. Sometimes "embedded" is used instead of "internal" but the word "embedded" can mean different things - for example Lua is described as "Lua: an extensible embedded language" where embedded has nothing to do with embedded (internal) DSL (in which sense it is quite the opposite - an external DSL) but it means that it is embedded in the same sense that, say, SQLite is an embedded database. There is even eLua where "e" stands for "embedded" in a third sense - that it is meant for embedded systems! That's why I don't like using the term "embedded DSL" because things like eLua can be "DSLs" that are "embedded" in two different senses while not being an "embedded DSL" at all!

To make things worse some projects introduce even more confusion to the mix. Eg. Flatiron templates are described as "DSL-free" while in fact it is just a perfect example of an internal DSL with syntax like: map.where('href').is('/').insert('newurl');

That having been said, when I wrote "JavaScript is a very powerful language, much more powerful than CSS (even including any of CSS preprocessors). It kind of depends on whether you prefer internal or external DSLs for those sorts of things. Again, a matter of preference." I was talking about those two scenarios:

One:

```<code>/** @jsx React.DOM */
var colored = {
  color: myColor
};
React.renderComponent(<div style={colored}>Hello World!</div>, mountNode);
</code>```

Two:

```<code>// SASS:
.colored {
  color: $my-color;
}
// HTML:
<div class="colored">Hello World!</div>
</code>```

The first example uses what was described in the question as: "writing CSS in JavaScript. Not pretty." The second example uses Sass. While I agree that using JavaScript to write CSS may not be pretty (for some definitions of "pretty") but there is one advantage of doing it.

I can have variables and functions in Sass but are they lexically scoped or dynamically scoped? Are they statically or dynamically typed? Strongly or weakly? What about the numeric types? Type coersion? Which values are truthy and which are falsy? Can I have higher-order functions? Recursion? Tail calls? Lexical closures? Are they evaluated in normal order or applicative order? Is there lazy or eager evaluation? Are arguments to functions passed by value or by reference? Are they mutable? Immutable? Persistent? What about objects? Classes? Prototypes? Inheritance?

Those are not trivial questions and yet I have to know answers to them if I want to understand Sass or Less code. I already know those answers for JavaScript so it means that I already understand every internal DSL (like the inline styles in React) on those very levels so if I use React then I have to know only one set of answers to those (and many similar) questions, while when I use for eg. Sass and Handlebars then I have to know three sets of those answers and understand their implications.

It's not to say that one way or the other is always better but every time you introduce another language to the mix then you pay some price that may not be as obvious at a first glance, and this price is complexity.

I hope I clarified what I originally meant a little bit.

Data binding

Two-way binding

This is a really interesting subject and in fact also a matter of preference. Two-way is not always better than one-way. It's a question of how do you want to model mutable state in your application. I always viewed two-way bindings as an idea somewhat contrary to the principles of functional programming but functional programming is not the only paradigm that works, some people prefer this kind of behavior and both approaches seem to work pretty well in practice. If you're interested in the details of the design decisions related to the modeling of the state in React then watch the talk by Pete Hunt (linked to in the question) and the talk by Tom Occhino and Jordan Walke who explain it very well in my opinion.

Update: See also another talk by Pete Hunt: Be predictable, not correct: functional DOM programming.

Update 2: It's worth noting that many developers are arguing against bidirectional data flow, or two-way binding, some even call it an anti-pattern. Take for example the Flux application architecture that explicitly avoids the MVC model (that proved to be hard to scale for large Facebook and Instagram applications) in favor of a strictly unidirectional data flow (see the Hacker Way: Rethinking Web App Development at Facebook talk by Tom Occhino, Jing Chen and Pete Hunt for a good introduction). Also, a lot of critique against AngularJS (the most popular Web framework that is loosely based on the MVC model, known for two-way data binding) includes arguments against that bidirectional data flow, see:

Things I Wish I Were Told About Angular.js by Ruoyu Sun

You have ruined HTML by Danny Tuppeny

AngularJS: The Bad Parts by Lars Eidnes

What’s wrong with Angular.js by Jeff Whelpley ("Two way databinding is an anti-pattern.")

Why you should not use Angular.js by Egor Koshelko ("Two-way data binding is not how to handle events in principle.")

Update 3: Another interesting article that nicely explains some of the issues disscussed above is Deconstructing ReactJS's Flux - Not using MVC with ReactJS by Mikael Brassman, author of RefluxJS (a simple library for unidirectional data flow application architecture inspired by Flux).

Update 4: Ember.js is currently going away from the two-way data binding and in future versions it will be one-way by default. See: The Future of Ember talk by Stefan Penner from the Embergarten Symposium in Toronto on November 15th, 2014.

Update 5: See also: The Road to Ember 2.0 RFC - interesting discussion in the pull request by Tom Dale:

"When we designed the original templating layer, we figured that making all data bindings two-way wasn't very harmful: if you don't set a two-way binding, it's a de facto one-way binding!

We have since realized (with some help from our friends at React), that components want to be able to hand out data to their children without having to be on guard for wayward mutations.

Additionally, communication between components is often most naturally expressed as events or callbacks. This is possible in Ember, but the dominance of two-way data bindings often leads people down a path of using two-way bindings as a communication channel. Experienced Ember developers don't (usually) make this mistake, but it's an easy one to make." [emphasis added]

Native vs. VM

Native browser support (read "guaranteed to be faster")

Now finally something that is not a matter of opinion.

Actually here it is exactly the other way around. Of course "native" code can be written in C++ but what do you think the JavaScript engines are written in?

As a matter of fact the JavaScript engines are truly amazing in the optimizations that they use today - and not only V8 any more, also SpiderMonkey and even Chakra shines these days. And keep in mind that with JIT compilers the code is not only as native as it can possibly be but there are also run time optimization opportunities that are simply impossible to do in any statically compiled code.

When people think that JavaScript is slow, they usually mean JavaScript that accesses the DOM. The DOM is slow. It is native, written in C++ and yet it is slow as hell because of the complexity that it has to implement.

Open your console and write:

```<code>console.dir(document.createElement('div'));
</code>```

and see how many properties an empty div element that is not even attached to the DOM has to implement. These are only the first level properties that are "own properties" ie. not inherited from the prototype chain:

align, onwaiting, onvolumechange, ontimeupdate, onsuspend, onsubmit, onstalled, onshow, onselect, onseeking, onseeked, onscroll, onresize, onreset, onratechange, onprogress, onplaying, onplay, onpause, onmousewheel, onmouseup, onmouseover, onmouseout, onmousemove, onmouseleave, onmouseenter, onmousedown, onloadstart, onloadedmetadata, onloadeddata, onload, onkeyup, onkeypress, onkeydown, oninvalid, oninput, onfocus, onerror, onended, onemptied, ondurationchange, ondrop, ondragstart, ondragover, ondragleave, ondragenter, ondragend, ondrag, ondblclick, oncuechange, oncontextmenu, onclose, onclick, onchange, oncanplaythrough, oncanplay, oncancel, onblur, onabort, spellcheck, isContentEditable, contentEditable, outerText, innerText, accessKey, hidden, webkitdropzone, draggable, tabIndex, dir, translate, lang, title, childElementCount, lastElementChild, firstElementChild, children, nextElementSibling, previousElementSibling, onwheel, onwebkitfullscreenerror, onwebkitfullscreenchange, onselectstart, onsearch, onpaste, oncut, oncopy, onbeforepaste, onbeforecut, onbeforecopy, webkitShadowRoot, dataset, classList, className, outerHTML, innerHTML, scrollHeight, scrollWidth, scrollTop, scrollLeft, clientHeight, clientWidth, clientTop, clientLeft, offsetParent, offsetHeight, offsetWidth, offsetTop, offsetLeft, localName, prefix, namespaceURI, id, style, attributes, tagName, parentElement, textContent, baseURI, ownerDocument, nextSibling, previousSibling, lastChild, firstChild, childNodes, parentNode, nodeType, nodeValue, nodeName

Many of them are actually nested objects - to see second level (own) properties of an empty native div in your browser, see this fiddle.

I mean seriously, onvolumechange property on every single div node? Is it a mistake? Nope, it's just a legacy DOM Level 0 traditional event model version of one of the event handlers "that must be supported by all HTML elements, as both content attributes and IDL attributes" [emphasis added] in Section 6.1.6.2 of the HTML spec by W3C - no way around it.

Meanwhile, these are the first level properties of a fake-DOM div in React:

props, _owner, _lifeCycleState, _pendingProps, _pendingCallbacks, _pendingOwner

Quite a difference, isn't it? In fact this is the entire object serialized to JSON (LIVE DEMO), because hey you actually can serialize it to JSON as it doesn't contain any circular references - something unthinkable in the world of native DOM (where it would just throw an exception):

```<code>{
  "props": {},
  "_owner": null,
  "_lifeCycleState": "UNMOUNTED",
  "_pendingProps": null,
  "_pendingCallbacks": null,
  "_pendingOwner": null
}
</code>```

This is pretty much the main reason why React can be faster than the native browser DOM - because it doesn't have to implement this mess.

See this presentation by Steven Luscher to see what is faster: native DOM written in C++ or a fake DOM written entirely in JavaScript. It's a very fair and entertaining presentation.

Update: Ember.js in future versions will use a virtual DOM heavily inspired by React to improve perfomance. See: The Future of Ember talk by Stefan Penner from the Embergarten Symposium in Toronto on November 15th, 2014.

To sum it up: features from Web Components like templates, data binding or custom elements will have a lot of advantages over React but until the document object model itself gets significantly simplified then performance will not be one of them.

Update

Two months after I posted this answers there was some news that is relevant here. As I have just written on Twitter, the lastest version of the Atom text editor written by GitHub in JavaScript uses Facebook's React to get better performance even though according to Wikipedia "Atom is based on Chromium and written in C++" so it has full control of the native C++ DOM implementation (see The Nucleus of Atom) and is guaranteed to have support for Web Components since it ships with its own web browser. It is just a very recent example of a real world project that could've used any other kind of optimization typically unavailable to Web applications and yet it has chosen to use React which is itself written in JavaScript, to achieve best performance, even though Atom was not built with React to begin with, so doing it was not a trivial change.

Update 2

There is an interesting comparison by Todd Parker using WebPagetest to compare performance of TodoMVC examples written in Angular, Backbone, Ember, Polymer, CanJS, YUI, Knockout, React and Shoestring. This is the most objective comparison that I've seen so far. What is significant here is that all of the respective examples were written by experts in all of those frameworks, they are all available on GitHub and can be improved by anyone who thinks that some of the code could be optimized to run faster.

Update 3

Ember.js in future versions will include a number of React's features that are discussed here (including a virtual DOM and unidirectional data binding, to name just a few) which means that the ideas that originated in React are already migrating into other frameworks. See: The Road to Ember 2.0 RFC - interesting discussion in the pull request by Tom Dale (Start Date: 2014-12-03): "In Ember 2.0, we will be adopting a "virtual DOM" and data flow model that embraces the best ideas from React and simplifies communication between components."

As well, Angular.js 2.0 is implementing a lot of the concepts discussed here.

Update 4

I have to elaborate on few issues to answer this comment by Igwe Kalu:

"it is not sensible to compare React (JSX or the compilation output) to
  plain JavaScript, when React ultimately reduces to plain JavaScript.
  [...]
  Whatever strategy React uses for DOM insertion can be applied without
  using React. That said, it doesn't add any special benefits when
  considering the feature in question other than the convenience."
  (full comment here)

In case it wasn't clear enough, in part of my answer I am comparing the performance of operating directly on the native DOM (implemented as host objects in the browser) vs. React's fake/virtual DOM (implemented in JavaScript). The point I was trying to make is that the virtual DOM implemented in JavaScript can outperform the real DOM implemented in C++ and not that React can outperform JavaScript (which obviously wouldn't make much sense since it is written in JavaScript). My point was that "native" C++ code is not always guaranteed to be faster than "not-native" JavaScript. Using React to illustrate that point was just an example.

But this comment touched an interesting issue. In a sense it is true that you don't need any framework (React, Angular or jQuery) for any reason whatsoever (like performance, portability, features) because you can always recreate what the framework does for you and reinvent the wheel - if you can justify the cost, that is.

But - as Dave Smith nicely put it in How to miss the point when comparing web framework performance: "When comparing two web frameworks, the question is not can my app be fast with framework X. The question is will my app be fast with framework X."

In my 2011 answer to: What are some empirical technical reasons not to use jQuery I explain a similar issue, that it is not impossible to write portable DOM-manipulation code without a library like jQuery, but that people rarely do so.

When using programming languages, libraries or frameworks, people tend to use the most convenient or idiomatic ways of doing things, not the perfect but inconvenient ones. The true value of good frameworks is making easy what would otherwise be hard to do - and the secret is making the right things convenient. The result is still having exactly the same power at your disposal as the simplest form of lambda calculus or the most primitive Turing machine, but the relative expressiveness of certain concepts means that those very concepts tend to get expressed more easily or at all, and that the right solutions are not just possible but actually implemented widely.

Update 5

React + Performance = ? article by Paul Lewis from July 2015 shows an example where React is slower than vanilla JavaScript written by hand for  an infinite list of Flickr pictures, which is especially significant on mobile. This example shows that everyone should always test performance for specific use case and specific target platforms and devices.

Thanks to Kevin Lozandier for bringing it to my attention.

Body:
Update: this answer seems to be pretty popular so I took some time to clean it up a little bit, add some new info and clarify few things that I thought were not clear enough. Please comment if you think anything else needs clarification or updates.

Most of your concerns are really a matter of opinion and personal preference but I'll try to answer as objectively as I can:

Native vs. Compiled

Write JavaScript in vanilla JavaScript, write CSS in CSS, write HTML
  in HTML.

Back in the day there were hot debates whether one should write native Assembly by hand or use a higher level language like C to make the compiler generate Assembly code for you. Even before that people refused to trust assemblers and preferred to write native machine code by hand (and I'm not joking).

Meanwhile, today there are a lot of people who write HTML in Haml or Jade, CSS in Sass or Less and JavaScript in CoffeeScript or TypeScript. It's there. It works. Some people prefer it, some don't.

The point is that there is nothing fundamentally wrong in not writing JavaScript in vanilla JavaScript, CSS in CSS and HTML in HTML. It's really a matter of preference.

Internal vs. External DSLs

 Style encapsulation using Shadow DOM
   React instead has this, which requires writing CSS in JavaScript. Not pretty.

Pretty or not, it is certainly expressive. JavaScript is a very powerful language, much more powerful than CSS (even including any of CSS preprocessors). It kind of depends on whether you prefer internal or external DSLs for those sorts of things. Again, a matter of preference.

(Note: I was talking about the inline styles in React that was referenced in the original question.)

Types of DSLs - explanation

Update: Reading my answer some time after writing it I think that I need to explain what I mean here. DSL is a domain-specific language and it can be either internal (using syntax of the host language like JavaScript - like for example React without JSX, or like the inline styles in React mentioned above) or it can be external (using a different syntax than the host language - like in this example would be inlining CSS (an external DSL) inside JavaScript).

It can be confusing because some literature uses different terms than "internal" and "external" to describe those kinds of DSLs. Sometimes "embedded" is used instead of "internal" but the word "embedded" can mean different things - for example Lua is described as "Lua: an extensible embedded language" where embedded has nothing to do with embedded (internal) DSL (in which sense it is quite the opposite - an external DSL) but it means that it is embedded in the same sense that, say, SQLite is an embedded database. There is even eLua where "e" stands for "embedded" in a third sense - that it is meant for embedded systems! That's why I don't like using the term "embedded DSL" because things like eLua can be "DSLs" that are "embedded" in two different senses while not being an "embedded DSL" at all!

To make things worse some projects introduce even more confusion to the mix. Eg. Flatiron templates are described as "DSL-free" while in fact it is just a perfect example of an internal DSL with syntax like: map.where('href').is('/').insert('newurl');

That having been said, when I wrote "JavaScript is a very powerful language, much more powerful than CSS (even including any of CSS preprocessors). It kind of depends on whether you prefer internal or external DSLs for those sorts of things. Again, a matter of preference." I was talking about those two scenarios:

One:

/** @jsx React.DOM */
var colored = {
  color: myColor
};
React.renderComponent(<div style={colored}>Hello World!</div>, mountNode);

Two:

// SASS:
.colored {
  color: $my-color;
}
// HTML:
<div class="colored">Hello World!</div>

The first example uses what was described in the question as: "writing CSS in JavaScript. Not pretty." The second example uses Sass. While I agree that using JavaScript to write CSS may not be pretty (for some definitions of "pretty") but there is one advantage of doing it.

I can have variables and functions in Sass but are they lexically scoped or dynamically scoped? Are they statically or dynamically typed? Strongly or weakly? What about the numeric types? Type coersion? Which values are truthy and which are falsy? Can I have higher-order functions? Recursion? Tail calls? Lexical closures? Are they evaluated in normal order or applicative order? Is there lazy or eager evaluation? Are arguments to functions passed by value or by reference? Are they mutable? Immutable? Persistent? What about objects? Classes? Prototypes? Inheritance?

Those are not trivial questions and yet I have to know answers to them if I want to understand Sass or Less code. I already know those answers for JavaScript so it means that I already understand every internal DSL (like the inline styles in React) on those very levels so if I use React then I have to know only one set of answers to those (and many similar) questions, while when I use for eg. Sass and Handlebars then I have to know three sets of those answers and understand their implications.

It's not to say that one way or the other is always better but every time you introduce another language to the mix then you pay some price that may not be as obvious at a first glance, and this price is complexity.

I hope I clarified what I originally meant a little bit.

Data binding

Two-way binding

This is a really interesting subject and in fact also a matter of preference. Two-way is not always better than one-way. It's a question of how do you want to model mutable state in your application. I always viewed two-way bindings as an idea somewhat contrary to the principles of functional programming but functional programming is not the only paradigm that works, some people prefer this kind of behavior and both approaches seem to work pretty well in practice. If you're interested in the details of the design decisions related to the modeling of the state in React then watch the talk by Pete Hunt (linked to in the question) and the talk by Tom Occhino and Jordan Walke who explain it very well in my opinion.

Update: See also another talk by Pete Hunt: Be predictable, not correct: functional DOM programming.

Update 2: It's worth noting that many developers are arguing against bidirectional data flow, or two-way binding, some even call it an anti-pattern. Take for example the Flux application architecture that explicitly avoids the MVC model (that proved to be hard to scale for large Facebook and Instagram applications) in favor of a strictly unidirectional data flow (see the Hacker Way: Rethinking Web App Development at Facebook talk by Tom Occhino, Jing Chen and Pete Hunt for a good introduction). Also, a lot of critique against AngularJS (the most popular Web framework that is loosely based on the MVC model, known for two-way data binding) includes arguments against that bidirectional data flow, see:

Things I Wish I Were Told About Angular.js by Ruoyu Sun

You have ruined HTML by Danny Tuppeny

AngularJS: The Bad Parts by Lars Eidnes

What’s wrong with Angular.js by Jeff Whelpley ("Two way databinding is an anti-pattern.")

Why you should not use Angular.js by Egor Koshelko ("Two-way data binding is not how to handle events in principle.")

Update 3: Another interesting article that nicely explains some of the issues disscussed above is Deconstructing ReactJS's Flux - Not using MVC with ReactJS by Mikael Brassman, author of RefluxJS (a simple library for unidirectional data flow application architecture inspired by Flux).

Update 4: Ember.js is currently going away from the two-way data binding and in future versions it will be one-way by default. See: The Future of Ember talk by Stefan Penner from the Embergarten Symposium in Toronto on November 15th, 2014.

Update 5: See also: The Road to Ember 2.0 RFC - interesting discussion in the pull request by Tom Dale:

"When we designed the original templating layer, we figured that making all data bindings two-way wasn't very harmful: if you don't set a two-way binding, it's a de facto one-way binding!

We have since realized (with some help from our friends at React), that components want to be able to hand out data to their children without having to be on guard for wayward mutations.

Additionally, communication between components is often most naturally expressed as events or callbacks. This is possible in Ember, but the dominance of two-way data bindings often leads people down a path of using two-way bindings as a communication channel. Experienced Ember developers don't (usually) make this mistake, but it's an easy one to make." [emphasis added]

Native vs. VM

Native browser support (read "guaranteed to be faster")

Now finally something that is not a matter of opinion.

Actually here it is exactly the other way around. Of course "native" code can be written in C++ but what do you think the JavaScript engines are written in?

As a matter of fact the JavaScript engines are truly amazing in the optimizations that they use today - and not only V8 any more, also SpiderMonkey and even Chakra shines these days. And keep in mind that with JIT compilers the code is not only as native as it can possibly be but there are also run time optimization opportunities that are simply impossible to do in any statically compiled code.

When people think that JavaScript is slow, they usually mean JavaScript that accesses the DOM. The DOM is slow. It is native, written in C++ and yet it is slow as hell because of the complexity that it has to implement.

Open your console and write:

console.dir(document.createElement('div'));

and see how many properties an empty div element that is not even attached to the DOM has to implement. These are only the first level properties that are "own properties" ie. not inherited from the prototype chain:

align, onwaiting, onvolumechange, ontimeupdate, onsuspend, onsubmit, onstalled, onshow, onselect, onseeking, onseeked, onscroll, onresize, onreset, onratechange, onprogress, onplaying, onplay, onpause, onmousewheel, onmouseup, onmouseover, onmouseout, onmousemove, onmouseleave, onmouseenter, onmousedown, onloadstart, onloadedmetadata, onloadeddata, onload, onkeyup, onkeypress, onkeydown, oninvalid, oninput, onfocus, onerror, onended, onemptied, ondurationchange, ondrop, ondragstart, ondragover, ondragleave, ondragenter, ondragend, ondrag, ondblclick, oncuechange, oncontextmenu, onclose, onclick, onchange, oncanplaythrough, oncanplay, oncancel, onblur, onabort, spellcheck, isContentEditable, contentEditable, outerText, innerText, accessKey, hidden, webkitdropzone, draggable, tabIndex, dir, translate, lang, title, childElementCount, lastElementChild, firstElementChild, children, nextElementSibling, previousElementSibling, onwheel, onwebkitfullscreenerror, onwebkitfullscreenchange, onselectstart, onsearch, onpaste, oncut, oncopy, onbeforepaste, onbeforecut, onbeforecopy, webkitShadowRoot, dataset, classList, className, outerHTML, innerHTML, scrollHeight, scrollWidth, scrollTop, scrollLeft, clientHeight, clientWidth, clientTop, clientLeft, offsetParent, offsetHeight, offsetWidth, offsetTop, offsetLeft, localName, prefix, namespaceURI, id, style, attributes, tagName, parentElement, textContent, baseURI, ownerDocument, nextSibling, previousSibling, lastChild, firstChild, childNodes, parentNode, nodeType, nodeValue, nodeName

Many of them are actually nested objects - to see second level (own) properties of an empty native div in your browser, see this fiddle.

I mean seriously, onvolumechange property on every single div node? Is it a mistake? Nope, it's just a legacy DOM Level 0 traditional event model version of one of the event handlers "that must be supported by all HTML elements, as both content attributes and IDL attributes" [emphasis added] in Section 6.1.6.2 of the HTML spec by W3C - no way around it.

Meanwhile, these are the first level properties of a fake-DOM div in React:

props, _owner, _lifeCycleState, _pendingProps, _pendingCallbacks, _pendingOwner

Quite a difference, isn't it? In fact this is the entire object serialized to JSON (LIVE DEMO), because hey you actually can serialize it to JSON as it doesn't contain any circular references - something unthinkable in the world of native DOM (where it would just throw an exception):

{
  "props": {},
  "_owner": null,
  "_lifeCycleState": "UNMOUNTED",
  "_pendingProps": null,
  "_pendingCallbacks": null,
  "_pendingOwner": null
}

This is pretty much the main reason why React can be faster than the native browser DOM - because it doesn't have to implement this mess.

See this presentation by Steven Luscher to see what is faster: native DOM written in C++ or a fake DOM written entirely in JavaScript. It's a very fair and entertaining presentation.

Update: Ember.js in future versions will use a virtual DOM heavily inspired by React to improve perfomance. See: The Future of Ember talk by Stefan Penner from the Embergarten Symposium in Toronto on November 15th, 2014.

To sum it up: features from Web Components like templates, data binding or custom elements will have a lot of advantages over React but until the document object model itself gets significantly simplified then performance will not be one of them.

Update

Two months after I posted this answers there was some news that is relevant here. As I have just written on Twitter, the lastest version of the Atom text editor written by GitHub in JavaScript uses Facebook's React to get better performance even though according to Wikipedia "Atom is based on Chromium and written in C++" so it has full control of the native C++ DOM implementation (see The Nucleus of Atom) and is guaranteed to have support for Web Components since it ships with its own web browser. It is just a very recent example of a real world project that could've used any other kind of optimization typically unavailable to Web applications and yet it has chosen to use React which is itself written in JavaScript, to achieve best performance, even though Atom was not built with React to begin with, so doing it was not a trivial change.

Update 2

There is an interesting comparison by Todd Parker using WebPagetest to compare performance of TodoMVC examples written in Angular, Backbone, Ember, Polymer, CanJS, YUI, Knockout, React and Shoestring. This is the most objective comparison that I've seen so far. What is significant here is that all of the respective examples were written by experts in all of those frameworks, they are all available on GitHub and can be improved by anyone who thinks that some of the code could be optimized to run faster.

Update 3

Ember.js in future versions will include a number of React's features that are discussed here (including a virtual DOM and unidirectional data binding, to name just a few) which means that the ideas that originated in React are already migrating into other frameworks. See: The Road to Ember 2.0 RFC - interesting discussion in the pull request by Tom Dale (Start Date: 2014-12-03): "In Ember 2.0, we will be adopting a "virtual DOM" and data flow model that embraces the best ideas from React and simplifies communication between components."

As well, Angular.js 2.0 is implementing a lot of the concepts discussed here.

Update 4

I have to elaborate on few issues to answer this comment by Igwe Kalu:

"it is not sensible to compare React (JSX or the compilation output) to
  plain JavaScript, when React ultimately reduces to plain JavaScript.
  [...]
  Whatever strategy React uses for DOM insertion can be applied without
  using React. That said, it doesn't add any special benefits when
  considering the feature in question other than the convenience."
  (full comment here)

In case it wasn't clear enough, in part of my answer I am comparing the performance of operating directly on the native DOM (implemented as host objects in the browser) vs. React's fake/virtual DOM (implemented in JavaScript). The point I was trying to make is that the virtual DOM implemented in JavaScript can outperform the real DOM implemented in C++ and not that React can outperform JavaScript (which obviously wouldn't make much sense since it is written in JavaScript). My point was that "native" C++ code is not always guaranteed to be faster than "not-native" JavaScript. Using React to illustrate that point was just an example.

But this comment touched an interesting issue. In a sense it is true that you don't need any framework (React, Angular or jQuery) for any reason whatsoever (like performance, portability, features) because you can always recreate what the framework does for you and reinvent the wheel - if you can justify the cost, that is.

But - as Dave Smith nicely put it in How to miss the point when comparing web framework performance: "When comparing two web frameworks, the question is not can my app be fast with framework X. The question is will my app be fast with framework X."

In my 2011 answer to: What are some empirical technical reasons not to use jQuery I explain a similar issue, that it is not impossible to write portable DOM-manipulation code without a library like jQuery, but that people rarely do so.

When using programming languages, libraries or frameworks, people tend to use the most convenient or idiomatic ways of doing things, not the perfect but inconvenient ones. The true value of good frameworks is making easy what would otherwise be hard to do - and the secret is making the right things convenient. The result is still having exactly the same power at your disposal as the simplest form of lambda calculus or the most primitive Turing machine, but the relative expressiveness of certain concepts means that those very concepts tend to get expressed more easily or at all, and that the right solutions are not just possible but actually implemented widely.

Update 5

React + Performance = ? article by Paul Lewis from July 2015 shows an example where React is slower than vanilla JavaScript written by hand for  an infinite list of Flickr pictures, which is especially significant on mobile. This example shows that everyone should always test performance for specific use case and specific target platforms and devices.

Thanks to Kevin Lozandier for bringing it to my attention.


答:
Most useful programming languages allow data items to be written and read in arbitrary sequences, such that it will often not be possible to statically determine the order in which reads and writes will occur before a program is run.  There are many cases where code will in fact store useful data into every slot before reading it, but where proving that would be difficult.  Thus, it will often be necessary to run programs where it would be at least theoretically possible for code to attempt to read something which has not yet been written with a useful value.  Whether or not it is legal for code to do so, there's no general way to stop code from making the attempt.  The only question is what should happen when that occurs.

Different languages and systems take different approaches.

One approach would be to say that any attempt to read something that has not been written will trigger an immediate error.

A second approach is to require code to supply some value in every location before it would be possible to read it, even if there would be no way for the stored value to be semantically useful.

A third approach is to simply ignore the problem and let whatever would happen "naturally" just happen.

A fourth approach is to say that every type must have a default value, and any slot which has not been written with anything else will default to that value.

Approach #4 is vastly safer than approaach #3, and is in general cheaper than approaches #1 and #2.  That then leaves the question of what the default value should be for a reference type.  For immutable reference types, it would in many cases make sense to define a default instance, and say that the default for any variable of that type should be a reference to that instance.  For mutable reference types, however, that wouldn't be very helpful.  If an attempt is made to use a mutable reference type before it has been written, there generally isn't any safe course of action except to trap at the point of attempted use.

Semantically speaking, if one has an array customers of type Customer[20], and one attempts Customer[4].GiveMoney(23) without having stored anything to Customer[4], execution is going to have to trap.  One could argue that an attempt to read Customer[4] should trap immediately, rather than waiting until code attempts to GiveMoney, but there are enough cases where it's useful to read a slot, find out that it doesn't hold a value, and then make use of that information, that having the read attempt itself fail would often be a major nuisance.

Some languages allow one to specify that certain variables should never contain null, and any attempt to store a null should trigger an immediate trap.  That is a useful feature.  In general, though, any language which allows programmers to create arrays of references will either have to allow for the possibility of null array elements, or else force the initialization of array elements to data which cannot possibly be meaningful.


问:
A RESTful way to verify server state
I'm interested in building verifications into a REST service to help with service monitoring.

For example, one could run assertions like http://example.com/posts/verify?min-posts=5&since=1-hour-ago which would respond with an error unless 5 new posts had been created in the past hour.

Are there any existing services like this, or best practices? I'm particularly interested in a recommended error code for failed verifications, as I can't really see anything appropriate in the 4xx series. Errors like "Precondition Required" and "Internal Server Error" are more about the actual request or processing of it, than the meaning of it.

答:
I don't exactly understand your specific example, but I'll still try to give my advice.

REST is all about entities, or state, and state transitions. It kinda seems like what you want to do is query for some state. Let's look at the common HTTP verbs:

POST
- Commonly used for creating additional state on the server.

PUT
- Commonly used for creating or updating existing state on the server.

DELETE
- Used for deleting some state from the server.

The above methods don't make sense for checking existing state, which you want to do. I've left out CONNECT, TRACE, and OPTIONS, since those also don't seem to be appropriate here.

GET
- Used for getting state from the server.

HEAD
- Same as GET but only returns the metadata.

So it seems like GET or HEAD may be most appropriate, depending on where you are returning the information (in the metadata or entity/body). Since you are not transferring state to the server, but querying it, perhaps it should be the responsibility of the client making the assertion to do that instead of the server doing assertions.

If you want to take advantage of HTTP error codes, perhaps you could add a query parameter. For example HEAD posts?min_posts=5 could return 404 (Not Found) if there are no posts meeting that requirement. Otherwise it could return 204 (No Content) if it met the requirement.

If you don't want to use GET or HEAD, you could try using POST, but that requires you to create some entity representing the state that you are POSTing, ex. an "assertion" entity. It could return 409 (Conflict) if the assertion fails, since the state of the resource in the request (i.e. the assertion) has a conflict (i.e. is not true or did not pass). If the assertion passes, you could return 204 (No Content).  This approach kinda seems like a hack to me, though. But it may actually make sense, depending on the details of your system.

I also want to add that a "REST" API is rarely implemented correctly. Sometimes due to acceptable/practical tradeoffs from the REST guidelines. Other times due to ignorance of what REST means.

Title: A RESTful way to verify server state


问:
What is a good integration test strategy?
I'm getting started on a project wherein I want to have pretty thorough test coverage, and I have the luxury of driving the test strategy.  I've settled on a workable plan for unit testing, and I've also settled on using Gherkin to describe features and a port of Cucumber to run the scenarios as end-to-end acceptance tests.

The problem is that I sense that there is a gap in between those two layers.  I can test all my units in isolation, and I can test that my features work, but I can think of other things that I'm going to want to test.

I'm also coming from a different project with (poorly-implemented) automated tests that are a very brittle and are a maintenance nightmare, the goal of these tests being to mostly replace manual regression testing.  Writing more maintainable tests is a must, but at a higher level I'm not sure that our tests are the right ones.

As an example, given a web application, say there's a form to add an event with start and end dates.  As an end-to-end test, we can validate that you can, in fact, add an event.  But if your start date is after your end date, then you get an error message, and I wouldn't think that how a trivial user input error is handled belongs in a feature file.  On the other hand, there seems to be a pretty strong belief that unit testing the UI isn't worth it; instead, one should do automated integration testing.

So what do I do for this code?

Do I unit test the components related to error messages in general, as well as that this form is going to show them, and skip automating that they actually appear?
Do I do the above and then automate that just one error message somewhere shows as intended, and assume the rest will work?
Do I try to automate every different potential failure case for every form?

This hits the middle ground of integration testing, of which I am leery.  Based on my experience, maintaining a large number of integration tests does not seem worth the value.  On the other hand, there is functionality above the unit level and below the feature level that I would ideally like tested, both in the UI and outside of it.  And I'm concerned about what kind of confidence automated regression can bring if it isn't hitting everything.

I am perfectly willing to write integration tests, but in the context of when to write tests, what tests to write, and how many to write, what is a good approach to addressing this problem?

答:
It all comes down to being cost-effective and pragmatic.  Because you are in charge of testing for this project, be careful not to use every type of testing approach or change things that have worked in the past, or introduce a bunch of new tools or practices just for the sake of doing so. I am not saying that is your plan, but just wanted to state that.

If the GUI contains a lot of logic, which it shouldn't, then it must be tested. Ideally the GUI contains very little logic (or none, but realistically that is challenging to do). If it does contain a lot of logic, see if it is feasible or cheaper to refactor the GUI code versus creating and maintaining a large base of slow GUI tests. If the GUI contains little to no logic, then you can maybe get away with not testing it at all, or very few very basic tests to make sure the "connections" are all good, as mentioned above. Also since there are only a few, you don't have to worry about their performance and the maintenance overhead isn't as high.

You should integration test the rest of your system (everything exception GUI) at least, though. The system should be designed in such a way that it doesnt require a GUI to drive it, it could be an (automated) command line interface, web service interface, etc.

There should be the highest number of unit tests, then a smaller number of these "core" integration tests, and very few large/ GUI tests.


答:
The biggest problem with nuisance messaging from maintenance systems, whether they be automated tests, log files, or some other information source is that the receivers of those messages become attenuated to the noise and tune it out.

Right now, you may look at three failing unit tests and think,"No big deal," but it's a slippery slope.  You probably don't have a test runner sophisticated enough to "ignore all but these three failures" to show you a green bar, and you probably only vaguely look at "n tests run, m passed, x failed" when you run the tests.

The purpose of unit tests is to pay attention so you don't have to.  This allows you the freedom to refactor with the knowledge that the tests will tell you if you've overlooked something.

It sounds as if you think the unit test should stay.  In that case, you have to fix the code so the test passes, even if you have to inject a mock for some other component. (It's a unit test, not an integration test.)


问:
variable overwriting in PHP
For example I have this code:

```<code>$route = 'product/category';

//variable overload
$type  = explode('/',$route);
$type  = $type[1];
</code>```

My thinking behind this is that I actually don't need unique variable name for exploded variable, so why not to overwrite?

Is this really bad concept? Or is there some more elegant way to write this?

答:
Other elegant solution:

```<code>list($type, ) = explode("/", $route);
</code>```

I think it's the best one.

Title: variable overwriting in PHP

Body:
Other elegant solution:

list($type, ) = explode("/", $route);

I think it's the best one.


问:
How to not let anyone inspect elements of a webpage?
I was thinking to make some jQuery functions that will use ajax to control mysql. The whole idea is to make separate files of PHP (e.g query.php, addRow.php, update.php and delete.php) provide data to them via the GET variables like query.php?sql=SELECT * FROM table and then control them with jQuery AJAX functions that I'll make later. Expected code:

```<code>$(element).click(function (e) {
    mysql.query("DELETE row FROM table WHERE name = 'John Doe'");
});
</code>```

And then it'll send query through AJAX and the query will be performed.

So the problem is SECURITY . I mean anyone can just change javascript from browser's inspector or use console to control my databases. What can be done for this problem. Is there anyway to not let anyone change elements in the browser console. If not is there ANYWAY to overcome this security problem?

答:
Never expose direct access to your database from the web layer. You can never lock that down; someone will send "DROP TABLE table" to your server, however much you lock down the JS source.

All they have to do is see what the browser sends to your server to detect that your server accepts arbitrary SQL commands.

Not that you can lock down the JS code; it is not the browser you need to worry about, anyone can send a HTTP request and start introspecting your client-side code anyway.

Build a RESTful API instead, use that from the client. Such an API is limited in the damage it can do if someone starts calling it directly.


答:
I am not aware about a best practice for this.

What I would do, is to send the assertions as custom request header with the normal request.

X-ASSERTION min_posts=5.

Then on the server first to parse the header and process the assertions and depending on the result either return HTTP error (as proposed in other answer 204 No Content, 409 Conflict or other more appropriate), or the result of the request.

Additional information about the result of the assertion could be returned again as custom header in the response headers.

STATUS 409 Confilct;
X-ASSERTION-RESULT min_posts=3

I think this would be in compliance with the REST principles, as the assertion is actually exchanging metadata (data about the data) and the place for the metadata is in the header.

However in practice this could be unreliable or difficult to implement as many firewalls or shared hosting servers would strip out the custom headers.

Title: A RESTful way to verify server state

Body:
I'm interested in building verifications into a REST service to help with service monitoring.

For example, one could run assertions like http://example.com/posts/verify?min-posts=5&since=1-hour-ago which would respond with an error unless 5 new posts had been created in the past hour.

Are there any existing services like this, or best practices? I'm particularly interested in a recommended error code for failed verifications, as I can't really see anything appropriate in the 4xx series. Errors like "Precondition Required" and "Internal Server Error" are more about the actual request or processing of it, than the meaning of it.


答:
Is there anyway to not let anyone change elements in the browser console. If not is there ANYWAY to overcome this security problem?

No.

Anything that is in an HTTP response delivered to a user's machine can be intercepted and read / changed by the user ... if they have a little bit of technical expertise.  That includes anything that is delivered encrypted, and decrypted on the fly in the user's browser.

And even if you could prevent the user tweaking your SQL in the webpage, you can't prevent them sending a different SQL to your database, using the database auth credentials that you embedded in your Javascript.

Title: How to not let anyone inspect elements of a webpage?

Body:
I was thinking to make some jQuery functions that will use ajax to control mysql. The whole idea is to make separate files of PHP (e.g query.php, addRow.php, update.php and delete.php) provide data to them via the GET variables like query.php?sql=SELECT * FROM table and then control them with jQuery AJAX functions that I'll make later. Expected code:

```<code>$(element).click(function (e) {
    mysql.query("DELETE row FROM table WHERE name = 'John Doe'");
});
</code>```

And then it'll send query through AJAX and the query will be performed.

So the problem is SECURITY . I mean anyone can just change javascript from browser's inspector or use console to control my databases. What can be done for this problem. Is there anyway to not let anyone change elements in the browser console. If not is there ANYWAY to overcome this security problem?