问:
Do frameworks put too much abstraction?
I've been programming for a little under a year and have some experience writing systems applications, web apps, and scripts for businesses/organizations. However, one thing I've never really done is working with a framework like Django, Rails or Zend.

Looking over the Django framework, I'm a little frustrated with how much is abstracted away in frameworks. I understand the core goals of DRY and minimal code, but some of this over-reliance on different modules and heavy abstraction of core functions feels like it:

Makes programs get dated really fast because of the ever-changing nature of modules/frameworks,

Makes code hard to understand because of the plethora of frameworks and modules available and all of their idiosyncrasies,

Makes code less logical unless you've read all of the documentation; i.e., I can read through some list comprehensions and conditional logic and figure out what a program is doing, but when you see functions that require passing in arbitrary strings and dictionaries, things get a little hard to understand unless you're already a guru in a given module; and:

Makes it difficult and tedious to switch between frameworks. Switching between languages is already a challenge, but it's manageable if you have a strong enough understanding of their core functionality/philosophy. Switching between frameworks seems to be more a matter of rote memorization, which in some ways seems to encourage the very inefficiency these frameworks were designed to eliminate.

Do we really need to put like 50 layers of abstraction on top of something as simple as a MySQL query? Why not use something like PHP's PDO interface, where prepared statements/input testing is handled but the universally understandable SQL query is still a part of the function?

Are those abstractions really useful? Isn't feature bloat making them useless, making applications more difficult compared to similar applications written without using a framework?

答:
Some people say this is the Hollywood Principle of frameworks: "Don't call us, we'll call you".  In contrast, whenever you use a library, your code calls the library, not the other way around.

As you can see, the important point is who is in control -- namely, in control of the flow of control. Who decides which statement is run after which one?

There are arguments pro and contra, and whenever I see such endless discussions, I tend to think this must be a matter of taste, rather than an objectively decidable question.  Otherwise, it would have been decided already.

In my view, whether you prefer to use frameworks or libraries tells something about what kind of developer you are, and not whether one of both approaches is superior and will eventually prevail.

If you prefer frameworks, you prefer to exchange freedom for security: you are probably more pragmatic and you tend to trust others to do their work properly. If you prefer libraries, you prefer to exchange security for freedom: you are probably more of an idealist and you question other's ideas and claims.

I do not think it would be wise to decide it is better to be like the former or the latter.

Answering your question: Do frameworks put too much abstraction?  It depends on who you are, and specifically on what distance from first principles do you feel comfortable with.

...

And even more specifically, if you do not like frameworks like Django, go search for "microframeworks" like Flask :)

Title: Do frameworks put too much abstraction?


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答: I guess the percentage of people without JavaScript turned on is negligible. But be careful with search engine bots! They usually don't use JavaScript, but you wouldn't want them to skip some important content of yours because of that, right?</p>

ContentLicense: CC BY-SA 2.5


问:
Under what license may this PyQt-based "Hello World" app be distributed?
Update: I was wrong about the PyQt license.  It isn't merely a GPL license.  The PyQt authors include a special set of exceptions that allow users to release their own code under a different license, as long as it is one of the Open-Source licenses specifically listed in the PyQt GPL_EXCEPTION.TXT file.

For the purpose of this discussion, consider the following fully-functional app, which depends on PyQt:

# hello_world.py
from PyQt4.QtGui import QApplication, QPushButton
app = QApplication([])
button = QPushButton("Hello, World!", clicked=app.quit)
button.show()
app.exec_()
```

(In case it's relevant to the discussion, please note that Python programs like this one do not require "linking" per se.)

My preference is to distribute my code under a permissive license, e.g. the BSD license.  However, PyQt is released under the GNU GPL GNU GPL with special exceptions.  With that in mind, what are my options here?  Am I obligated to release under the GPL, even if I don't distribute PyQt itself?

To be more specific, in which (if any) of the following scenarios am I permitted to release my code under the BSD license vs. being obligated to release under the GPL?

Scenario 1: I give you a fully-packaged binary that includes hello_world.py and PyQt.

Scenario 2: I give you the source code of hello_world.py and PyQt in a single download (say, a .tar.gz), but it's up to you to get them running together.

Scenario 3: I give you hello_world.py alone, leaving you to obtain PyQt on your own.

I know that most of us aren't lawyers, so it is very much appreciated if you can cite the sources your answer is based on.

答:
Once GPL, Always GPL.

You can't distribute under the BSD if one of the libraries on which your application depends is licensed under GPL, nor can you close your source code.

Dual licensing using GPL and a commercial license is a common arrangement among vendors.  It basically states that, if you want to use their library for a "true" open-source application (where you provide the entirety of the application's source code to the end-user, and let them do with it what they wish with it, so long as they also abide by the GPL) then you are welcome to use their library for that purpose.  Otherwise, you can gain the right to close your source by buying a commercial copy of their license.

So the short answer is, so long as you are providing the source code to your application, all three scenarios should be OK. Your distribution license would be GPL, not BSD.

My citation is the GPL license.

ContentLicense: CC BY-SA 3.0


问:
Gathering IP address and workstation information; does it belong in a state class?
I'm writing an enterprisey utility that collects exception information and writes to the Windows Event Log, sends an email, etc. This utility class will be used by all applications in the corporation: web, BizTalk, Windows Services, etc.

Currently this class:

holds state given to it via public properties

calls out to .NET Framework methods to gather information about runtime details. Included are call to various properties and methods from System.Environment, Reflection details, etc.

This implementation has the benefit of allowing all those callers not to have to make these same calls themselves. This means less code for the caller to forget, screw up, etc.

Should this state class (please what's the phrase I'm looking for [like DTO]?) know how to resolve/determine runtime details (like the IP address and machine name that it's running on)?

It seems to me on second thought that it's meant to be a class that should hold state, and not know how to call out to the .NET Framework to find information.

```<code>var myEx = new AppProblem{MachineName="Riker"};

//Will get "Riker 10.0.0.1" from property MachineLongDesc
Console.WriteLine("full machine details: " + myEx.MachineLongDesc);

