问:
How to set up a distributed version control that can commit to subversion
We have a trac server setup that works with the svn commits, so we can do things like "fixed #183" in the commit messages, and reference the changes involved.  Right now I have eclipse with subclipse + trac plugins, and it works pretty well.

But I don't have internet all the time and it becomes very difficult to commit to an inaccessible svn server.

I would like to use some type of local repository for commits, and then push commits all at once, but individually to server.  Changing svn / trac isn't an option at this time.  Other developers can touch the svn server directly.

Is there a way to cache the commits locally, and then send them when I have internet again?  Take in mind that I can't just do one big commit of all my changes because it makes it a nightmare since I can't selectively merge.

Basically is there a way to do this with git/bzr/mercurialand still use svn/trac as intended?

I'd be willing to do some scripting, but I don't know where to start.

答:
git-svn does pretty much exactly what you want. I used to do this at a former place; they had SVN installed as source control, but the connection was unreliable so I tracked my changes locally in Git and only committed to the main repo when I had a hard line into the office server. It was really, REALLY useful having local branches, and merging my code in got much easier once I switched over.

The link up there is basically an online man page. If you decide to go this route, also check out the tutorials available online.

The only real complaint I had was that the initial checkout took a good 40 minutes; I went to grab a sandwich and a tea, and it had just finished when I got back. Committing and pushing thereafter was a breeze (actually much faster than the SVN process), but don't be surprised if that first pull takes a while.

ContentLicense: CC BY-SA 2.5


问:
Do any object-oriented programming languages support "collective constructors"?
I was recently considering that sometimes several objects depend on each other (e.g. if they contain cyclic references) and therefore it would be useful to create them as part of one atomic operation that makes sure that, after construction, the new objects fulfil some collective constraint.

In order to do this one could have constructors that can create more than one object. The programmer would then put in a single constructor all the code ensuring that, once objects o1, ..., on have been created, they satisfy all required constraints (e.g. all links between the new objects are already in place). I have made up the term collective constructors
myself because I have never heard of such a feature, but there might well exist an accepted name for this concept.

So, is there any programming language supporting this kind of constructors? If not, has the idea been tried out already?

答:
Ruby, Smalltalk, Self, Newspeak etc. don't have constructors, they just have a naming convention for factory methods (e.g. new in Ruby). Since they are just bog standard methods like any other method, they can do anything they want, including allocating and initializing as many objects as they want. The main problem is that such factory methods return, by convention, a single object that is an instance of the class the factory method was called on. I.e. when calling Foo.new it is expected that you get back a single object which is an instance of Foo. But, with sufficient documentation, you could return some structure (e.g. an Array) of multiple new objects.

Example:

```<code>class Foo
  def self.new
    new_foo = super

    new_bar = Bar.new
    new_bar.foo = new_foo

    new_foo.bar = new_bar

    return new_foo, new_bar
  end

  attr_accessor :bar
end

class Bar
  attr_accessor :foo
end

foo, bar = Foo.new
</code>```

In ECMAScript, constructors are just regular procedures, or rather, any procedure can be used as a constructor just by sticking the new keyword in front of it. Again, since they are just regular procedures, they can do anything they want.

ContentLicense: CC BY-SA 3.0

Body:
Ruby, Smalltalk, Self, Newspeak etc. don't have constructors, they just have a naming convention for factory methods (e.g. new in Ruby). Since they are just bog standard methods like any other method, they can do anything they want, including allocating and initializing as many objects as they want. The main problem is that such factory methods return, by convention, a single object that is an instance of the class the factory method was called on. I.e. when calling Foo.new it is expected that you get back a single object which is an instance of Foo. But, with sufficient documentation, you could return some structure (e.g. an Array) of multiple new objects.

Example:

class Foo
  def self.new
    new_foo = super

    new_bar = Bar.new
    new_bar.foo = new_foo

    new_foo.bar = new_bar

    return new_foo, new_bar
  end

  attr_accessor :bar
end

class Bar
  attr_accessor :foo
end

foo, bar = Foo.new

In ECMAScript, constructors are just regular procedures, or rather, any procedure can be used as a constructor just by sticking the new keyword in front of it. Again, since they are just regular procedures, they can do anything they want.


问:
How to conceptually consider and implement user interface rules for numerous controls and data inputs?
I have a user interface with numerous controls and data inputs on it. Buttons, text fields, and checkboxes, etc. Imagine the following "rules" exist for a sample UI with 2 of those controls:

B2 cannot be used until TF1 and TF2 both have values

TF2 cannot be entered until TF1 has a value

CB2 cannot be checked unless TF1 has a value

CB2 cannot be checked unless CB1 is checked

These rules are arbitrary here, but I have a variety of business rules which will ultimately govern the UI functionality.

I would like to implement logic for this in my UI code to enforce these rules. However, I am having a hard time determining a good way to do so. I can think of two primary ways but I'm not really a fan of either.

Method 1 - adding logic to each control callback

One way to do this would be to add the logical check(s) to each method callback. So for the first rule, in the code associated with B2, include hard coded checks like if TF1 == "" and if TF2 == "". I am not a fan of this idea because I'm going to scatter any sequencing/logic everywhere in my UI and it seems inevitable sometime this process will result in obscure and impossible to track down bugs. Also seems like maintenance will be impossibly complex.

Method 2 - build collection of all rules

The way I'm leaning towards is building a collection of rules. The first step would be defining a set of rules for "passing" for each type of control and its associated lookups, such as:

For checkboxes, "passes" check for true, "fails" if false

For textboxes, "passes" if not empty, "fails" if = ""

I can then create a collection of all the prerequisite pass/fail checks for each UI component and its associated components. This can be abstracted into a single check method called in each UI action like:

myChecker(mControlName)

where myChecker is a method which iterates through the list of all matching rules, checks them, and returns true/false based on whether the rules pass. This method could be called from each UI control before any control-specific logic takes place.

This is nice, but it seems creating the rules and not forgetting any might be even more complex than the first method. Additionally, all control types have to have a "pass/fail" criteria or the myChecker method might become ridiculously complex with lots of hard to read if statements.

Am I missing something? There has to be a more clearly defined pattern or some better strategy for incorporating these sorts of validation/rules into a UI.

答:
Method 3 - adding custom logic to each control callback and a collection of (shared) rules:

Trying to create a single check method that works for all your UI controls may prove very difficult.  ...and worse, it may have to contain so many options and exceptions that it will just be too unwieldy and hard-to-maintain.  It's generally a bad idea to make a kitchen sink method.

Adding logic to each control callback isn't that bad.  If there are many controls with the same/similar logic you should factor that part out, and they can all call the same validation check.  Bugs should actually be easier to track down, since there isn't some monstrous method that handles everything to look through each time.  The bugs will be more local to each control.