public class AppProblem
{
    public string MachineName{get;set;}
    public string MachineLongDesc{
        get{
            if(string.IsNullOrEmpty(this.MachineName)
            {
                this.MachineName = Environment.MachineName;
            }
            return this.MachineName + " " + GetCurrentIP();
        }
    }

    private string GetCurrentIP()
    {
        return System.Net.Dns.GetHostEntry(this.MachineName)
                     .AddressList.First().ToString();
    }
}
</code>```

This code was written by hand from memory, and presented for simplicity, trying to illustrate the concept.

答:
It seems to me on 2nd through that it's meant to be a class that should hold state, and not know how to call out to the .NET Framework to find info.

Spot on. What you have is just a data container. It doesn't need any methods; there's no implementation details to hide. There's a ton of things you could choose to do with that data, and multiple ways of doing each of those things; if you use methods instead of static functions the class will bloat as you add every new little use case you find.

For bonus points, make it immutable and give it value semantics.


问:
Branch per feature: What are the actual benefits (and risks)?
I've read quite a lot of posts lately about different branching strategies (e.g a lot of links from To branch or not to branch?), and while almost every article explains on how to do this or that strategy they rarely explain the why.

Currently our team is investigating whether or not to switch to "feature branches". We're currently using a "everyone commits to trunk" model and we have release branches, which we use to do hotfixes to previous releases. All in all, this model has worked very well in the past. So actually I'd say - if it ain't broken, don't fix it.

However, there might be a point that I'm missing, so I'd like to ask: What are actual tangible benefits of using a feature branch strategy over "everyone commits to trunk"? What are the drawbacks of feature branches in your experience?

答:
The main advantages are you might have too large a team size, or want to work too many hours in the day, to keep busy by only delivering the required functionality.

This problem is solved by adding long-lived feature branches. This multiplies the effective size of your code base by the number of such branches, creating adequate work for everyone on the team. And unlike simply adding more features, this avoids complicating the software, or losing opportunities for future revenue. Everyone is busy visibly typing (or at least clicking) all the time, so noone looks bad to management.

Another advantage is it avoids having to learn how to properly use a modern distributed version control system such as git to adapt to different circumstances such as an unplanned context switch, the need to patch an old release, or back out a bad change. Instead, one technique fits all contingencies, and everything can be pushed centrally just as if you were using a faster Visual SourceSafe.


问:
How do I go about writing a programming language specification?
I really enjoy programming language design. Sometimes I think my language projects and their potential users would benefit from a comprehensive standards document. I've looked at many language standards, ranging from the very formal (C++) to the rather informal (ECMAScript), but I can't really get a handle on how I should break things down and organise such a document, even though I think I'm pretty good at technical writing in general.

Should I write it like a long tutorial, or more like a formal math paper? How do I keep it up to date if I'm developing it alongside a reference implementation? Should I just give up and treat the implementation and documentation as the de facto standard? Further, is there really any significant benefit to having a standard? Does requiring a standard mean that the language is needlessly complex?

答:
Read lots and keep it simple

Designing a new language is hard. Really hard. But ultimately very satisfying if it becomes popular and really solves a problem that people are experiencing in an elegant manner.

As I mentioned in the comments, I'd advise you to read Domain Specific Languages by Martin Fowler for the following reasons:

He goes into a lot of practical depth about why you should design a language

There are details on how to do it (parsers, lexical analysers, language workbenches etc)

There are detailed implementation instructions about how your chosen syntax can be made to handle concepts like closures, annotations, literal lists, dynamic reception etc

As for how to go about writing your specification, think about your audience. Obviously, before putting finger to keyboard to design your language you will have thought carefully about what it is intended to do.

If it's a new, interpreted language to replace JavaScript then you'll be wanting a very laissez faire approach in order to reach web developers with a limited attention span and a desire for immediate results - or quicker if possible.

If it's going to be used on the next mission to Titan, then extremely detailed specifications showing exact formal proofs of the behaviour of each component will be the minimal entry level.

So, it's not a straightforward thing. To approach the specification, you would probably be better off gaining a lot of experience in creating your languages and also working with those who actually use them on a day to day basis. If you have willing victims... er... developers, at work who can take some time to learn your language then they can give you feedback on what is needed to get them to use it.

In short, keep it simple and more people will use it.


问:
What is State, Mutable State and Immutable State?
This is a newbie question, but I couldn't find a newbie-proof enough answer on Google.

What do people mean when they say 'state' - in programming in general, and in OO programming specifically?

Also, what is mutable and immutable state - again, generally in programming and also specifically in OOP?

答:
State is simply information about something held in memory.

As a simple exercise in object orientation, think of a class as a cookie cutter, and cookies as objects.  You can create a cookie (instantiate an object) using the cookie cutter (class).  Let's say one of the properties of the cookie is its color (which can be changed by using food coloring).  The color of that cookie is part of its state, as are the other properties.

Mutable state is state that can be changed after you make the object (cookie).  Immutable state is state that cannot be changed.

Immutable objects (for which none of the state can be changed) become important when you are dealing with concurrency, the ability for more than one processor in your computer to operate on that object at the same time.  Immutability guarantees that you can rely on the state to be stable and valid for the object's lifetime.

In general, the state of an object is held in "private or member variables," and accessed through "properties" or getter/setter methods.


问:
Best practice for storing information from a php script for future use
My employer uses forms to help people search for products. The product lists can change from time to time and the forms need to be updated again.

The product information can be accessed through a third party API which I started tinkering with, I've recently built a script that retrieves the information with PHP and creates and populates a form dynamically with Javascript.

So far so good, but...

There are limitations to the API, mainly it can only be accessed a certain number of times per hour, it is probably more than my form/script would use but I want to create a script that is minimally intrusive.

My main question is...

What is the best practice for accessing the information once and storing it long enough to let the API reset? I was wondering about creating a cookie but there is the possibility of users that have them disabled.

(Also, I am doing this as a personal project but I like the people I work for and I think this would help them out.)

Thanks in advance.

答:
Usually you can store/cache the API results on your server and perform the query your own cache before API. If you couldn't find anything on the cache, or if the result from cache already was expired or too old, then use the API to get the results and store/update the cache again.

It could be as simple as a table with with query, result, datetime columns or quite complicated if the API is based on HTTP POST requests or if users do have a Custom Queries that could return Customized Results.

For the later case you can implement a cache per request mechanism. It won't be as efficient and easy to implement as the first solution, so don't opt for it unless you are certain that's what you need.

A simple 1:1 cache could be something like an intermediate layer in which you can totally capture the requested API URI and then use it as the key, then store and link the results back to this key. The key could be as simple as a file name and the results could be a JSON file containing results' data.

Later on before sending any request to the API, you should check out your cache directory first to see if you already have such a query/results in the cache or not. It will be useful just if users request a same thing more than once, otherwise, if the requests are mostly unique, don't bother yourself to implement the cache.


问:
Again MVVM / MVP story , passing interface of a view to its view model why it is bad?
I have used WPF for an Enterprise solution (hundreds views heavily used Data inputs and validation) in MVP pattern (it was a clean solution usually small amount of code behind forms and main code was in pretension layer which we called it user interface process or UIP layer  )

For the next small projects I used WPF with MVVM. generally some ideas of MVVM looks nice like commands and bindings especially the concept of ViewModel (having a special version of Model dedicated for View)

But I did not like so much the  concept of Messaging and event aggregator I usually try to minimize usage of this patterns (for example between ViewModels I  use ordinary  Object oriented function call or from a View to ViewModel (I have  ViewModel in my View so I use them to call ViewModel from View) but for a call from a  view model to view I use messaging. though sometimes in place of sending  messages (from ViewModel to View) I send  an Interface of view to its ViewModel and use that interface to call a function in a view.
Any body can tell me is this practice an anti pattern and  why it is bad?

答:
Seems fine to me. ViewModel defines an interface it requires View to implement. But you should only use this when you can't use data binding properly. Eg. you want view to do some action that is not tied to data the view presents.

Why I think this is fine is: The major point of MVVM (or MVP for that matter) is to remove direct dependency between View and ViewModel in either direction. In MVVM, this is mostly achieved by heavy use of reflection in data binding. But sometimes that is not enough, because you cannot easily invoke some action on View from ViewModel. To do that, you create abstraction that represents this action so ViewModel can call this abstracion and View realizes this abstraction. This way, there is still no direct dependence between View and ViewModel, but you can overcome the limitation of data binding.


问:
When should I *not* use Unicode?
Unicode seems that its becoming more and more ubiquitous these days if it's not already, but I have to wonder if there are any domains were Unicode isn't the best implementation choice. Are there any languages or scripts that Unicode will not work well or won't work at all? Are there any technical reasons to use a different system entirely (other than working with legacy systems)? Naturally, I would assume that the answer is to always use Unicode. Am I wrong?</p>

答:
ASCII generally uses less memory than Unicode, and doesn't require special encodings.  I would imagine that, if you're building a small embedded system for an English user, where the amount of memory is constrained, then Unicode might actually be an impediment.

Unicode is intended for larger systems where you might want to make it possible later to modify the software for other human languages and character sets.

Title: When should I *not* use Unicode?


答:
The only time I would avoid Unicode is in an embedded system where the requirements specifically state the system only needs to support a single code page (or ASCII).

Software is almost too easy to reuse. Whether a public project that will be used in ways the author is aware or did not envision, or corporate projects that some suit repurposes, you never know when and where software will be reused. With our global Internet people of all languages may have a use for your software, and it should support languages such as Chinese which are in widespread use and require Unicode to function well.

Embedded systems (a category in which I do NOT include smartphones) are the only domain I can think of that would resist the trend of software being used in diverse locations.

Edit: I just realized I did not really specify why I would avoid Unicode in those situations, even though the answer is fairly obvious. While some combinations of characters and encodings can take up the same space as an 8-bit character (e.g. UTF-8 English), not all will. This can increase space, especially when using characters that necessarily must use multiple bytes (e.g. Chinese, spoken by billions of people). Furthermore, decoding Unicode and transforming it to a glyph on a user interface requires additional code for which an embedded system may not have memory. If I had to develop a routine to transform ASCII characters into glyphs it would likely be a fairly small lookup table, and not involve decoding a variable-length character into a code plane with thousands of glyphs.

Title: When should I *not* use Unicode?

Body: Unicode seems that its becoming more and more ubiquitous these days if it's not already, but I have to wonder if there are any domains were Unicode isn't the best implementation choice. Are there any languages or scripts that Unicode will not work well or won't work at all? Are there any technical reasons to use a different system entirely (other than working with legacy systems)? Naturally, I would assume that the answer is to always use Unicode. Am I wrong?</p>


答:
You have state when you associate values (numbers, strings, complex data structures) to an identity and a point in time.

For example, the number 10 by itself does not represent any state: it is just a well-defined number and will always be itself: the natural number 10. As another example, the string "HELLO" is a sequence of five characters, and it is completely described by the characters it contains and the sequence in which they appear. In five million years from now, the string "HELLO" will still be the string "HELLO": a pure value.

In order to have state you have to consider a world in which these pure values are associated to some kind of entities that possess an identity.
Identity is a primitive idea: it means you can distinguish two things regardless of any other properties they may have. For example, two cars of the same model, same colour, ... are two different cars.

Given these things with identity, you can attach properties to them, described by pure values. E.g., my car has the property of being blue. You can describe this fact by associating the pair

```<code>("colour", "blue")
</code>```

to my car.
The pair ("colour", "blue") is a pure value describing the state of that particular car.

State is not only associated to a particular entity, but also to a particular point in time. So, you can say that today, my car has state

```<code>("colour", "blue")
</code>```

Tomorrow I will have it repainted in black and the new state will be

```<code>("colour", "black")
</code>```

Note that the state of an entity can change, but its identity does not change by definition. Well, as long as the entity exists, of course: a car may be created and destroyed, but it will keep its identity throughout its lifetime. It does not make sense to speak about the identity of something that does not exist yet / any more.

If the values of the properties attached to a given entity change over time, you say that the state of that entity is mutable. Otherwise, you say that the state is immutable.

The most common implementation is to store the state of an entity in some kind of variables (global variables, object member variables), i.e. to store the current snapshot of a state. Mutable state is then implemented using assignment: each assignment operation replaces the previous snapshot with a new one. This solution normally uses memory locations to store the current snapshot. Overwriting a memory location is a destructive operation that replaces a snapshot with a new one. (Here you can find an interesting talk about this place-oriented programming approach.)

An alternative is to view the subsequent states (history) of an entity as a stream (possibly infinite sequence) of values, see e.g. Chapter 3 of SICP.
In this case, each snapshot is stored at a different memory location, and the program can examine different snapshots at the same time. Unused snapshots can be garbage-collected when they are no longer needed.

Advantages / disadvantages of the two approaches

Approach 1 consumes less memory and allows to construct a new snapshot more efficiently since it involves no copying.

Approach 1 implicitly pushes the new state to all the parts of a program holding a reference to it, approach 2 would need some mechanism to push a snapshot to its observers, e.g. in the form of an event.

Approach 2 can help to prevent inconsistent state errors (e.g. partial state updates): by defining an explicit function that produces a new state from an old one it is easier to distinguish between snapshots produced at different points in time.

Approach 2 is more modular in that it allows to easily produce views on the state that are independent of the state itself, e.g. using higher-order functions such as map and filter.

Title: What is State, Mutable State and Immutable State?

Body:
This is a newbie question, but I couldn't find a newbie-proof enough answer on Google.

What do people mean when they say 'state' - in programming in general, and in OO programming specifically?

Also, what is mutable and immutable state - again, generally in programming and also specifically in OOP?

Body:
You have state when you associate values (numbers, strings, complex data structures) to an identity and a point in time.

For example, the number 10 by itself does not represent any state: it is just a well-defined number and will always be itself: the natural number 10. As another example, the string "HELLO" is a sequence of five characters, and it is completely described by the characters it contains and the sequence in which they appear. In five million years from now, the string "HELLO" will still be the string "HELLO": a pure value.

In order to have state you have to consider a world in which these pure values are associated to some kind of entities that possess an identity.
Identity is a primitive idea: it means you can distinguish two things regardless of any other properties they may have. For example, two cars of the same model, same colour, ... are two different cars.

Given these things with identity, you can attach properties to them, described by pure values. E.g., my car has the property of being blue. You can describe this fact by associating the pair

("colour", "blue")

to my car.
The pair ("colour", "blue") is a pure value describing the state of that particular car.

State is not only associated to a particular entity, but also to a particular point in time. So, you can say that today, my car has state

("colour", "blue")

Tomorrow I will have it repainted in black and the new state will be

("colour", "black")

Note that the state of an entity can change, but its identity does not change by definition. Well, as long as the entity exists, of course: a car may be created and destroyed, but it will keep its identity throughout its lifetime. It does not make sense to speak about the identity of something that does not exist yet / any more.

If the values of the properties attached to a given entity change over time, you say that the state of that entity is mutable. Otherwise, you say that the state is immutable.

The most common implementation is to store the state of an entity in some kind of variables (global variables, object member variables), i.e. to store the current snapshot of a state. Mutable state is then implemented using assignment: each assignment operation replaces the previous snapshot with a new one. This solution normally uses memory locations to store the current snapshot. Overwriting a memory location is a destructive operation that replaces a snapshot with a new one. (Here you can find an interesting talk about this place-oriented programming approach.)

An alternative is to view the subsequent states (history) of an entity as a stream (possibly infinite sequence) of values, see e.g. Chapter 3 of SICP.
In this case, each snapshot is stored at a different memory location, and the program can examine different snapshots at the same time. Unused snapshots can be garbage-collected when they are no longer needed.

Advantages / disadvantages of the two approaches

Approach 1 consumes less memory and allows to construct a new snapshot more efficiently since it involves no copying.

Approach 1 implicitly pushes the new state to all the parts of a program holding a reference to it, approach 2 would need some mechanism to push a snapshot to its observers, e.g. in the form of an event.

Approach 2 can help to prevent inconsistent state errors (e.g. partial state updates): by defining an explicit function that produces a new state from an old one it is easier to distinguish between snapshots produced at different points in time.

Approach 2 is more modular in that it allows to easily produce views on the state that are independent of the state itself, e.g. using higher-order functions such as map and filter.


问:
What is the recommended approach for helper functions in JavaScript?
What is the recommended approach for helper functions? I would like to choose one technique, and run with it to create my new "class".

Here are the design options I have pondered:

Option 1: Helper function in outer scope, invoke with context of instance

```<code>function createPane (pane) {
    // logic to create pane
    var proto = Object.create(this.paneList);
    $.extend(paneProto, pane);
    return paneProto;
}

Panes.prototype.initialize = function (panes) {
    var _this = this;
    _.each(panes, function () {
        _this.panes.push(createPane.call(_this, this));
    });
}
</code>```

Pros: Simple syntax. createPane is not published on the instance.

Cons: createPane is accessible in other scopes.

Option 2: Helper function in closure, invoke with context of instance

```<code>Panes.prototype.initialize = (function () {

    function createPane (pane) {
        // same logic as last createPane
    }

    return function (panes) {
        // same logic as before - calls createPane
    }

})();
</code>```

Pros: createPane is not published on the instance.

Cons: Lower readability and testability; Testing of this helper must occur in the scope of initialize.

Option 3: Prepend _ to name to indicate a private method

```<code>Panes.prototype._createPane = function (pane) {
    // same logic as last createPane
}

Panes.prototype.initialize = function (panes) {
    // same logic as last, except calls this._createPane
}
</code>```

Pros: Implicit context of _createPane is the instance. Testability from the outside.

Cons: Exposing helper function on the instance.

Option 4: Helper functions as arguments

```<code>Panes.prototype.initialize = (function (createPane) {

    return function (panes) {
        // same logic as before - calls createPane
    }

})(function createPane () {
   // same logic as last createPane
});
</code>```

Pros: createPane is not published on the instance. Helper functions lack access to each other.

Cons: Lower readability and testability; Testing of this helper must occur in the scope of initialize.

答:
First JavaScript doesn't have Classes.

Second, your third option seems more rational to me, but it highly depends to your requirements as well. Also you should not be much worried about exposing the helper function. The pros of the solution totally justifies the compromise to me.

Third, your time as a developer is valuable; Don't make trivial tasks hard to implement, time consuming and more pron to human-errors. Simplicity of source code is a great feature itself.


问:
Why is 0 false?
This question may sound dumb, but why does 0 evaluates to false and any other [integer] value to true is most of programming languages?

String comparison

Since the question seems a little bit too simple, I will explain myself a little bit more: first of all, it may seem evident to any programmer, but why wouldn't there be a programming language - there may actually be, but not any I used - where 0 evaluates to true and all the other [integer] values to false? That one remark may seem random, but I have a few examples where it may have been a good idea. First of all, let's take the example of strings three-way comparison, I will take C's strcmp as example: any programmer trying C as his first language may be tempted to write the following code:

if (strcmp(str1, str2)) { // Do something... }
```

<p>Since <code>strcmp</code> returns <code>0</code> which evaluates to <code>false</code> when the strings are equal, what the beginning programmer tried to do fails miserably and he generally does not understand why at first. Had <code>0</code> evaluated to <code>true</code> instead, this function could have been used in its most simple expression - the one above - when comparing for equality, and the proper checks for <code>-1</code> and <code>1</code> would have been done only when needed. We would have considered the return type as <code>bool</code> (in our minds I mean) most of the time.</p>

<p>Moreover, let's introduce a new type, <code>sign</code>, that just takes values <code>-1</code>, <code>0</code> and <code>1</code>. That can be pretty handy. Imagine there is a spaceship operator in C++ and we want it for <code>std::string</code> (well, there already is the <code>compare</code> function, but spaceship operator is more fun). The declaration would currently be the following one:</p>

<pre class="lang-cpp prettyprint-override"><code>sign operator<=>(const std::string& lhs, const std::string& rhs);
</code>```

Had 0 been evaluated to true, the spaceship operator wouldn't even exist, and we could have declared operator== that way:

sign operator==(const std::string& lhs, const std::string& rhs);
```

<p>This <code>operator==</code> would have handled three-way comparison at once, and could still be used to perform the following check while still being able to check which string is lexicographically superior to the other when needed:</p>

<pre class="lang-cpp prettyprint-override"><code>if (str1 == str2) { // Do something... }
</code>```

Old errors handling

We now have exceptions, so this part only applies to the old languages where no such thing exist (C for example). If we look at C's standard library (and POSIX one too), we can see for sure that maaaaany functions return 0 when successful and any integer otherwise. I have sadly seen some people do this kind of things:

#define TRUE 0
// ...
if (some_function() == TRUE)
{
    // Here, TRUE would mean success...
    // Do something
}
```

<p>If we think about how we think in programming, we often have the following reasoning pattern:</p>

<pre class="lang-none prettyprint-override"><code>Do something
Did it work?
Yes ->
    That's ok, one case to handle
No ->
    Why? Many cases to handle
</code>```

If we think about it again, it would have made sense to put the only neutral value, 0, to yes (and that's how C's functions work), while all the other values can be there to solve the many cases of the no. However, in all the programming languages I know (except maybe some experimental esotheric languages), that yes evaluates to false in an if condition, while all the no cases evaluate to true. There are many situations when "it works" represents one case while "it does not work" represents many probable causes. If we think about it that way, having 0 evaluate to true and the rest to false would have made much more sense.

Conclusion

My conclusion is essentially my original question: why did we design languages where 0 is false and the other values are true, taking in account my few examples above and maybe some more I did not think of?

Follow-up: It's nice to see there are many answers with many ideas and as many possible reasons for it to be like that. I love how passionate you seem to be about it. I originaly asked this question out of boredom, but since you seem so passionate, I decided to go a little further and ask about the rationale behind the Boolean choice for 0 and 1 on Math.SE :)

答:
You should consider that alternative systems can also be acceptable design decisions.

Shells: 0 exit status is true, non-zero is false

The example of shells treating a 0 exit status as true has already been mentioned.

$ ( exit 0 ) && echo "0 is true" || echo "0 is false"
0 is true
$ ( exit 1 ) && echo "1 is true" || echo "1 is false"
1 is false
```

<p>The rationale there is that there is one way to succeed, but many ways to fail, so using 0 as the special value meaning "no errors" is pragmatic.</p>

<h3>Ruby: 0 is just like any other number</h3>

<p>Among "normal" programming languages, there are some outliers, such as Ruby, that treat 0 as a true value.</p>

```$ irb
irb(main):001:0> 0 ? '0 is true' : '0 is false'
=> "0 is true"
```

<p>The rationale is that only <code>false</code> and <code>nil</code> should be false.  For many Ruby novices, it's a gotcha.  However, in some cases, it's nice that 0 is treated just like any other number.</p>

```irb(main):002:0> (pos = 'axe' =~ /x/) ? "Found x at position #{pos}" : "x not found"
=> "Found x at position 1"
irb(main):003:0> (pos = 'xyz' =~ /x/) ? "Found x at position #{pos}" : "x not found"
=> "Found x at position 0"
irb(main):004:0> (pos = 'abc' =~ /x/) ? "Found x at position #{pos}" : "x not found"
=> "x not found"
```

However, such a system only works in a language that is able to distinguish booleans as a separate type from numbers.  In the earlier days of computing, programmers working with assembly language or raw machine language had no such luxuries.  It is probably just natural to treat 0 as the "blank" state, and set a bit to 1 as a flag when the code detected that something happened.  By extension, the convention developed that zero was treated as false, and non-zero values came to be treated as true.  However, it doesn't have to be that way.

Java: Numbers cannot be treated as booleans at all

In Java, true and false are the only boolean values.  Numbers are not booleans, and cannot even be cast into booleans (Java Language Specification, Sec 4.2.2):

There are no casts between integral types and the type boolean.

That rule just avoids the question altogether — all boolean expressions have to be explicitly written in the code.

Title: Why is 0 false?

Body:
You should consider that alternative systems can also be acceptable design decisions.

Shells: 0 exit status is true, non-zero is false

The example of shells treating a 0 exit status as true has already been mentioned.

$ ( exit 0 ) && echo "0 is true" || echo "0 is false"
0 is true
$ ( exit 1 ) && echo "1 is true" || echo "1 is false"
1 is false

The rationale there is that there is one way to succeed, but many ways to fail, so using 0 as the special value meaning "no errors" is pragmatic.

Ruby: 0 is just like any other number

Among "normal" programming languages, there are some outliers, such as Ruby, that treat 0 as a true value.

$ irb
irb(main):001:0> 0 ? '0 is true' : '0 is false'
=> "0 is true"

The rationale is that only false and nil should be false.  For many Ruby novices, it's a gotcha.  However, in some cases, it's nice that 0 is treated just like any other number.

irb(main):002:0> (pos = 'axe' =~ /x/) ? "Found x at position #{pos}" : "x not found"
=> "Found x at position 1"
irb(main):003:0> (pos = 'xyz' =~ /x/) ? "Found x at position #{pos}" : "x not found"
=> "Found x at position 0"
irb(main):004:0> (pos = 'abc' =~ /x/) ? "Found x at position #{pos}" : "x not found"
=> "x not found"

However, such a system only works in a language that is able to distinguish booleans as a separate type from numbers.  In the earlier days of computing, programmers working with assembly language or raw machine language had no such luxuries.  It is probably just natural to treat 0 as the "blank" state, and set a bit to 1 as a flag when the code detected that something happened.  By extension, the convention developed that zero was treated as false, and non-zero values came to be treated as true.  However, it doesn't have to be that way.

Java: Numbers cannot be treated as booleans at all

In Java, true and false are the only boolean values.  Numbers are not booleans, and cannot even be cast into booleans (Java Language Specification, Sec 4.2.2):

There are no casts between integral types and the type boolean.

That rule just avoids the question altogether — all boolean expressions have to be explicitly written in the code.


问:
Unit testing - External vs Internal dependencies
Unit tests should be isolated, automated ( ie we don't need to do any prior-configuration for all tests to run at the click of a button ) and consistent in their results. For these reasons we should stub any external dependencies ( ie databases, webservices etc ) used by unit under test UUT ( with integration tests UUTs do use external dependencies ).

But based on what criteria do we decide which internal dependencies called by UUT ( by internal dependencies I'm referring to code which is under our control and that doesn't communicate with any external systems ) also need to be stubbed and which don't need to be?

Is perhaps the criteria that methods defined in the same class as UUT don't need to be stubbed, while methods defined in other classes should be, or ...?

答:
The criteria of "Is it currently being tested by this specific unit test?" </p>

<p>If it's not being tested, yeah, stub it, mock it, fake it, set it to a hard known value, whatever. That way you know it's impact on the thing that's actually under test.
Even though it's internal to your project and you control the source, it's external to the current thing you're testing. </p>

Body:
The criteria of "Is it currently being tested by this specific unit test?"

If it's not being tested, yeah, stub it, mock it, fake it, set it to a hard known value, whatever. That way you know it's impact on the thing that's actually under test.
Even though it's internal to your project and you control the source, it's external to the current thing you're testing.


问:
Automating form error handling
I'm not sure if I'm being clever or making things more difficult. I'm working within a custom MVC framework, and within some of my "views" which contain forms I'm preserving input and styling errors as follows:

```<code><form action="submit" method="POST">
<label for="name" class="italic">Name:</label>
<input <?php if (in_array('name', $error)) { echo 'class="form-error"'; } ?> type="text" name="name" value="<?php if (isset($name)) { echo $name; } elseif (isset($valid_user)) { echo $valid_user['name']; } ?>" maxlength="20" required="required" />
<br /><input type="submit" class="submit" value="Update" />
</code>```

In this example, $valid_user['name'] would be the default value for existing data (when the form is first loaded), and $name would be the posted value being displayed here again in case there was a user error that needs to be fixed.

Embedding all of these values is very time consuming when creating new forms, so I'm trying to make things easier on myself. I want to stick with a server-side solution since I believe websites should be complimented by Javascript, not dependent on it. I figure I could probably do all of this dynamically using PHP's DOMDocument:

```<code>$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->loadHTMLFile($view);
$forms = $dom->getElementsByTagName('form');
$total_forms = $forms->length;

for ($i = 0; $i < $total_forms; $i++) {
    $inputs = $forms->item($i)->getElementsByTagName('input');
    $total_inputs = $inputs->length;

    if ($total_inputs > 0) {
        foreach ($inputs as $input) {
            $type = $input->getAttribute('type');
            switch ($type) {
                case 'text':
                    // check for errors
                    $attr_name = $input->getAttribute('name');
                    if (in_array($attr_name, $error)) {
                        $input->setAttribute('class', 'form-error');
                    }

                    // check for default / posted values
                    if (isset($$attr_name)) {
                        $input->setAttribute('value', $$attr_name);
                    } elseif (isset($_POST[$attr_name])) {
                        $input->setAttribute('value', $_POST[$attr_name]);
                    }
                    break;
            }
        }
    }
}

echo $header;
// remove unwanted tags that are being automatically added
echo preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
echo $footer;
</code>```

Going with this approach will obviously require writing a lot of extra code, so before going any further I'm just curious what your opinions are or if there are any potential downfalls I'm maybe not thinking of? Would it be better to stick with my original approach or are there other solutions to make this less tedious?

答:
The first thing I can suggest you is to take out the Logic from Mark-up or basically avoid to write in-line logic in your mark-up. So you can re-write your first example like this:

```<code>if ( in_array('name', $error) ) {
    $class = 'form-error';
} else {
    $class = null;
}
// or ...
$class = in_array( 'name', $error ) ? 'form-error' : null;

if ( isset($name) ) {
    $value = $name;
} else if ( isset($valid_user) ) {
    $value = $valid_user['name'];
}
</code>```

And then you can simply re-write the mark-up like this, which is much simpler:

```<code><input class="<?php echo $class; ?>" value="<?php echo $value; ?>" ...
</code>```

If you want to go for the second way I suggest you to use Jade instead of PHP's DOM class.

Also to me either ways seems fine, however the later one could be an overkill.

Title: Automating form error handling

Body:
The first thing I can suggest you is to take out the Logic from Mark-up or basically avoid to write in-line logic in your mark-up. So you can re-write your first example like this:

if ( in_array('name', $error) ) {
    $class = 'form-error';
} else {
    $class = null;
}
// or ...
$class = in_array( 'name', $error ) ? 'form-error' : null;

if ( isset($name) ) {
    $value = $name;
} else if ( isset($valid_user) ) {
    $value = $valid_user['name'];
}

And then you can simply re-write the mark-up like this, which is much simpler:

<input class="<?php echo $class; ?>" value="<?php echo $value; ?>" ...

If you want to go for the second way I suggest you to use Jade instead of PHP's DOM class.

Also to me either ways seems fine, however the later one could be an overkill.


问:
Search for the (slowly moving) number with penalty for too high test value
You task is to design a search algorithm that will find my secret number, which is between 0 and 2^64. If your test value is too low you can test again in 1 second. If your test value is too high you are not allowed to test again the next 300 seconds.

Every second I will add 1 to or subtract 1 from the number. I will not tell you what I have done, and while it may be random it also might not be random.

How can you find the approximate number fast?

The obvious answer is to use a binary search, but since the penalty is high for guessing too high, I would think it needs some adjustment.

Background

I need to find the speed of a system. The speed changes slowly. It takes 1 second to do a guess. If my guess is too low: no problem. If it is too high, then system reboots, causing a 5 minute delay.

My goal is to get a decent estimate of the speed relatively fast.

答:
I am not a statistician, but it seems to me that guessing 1/300 of the overall range would get you the answer most quickly, a weighted binary search.

So, the first guess is (1/300) * 2^64

The second guess is either

on success (1/300) * (1/300) * 2^64 or

on failure (1/300) + (1/300) * (2^64 - (1/300))

etc.


问:
How to design a domain entity that uses a dependency to manage a state field?
I'm new to DDD and IOC/DI and I'm having some trouble figuring out how to design an entity that needs to use a state pattern to manage its status. As the transitions are somewhat complicated, I'm using a finite state machine (FSM) to handle the states (I'm using Stateless).

To further complicate the situation, the FSM needs to be loosely coupled to an entity. I.e. while I know that the state of the entity must be handled by a FSM, I don't necessarily know exactly what the FSM is (i.e. the entity doesn't know what states/triggers/transitions it might go through). The users use the term workflow to define the FSM (state, triggers, transitions, rules etc).  The workflow changes independently of the entity. They might want to add new states, change rules, triggers etc. independent of any changes to the entity.

I'm handling this by dynamically loading an assembly that contains a definition of the FSM (which implements a known interface), then using a service that is injected into the entity, the entity calls the service and gets the FSM it is using. This involves potentially loading assemblies, caching the factory that creates the FSM and then assigning the FSM that is in the appropriate state to the entity. Finally, the FSM can return the set of valid triggers that can be provided to the UI so one of the those triggers can be selected and fired.  The actual workflow in completely encapsulated externally to the entity.

So, currently I'm my entity looks something like this:

```<code>public class EntityUsingWorkflow
{
  private readonly workflowService;

  public Order(IWorkflowService service, string workflowKey, string status)
  {
    this.workflowService = service;
    this.WorkflowKey = workflowKey;
    this.Status = status;

    // Note that the two lambdas are used to retrieve
    // and set the state on the entity.
    this.Workflow = service.GetStateMachine(workflowKey, () => this.Status, stateValue => this.Status = statValue );
  }

  public string WorkflowKey { get; set; }
  public IStateMachine Workflow { get; private set; }
  public string Status { get; private set; }

}
</code>```

I'm concerned with this design. My basic understanding is that domain entities should not have dependencies injected into them, yet here I am injecting one. I also understand that the entity needs to handle its own state, so I'm hesitant to move the workflow completely out of the entity. Other ideas I've had, like an init method, would just move the injection to method injection.

What would be a clean way to design an entity with these requirements? Is it OK to inject a dependency in this situation?

答:
It's perfectly fine - indeed, it's a good idea - to use dependency injection in your domain model.

You should to develop your domain model independently of any particular technology or library. The particulars of such-and-such database or so-and-so library are not the concern of your domain model: if you need to swap databases your business rules will remain the same. So we apply the dependency inversion principle and depend on interfaces which address the concerns of the domain model and adapters which adapt a given technological concern to the domain. (Importantly, the interface is phrased in terms of domain-level operations and lives in the same package as your domain classes.)

A great example of this is the Repository pattern. The Repository adapts the database to an interface which suits the domain model. So you can write customerRepository.FindByEmailAddress(email) and not worry about the exact SQL statements that retrieve the customer for you. And by depending on an interface, your domain model has no idea whether it's a SQL database, a file, or MongoDB or Neo4j, or whatever.

So the Dependency Inversion Principle, and Dependency Injection, is of tremendous use in DDD. What I think is a less good idea is keeping your domain in an IOC container. The problem is that you end up storing domain-level information (like how to attach an order to a customer) away from your domain classes in a configuration file somewhere. IOC hides details that shouldn't really be hidden from your domain model. Also, the details of your particular container tend to leak into your domain classes.

Use IOC at the boundaries of your system, if you must, to wire up command handlers and other API services. Use Dependency Inversion and Dependency Injection in your domain model whenever it makes sense to do so, but keep IOC out of the picture.


答:
I did some empirical simulation of a simplified version of this system. It seems intuitive that one could use a binary search, modified with a weight factor to bias the "midpoint" selection toward lower numbers. Another answer proposed 300 (so choosing a midpoint that is 1/300 of the way from the left to the right), but I wanted to check this.

I wrote a simulation (code here) which runs 1000 trials for each weighting factor between 2 (standard binary search taking the midpoint at 1/2) and 499 (taking the midpoint at 1/499). The results can be seen in this spreadsheet, and the resulting graph looks something like this:

What this appears to show is that a standard binary search does perform badly, as expected. However, the optimal weight factor appears to be something around 70 (so choosing the midpoint for the binary search as 1/70 of the way from the left to the right bound). (I'm not sure why this is true, perhaps a question for https://math.stackexchange.com.)

I did not attempt to model the target "wandering" behaviour in your question. You may modify the simulation to add this feature.

Title: Search for the (slowly moving) number with penalty for too high test value

Body:
You task is to design a search algorithm that will find my secret number, which is between 0 and 2^64. If your test value is too low you can test again in 1 second. If your test value is too high you are not allowed to test again the next 300 seconds.

Every second I will add 1 to or subtract 1 from the number. I will not tell you what I have done, and while it may be random it also might not be random.

How can you find the approximate number fast?

The obvious answer is to use a binary search, but since the penalty is high for guessing too high, I would think it needs some adjustment.

Background

I need to find the speed of a system. The speed changes slowly. It takes 1 second to do a guess. If my guess is too low: no problem. If it is too high, then system reboots, causing a 5 minute delay.

My goal is to get a decent estimate of the speed relatively fast.


问:
What made BASIC profitable?
In the 1970s, a man called Bill Gates developed an interpreter for BASIC: the Altair BASIC. Per my understanding, he was able to persuade the guy in charge of a microcomputer company to include the interpreter program on every microcomputer he sold, which I assume brought Gates and his crew some royalties. Apparently this made Gates a fortune. What I don't understand is why programing languages aren't as profitable today. What factors in the past made them profitable, but not today ?</p>

答:
I don't think Bill Gates made a lot of money off of the Alttair (did anyone?). A bigger break was buying a DOS from someone else, fixing it up and selling licenses to IBM for their PC. IBM along with a lot of other makers of PC's had few choices of operating systems so they stuck with MS-DOS. This did include BASIC, which was a big benefit at the time because there was little software on the market. Users were more of the "hobbyist" type who were willing to write their own software.

How many people do you know today that own a computer, tablet, smartphone etc. that want to program them so much, they're willing to pay for the programming language? Not many. There are few devices where you can't get some type of IDE for free. Even Microsoft has several free versions of Visual Studio.

The more people who have access to development tools for your hardware and/or operating system, the more software that is going to get created on your stack. The more people who will buy it. It's sort of a give them the razor but sell them the blades.

Sorry, I'm running on personal memory here and didn't research any of the profitability claims. I know this isn't exact, but if I'm way off, please advise.

Title: What made BASIC profitable?


答:
He got there early.

Since then the internet has revolutionised the way we share and create sofware. No longer do you need to source a floppy disk with the specific software you need, it is all a mere download away.

The market is saturated and the development community has embraced open-source and free software, the competition is rife and we are late to the party.

Secondly now there is this much competition it is in a language creator's interests to release and distribute tools for working in that language for free. There are a ton of fantastic languages already, if you want adoption then you have to make it easy.

There is just no need for me to buy a compiler/interpreter when I could sooner switch to an open-source, community driven and in my personal opinion, safer option.

Title: What made BASIC profitable?

Body: In the 1970s, a man called Bill Gates developed an interpreter for BASIC: the Altair BASIC. Per my understanding, he was able to persuade the guy in charge of a microcomputer company to include the interpreter program on every microcomputer he sold, which I assume brought Gates and his crew some royalties. Apparently this made Gates a fortune. What I don't understand is why programing languages aren't as profitable today. What factors in the past made them profitable, but not today ?</p>


问:
How to approach multiple page form with just one save option
The screen shot shows the magento product upload page.

The left nav allows you to switch to different options for the product. Basically each option in the left nav appears as a different page. However when you save and close, it will save all the updates made on each page.

Using Foundation4, html, css, js - what would be the best approach to replicating something similar? Say I want 3 pages and one save button option.

Using http://foundation.zurb.com/docs/components/section.html#panel2 and having the save buttons the top line form level seems a possible option.

答:
I just had an idea I used once in an example project for a class. It's sort of a workaround, but with proper organisation it could even be called good code.

Basically, you would set up a JavaScript object at the start of your page containing all the settings. You would then build your tabs' content in separate pages. Each page will contain both the controls and text you need in each tab and a script that sets the object's respective attributes on change.

On the main page, bind AJAX calls to each tab that load the chosen tab's content and destroy the previously loaded content.

It's not tested software, just a possible solution that came to mind. I've done something similar regarding changing variables set by one page in a script that has been AJAX loaded. Just make sure the event listener for change is bound to all inputs after every AJAX request and it should work fine.

Upon submitting (saving), make the last AJAX call sending the mentioned object via POST. jQuery offers a wonderful shortcut for it.


答:
Short answer: the internet.

Longer answer: The internet provides a cheap, fast, international, searchable, well-known method of communication.  The internet technically existed in the 70's, it wasn't until the 90's that it became really well-known.

It is difficult for a bunch of people who want to get together and write a high quality, free compiler (or interpreter) to communicate via printed program listings or floppies sent by snail mail.  It's also more difficult for people who are interested in doing things like that to find each other using common communication techniques of the 70's: sure, you can post things like want ads in the paper, but if I put an ad in the paper in California somewhere, and you read your paper in Florida, you remain unaware of my existence.

Even with a bad search engine, typing "free compiler" or "programming language" is likely to get results that might lead people like that to find each other.  Searchability makes a huge difference -- I've found a number of interesting things online that I probably would never have even heard of without the internet, and I doubt I'm unusual in that way.

So when people started writing programming tools online, and distributing them for free to all comers, people started using them, and some of them also helped make them better.  Programming languages are also something that many programmers find interesting, so this effect would be stronger for programming languages than for some other kinds of software.

Basic economics: you can demand a higher price for something people want if it's harder to find.  After the internet took off, programming languages were easier to get from someone other than a company, and free is a pretty low price.

Title: What made BASIC profitable?


答:
The first significant difference is that when Gates wrote his version of BASIC, computer hardware was expected to ship with one or more development languages.  Today, people are expected to get languages separately.

The second significant difference is that today, the Open Source community develops robust, free compilers/interpreters for popular languages.  That community did not exist then.

Finally, there is a misconception in the question in that Gates wasn't the inventor of the BASIC language.  He was the author of a particular implementation of it.  It's not clear to me that the inventors of the language made a particularly large amount of money on it.  Also consider that today, Microsoft makes a lot of money on their implementation of C++.  (And again, the designer of that language didn't become particularly rich on it.)  So in that sense, the same sorts of people are making money on languages as in the seventies.

Title: What made BASIC profitable?


答:
Network protocols. They're almost always defined in 7-bit ASCII. I suppose that falls under "legacy systems."

If it makes you feel better, imagine that SMTP's HELO, EHLO, DATA commands are binary. They're all 4 characters long for a reason.

HTTP GET and the URL and all of the HTTP Headers are also in ASCII.

DNS is most definitely ASCII.

Almost all of the network protocols are implemented first in C and intended for very fast processing. The technical reasons to avoid Unicode here are that the communicating processes are really just exchanging raw binary data. The "words" in the protocol are just to make it readable for people with a network sniffer and so that people can do very basic testing using telnet or netcat.

In these situations Unicode conversion is almost always a waste of time.

Pretty much the only place I can think Unicode would be useful for something like web servers and proxies is case insensitive rewrite rules. Case sensitive rules wouldn't matter because UTF-8 matches just fine without decoding.

Personally, I don't believe in case insensitive processing in network servers or file systems. If the request fails to find a resource, bounce it to an error handler script and it can mess around trying to guess at what the user was really after. That keeps things fast and very simple in the common case.

I would ask "Would you define a new network protocol to use Unicode?" except I am afraid I know the answer. I see people writing nasty, nasty JSON and XML "protocols" all the time. And whoever decided to transfer binary data inside XML in Base64 encoding should probably be shot, drawn, quartered, drowned and then buried alive. "Oooh, gigabit networks! I'll just expand everything hugely and make it impossible to use zero-copy!" Bonus points for then compressing the XML for transfer. Bloat it out, pack it down so you can unpack it and unbloat it. While making three copies some of which are expanding the XML and Base64 data into 32-bit UCS-4 "wide characters". Probably in Java so you can use an extra gig of RAM just because.

Title: When should I *not* use Unicode?


答:
When PCs were first available, there were few programs available.  Without a programming language, the computer would be pretty well useless.  BASIC as implemented then was a simple small language which could be run in very little memory.

Microsoft got its start selling MS-DOS to IBM. The availability of programming language is reported to have made the deal.  The profit was in selling the operating system, not the programming language.

Legend has it that Bill Gates claimed that he had a Basic interpreter which the competing operating did not. He then wrote the Basic quickly after striking the deal and before demoing the operating system.  I don't know if this is true or not.

In those days there were few available languages, and fewer still suitable for the limited memory available on a PC.  Memory at that time was measured in Kilobytes, and it was believed a PC would never require a Megabyte.

These days we have a wide variety of languages, most of which are available as open source.  The capabilities we have on the simplest cell phones would have been consider wild fantasies in the early days of computing.

Title: What made BASIC profitable?


问:
Simple Design for Singleton function in java for Kernel
I understand that Singelton helps to instantiate only one class AT A TIME. I try to learn how to Design for Singleton function in java.  I want to know it better to understand Kernel. So I try to do this following, but I like to know if it's the only way to come up with private constructor.</p>

```<code>public class Singleton {
    private static Singleton instance = null;

    private Singleton() {   }

    public static synchronized Singleton getInstance() {
        if (instance == null) {
                    instance = new Singleton ();
        }
        return instance;
    }
}
</code>```

答:
If I understand your question correctly, then yes, to create a Singleton class, you have to use the private constructor as it is the only way to prevent another class from creating an instance of your class.

If your question is another way of getting around getInstance(), then it is also possible to use a private static inner class and either use that to store the reference as in this android related question.

```<code>public class Singleton {

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        return Implementation.INSTANCE;
    }

    private static class Implementation {
        public static final Singleton INSTANCE = new Singleton();
    }
}
</code>```

Body:
If I understand your question correctly, then yes, to create a Singleton class, you have to use the private constructor as it is the only way to prevent another class from creating an instance of your class.

If your question is another way of getting around getInstance(), then it is also possible to use a private static inner class and either use that to store the reference as in this android related question.

public class Singleton {

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        return Implementation.INSTANCE;
    }

    private static class Implementation {
        public static final Singleton INSTANCE = new Singleton();
    }
}


问:
Static classes and/or singletons -- How many does it take to become a code smell?
In my projects I use quite a lot of static classes. These are usually classes that naturally seem to fit into a single-instance type of thing. Many times I use static classes and recently I've started using some singletons.

How many of these does it take to become a code smell? For instance, in my recent project which has a lot of static classes is an Authentication library for ASP.Net.

I use a static class for a helper class that fixes ASP.Net error codes so it can be used like

```<code>CustomErrorsFixer.Fix(Context);
</code>```

Or my authentication class itself is a static class

```<code>//in global.asax's begin_application
Authentication.SomeState="blah";
Authentication.SomeOption=true;
//etc

//in global.asax's begin_request
Authentication.Authenticate();
</code>```

When are static or singleton classes bad to use? Am I doing it wrong, or am I just in a project that by definition has very little per-instance state associated with it?

The only per-instance state I have is stored in HttpContext.Current.Items like so:

```<code>    /// <summary>
    /// The current user logged in for the HTTP request. If there is not a user logged in, this will be null.
    /// </summary>
    public static UserData CurrentUser{
        get{
            return HttpContext.Current.Items["fscauth_currentuser"] as UserData; //use HttpContext.Current as a little place to persist static data for this request
        }
        private set{
            HttpContext.Current.Items["fscauth_currentuser"]=value;
        }
    }
</code>```

答:
The reason they are often a code smell is that a Singleton is to create a global. If you require a state to be global to the application and stored for the life of the application, then Singletons might be a good idea. The main problem, is that you are removing the ability for the programmer to decide whether they want the state to be global or temporary.

The reason static methods are often a code smell is that they are often used to namespace functions. The problem is static methods make it extremely difficult to unit test, to extend and replace functionality. If I want to use my class, I have to go through the entire source code and replace every reference to your call to the static method. If I don't have your source code, well, I either deal with it, use another library or rewrite all classes that reference the static method.

As you can tell, static methods can be more than a code smell, they can be downright fight against productivity. If the library is only going to be used by the author, then it doesn't really matter in the end.


答:
Also think how programs are compiled/distributed has changed.  Remember, before DOS, most computing was on mainframe-esque systems.  Compilers were delivered as part of the hardware because you rarely got off-the-shelf software.  If you were lucky, you got source and compiled for that machine.  Even today, in many Unix-environments, you still have to compile for platforms because the binaries are not portable.  This was the norm back then, not the standard.

So the assumption that there needed to be a compiler was more a reflection on what people thought they needed from a computer to be productive.  These days, because so much from a hardware and/or operating system has been standardized, it's possible to compile an application and deliver it to another machine and it will run just fine, thank you.

The money is in the commercialization of compiled binaries because that's how people use computers these days (how many applications do you use that you have not compiled... if you're like me, most of them, if not all).  In the time of DOS, the money was in the language / compiler because that's how people used computers back then (the people using the applications either compiled them, or sat down the hall from the people who did).

Title: What made BASIC profitable?


问:
Loosely compare user input with database record
I have a database table with 3 columns; id, question and answer. On the front-end, I have a PHP application that shows questions to the user. The application would then compare the user input with the answer on the database.

Using only PHP, how do I loosely compare user's input with the record on the database and pass it as correct even though it is not a strict match? For example:-

Question: What is the structure of a water molecule?
Answer on database: Hydrogen and oxygen
Acceptable answers: Oxygen and hydrogen, hydrogen n oxygen, hydrogen & oxygen

答:
Levenshtein, SoundeX and Metaphone functions could be helpful.

You might need to break the original answers to words, in order to make a better comparison. Also taking out and, [space]n[space], & from both correct answers and the user input could lead you to a much better results.


问:
How to avoid errors and not miss anything
I have a problem that is more serious than it might seem.

I've been programming for about three years , and I have learned and improved a lot , I read the code easily to others, understand the problems and transform them into code, I easily adapt to new technology and I love to learn how it all works . That's all fine .

The problem I have is that I often forget small details , which then turn out to be critical . For instance , yesterday, after changing a database query to retrieve some data filtering by twenty fields , forgot to load all the data ( the query returned only the data of the primary key of the whole object ) . Other times are smaller things that do not make the whole process fails, but still I am afraid to fail at something serious , that my superiors grow weary of my mistakes , etc. .

I would like to know how I can schedule the job to not forget anything or at least soon realize that I have forgotten something or have missed something ...

答:
Testing, testing, testing. Automated Tests. TDD. BDD.

Nearly all people commit mistakes (and some costly ** ahem **). Don't fear them, just learn from them when you do make mistakes. And test your code. Look at the possible places that it can fail (at the limits of the data, on special cases, ...) and create appropriate tests.


答:
I'm not a senior programmer either, but I would say you'll have to test your code to be sure of what you wrote.
You'll never avoid programming mistakes (we're all human beings), but you can try and test your code all the time.</p>

Title: How to avoid errors and not miss anything

Body:
I have a problem that is more serious than it might seem.

I've been programming for about three years , and I have learned and improved a lot , I read the code easily to others, understand the problems and transform them into code, I easily adapt to new technology and I love to learn how it all works . That's all fine .

The problem I have is that I often forget small details , which then turn out to be critical . For instance , yesterday, after changing a database query to retrieve some data filtering by twenty fields , forgot to load all the data ( the query returned only the data of the primary key of the whole object ) . Other times are smaller things that do not make the whole process fails, but still I am afraid to fail at something serious , that my superiors grow weary of my mistakes , etc. .

I would like to know how I can schedule the job to not forget anything or at least soon realize that I have forgotten something or have missed something ...


答:
I would like to know how I can schedule the job to not forget anything

You can't. Whether you're Robin Seggelmann or Donald Knuth, writing a computer program of any realistic size is simply not a task that the human mind can achieve wholly without errors. That's a simple truth, it's just often ignored because the mind has a fantastically advanced capability of overestimating its own powers. In fact, it usually assumes that it is infallible, but it virtually never is.

or at least soon realize that I have forgotten something or have missed something

That's what testing is for. Testing is not a disgrace, it's a normal and expected part of development. (It's debugging that is a disgrace, because having to debug indicates that you wrote code where you yourself don't understand how it works.)