答:
I think you are on the right track with method 2 (though in some cases it might be overkill, I don't think it is even close to overkill in your case).

There are some patterns at least somewhat relevant - MVC, MVVM, MVP would help you move the logic for "passing" from the UI controls.  Instead of business logic happening in the control, some other code could run the business logic, update a model, then data bind from the model to the controls.

You can do a more manual data bind if you are running on older framework like VB6, or, god forbid, Microsoft Access.

This may seem like extra work to do the same thing, but it lets you write unit tests of the business logic.  It may help some with concurrency issues, since updating the model doesn't immediately start firing UI events.

There are also ways to make the business logic more maintainable than a forest of if statements.  Usually at that point you turn the rules that govern the if/then statements into whatever data structure can capture it.  Then you run through the data structure and apply the rules.  Often this is easier to follow than code, but since the business rules could potentially be anything there is no real general case to go by.

Title: How to conceptually consider and implement user interface rules for numerous controls and data inputs?

Body:
I have a user interface with numerous controls and data inputs on it. Buttons, text fields, and checkboxes, etc. Imagine the following "rules" exist for a sample UI with 2 of those controls:

B2 cannot be used until TF1 and TF2 both have values

TF2 cannot be entered until TF1 has a value

CB2 cannot be checked unless TF1 has a value

CB2 cannot be checked unless CB1 is checked

These rules are arbitrary here, but I have a variety of business rules which will ultimately govern the UI functionality.

I would like to implement logic for this in my UI code to enforce these rules. However, I am having a hard time determining a good way to do so. I can think of two primary ways but I'm not really a fan of either.

Method 1 - adding logic to each control callback

One way to do this would be to add the logical check(s) to each method callback. So for the first rule, in the code associated with B2, include hard coded checks like if TF1 == "" and if TF2 == "". I am not a fan of this idea because I'm going to scatter any sequencing/logic everywhere in my UI and it seems inevitable sometime this process will result in obscure and impossible to track down bugs. Also seems like maintenance will be impossibly complex.

Method 2 - build collection of all rules

The way I'm leaning towards is building a collection of rules. The first step would be defining a set of rules for "passing" for each type of control and its associated lookups, such as:

For checkboxes, "passes" check for true, "fails" if false

For textboxes, "passes" if not empty, "fails" if = ""

I can then create a collection of all the prerequisite pass/fail checks for each UI component and its associated components. This can be abstracted into a single check method called in each UI action like:

myChecker(mControlName)

where myChecker is a method which iterates through the list of all matching rules, checks them, and returns true/false based on whether the rules pass. This method could be called from each UI control before any control-specific logic takes place.

This is nice, but it seems creating the rules and not forgetting any might be even more complex than the first method. Additionally, all control types have to have a "pass/fail" criteria or the myChecker method might become ridiculously complex with lots of hard to read if statements.

Am I missing something? There has to be a more clearly defined pattern or some better strategy for incorporating these sorts of validation/rules into a UI.


答:
This sounds like the Builder Pattern to me, which is a more complex form of a Factory.  One Java example is a StringBuilder, which you use to build up a String, then call builder.toString() when you want the immutable result.  However, you can use the builder pattern to build more complex non-homogenous collections of objects.  You could use friend semantics in a builder to get access to private variables that would be considered immutable after the result object is created.

Functional languages might provide some inspiration.  Scala, for example, has a mutable ListBuffer that can be used for the building stage, then converted to an immutable List.

Another possibly relevant concept is Freezable Objects, by which an object is considered mutable until a Freeze() method is called on it.  A builder could use the unfrozen objects, then freeze them before returning.

Title: Do any object-oriented programming languages support "collective constructors"?

Body:
I was recently considering that sometimes several objects depend on each other (e.g. if they contain cyclic references) and therefore it would be useful to create them as part of one atomic operation that makes sure that, after construction, the new objects fulfil some collective constraint.

In order to do this one could have constructors that can create more than one object. The programmer would then put in a single constructor all the code ensuring that, once objects o1, ..., on have been created, they satisfy all required constraints (e.g. all links between the new objects are already in place). I have made up the term collective constructors
myself because I have never heard of such a feature, but there might well exist an accepted name for this concept.

So, is there any programming language supporting this kind of constructors? If not, has the idea been tried out already?


问:
Continuous Delivery: Kanban, SCRUM, or other?
I was wondering if there was an SDLC (software development lifecycle) or methodology (Kanban, SCRUM, waterfall, otherwise, etc.) that was particularly well-suited for continuous delivery systems, and why?

I'm sure each methodology has pros/cons that make it suited for certain components of CD, but there must be one that incorporates principles/values that make it better geared for CD...

答:
I will start with SCRUM. SCRUM has powerful principles that will guide your team through your projects.

It is a powerful, simple, and flexible framework. Since it's a framework it doesn't handle every step that you might need in your SDLC. It only provides basic guiding principles that's why SCRUM is usually used with other practices like XP and continuous delivery.

Sample implementation of SCRUM and other principles:

SCRUM and Pair Programing (XP)

SCRUM and Continuous delivery

SCRUM and Planning Game (XP)


问:
How important is to initialize a variable
How important is it to initialize variables?

Does proper initializing avoid memory leaks or have performance advantages?

答:
As others said, it depends on the language. But I'll demonstrate my Java (and Effective Java) ideas about initializing variables. These should be usable for many other higher level languages.

Constants and class variables

Class variables - marked with static in Java - are like constants. These variables should normally be final and initialized directly after definition using = or from within a class initializer block static { // initialize here }.

Fields

As in many higher level and scripting languages fields will be automatically be assigned a default value. For numbers and char this will be the zero value. For Strings and other objects it will be null. Now null is dangerous and should be used sparingly. So these fields should be set to a valid value as soon as possible. The constructor is normally a perfect place for this. To make sure that the variables are set during the constructor, and not changed afterwards you can mark them with the final keyword.

Try and resist the urge to use null as some kind of flag or special value. It is better to e.g. include a specific field to hold state. A field with the name state which uses the values of a State enumeration would be a good choice.

Method parameters

Because changes to values of parameters (be it references to objects or basic types like integers etc) will not be seen by the caller, parameters should be marked as final. This means that the values of the variable itself cannot be changed. Note that the value of mutable object instances can be changed, the reference can not be changed to point to a different object or null though.

Local variables

Local variables are not automatically initialized; they need to be initialized before their value can be used. One method to make sure that your variable is initialized is to initialize them to some kind of default value directly. This is however something you should not do. Most of the time the default value is not a value you would expect.

It is much better to only define the variable precisely where you need the variable. If the variable is only to take a single value (which is true for most variables in good code) then you can mark the variable final. This makes sure that the local variable is assigned exactly once, not zero times or two times. An example:

```<code>public static doMethod(final int x) {
    final int y; // no assignment yet, it's final so it *must* be assigned
    if (x < 0) {
        y = 0;
    } else if (x > 0) {
        y = x;
    } else {
        // do nothing <- error, y not assigned if x = 0
        // throwing an exception here is acceptable though
    }
}
</code>```

Note that many languages will warn you if a variable remains uninitialized before use. Check the language specifications and forums to see if you don't worry needlessly.

Body:
As others said, it depends on the language. But I'll demonstrate my Java (and Effective Java) ideas about initializing variables. These should be usable for many other higher level languages.

Constants and class variables

Class variables - marked with static in Java - are like constants. These variables should normally be final and initialized directly after definition using = or from within a class initializer block static { // initialize here }.

Fields

As in many higher level and scripting languages fields will be automatically be assigned a default value. For numbers and char this will be the zero value. For Strings and other objects it will be null. Now null is dangerous and should be used sparingly. So these fields should be set to a valid value as soon as possible. The constructor is normally a perfect place for this. To make sure that the variables are set during the constructor, and not changed afterwards you can mark them with the final keyword.

Try and resist the urge to use null as some kind of flag or special value. It is better to e.g. include a specific field to hold state. A field with the name state which uses the values of a State enumeration would be a good choice.

Method parameters

Because changes to values of parameters (be it references to objects or basic types like integers etc) will not be seen by the caller, parameters should be marked as final. This means that the values of the variable itself cannot be changed. Note that the value of mutable object instances can be changed, the reference can not be changed to point to a different object or null though.

Local variables

Local variables are not automatically initialized; they need to be initialized before their value can be used. One method to make sure that your variable is initialized is to initialize them to some kind of default value directly. This is however something you should not do. Most of the time the default value is not a value you would expect.

It is much better to only define the variable precisely where you need the variable. If the variable is only to take a single value (which is true for most variables in good code) then you can mark the variable final. This makes sure that the local variable is assigned exactly once, not zero times or two times. An example:

public static doMethod(final int x) {
    final int y; // no assignment yet, it's final so it *must* be assigned
    if (x < 0) {
        y = 0;
    } else if (x > 0) {
        y = x;
    } else {
        // do nothing <- error, y not assigned if x = 0
        // throwing an exception here is acceptable though
    }
}

Note that many languages will warn you if a variable remains uninitialized before use. Check the language specifications and forums to see if you don't worry needlessly.


问:
Is there a way to efficiently allow a user to upload multiple content at once for e-commerce type sites?
Sellers on large sites like Amazon and Newegg need to provide names, descriptions, and images for their products to be displayed on the e-commerce sites.

These sellers could have 10000+ products to sell, each with their own unique name/descriptions/images. I can't imagine that e-commerce sites would have their sellers upload each product individually through some standard HTML form. Especially when a product can have multiple images, this method of uploading just seems too inefficient.

I'm guessing these sites allow sellers to upload via an API that the e-commerce site provides so that the uploading task may be automated with a script, but how exactly is this accomplished? Through JSON? JSON works great with text strings, but JSON doesn't allow for file uploads (so images can't be uploaded?).

答:
Large sellers like the one I work for generate feeds formatted a specific way for sites like amazon, ebay and so on. These feeds are text files on our website that have all of the information the company we're selling on need.

The sites, like amazon, will scrape our feeds about every our and update their catalog. Images are actually hosted on our site, they only get the url. Some places will follow the url and download the image, others simply hotlink to your site.

Formatting is a little different for each site, but they are all very simple. Just text with line breaks. Not JSON or XML. There are a variety of plugins that these companies offer to help facilitate the process. For example ebay has m2epro to allow a Magento based site generate feeds for listing on ebay.

The key is to keep things simple. No one likes for the listers. No one likes jumping through hoops to get their items listed.


答:
(e.g. if they contain cyclic references) [...] In order to do this one could have constructors that can create more than one object. The programmer would then put in a single constructor all the code ensuring that, once objects o1, ..., on have been created,

Cyclic dependencies between the objects? Then the answer is "don't use (just) a constructor", because cyclic method calls don't make any sense.  Instead, this is a classic scenario for some Factory methods.

Here's an example (in PHP) which is sort of silly but illustrates the general idea: You cannot create a Sprocket without an associated Widget, and vice-versa. Each object has a reference to the other when it becomes available.

```<code>class Widget {
    protected $sprocket = null;
    public function getSprocket(){ return $this->sprocket; }

    protected function __construct(){
        // Constructor cannot be called from outside, not public
        // Initialize self, to a limited degree
    }
    public static function create(Sprocket $partner=null){
        $me = new Widget(); // Can call constructor from same class

        // Here we can make all sorts of changes and additions and other
        // objects, wiring them all together, before revealing the result
        // to the outside world.

        if($partner !== null){
            $me->sprocket = $partner;

        }else{
            $me->sprocket = Sprocket::create($me);
        }
        return $me;
    }

}

/*
 * Practically identical to Widget, just with some renaming
 */
class Sprocket {
    protected $widget = null;
    public function getWidget(){ return $this->widget; }

    protected function __construct(){  }
    public static function create(Widget $partner=null){
        $me = new Sprocket();
        if($partner !== null){
            $me->widget = $partner;
        }else{
            $me->widget = Widget::create($me);
        }
        return $me;
    }
}

/*
$mw = new Widget(); // NOT ALLOWED! Constructor not public
*/

$w = Widget::create(); // OK to call
$s = $w->getSprocket();
$w2 = $s->getWidget();

assert($w == $w2);
</code>```

If I had to do this in PHP 5.2 in real life, I'd simply just leave the constructors public, and tell people not to use them. Instead I'd have a makeWidgetWithSprocket() function. If the language was Java, I'd use its package-level visibility controls to further prevent mistakes.

Additional reading:

If you want to pass lots of options and settings to create(), consider the Builder pattern.

If you find yourself needing a lot of flexibility to rewire things in different ways, look at Inversion of Control frameworks, which commonly (but not always) use dependency injection to connect objects together "from the outside".

Body:
(e.g. if they contain cyclic references) [...] In order to do this one could have constructors that can create more than one object. The programmer would then put in a single constructor all the code ensuring that, once objects o1, ..., on have been created,

Cyclic dependencies between the objects? Then the answer is "don't use (just) a constructor", because cyclic method calls don't make any sense.  Instead, this is a classic scenario for some Factory methods.

Here's an example (in PHP) which is sort of silly but illustrates the general idea: You cannot create a Sprocket without an associated Widget, and vice-versa. Each object has a reference to the other when it becomes available.

class Widget {
    protected $sprocket = null;
    public function getSprocket(){ return $this->sprocket; }

    protected function __construct(){
        // Constructor cannot be called from outside, not public
        // Initialize self, to a limited degree
    }
    public static function create(Sprocket $partner=null){
        $me = new Widget(); // Can call constructor from same class

        // Here we can make all sorts of changes and additions and other
        // objects, wiring them all together, before revealing the result
        // to the outside world.

        if($partner !== null){
            $me->sprocket = $partner;

        }else{
            $me->sprocket = Sprocket::create($me);
        }
        return $me;
    }

}

/*
 * Practically identical to Widget, just with some renaming
 */
class Sprocket {
    protected $widget = null;
    public function getWidget(){ return $this->widget; }

    protected function __construct(){  }
    public static function create(Widget $partner=null){
        $me = new Sprocket();
        if($partner !== null){
            $me->widget = $partner;
        }else{
            $me->widget = Widget::create($me);
        }
        return $me;
    }
}

/*
$mw = new Widget(); // NOT ALLOWED! Constructor not public
*/

$w = Widget::create(); // OK to call
$s = $w->getSprocket();
$w2 = $s->getWidget();

assert($w == $w2);

If I had to do this in PHP 5.2 in real life, I'd simply just leave the constructors public, and tell people not to use them. Instead I'd have a makeWidgetWithSprocket() function. If the language was Java, I'd use its package-level visibility controls to further prevent mistakes.

Additional reading:

If you want to pass lots of options and settings to create(), consider the Builder pattern.

If you find yourself needing a lot of flexibility to rewire things in different ways, look at Inversion of Control frameworks, which commonly (but not always) use dependency injection to connect objects together "from the outside".


问:
Documenting/defining data structures in Python
What is the preferred way to document the contents of and logic behind  dynamically generated data structures in Python? E.g. a dict which contains the mapping of a string to a list of lists of strings? </p>

<p>I find it hard to transport the meaning and algorithmic workings of the data elements through Python code alone. It is unsatisfying and sometimes counterproductive to try to shape the code which erects such a dict into a form which tells another programmer easily about the structure of a dict entry. Similarly, placing a comment with an example entry is anything but optimal in my eyes. </p>

答:
If you are writing code that may be used by other programmers in isolation to you, and you are using data structures that are beyond simple built-ins, consider whether or not you can encapsulate them as classes.

Lets look at some example methods and what they return.

```<code>def getMatrix(**args):
</code>```

Calling this I can presume that the output will be an list of lists wth some simple value inside. Not much help needed.

```<code>def getCharacterCounts(**args):
</code>```

In this, I could presume that based on the arguements I'll get a dictionary where each key is a character and then the value will be a count based on the occurances in some string.

```<code>def getPerson(**args):
</code>```

Ah, now we are getting into trouble. A person is a complex thing, and I could store it as a dictionary, like so:

```<code>person = {  name:"Bob",
            age: 37,
            date_of_birth: "1932-01-15",
            hobbies:['programming','arguing on the internet', 'cross stitch'],
         }
</code>```

But, as this data structure gets larger, more fields occur, the example gets bigger and then the documentation needs to start including how to resolve issues when values conflict - for example, unless we are transported back to the year 1969, the date-of-birth and age are inconsistent.

In summation, if you are using a data structre that is varied in structure and includes some "algorithmic workings" then perhaps its time to call upon the power of Object-Oriented ProgrammingTM.

Body:
If you are writing code that may be used by other programmers in isolation to you, and you are using data structures that are beyond simple built-ins, consider whether or not you can encapsulate them as classes.

Lets look at some example methods and what they return.

def getMatrix(**args):

Calling this I can presume that the output will be an list of lists wth some simple value inside. Not much help needed.

def getCharacterCounts(**args):

In this, I could presume that based on the arguements I'll get a dictionary where each key is a character and then the value will be a count based on the occurances in some string.

def getPerson(**args):

Ah, now we are getting into trouble. A person is a complex thing, and I could store it as a dictionary, like so:

person = {  name:"Bob",
            age: 37,
            date_of_birth: "1932-01-15",
            hobbies:['programming','arguing on the internet', 'cross stitch'],
         }

But, as this data structure gets larger, more fields occur, the example gets bigger and then the documentation needs to start including how to resolve issues when values conflict - for example, unless we are transported back to the year 1969, the date-of-birth and age are inconsistent.

In summation, if you are using a data structre that is varied in structure and includes some "algorithmic workings" then perhaps its time to call upon the power of Object-Oriented ProgrammingTM.


问:
Avoid Initial AJAX Call for Loading Data
Here is the typical sequence of events when someone navigates to a page in my application:

The user navigates to my application, including URL parameters and query strings.

The server receives the request and generates the HTML

On the client, AngularJS grabs any parameters and makes an AJAX call

The resulting data is then bound

Personally, I find it a bit wasteful that this requires two hits to the server. It leads to a delay between the HTML being returned and the inputs being populated.

Am I missing something? Is there a way to avoid going back and forth the first time?

答:
I don't know the specifics of angular, but there is no reason to not insert any initial data into the page directly. In Fact backbone suggests doing exactly that. All you would have to do is put in your template something like this

```<code><script>
var initial_data = {json with your data here};
</script>
</code>```

Where you inject the json from whatever server side framework you are using.

Body:
I don't know the specifics of angular, but there is no reason to not insert any initial data into the page directly. In Fact backbone suggests doing exactly that. All you would have to do is put in your template something like this

<script>
var initial_data = {json with your data here};
</script>

Where you inject the json from whatever server side framework you are using.


问:
How to prevent deep indentations?
What steps and measures can I take to prevent deep indentations in my code?</p>

答: Deep indentation is usually not a problem if every function/method in your program does one and only one thing. Occasionally, it might be necessary to nest conditionals a few levels deep, but I can honestly say I've only written deeply indented code a handful of times in 12+ years of coding.

Title: How to prevent deep indentations?


问:
How often do you use Formal UML?
I used ad-hoc MUML (made-up modeling language) to design and explain system fairly frequently.  It looks similar to UML and tends to be pretty well understood.

However, I've had a professor or two that harped on the use of strict, formal UML, as close to the spec as possible.  I always suspected that strict UML wasn't really as common as they claimed.  So, how 'bout it- how often do you actually draw out complete diagrams that use all the proper line endings, multiplicity, member type symbols, etc?

答:
I just dropped out of my supposedly top-tier college (at least temporarily) because of their rigid insistence on excessively time-consuming visual modeling activities, forum chores, excessively redundant soft skill stuff that anyone who grew up around computers or has ever leered thoughtfully towards a user-interface would get well-enough that the thought of going deep into debt for it would make one want to break things in utter frustration.

I had to choose between learning what I saw entry-level and junior-level jobs demanding and what hoops CES sets for the university's ABET accreditation, which causes decision-makers to play dumb when there are glaring problems with time-constraints and unrealistic expectations that a PERT assessment would reveal. The university does not practice what it teaches.

In my opinion, the Unified Process has a lot of merit, but the entire practice of minting visual artifacts, what ever the modeling language is a bit ridiculous. An iteratively-refined document containing a seriated list, such as might be produced with Word, Workflowy, Evernote, OpenOffice, or name a word processor is perfectly capable of documenting what is required by the Unified Process. Something this plain-jane can be easily worked on by multiple users, version-controlled, and if one chose the right tool to do it in, a team could even work on it at the same time. This is so much more easily done than when UML seemed like a necessary mode of uniting the hordes.

Title: How often do you use Formal UML?


问:
What is the difference between writing test cases for BDD and TDD?
I have been learning writing test cases for BDD (Behavior Driven Development) using specflow. If I write comprehensive tests with BDD, is it necessary to write TDD (Test Driven Development) test separately? Is it necessary to write test cases for both TDD and BDD separately, or are they effectively the same thing?

It seems to me that both are same, the only difference being that BDD test cases can be understood by non developers and testers.

答:
Since my last reply wasn't very successful, I will try a very straightforward approach.

Behaviour Driven Development is a subset of Test Driven Development

TDD focuses on each and every unit test for every function, doesn't matter what it does. BDD focuses on software that matters

Idiom. TDD settles for tests, BDD enforces story telling format

JavaScript Examples

Unit tests in jasmine (BDD)

```<code>describe("A suite", function() {
  it("contains spec with an expectation", function() {
    expect(true).toBe(true);
  });
});
</code>```

Unit tests in jsUnity (TDD)

```<code>function test_lists() { assert.areEqual([1, 2, 3], [1, 2, 3]) }
</code>```

Here are some Python libraries that help create more BDD like tests with unittest frameworks:

Lettuce: Cucumber for python

HamCrest

Body:
Since my last reply wasn't very successful, I will try a very straightforward approach.

Behaviour Driven Development is a subset of Test Driven Development

TDD focuses on each and every unit test for every function, doesn't matter what it does. BDD focuses on software that matters

Idiom. TDD settles for tests, BDD enforces story telling format

JavaScript Examples

Unit tests in jasmine (BDD)

describe("A suite", function() {
  it("contains spec with an expectation", function() {
    expect(true).toBe(true);
  });
});

Unit tests in jsUnity (TDD)

function test_lists() { assert.areEqual([1, 2, 3], [1, 2, 3]) }

Here are some Python libraries that help create more BDD like tests with unittest frameworks:

Lettuce: Cucumber for python

HamCrest


问:
Why are "class" variables misspelled?
I have started to see variable initialisations like that in Java libraries:

```<code>Class clazz = new Class();
</code>```

or

```<code>Class klass = new Class();
</code>```

Is there a particular reason for people to misspell the word "class" when declaring these variables, and to use a "kool boyz" sort of writing style? Also what is wrong with using something like cls or something similar?

答:
This is a special case with the name class, as that is a reserved keyword in some languages such as Java and thus cannot be used as the variable name. Using clazz or klass is a way to workaround that. Other options would include e.g. myClass.

In Java it's pretty common, as even the JDK uses that convention. See also https://stackoverflow.com/a/2530174/160539

"class" is what you want, but abbreviating or inserting junk ("a", "the", "_", etc) reduces clarity. clazz just says class. "International" English speakers (those reading both English and American) are used to transposing 's' and 'z'.

Since Java has had disclosed source and a suitable culture right from the start, worthwhile Java code and tutorials pick up the same conventions...

Title: Why are "class" variables misspelled?


答:
The server receives the request and generates the HTML

One-page application should be a skeleton, some views and some models (MV*). I think is incorrect to say that, at the first call, the server generates the HTML. In fact, Angular, or backbone, or any other Javascript frameworks, they want to manipulate the DOM (and they do it very well).

The role of the server, and the first call is to response with a skeleton. From that moment on, the server job is to handle RESTful.

What I'm considering is that building hybrid Web Apps (where an ASP.NET application or PHP meet MV*) can be a little confusing, especially because probably these are generating a lot of HTML in their core.

So the potential of Angular.js (or...) is reduced (mixing both philosophies), just because on the server side, there are still many processes of transformation of the DOM, and the javascript framework is ready to handle this at 100%, but it does so merely in part.

Title: Avoid Initial AJAX Call for Loading Data

Body:
Here is the typical sequence of events when someone navigates to a page in my application:

The user navigates to my application, including URL parameters and query strings.

The server receives the request and generates the HTML

On the client, AngularJS grabs any parameters and makes an AJAX call

The resulting data is then bound

Personally, I find it a bit wasteful that this requires two hits to the server. It leads to a delay between the HTML being returned and the inputs being populated.

Am I missing something? Is there a way to avoid going back and forth the first time?


问:
J2EE - Session swap
Application server - JBoss AS 7.1.1

JDK6

J2EE 1.3

My web application is more than 10 years old and facing this session swap problem in my portal. Noticed
that swap happens mostly when many concurrent users accessing the portal and underlying windows server is busy
(more than 90% CPU usage)

To analyse this issue, I logged customer data (customer id, ip address, jsession id) to a table and found
that customer having unique jsession id initially has his data and all of a sudden for the same jsession id and
ip address receiving different customer data.

```<code>customer1  123.123.12.123   jsessionid123    11:10:02
customer2  123.123.12.123   jsessionid123    11:10:04
</code>```

ip address (123.123.12.123) having jsession id (jsessionid123) somehow gets customer2 data

Any order placed by customer1 in ip - 123.123.12.123 gets created for customer2, I confirmed this by
calling customer2 and they confirmed that they didn't place the order. customer1 won't realise he placed
order for customer2 - all the data gets changed, like basket items, customer object, products etc.

Now I need to find a fix for this, but first I need to know which part of my code is creating this problem.

Do I have to use a stress test software? or any better mechanism to find out the problematic code?

答:
I've experienced something like this before. In my experience, the Action class that's supposed to receive data from the JSP is instantiated as a singleton, so when there are many concurrent users, the singleton class gets 'reused' which caused the apparent 'session-swapping'.

So check the whatever class is receiving your user inputs (for example, Action class in struts framework), and make sure that its not singleton.

Title: J2EE - Session swap


问:
Can we live without constructors?
Let's say in some reason all objects are created this way $obj = CLASS::getInstance(). Then we inject dependencies using setters and perform starting initialization using $obj->initInstance(); Are there any real troubles or situations, which can't be solved, if we won't use constructors at all?

P.s. the reason to create object this way, is that we can replace class inside getInstance() according to some rules.

I'm working in PHP, if that matter

答:
Yes, you can do nearly everything without using constructors but this is clearly squandering benefits of Object-Oriented Programming languages.

In modern languages (I'll talk here about C# which I program in) you can limit parts of code that can be run only in a constructor. Thanks to which you can avoid clumsy mistakes. One of such a thing is readonly modifier:

```<code>public class A {
    readonly string rostring;

    public A(string arg) {
        rostring = arg;
    }

    public static A CreateInstance(string arg) {
        var result = new A();
        A.rostring = arg;  // < because of this the code won't compile!
        return result;
    }
}
</code>```

As recommended by Joachim Sauer previously instead of using Factory design patter read about Dependency Injection. I would recommend reading Dependency Injection in .NET by Mark Seemann.

Title: Can we live without constructors?

Body:
Yes, you can do nearly everything without using constructors but this is clearly squandering benefits of Object-Oriented Programming languages.

In modern languages (I'll talk here about C# which I program in) you can limit parts of code that can be run only in a constructor. Thanks to which you can avoid clumsy mistakes. One of such a thing is readonly modifier:

public class A {
    readonly string rostring;

    public A(string arg) {
        rostring = arg;
    }

    public static A CreateInstance(string arg) {
        var result = new A();
        A.rostring = arg;  // < because of this the code won't compile!
        return result;
    }
}

As recommended by Joachim Sauer previously instead of using Factory design patter read about Dependency Injection. I would recommend reading Dependency Injection in .NET by Mark Seemann.


问:
How would I structure my code into an MVC format?
I want to have the home page (root of the website), check if a cookie exists for a user being logged in, and then based off of that determining whether or not to load the sign up page (landing page) or the feed of the user logged in.

Where would I have this check occur?

I've kept it in the controller for now, but based on some articles I've read (such as Skinny Controller, Fat Model, I'm not sure that's the right place to keep it in.

答:
Skinny Controller, Fat Model says that logic should be implemented in the model, since it allows better code reuse. The reasoning is that while a controller is tied to a single user action(or group of user actions), the model is used through the application, so putting the code in it allows to reuse it wherever we use the module.

This, however, applies only to code that operates on model data. In your case, you want to check for the existence of a cookie. Cookies are not related to a specific model - they are part of the HTTP request - so the natural place for them is the controller, since it's the controller's job to receive the user action and decide how to respond to it.

Still - this is code you'll want to reuse(I'm assuming you'll want to perform that check for many pages), so I wouldn't tie it to a specific controller - it needs to be shared among all controllers. In RoR, for example, you'll put it in the ApplicationController - the base class for all controllers used in your application. I don't know what framework you are using, or if you are rolling your own, but you should look for something similar.


答:
If you really have to use a reserved word, then in .NET you can escape it like this:

```<code>var @class = new Class();
</code>```

In my mind it's better than calling something 'klass'. I won't be surprised if other languages (JAVA) offer something similar.

Generally I would avoid 'cls', 'klass' or anything that requires additional mind mapping. It's a background noise and it's not needed.

Title: Why are "class" variables misspelled?

Body:
I have started to see variable initialisations like that in Java libraries:

```<code>Class clazz = new Class();
</code>```

or

```<code>Class klass = new Class();
</code>```

Is there a particular reason for people to misspell the word "class" when declaring these variables, and to use a "kool boyz" sort of writing style? Also what is wrong with using something like cls or something similar?

Body:
If you really have to use a reserved word, then in .NET you can escape it like this:

var @class = new Class();

In my mind it's better than calling something 'klass'. I won't be surprised if other languages (JAVA) offer something similar.

Generally I would avoid 'cls', 'klass' or anything that requires additional mind mapping. It's a background noise and it's not needed.


问:
Javascript - Avoiding variable redundancy in nested for loops
Please bear with me, I could only explain the problem in the comments of the code snippet below. Please read through them carefully. Question at the end:

I usually tend to name the variables used in for loops with i, like this:

```<code> for (var i = 0; i < arr.length; i++){
      // do some COMPLEX operations here
 }
</code>```

This looks fairly simple; but when I'm at it I may require nested for loops within the above for loop. So, introducing the complexity now:

```<code> for (var i = 0; i < arr.length; i++) {
      // do some
      // VERY
      // COMPLEX
      // operations
      // here

      for (var i = 0; i < javascript_object.list.length; i++) {
          // I may have inadvertently forgot of the variable 'i' was been used earlier
          for (var j = 0; j < javascript_object.list[i].another_list.length; j++) {
              // Perform more complex operations here
          }
      }

      this.getReports(arr[i]) // the value of this i
         // which I now think refer to the first for loop might have been changed
         // in second for loop and may lead to dangerous results!
 }
</code>```

How to avoid this from happening? How could the variables be named carefully so that it wouldn't clash with other variables being declared elsewhere?

答:
Use JSLint or JSHint to lint your code directly inside your IDE / Editor. From the Book "JavaScript: the Good Parts" by Douglas Crockford (author of JSLint):

JSLint is a code quality tool for JavaScript. It takes a source text
  and scans it. If it finds a problem, it returns a message describing
  the problem and an approximate location within the source. The problem
  is not necessarily a syntax error, although it often is. JSLint looks
  at some style conventions as well as structural problems. It does not
  prove that your program is correct. It just provides another set of
  eyes to help spot problems.


答:
To balance some of the other answers, claiming:

A constructor gives you the opportunity to set all member variables of
  the object to a valid state... you will never have an invalid object, which will save you from a lot of bugs.

and

With a constructor, an object owns its own construction logic so as to ensure that there are no invalid instances of such class.

Such statements sometimes imply the assumption that:

If an class has a constructor that, by the time it exits, has put the object into a valid state, and none of the class's methods mutate that state to make it invalid, then it is impossible for code outside the class to detect an object of that class in an invalid state.

But this is not quite true. Most languages do not have a rule against a constructor passing this (or self or whatever the language calls it) to external code. Such a constructor completely abides by the rule stated above, and yet it risks exposing semi-constructed objects to external code. It's a minor point but easily overlooked.

Title: Can we live without constructors?

Body:
Let's say in some reason all objects are created this way $obj = CLASS::getInstance(). Then we inject dependencies using setters and perform starting initialization using $obj->initInstance(); Are there any real troubles or situations, which can't be solved, if we won't use constructors at all?

P.s. the reason to create object this way, is that we can replace class inside getInstance() according to some rules.

I'm working in PHP, if that matter


问:
Etymology of 'virtual' (method/method table/inheritance)
As far as I know, it generally refers to late or dynamic bindng. So why a word like late or dynamic wasn't used?

答:
The word itself was introduced with SIMULA-67. Ole-Johan Dahl's history indicates that the introduction of 'virtual' into SIMULA occurred just before May 1967, just in time to be included in the paper Class and Subclass declaration that was presented at the IFIP TC2 Conference on Simulation Programming Languages.

However, there is no note to indicate why 'virtual' was chosen.


问:
Use a setStatus($arg) function or have separate enable() and disable() functions?
I've got two functions at the moment:

```<code>suspendGroupsAndUsers($groupId){}
enableGroupsAndUsers($groupId) {}
</code>```

But the difference between the two is one variable/string.  Should I just have:

```<code>setStatusGroupsAndUsers($status,$groupID) {}
</code>```

This feels more DRY...  Or have the above two functions actually call the setStatus function?

Gut says use setStatus ...

答: If your status can eventually become something else than a boolean value (enabled, suspended, hidden, banned, etc.), you may have to refactor if you only use setStatus.


答:
Look whether you are storing data in singletons (eg servlet) or in pooled objects. To be clear, variables inside function are ok, only something in servlet itself is problem.
In comment you say you choose action, if you choose existing instance, then you should not store session wide data in it.

Once I seen (ehm, caused) similar problem caused by incorrectly using phase listeners (in JSF) where we created listener for each request (which led to similar sindroms + after while it was extremely slow (executing listeners extremely many times). I quess that this is not your problem.

Title: J2EE - Session swap

Body:
Application server - JBoss AS 7.1.1

JDK6

J2EE 1.3

My web application is more than 10 years old and facing this session swap problem in my portal. Noticed
that swap happens mostly when many concurrent users accessing the portal and underlying windows server is busy
(more than 90% CPU usage)

To analyse this issue, I logged customer data (customer id, ip address, jsession id) to a table and found
that customer having unique jsession id initially has his data and all of a sudden for the same jsession id and
ip address receiving different customer data.

```<code>customer1  123.123.12.123   jsessionid123    11:10:02
customer2  123.123.12.123   jsessionid123    11:10:04
</code>```

ip address (123.123.12.123) having jsession id (jsessionid123) somehow gets customer2 data

Any order placed by customer1 in ip - 123.123.12.123 gets created for customer2, I confirmed this by
calling customer2 and they confirmed that they didn't place the order. customer1 won't realise he placed
order for customer2 - all the data gets changed, like basket items, customer object, products etc.

Now I need to find a fix for this, but first I need to know which part of my code is creating this problem.

Do I have to use a stress test software? or any better mechanism to find out the problematic code?


问:
Should JavaScript and PHP objects be treated as different objects in an interaction diagram?
I'm drawing a communication diagram for an application where you can buy books. I'm using domain-driven design and have a 'shop' object, a 'cart' object, and a 'book' object.

My first communication diagram, for when the user first comes to the site, is straightforward. I generate all HTML (to show all books and an empty cart) back end with the help of PHP. I use an MVC pattern; so first I send a message to a 'controller' which creates a 'shop' with 'book's and an empty 'cart' before sending these to the view.

My second communication diagram is where I run into problem: It is about adding a book from the shop to the cart. I already have all the information I need to add the book to the 'cart' on the client side; since all book information is already in the shop. So when writing the communication diagram, should my first message, that is, AddBookToCart(bookId:int), be to a JavaScript object called 'shop' which gets the book info and send a message 'AddBookToCart(bookinfo:object) to 'cart' which in turn update the page?

I have never done communication diagrams with JavaScript in mind before, so I'm really confused about how to deal with the front end.

(I have been searching for over five hours, but I didn't find anything on this topic. It's like it's not even an issue to people. Am I viewing this problem completely wrong? Otherwise any resources, or even search terms to use to learn about how to model (and code) these kind of things would be much appreciated)

答:
Given the uncertainty of my answer, I make it a community wiki. Feel free to edit it.

It depends on the abstraction level you use. One way is to be language-agnostic. Here's an example of a sequence diagram:

Source: UML Sequence Diagrams Examples

As you can see, the diagram encompasses both client-side and server-side. Applying the same to a communication diagram would be harder, since communication diagrams have generally a smaller scope, but it's still possible.

The major factor to take in account is what is the purpose of your communication diagram.

One possibility is to use a communication diagram to show the entire process. Such diagram may be language-agnostic and mix several parts of the system or layers within it.

This is suited well for an overall view of a system in a highly abstract way. It may be used, for example, to give a general idea to a new developer of some complicated stuff which happens between a client and a service, between JavaScript and server-side language or between a consumer and its API.

If your company has a single developer who does both client and server-side programming, then such diagram may be useful to him.

Another possibility is to use a communication diagram to show precise flow within a layer of a part of a system. Here, other parts and layers would be interpreted as black boxes which communicate through interfaces.

This is suited well for a detailed view of communications flow within a system. For example, a JavaScript developer cares about communications flow happening in the browser, but doesn't care about server-side stuff. In the same way, a developer of an API won't need to look at the communications diagram which explains how a client of the API is dealing with the different messages.

If your company has dedicated client-side programmers and dedicated server-side programmers, they would probably favor this sort of communication diagrams (which doesn't exclude that they should also have a good overall view of the whole system.)

In practice, I've never seen communication diagrams so general that they would encompass for example both client and server-side. I don't think it's wrong to do such diagrams, but it's not a common practice.

Edit: I talked with a colleague more experienced than I in UML; his suggestion is to create two communication diagrams, one for JavaScript, another one for server-side. Mixing both would make the diagram more complicate than it needs to be, and some people may not understand which step is happening where.

So unless you are sure that having a single diagram would benefit you, stick with separate diagrams that you can put side by side for an overall view.


问:
Which layer should order the columns shown to the user when using MVC?
Say you want to render a table with five columns, but you want the order of the columns to be different depending on some specific parameter. This would be very easy to accomplish if the model sets the order. The view can then simply use a loop and create the table accordingly.

However, unless I have misunderstood things, we want to let the view handle how things are rendered (although I guess there may a gray area involved here in terms of what the view "should decide how to render")? It also feels ugly to let the model set formatting / order, but maybe this is another thing I might have misunderstood?

If the view is supposed to deal with the order of the columns, what is a good way to accomplish it (read: having to use a lot of if-statements and other ugly code in the view)?

答:
Split (conceptualy) your View into ViewView and ViewModel. In view model you will have things like order of columns, number of rows on page, current page, whether you are in edit mode. Simply things that you need to store, but does not make sense to store them in model (different view will not use them).

In what form view model is stored depends on view. It can be in session scoped variable on server (in web application), in hidden field (in web application), on mobile device (in mobile application communicating with server, so model itself is on server), just in different class (in standalone desktop/mobile app).


问:
Should programmers help testers in designing tests?
How much should programmers help testers in designing tests?

I don't think they should help at all.  My worry is that if they help testers in designing tests for their own code, they'll 'infect' the testers with their own prejudices and blind spots about that code.

I feel that the requirements should be sufficient for giving the information needed for testers to create their tests.  If there is some part of the implementation that the programmers find worrisome, then I think it's their duty to implement unit tests to test that part or even run their own informal system tests to test that part.

Not everyone I know agrees with this though (and I understand some of their points to a certain extent).  What do others think about this?  Is this discussed in the literature anywhere?

答:
As a tester, I have no objection at all to programmers suggesting test cases (though that doesn't mean I'll stick to only those test cases), or describing implementation details.  Sometimes it can be really helpful to have someone say "I think this bit might be risky, I'd really like it if you tested this bit pretty thoroughly".  Knowing some of the implementation details helps me to apply years of experience to choose the tests I think most likely to fail.  Sometimes just a brief mention means a few tests suddenly zoom right up my priority list.

Does it taint me? I'm kinda tickled by the idea of programmers chivalrously striving to preserve my tester purity, but really - no, this is a myth.  More information usually triggers even more questions for me, not fewer.  I guess it's a mindset thing - I don't find bugs because I'm ignorant, I find issues because I'm a skeptical, untrusting type who just is too darn stubborn to wholly take anything on trust.  On every system I've tested, I've found that I find more issues, and more "interesting" ones, the more deeply I come to understand it.


问:
Why do so many languages treat numbers starting with 0 as octal?
I've read Where are octals useful? and it seems like octals are something that were once upon a time useful.

Many languages treat numbers preceding with a 0 as octal, so the literal 010 is actually 8. A few among these is JavaScript, Python (2.7), and Ruby.

But I don't really see why these languages need octal, especially when the more likely use of the notation is to denote a decimal number with a superfluous 0.

JavaScript is a client-side language, octal seems pretty useless. All three are pretty modern in other sense, and I don't think that there would be much code using octal notation that would be broken by removing this "feature".

So, my questions are:

Is there any point of these languages supporting octal literals?

If octal literals are necessary, why not use something like 0o10? Why copy an old notation that overrides a more useful use case?

答:
There is a value to consistency. If you can't reliably determine how a number is going to be translated you will have real problems using a value in different contexts.

It also means you don't have to write your own parser.  There is great value in using well tested library routines.

Also if you don't support the leading 0 syntax you don't have a simple way to write octal values.

While we don't depend as much on octal numbers as we once did, they are still of value.  While the same results can be obtained with hexadecimal numbers, in some contexts octal is easier to understand.

So far I have only seen one use for leading zeros in decimal numbers.  That is in the display and entry of fixed length decimal fields like identification numbers.  It has been years since I have seen fields like that with a leading zero.  While this reduces the available values by 10%, it eliminates the problem that users often leave off the leading zeros when entering them.


问:
Intentional misspellings to avoid reserved words
I often see code that include intentional misspellings of common words that for better or worse have become reserved words:

klass or clazz for class: Class clazz = ThisClass.class

kount for count in SQL: count(*) AS kount

Personally I find this decreases readability.  In my own practice I haven't found too many cases where a better name couldn't have been used — itemClass or recordTotal.

An example from the JavaDocs for Class show this in the parameters:

```<code> public <U> Class<? extends U> asSubclass(Class<U> clazz)
</code>```

Does this show a reasonable use case?

答:
Intentional misspellings to avoid reserved words is a bad idea.

Misspellings are hard to distinguish from the correct spelling, therefore they make the code harder to read.

Misspellings are hard to remember, so that several inconsistent misspellings are likely to compete within code, which makes code harder to write and harder to read.

Reserved words refer to the language being used to solve the problem, not to the problem itself. A variable name should point to a concept related to the problem.

It is therefore better to pick an alternative, descriptive name, or if no satisfying alternative exists, to qualify the reserved word as in:

```<code>public static Method findBenchmarkMethod(BenchmarkRecord benchmark) {
    Class<?> benchmarkedClass = ClassUtils.loadClass(benchmark.generatedClass());
    return findBenchmarkMethod(benchmarkedClass, benchmark.generatedMethod());
}
</code>```

Body:
Intentional misspellings to avoid reserved words is a bad idea.

Misspellings are hard to distinguish from the correct spelling, therefore they make the code harder to read.

Misspellings are hard to remember, so that several inconsistent misspellings are likely to compete within code, which makes code harder to write and harder to read.

Reserved words refer to the language being used to solve the problem, not to the problem itself. A variable name should point to a concept related to the problem.

It is therefore better to pick an alternative, descriptive name, or if no satisfying alternative exists, to qualify the reserved word as in:

public static Method findBenchmarkMethod(BenchmarkRecord benchmark) {
    Class<?> benchmarkedClass = ClassUtils.loadClass(benchmark.generatedClass());
    return findBenchmarkMethod(benchmarkedClass, benchmark.generatedMethod());
}


答:
This is somewhat anecdotal, but I usually reserve constructors for state essential for the object to be complete and usable.  Barring any setter-injection, once the constructor is run, my object should be able to perform the tasks required of it.

Anything that can be deferred, I leave out of the constructor (preparing output values, etc).  With this approach, I feel not using constructors for anything but dependency injection makes sense.

This also has the added benefit of hard-wiring your mental design process to not do anything prematurely.  You won't initialize or perform logic that may never end up being used because at best all you're doing is basic setup for the work ahead.

Title: Can we live without constructors?


答:
Blind copying of C, just like ratchet freak said in his comment

The vast majority of "language designers" these days have never seen anything but C and its copies (C++, Java, Javascript, PHP, and probably a few dozen others I never heard of).  They have never touched FORTRAN, COBOL, LISP, PASCAL, Oberon, FORTH, APL, BLISS, SNOBOL, to name a few.

Once upon a time, exposure to multiple programming languages was MANDATORY in the computer science curriculum, and that didn't include counting C, C++, and Java as three separate languages.

Octal was used in the earlier days because it made reading binary instruction values easier.  The PDP-11, for example, BASICALLY had a 4-bit opcode, 2 3-bit register numbers, and 2 3-bit access mechanism fields.  Expressing the word in octal made everything obvious.

Because of C's early association with the PDP-11, octal notation was included, since it was very common on PDP-11s at the time.

Other machines had instruction sets that didn't map well to hex.  The CDC 6600 had a 60-bit word, with each word containing typically 2 to 4 instructions.  Each instruction was 15 or 30 bits.

As for reading and writing values, this is a solved problem, with a well-known industry best practice, at least in the defense industry.  You DOCUMENT your file formats.  There is no ambiguity when the format is documented, because the document TELLS you whether you are looking at a decimal number, a hex number, or an octal number.

Also note: If your I/O system defaults to leading 0 meaning octal, you have to use some other convention on your output to denote hexadecimal values.  This is not necessarily a win.

In my personal opinion, Ada did it best:  2#10010010#, 8#222#, 16#92#, and 146 all represent the same value.  (That will probably get me at least three downvotes right there, just for mentioning Ada.)

Title: Why do so many languages treat numbers starting with 0 as octal?

Body:
I've read Where are octals useful? and it seems like octals are something that were once upon a time useful.

Many languages treat numbers preceding with a 0 as octal, so the literal 010 is actually 8. A few among these is JavaScript, Python (2.7), and Ruby.

But I don't really see why these languages need octal, especially when the more likely use of the notation is to denote a decimal number with a superfluous 0.

JavaScript is a client-side language, octal seems pretty useless. All three are pretty modern in other sense, and I don't think that there would be much code using octal notation that would be broken by removing this "feature".

So, my questions are:

Is there any point of these languages supporting octal literals?

If octal literals are necessary, why not use something like 0o10? Why copy an old notation that overrides a more useful use case?


答:
They get it from C. Why copy? Because the base implementation of all 3 is in C. Python's default implementation is CPython. Ruby was originally built in C as well. Javascript is the most interesting case here. It's run in the browser. Care to guess what the first web browser was written in?

So why would all three of these languages be implemented in C? Because they all originate on UNIX systems. So it's a case of convention being driven by ecosystem. Perl does this as well. Lua likely would if Lua used integers rather than doubles.

So it's a question of the environment of these languages being written in C so they take their conventions from C. A good supporting corollary is Visual Basic which uses &O instead. As far as needing it, it seems to be more of a leaky abstraction turned convention than anything else.


问:
What are the most important concepts to understand for "fluency in developer English"?
In April, I'm going to be giving a talk called **English 2.0 - Understanding the Language of Developers" to a group of English teachers. The purpose is in two hours to give them a quick background in key concepts so that they can better understand developer blogs and podcasts and are able to ask better questions when talking to developers.

What do you think are the most important concepts to understand, concepts that developers take for granted but the general public is not familiar with? Here are a few ideas:

version control

abstractions

pub/sub

push vs. pull

debugging

modularity

three-tier architecture

class/object

"spaghetti code" vs. OOP

exception throwing

crowd sourcing

refactoring

the cloud

DRY - don't repeat yourself

client/server

unit testing

designer/developer

答: You might want to discuss the precision of language. I sometimes joke that software development necessarily turns us into pedants, not because we enjoy it, but because when you're programming you very often need to be precise. This then leads into the large amount of jargon, because domain-specific language allows you to be both quick and precise.</p>


问:
What algorithm should I use to find the shortest path in this graph
I have a problem about the calculation of shortest paths on an unweighted and undirected graph.

Which algorithm I use to calculate the shortest path between a node A and node B that passing through a node C on an undirected and unweighted graph?

答:
You can split the solution into 2 steps, first find a path from A to C, and then find one from C to B and concatenate them.

To find the individual paths you'll want to use Dijkstra (given that unweighted likely means there is no heuristic to get for A*).


答:
I'd love it if you'd address non-standard uses of punctuation typical with some programmers, like "I refuse to put the comma in a string literal quotation when the source did not use a comma", <----- said Brian.

The use of brackets, [], and mustaches (or braces, for the less hip crowd) {} could be similarly given treatment.

3- Recursion might be fun to point out. See point 3.

For a fun break, it might be enjoyable to point out some purely cultural inspirations that are common to much of the developer community, from raptors (thanks, XKCD), to Monty Python, to a pointer back to some of the early common grounds that founded the modern community: IRC, bulletin boards/forums, and Usenet.

Title: What are the most important concepts to understand for "fluency in developer English"?

Body:
In April, I'm going to be giving a talk called **English 2.0 - Understanding the Language of Developers" to a group of English teachers. The purpose is in two hours to give them a quick background in key concepts so that they can better understand developer blogs and podcasts and are able to ask better questions when talking to developers.

What do you think are the most important concepts to understand, concepts that developers take for granted but the general public is not familiar with? Here are a few ideas:

version control

abstractions

pub/sub

push vs. pull

debugging

modularity

three-tier architecture

class/object

"spaghetti code" vs. OOP

exception throwing

crowd sourcing

refactoring

the cloud

DRY - don't repeat yourself

client/server

unit testing

designer/developer


问:
How has an increase in the complexity of systems affected successive generations of programmers?
As a "new" programmer (I first wrote a line of code in 2009), I've noticed it's relatively easy to create a program that exhibits quite complex elements today with things like .NET framework for example. Creating a visual interface, or sorting a list can be done with very few commands now.

When I was learning to program, I was also learning computing theory in parallel. Things like sorting algorithms, principles of how hardware operates together, boolean algebra, and finite-state machines. But I noticed if I ever wanted to test out some very basic principle I'd learned in theory, it was always a lot more difficult to get started because so much technology is obscured by things like libraries, frameworks, and the OS.

Making a memory-efficient program was required 40/50 years ago because there wasn't enough memory and it was expensive, so most programmers paid close attention to data types and how the instructions would be handled by the processor. Nowadays, some might argue that due to increased processing power and available memory, those concerns aren't a priority.

My question is if older programmers see innovations like these as a godsend or an additional layer to abstract through, and why might they think so? And do younger programmers benefit more learning low-level programming BEFORE exploring the realms of expansive libraries? If so then why?

答:
I feel that high level programming has many advantages and is an essential part of a programming language. One of the reasons why Java become successful was that it has a comprehensive library. You achieve more with less code - just call a predefined function.

We can now distinguish programming language users from programming language writers (compiler writers). We leave the optimisations to compiler writers. We focus more on maintainability, reuse, etc


答:
I think both testing and development are collaborative efforts, so of course (IMO), devs should give test ideas to testers. I don't think it infects them or taints testers at all. The tester, of course, should enhance those tests with many other testing approaches.

I'm also a big fan of testers helping developers - I've brainstormed design ideas with developers and paired with them to fix bugs (and pointed out the bugs and suggested fixes) many times in my career, and don't think I've ever tainted a developer with tester cooties.

If you don't see it as a collaborative effort, you'll just have code "thrown over the wall" from dev to test...and you'll end up with lower quality. That's the truth in my world, but (of course), ymmv.

Title: Should programmers help testers in designing tests?

Body:
How much should programmers help testers in designing tests?

I don't think they should help at all.  My worry is that if they help testers in designing tests for their own code, they'll 'infect' the testers with their own prejudices and blind spots about that code.

I feel that the requirements should be sufficient for giving the information needed for testers to create their tests.  If there is some part of the implementation that the programmers find worrisome, then I think it's their duty to implement unit tests to test that part or even run their own informal system tests to test that part.

Not everyone I know agrees with this though (and I understand some of their points to a certain extent).  What do others think about this?  Is this discussed in the literature anywhere?


答:
High-level abstraction is essential to achieving ongoing progress in computing.

Why?  Because humans can only hold so much knowledge in their heads at any given moment.  Modern, large scale systems are only possible today because you can leverage such abstractions.  Without those abstractions, software systems would simply collapse under their own weight.

Every time you write a method, you're creating an abstraction. You're creating a bit of functionality that's hidden behind a method call.  Why do you write them?  Because you can test the method, prove it works, and then invoke that functionality any time you want just by making the method call, and you don't have to think anymore about the code that's inside that method.

In the early days of computing, we used machine language.  We wrote very small, bare metal programs with intimate knowledge of the hardware we were writing them for.  It was a painstaking process.  There were no debuggers; your program usually either worked, or it crashed.  There was no GUI; everything was either command-line or batch process.  The code you wrote would only work on that particular machine; it would not work on a machine with a different processor or operating system.

So we wrote high-level languages to abstract all of that detail away.  We created virtual machines so that our programs could be portable to other machines.  We created garbage collection so that programmers wouldn't have to be so diligent about managing memory, which eliminated a whole class of difficult bugs.  We added bounds checking to our languages so that hackers couldn't exploit them with buffer overruns.  We invented Functional Programming so that we could reason about our programs in a different way, and rediscovered it recently to take better advantage of concurrency.

Does all this abstraction insulate you from the hardware?  Sure it does. Does living in a house instead of pitching a tent insulate you from nature?  Absolutely.  But everyone knows why they live in a house instead of a tent, and building a house is a completely different ball game than pitching a tent.

Yet, you can still pitch a tent when it is necessary to do that, and in programming, you can (if you're so inclined) still drop down to a level closer to the hardware to get performance or memory benefits that you might not otherwise achieve in your high-level language.

Can you abstract too much?  "Overtake the plumbing," as Scotty would say?  Of course you can.  Writing good API's is hard.  Writing good API's that correctly and comprehensively embody the problem domain, in a way that is intuitive and discoverable, is even harder.  Piling on new layers of software isn't always the best solution.  Software Design Patterns have, to some degree, made this situation worse, because inexperienced developers sometimes reach for them when a sharper, leaner tool is more appropriate.

Title: How has an increase in the complexity of systems affected successive generations of programmers?

Body:
As a "new" programmer (I first wrote a line of code in 2009), I've noticed it's relatively easy to create a program that exhibits quite complex elements today with things like .NET framework for example. Creating a visual interface, or sorting a list can be done with very few commands now.

When I was learning to program, I was also learning computing theory in parallel. Things like sorting algorithms, principles of how hardware operates together, boolean algebra, and finite-state machines. But I noticed if I ever wanted to test out some very basic principle I'd learned in theory, it was always a lot more difficult to get started because so much technology is obscured by things like libraries, frameworks, and the OS.

Making a memory-efficient program was required 40/50 years ago because there wasn't enough memory and it was expensive, so most programmers paid close attention to data types and how the instructions would be handled by the processor. Nowadays, some might argue that due to increased processing power and available memory, those concerns aren't a priority.

My question is if older programmers see innovations like these as a godsend or an additional layer to abstract through, and why might they think so? And do younger programmers benefit more learning low-level programming BEFORE exploring the realms of expansive libraries? If so then why?


答:
it just isn't necessary because of the increased amount of processing power and memory available.

Having cheap memory, enormous disks and fast processors isn't the only thing that has freed people from the need to obsess over every byte and cycle. Compilers are now far, far better than humans at producing highly optimized code when it matters.

Moreover, let's not forget what we're actually trying to optimize for, which is value produced for a given cost. Programmers are way more expensive than machines. Anything we do that makes programmers produce working, correct, robust, fully-featured programs faster and cheaper leads to the creation of more value in the world.

My question though is how do people feel about this "hiding" of lower-level elements. Do you older programmers see it as a godsend or an unnecessary layer to get through?

It is absolutely necessary to get any work done. I write code analyzers for a living; if I had to worry about register allocation or processor scheduling or any of those millions of other details then I would not be spending my time fixing bugs, reviewing performance reports, adding features, and so on.

All of programming is about abstracting away the layer below you in order to make a more valuable layer on top of it. If you do a "layer cake diagram" showing all the subsystems and how they are built on each other you'll find that there are literally dozens of layers between the hardware and the user experience. I think in the Windows layer cake diagram there's something like 60 levels of necessary subsystems between the raw hardware and the ability to execute "hello world" in C#.

Do you think younger programmers would benefit more learning low-level programming BEFORE exploring the realms of expansive libraries?

You put emphasis on BEFORE, so I must answer your question in the negative. I'm helping a 12 year old friend learn to program right now and you'd better believe I'm starting them in Processing.js and not x86 assembler. If you start a young programmer in something like Processing.js they'll be writing their own shoot-em-up games in about eight hours. If you start them in assembler they'll be multiplying three numbers together in about eight hours. Which do you think is more likely to engage the interest of a younger programmer?

Now if the question is "do programmers who understand layer n of the cake benefit from understanding layer n - 1?" the answer is yes, but that's independent of age or experience; it's always the case that you can improve your higher level programming by understanding better the underlying abstractions.


问:
Reason for a reflection error
I’m working on an Eclipse plug-in project.

Using this plug-in, users can create Eclipse Java projects with some specificities. For example, they can add Java classes’ names which will be saved in a file. These Java classes can be created on the src of the project or used from a jar file which must be added to the project classpath. In this case, the plug-in will use reflection to get some data from each class.

There are two different test cases that give the same error because the plug-in can't find the class to instantiate:

A jar contain a class having a name saved in the file is not added to the project classpath. So in this case the classpath is incomplete.

The user of the plug-in updated a jar in which its old version of the jar contained the named class, but the new version of jar does not (which could happen if class was deleted from the new version of the jar). In this case, the plug-in will not find the class but the classpath is complete.

So The plug-in must differentiate between the two test cases when it fails finding the class name using reflection.

How that can be done?

答:
The only way I see for you to achieve this is to force the user to declare among the class name if the class is part of the project or part of the classpath and use that info to give the error if the reflexion fails to find the class.

I don't believe there is any other way to do this since the project it self will be part of the "classpath" and the classloader treats every class as equal

Title: Reason for a reflection error


答:
I often see code that include intentional misspellings of common words that for better or worse have become reserved words:

klass or clazz for class: Class clazz = ThisClass.class

kount for count in SQL: count(*) AS kount

Personally I find this decreases readability. In my own practice I haven't found too many cases where a better name couldn't have been used — itemClass or recordTotal.

However, it's so common that I can't help but wonder if I'm the only one? Anyone have any advice or even better, quoted recommendations from well-respected programmers on this practice?

For local variables and formal arguments, it just doesn't matter.

Any name is fine as long as it is not intentionally misleading or annoyingly distracting.  In your example:

```<code>public static Method findBenchmarkMethod(BenchmarkRecord benchmark) {
    Class<?> clazz = ClassUtils.loadClass(benchmark.generatedClass());
    return findBenchmarkMethod(clazz, benchmark.generatedMethod());
}
</code>```

it doesn't matter whether the single local variable is "clazz" or "klass" or "cls" or simply "c".  I would probably just inline the expression:

```<code>return findBenchmarkMethod(ClassUtils.loadClass(benchmark.generatedClass()),
                           benchmark.generatedMethod());
</code>```

The length of a variable name should be related to the variable's scope.  For local variables in short methods (and they should all be short), very short names are fine.

Title: Intentional misspellings to avoid reserved words

Body:
I often see code that include intentional misspellings of common words that for better or worse have become reserved words:

klass or clazz for class: Class clazz = ThisClass.class

kount for count in SQL: count(*) AS kount

Personally I find this decreases readability.  In my own practice I haven't found too many cases where a better name couldn't have been used — itemClass or recordTotal.

An example from the JavaDocs for Class show this in the parameters:

```<code> public <U> Class<? extends U> asSubclass(Class<U> clazz)
</code>```

Does this show a reasonable use case?

Body:
I often see code that include intentional misspellings of common words that for better or worse have become reserved words:

klass or clazz for class: Class clazz = ThisClass.class

kount for count in SQL: count(*) AS kount

Personally I find this decreases readability. In my own practice I haven't found too many cases where a better name couldn't have been used — itemClass or recordTotal.

However, it's so common that I can't help but wonder if I'm the only one? Anyone have any advice or even better, quoted recommendations from well-respected programmers on this practice?

For local variables and formal arguments, it just doesn't matter.

Any name is fine as long as it is not intentionally misleading or annoyingly distracting.  In your example:

public static Method findBenchmarkMethod(BenchmarkRecord benchmark) {
    Class<?> clazz = ClassUtils.loadClass(benchmark.generatedClass());
    return findBenchmarkMethod(clazz, benchmark.generatedMethod());
}

it doesn't matter whether the single local variable is "clazz" or "klass" or "cls" or simply "c".  I would probably just inline the expression:

return findBenchmarkMethod(ClassUtils.loadClass(benchmark.generatedClass()),
                           benchmark.generatedMethod());

The length of a variable name should be related to the variable's scope.  For local variables in short methods (and they should all be short), very short names are fine.


问:
Best techniques for an AI of a card game
I’m trying to develop an AI for a card game and I’m a bit stuck about the technique/algorithm I should use. Here are a few assumptions about the game:

After the cards are distributed to players, there is no randomness. I mean here that every player can choose which cards he plays but no random process occurs as when distributing the cards at the beginning of the game.

There is restriction about the cards which can be played when a card was already played.

The player which wins the trick, plays then first. E.g. Player 1 plays a card, Player 2 plays a card and wins. Then Player 2 plays a card and then Player 1 plays.

I know a lot of hints/rules (e.g. if I know the player has cards A, B, C then I should play D) which helps me to win to the game. Thus I first wanted to use a Bayesian network to describes those rules. The problem is that I don’t know any probabilities to assign, but I could compute an heuristic using the history of played games (against a human). Second problems, it is very likely that I don’t know all rules and that there is some implicit rules which are needed by the AI to find the optimal play.

I’m unsure if this would be a good way to develop an AI for such a card game?

I am also wondering if there is others techniques which would best fit to the problem. For instance, I had a look at minimax (maybe with a pruning algorithm), but would be a good option for this problem? I’m quite unsure since the most important plays are at the beginning of the game when there is the highest unknown parameters (most of cards are not played yet).

答:
A case of recent personal experience:

I've been working on a card game myself (Bisca, a 2-player Portuguese game), and I've been getting good results using Monte Carlo methods, specially using the recent Information Set Monte Carlo Tree Search algorithm (ISMCTS, described with example source code in Python at http://www.aifactory.co.uk/newsletter/2013_01_reduce_burden.htm).

It plays reasonably well, with the ocasional incorrect move, just with the knowledge of game rules. I'm currently trying to grok it, to be able to enhance it, as according to the information I've read about it (and its "parent" MCTS) it's possible to enhance its game play with heuristics (http://www.orangehelicopter.com/ed/papers/aiide13.pdf) and opponent card inference.


答:
I had ideas on this subject, and I put them into a book 20 years ago.
It's long out of print, but you can still get used copies on Amazon.

One simple answer to your question is as old as Aristotle: Nature abhors a vacuum.
As much as machines have gotten faster and bigger, software has gotten slower and bigger.

To be more constructive, what I proposed was that information theory, and its direct relevance to software, be part of computer science education.
It is only taught now, if at all, in a very tangential way.

For example, the big-O behavior of algorithms can be very neatly and intuitively understood if you think of a program as a Shannon-type information channel, with input symbols, output symbols, noise, redundancy, and bandwidth.

On the other hand, the productivity of a programmer can be understood in similar terms using Kolmogorov information theory.
The input is a symbolic conceptual structure in your head, and the output is the program text that comes out through your fingertips.
The programming process is the channel between the two.
When noise enters the process, it creates inconsistent programs (bugs).
If the output program text has sufficient redundancy, it can permit the bugs to be caught and corrected (error detection and correction).
However, if it is too redundant it is too large, and its very size, combined with the error rate, causes the introduction of bugs.
As a result of this reasoning, I spent a good part of the book showing how to treat programming as a process of language design, with the goal of being able to define the domain-specific-languages appropriate for a need.
We do pay lip service to domain-specific-languages in CS education but, again, it is tangential.

Building languages is easy.
Every time you define a function, class, or variable, you are adding vocabulary to the language you started with, creating a new language with which to work.
What is not generally appreciated is that the goal should be to make the new language a closer match to the conceptual structure of the problem.
If this is done, then it has the effect of shortening the code and making it less buggy simply because, ideally, there is a 1-1 mapping between concepts and code.
If the mapping is 1-1, you might make a mistake and code a concept incorrectly as a different concept,
but the program will never crash, which is what happens when it encodes no consistent requirement.

We are not getting this.
For all our brave talk about software system design, the ratio of code to requirements is getting bigger, much bigger.

It's true, we have very useful libraries.
However, I think we should be very circumspect about abstraction.
We should not assume if B builds on A and that is good,
that if C builds on B it is even better.
I call it the "princess and the pea" phenomenon.
Piling layers on top of something troublesome does not necessarily fix it.

To terminate a long post, I've developed a style of programming (which sometimes gets me in trouble) where

Invention is not a bad thing. It is a good thing, as it is in other branches of engineering. Sure it may be creating a learning curve for others, but if the overall result is better productivity, it is worthwhile.

Haiku-style minimalist code. That especially goes for data structure design. In my experience, the biggest problem in software these days is bloated data structure.


问:
How can I share data across several websites?
I am trying to develop a simple system for sharing data across several websites. Most of them are developed in PHP while some are developed in Wordpress/Drupal. Redundant information is spread across several websites and this has caused a problem where we have to update the information across several websites separately.

I am trying to provide a solution where even static pages can get shared data. Here is my proposed architecture:

I am doing this for an academic institution. The data varies from simple fee structures to academic policies. For example consider academic costs.

Academic costs -> ug, graduate, pharmacy... each of the departments will have a fees structure categorized by off campus, on campus, commuter.

```<code>"Undergraduate": {
    "metaid": "0770",
    "Offcampus": {
      "FeesItems": {
        "comprehensive": {
          "label": "Comprehensive Fees",
          "value": "2,141"
      }
    }
  }
}
</code>```

For front end using mustache, they just have to include the js and use something like below to get values,

```<code><td>{{Undergraduate.Offcampus.FeesItems.comprehensive.label}} </td>
<td>{{Undergraduate.Offcampus.FeesItems.comprehensive.value}}</td>
</code>```

My questions:

Is this design scalable?

How to give the data owners the ability to edit the data?

How to store the data in SQL?

答:
Is this design scalable?

All designs are potentially scalable. An old (and outdated) rule is to add more hardware resources, and that's it.

Unfortunately, this rule does not work very well in the real world (the one where we pay for the resources that we make available to run the software, even if in the clouds).

In this case, the design of the software is absolutely scalable but maybe the question is: is this sustainable?

How to prevent stress

In the context of a data provider (public or through authentication), it is perhaps more prudent to include a cache system. To avoid a situation of high load on the database, it would be appropriate to add a publisher in your design.

I'm assuming that your "JSON Builder", is a component that interprets the request of the customer, reads data from the database, and finally sends the response.

If this is so, it is easy to understand that when you need to scale the system, the first to ask for resources, will be the database.

Distribute

Adding a cache system, probably the new resources will be allocated to publishers. A publisher can be a system of disconnected data, which receives (or fetches) information on the status of the data it holds.

At this point, it is easy to consider a publisher as a "low cost host" separate from the system, distributed (perhaps even through CDN), which uses a mechanism for continuous update its data (but at low cost for the database), to provide fresh data to the client.

Mechanism: Maybe a simple hash system, or an even simpler "last modified date"

How to give the data owners the ability to edit the data?

The question seems to have a simple answer. They will need an interface.

How to store the data in sql?

The comments are right, maybe it's offtopic