答:
on of the biggest misconceptions that I see is that lazy instantiation is needed for all singletons, it isn't.

Java has it's own lazy loading of classes that will allow for lazy instantiation when the class is first needed:

```<code>public class Singleton {
    private static Singleton instance = new Singleton ();

    private Singleton() {   }

    public static Singleton getInstance() {
        return instance;
    }
}
</code>```

often this is all you need for lazy instantiation of a singleton in java

Title: Simple Design for Singleton function in java for Kernel

Body:
I understand that Singelton helps to instantiate only one class AT A TIME. I try to learn how to Design for Singleton function in java.  I want to know it better to understand Kernel. So I try to do this following, but I like to know if it's the only way to come up with private constructor.</p>

```<code>public class Singleton {
    private static Singleton instance = null;

    private Singleton() {   }

    public static synchronized Singleton getInstance() {
        if (instance == null) {
                    instance = new Singleton ();
        }
        return instance;
    }
}
</code>```

Body:
on of the biggest misconceptions that I see is that lazy instantiation is needed for all singletons, it isn't.

Java has it's own lazy loading of classes that will allow for lazy instantiation when the class is first needed:

public class Singleton {
    private static Singleton instance = new Singleton ();

    private Singleton() {   }

    public static Singleton getInstance() {
        return instance;
    }
}

often this is all you need for lazy instantiation of a singleton in java


问:
Refactoring sought for replacing shared data types in .NET component
I am in charge with updating a software product that is made up of two components the Controller process and the UI process. The Controller and the UI communicate via XML messages. Furthermore, the Controller is built on top of a shared library that implements a number of business flows.

For builing the messages for Controller-UI communication, somebody decided to use .NET built-in serialization and deserialization and therefore created class types annotated with attributes that control serialization (XmlElement, XmlAttribute, etc) for each message, serializing it and deserializing it by using the default XML serializer.

For the first couple of controllers, this was fine. But now, while some of the messages can be reused, the other cannot. They will accomplish the similar functions but are structurally incompatible with the information we need them to contain.

Because this decision was made we are stuck with data-types that cannot model the data we need, and cannot be changed because they would break the other controllers. At the same time we need the functionality and messaging sequences implemented in the shared library.

I need a way out of this conundrum, one that has the smallest technical cost in relation to changing the other controllers, I need a sort of "structural polymorphism" for these types, where the type is the same but its internal structure different.

Perhaps these messages can be changed to 'object' data types, but in that case... I need a way to control from the outside of the shared library the casting that gets made inside the shared library.

How do I approach this, I am not experienced enough to find a clean refactoring for this? I feel stuck.

We are using .NET 4.5

答:
The default XML Serializer is quite flexible. Ignores (by default) what doesn't know (that's it information on the xml file/stream for which there is no member variable), and what it knows and it is not present (in the xml file/stream), it gives defaults. So, a very dirty way is just to add what you need where you need it. It will work. It will not be pretty.

If you want to have a bit more control, you can implement IXmlSerializable and override WriteXml and ReadXml methods to write or read only what is needed from/to the xml file/stream


问:
Environment-aware Code
There are situations where the deployed environment (development, test, or production, for example) might dictate the outcome of certain actions.

For example, perhaps a successful "user registration" process will send a notification email to the new user.  Environment-specific actions:

Development:  Do not actually send the email.  Email logs will provide enough for developers.

Test:  Send all emails to some testEnvironment@domain.com inbox and not to the user's address.

Production:  Send the email to the user.

I have listed three possible solutions below.

CurrentEnvironment configuration value

One way of solving this, which I have seen a lot, is to have some configuration value (whether it be in some xml config file or in the database) such as CurrentEnvironment which specifies the current environment in which the system is deployed to.  This would require case/if checks in code to determine the desired action:

```<code>if(CurrentEnvironment == Environment.Test)
{
    // Send all emails to some testEnvironment@domain.com inbox.
}
else if(CurrentEnvironment == Environment.Production)
{
    // Send the email to the user.
}
</code>```

This is not a maintainable solution in my opinion.

Wipe all email addresses

Another method is to run a change script, once restoring a database, to do the following:

Remove all user email addresses (in development),

Replace all user email addresses with testEnvironment@domain.com (in test)

This is an extra step in the release process which, if missed, could have some dangerous results.  Additionally, this solution only fixes the email problem.  There are perhaps many other situations where the environment matters.

Config transformation

Another idea is to use web.config transformations.  This way the config can be different for different environments.  For example, we will have the following configs:

```<code> web.config
   web.Development.config
   web.Test.config
   web.Production.config
</code>```

The transformation can then use different "providers" or set certain attributes according to the environment.  For example, an overrideDeliveryAddress can be set in the web.Test.config:

```<code><EmailService>
  <providers>
    <add
      name="EmailServiceProvider"
      type="CustomProviders.EmailServiceProvider, CustomProviders"
      smtp="smtp.domain.com" password="xyz"
      overrideDeliveryAddress="testEnvironment@domain.com"
      enabled="true"
    />
 </providers>
</EmailService>
</code>```

This solution requires much more work, but is more maintainable and less invasive.  Code is now environment-oblivious.

What other ways can the above be achieved?  Should code EVER be environment aware?

答:
First, you should not use your real production data (especially not person-related data) in development or test (you may use carefully choosen excerpts from production data, of course). So your data pools (maybe a database, maybe a pool of files, maybe both), should be separated between those environments. So the only thing you need to change is the config file where you switch between those 3 data pools (for example, the database connection string, or the path to the files). This means there will be no need for any "environment-aware code", the only single thing which is enironment-aware is that entry in your main configuration file.

For example, your development environment should have development database with a list of email adresses, and your test environment a different database with a different list, and your production environment a database with the real mail adresses.

The problem you are describing seems to be a situation where you try to load a copy of the production database into your development environment and replace your development database with that. This is most probably a scenario you should avoid, better provide import/export mechanisms to transfer small portions of data from one database into another, where personal data is normally not transferred. If you really need an original copy of the production DB in your dev environment (because otherwise you cannot reproduce a certain bug), go with solution 2 and delete or anonymize any personal data like mail adresses (in many scenarios you must do this either for reasons of privacy).

Title: Environment-aware Code


问:
According to software engineering which method are too long?
I was just working with a method of about 70 lines of code developed by others. It uses a very nice pattern structure, stuff like IOC container, but I wonder.. The method is too long?

Is it a so long method still easily readable?

The question could be finished, but now starts the premise from which my question has originated.

Before realizing its length (excessive for me) I was getting bored while trying to understand what it was doing.

It's full of instruction of this kind:

```<code>if (success == null)
{
    //Log response error
    logger.LogProviderActionResponse(userId, "actionName", transactionRequestId,
        _configuration.ResponseLogErrorTryAgainId, xmlResponse.InnerXml.ToXml(true));
    return new CheckActionResult(ActionStatus.Failed);
}
</code>```

What is it doing and why? It deals with logging of course, because the success variable is null, but what does it imply? And also there are many parameters, what is their meaning?

I would need to read it carefully, to study it.

The problem is that this method implements an interface and an abstract class, it has many siblings. Copy and pasted siblings which share the same structural behavior. But it's not immediate to distinguish structural information from domain specific information.

In developing a new action or a new provider I should only need to copy, paste and modify domain specific stuff. But it's hard.. since they are deeply mixed together with structural behavior...

Refactoring I would do to raise the readability

1st step

surround all this logging with a #region that can be collapsed

2nd step could be

to use Extract Method to trasnsform the previous log call to a single instruction. Something like:

Log.LogWithReason(Success.IsEmpty);

But the usage of return conflicts with this purpose requiring extra effort.

3rd step

would be to completely separate the Logging responsability (using AOP? Implementing it in the base class? using events?). If one method has 5 / 8 calls to the log for different reasons. It's too much aware of logging. In my opinion the Single responsibility principle is violated since the methods has gained the secondary responsability of being strongly aware about logging.

The question remains the one specified in the title but I hope to read a very mature comparison here based on the seeds idea I've wrote!

Thanks for your contribute

答:
A method is too long that does more than it needs to do. Any blanket statement that "any method longer than XXX lines/statements is too long" is bogus, shows only that the author of the statement is a mindless acedemic with no experience writing actually productive software.

It's all nice and dandy to claim that "anything that can be must be removed into another method" but if that makes the code harder to follow it's not the thing to do (and it might introduce performance problems which is even worse). Again, the theoretician can make such statements, the professional has to work with reality and reality may well clash with book theory.

I've worked on fixing systems that were created according to "standards" set by such theoreticians. Systems that on paper were marvels of beauty and design, but in practice were next to impossible to maintain and failed to perform (mostly because they were way too slow because of an overly high load due to excessive method calls and object creations).

Worst case of that was a system that took 72 hours to generate 500 form letters. When bypassing the mess of the system framework and linking the letter generator directly to the database, that went down to about 20 seconds (not counting the time needed for the physical printing which was another few minutes).

That's the price you pay if you let theoretical correctness take front seat over pragmatic and practical design.


答:
As you certainly have understood, testing is the solution.

There are several things that could help you.

Creating automated tests. There are tools for that such as Junit for Java and Nunit or the built-in unit testing of Visual Studio for .Net. The more your code is covered by these tests, the better it will get. (There are tools for that, please Google it). These tests should be executed automatically when you build your application.

If you have time, create testing plans for integration testing and all the tests you cannot do automatically.

Track your bugs (there are tools for that, such as JIRA, Bugzilla, etc.) and NEVER forget to update your automated tests and test plans so you can detect eventual regressions.

More generally if your project allows its use Test Driven Development (TDD) which basically requires that you write your tests before implementing your functionality.

Note that these points should be implemented by your whole team. Maybe there is something to suggest to your team leader or to your project manager.


答:
@jwenting is right that the number of lines should not be the primary reason for refactoring methods. Nevertheless it is a often an indicator for a "code smell". And when the situation is so clear as in your logging example, where the SRP is clearly violated, the method should be refactored. So your main criteria for "when to refactor" should be the SRP itself, the other SOLID principles, and the "single level of abstraction" (SLA) principle.

And the "number of lines" of a method should only be used as an indicator for "which method to check if it violates those principle and can be improved".

As you asked about "software engineering": if you are going to write something like a style guide for your code, don't add a rule like "avoid methods longer than XXX lines", better add a rule like "avoid methods violating the SRP".

Title: According to software engineering which method are too long?

Body:
I was just working with a method of about 70 lines of code developed by others. It uses a very nice pattern structure, stuff like IOC container, but I wonder.. The method is too long?

Is it a so long method still easily readable?

The question could be finished, but now starts the premise from which my question has originated.

Before realizing its length (excessive for me) I was getting bored while trying to understand what it was doing.

It's full of instruction of this kind:

```<code>if (success == null)
{
    //Log response error
    logger.LogProviderActionResponse(userId, "actionName", transactionRequestId,
        _configuration.ResponseLogErrorTryAgainId, xmlResponse.InnerXml.ToXml(true));
    return new CheckActionResult(ActionStatus.Failed);
}
</code>```

What is it doing and why? It deals with logging of course, because the success variable is null, but what does it imply? And also there are many parameters, what is their meaning?

I would need to read it carefully, to study it.

The problem is that this method implements an interface and an abstract class, it has many siblings. Copy and pasted siblings which share the same structural behavior. But it's not immediate to distinguish structural information from domain specific information.

In developing a new action or a new provider I should only need to copy, paste and modify domain specific stuff. But it's hard.. since they are deeply mixed together with structural behavior...

Refactoring I would do to raise the readability

1st step

surround all this logging with a #region that can be collapsed

2nd step could be

to use Extract Method to trasnsform the previous log call to a single instruction. Something like:

Log.LogWithReason(Success.IsEmpty);

But the usage of return conflicts with this purpose requiring extra effort.

3rd step

would be to completely separate the Logging responsability (using AOP? Implementing it in the base class? using events?). If one method has 5 / 8 calls to the log for different reasons. It's too much aware of logging. In my opinion the Single responsibility principle is violated since the methods has gained the secondary responsability of being strongly aware about logging.

The question remains the one specified in the title but I hope to read a very mature comparison here based on the seeds idea I've wrote!

Thanks for your contribute


问:
people fork my project but don't fetch from upstream - what can I do?
Several people have forked my github repo but they have not fetched-merged from upstream. So my original repo has evolved significantly since the fork took place, and meanwhile these people are showing an old outdated version of my work, which kind of makes me look bad (e.g. what they're displaying is incomplete, contains bugs that I've fixed since then, etc.).

These people apparently don't understand what a fork is for; they just push the fork button (perhaps as a way of saying "this is cool") and then walk away. Ideally what I'd like is for them either to keep their fork updated from upstream or make a significant contribution or delete the fork. Is there anything I can do about this? (There isn't, is there? This is just the price of being open source, isn't it?)

答:
No, there is nothing you can do about this.

Here's an article talking about this particular "problem" http://andrewwilkinson.wordpress.com/2010/01/27/where-github-possibly-went-wrong/

I am in a middle ground. I like that forks are easy to create and I think it allows people to easily play with and modify the code, and push back if they please. But, I think github's interface on top of forks is flawed. It should be very easy to determine which fork (or the original) is the one you should probably use / fork off from. Imo it would be easy to determine this by looking at the number of commits and how recent the commits were on each fork.


问:
Singleton: Why is a global point of access bad?
Most people here and on StackOverflow agree that Singletons are evil.

The main explanation I've come across against the use of Singletons, is they fact that they provide a global point of access to an object.

I admit to not understand why this is a bad thing. It's very convenient to be able to access an important and useful object from anywhere in your code, without having to 'pass it around' in order to get it.

So why is a global point of access in OOP a bad thing? Not only with Singletons, but generally. Please give concrete examples.

答:
Disadvantages are that:

it is not obvious where it is used

when you use something that uses it, you cannot supply alternatives (esp. when testing, you do not want to use eg. real credit card payment)

when you decide that you want two contexts in which it should be unique you must rewrite every usage.

These disadvantages are sometimes acceptable, sometimes not.

Note that problem is not in the fact that only one instance is used (it often is very usefull), but in it being hardcoded and invisible from outside.