问:
Best design to create dynamic set of questions(controls ) in silverlight web application?
I have around 15 templates (this will grow) and each template will have around 10-15 questions. Each question can have answers in different format like text box, list box, dropdown, radio button etc.

I need to show one template in a page, at a time based on the input I am getting.

What would be the best design approach for this?

Put questions data in database and Create dynamic control?

Putting in xml and display using xslt?

Creating static set of templates?

Or any other approach? I don't have too much time to do this.

I am going to use Silverlight for this.

答:
You should use a database, and depending on the complexity of your questionnaires will determine how "wild" you need to go into self-referencing structures and such. I'm assuming you'll be using a Relational DB.

Considerations:

```<code> 1). Will the questions be unique per "questionaire" or re-used?
 2). Will each answer only belong to one Question or re-used across questionnaires?
 3). Will they ever want each answer to lead to a different "next" question?
</code>```

Depending on the above will determine the "object" model, whether in code or as a database object.

Why use a database?

```<code> 1). Because you'll be able to slap an admin tool on it at some point .
 2). You can store the answers to the questions "relationally" to the questions.
</code>```

Now for the "types" of answers: textboxes, inputs, radios, checkboxes etc..

You're going to have to store an answer "type" (textbox, radio, input) on each possible answer that is stored in the DB (or XML). like a lookup table, or some other defined value indicating the control type to render.

Then in the client code, you're going to have to "resolve" them on the display side of things using a switch, or dynamic control building mechanism.

Now the tricky part is going to be when a "list of options" is required, like for a drop down. You'll have to have an "Answer with Associated Answers" type of reference, so you can pull the associated answers and if type "dropdown". However, you'd probably be better off rendering the "drop down" type answers as a "radio" button list since they provide the same "choose one of a set" / multiple choice type capability.

Here's some general direction based on my experience:

you'll need Structures something like: "Questionaire", "Questions", "Answers", and a "UserAnswers". then maybe a "JoinQuestionaireToQuestions" and a "JoinQuestionsToAnswers" if you want to get all reusable / fancy.

Then you'll look up the Quetsionaire you need to use, get all the questions and the answers for each question. And render them on the page using the dynamic control rendering mechanism you created.

Then either as they complete the Questionaire you store each response in the DB, or save each answer in the client and do one insert after they complete the form. You just keep the value of the input or form field and save that data as the answer "value".

Funny enough.. I recently brought an old project back to life that does something like this.. you can check out the javascript (built this 5+ years ago) on the page and see how i did it (it's not for the faint of heart) and it's more of a proof of concept, but it's all database driven and dynamically generated. Seriously just brought this back to life last week..

I put it under the URL: question commando , lol.. click on "discovery script" to start the Q and A. In my scenario, each answer can lead to a different question.

Anyhow, hope any of this helps...

Body:
You should use a database, and depending on the complexity of your questionnaires will determine how "wild" you need to go into self-referencing structures and such. I'm assuming you'll be using a Relational DB.

Considerations:

 1). Will the questions be unique per "questionaire" or re-used?
 2). Will each answer only belong to one Question or re-used across questionnaires?
 3). Will they ever want each answer to lead to a different "next" question?

Depending on the above will determine the "object" model, whether in code or as a database object.

Why use a database?

 1). Because you'll be able to slap an admin tool on it at some point .
 2). You can store the answers to the questions "relationally" to the questions.

Now for the "types" of answers: textboxes, inputs, radios, checkboxes etc..

You're going to have to store an answer "type" (textbox, radio, input) on each possible answer that is stored in the DB (or XML). like a lookup table, or some other defined value indicating the control type to render.

Then in the client code, you're going to have to "resolve" them on the display side of things using a switch, or dynamic control building mechanism.

Now the tricky part is going to be when a "list of options" is required, like for a drop down. You'll have to have an "Answer with Associated Answers" type of reference, so you can pull the associated answers and if type "dropdown". However, you'd probably be better off rendering the "drop down" type answers as a "radio" button list since they provide the same "choose one of a set" / multiple choice type capability.

Here's some general direction based on my experience:

you'll need Structures something like: "Questionaire", "Questions", "Answers", and a "UserAnswers". then maybe a "JoinQuestionaireToQuestions" and a "JoinQuestionsToAnswers" if you want to get all reusable / fancy.

Then you'll look up the Quetsionaire you need to use, get all the questions and the answers for each question. And render them on the page using the dynamic control rendering mechanism you created.

Then either as they complete the Questionaire you store each response in the DB, or save each answer in the client and do one insert after they complete the form. You just keep the value of the input or form field and save that data as the answer "value".

Funny enough.. I recently brought an old project back to life that does something like this.. you can check out the javascript (built this 5+ years ago) on the page and see how i did it (it's not for the faint of heart) and it's more of a proof of concept, but it's all database driven and dynamically generated. Seriously just brought this back to life last week..

I put it under the URL: question commando , lol.. click on "discovery script" to start the Q and A. In my scenario, each answer can lead to a different question.

Anyhow, hope any of this helps...


问:
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 found a fix for this problem. In my case, the in-house framework got the below code which caused the problem,

```<code>        ...
        req.setAttribute(key, value); /* This code gets executed for both REQUEST & SESSION */
        if (scope == Sp.SESSION) {
            req.getSession().setAttribute(key, value);
            ...
</code>```

I noticed somehow the code maps session objects to incorrect jsessionid, so I tried the below code,

```<code>        ...
        if (scope == Sp.REQUEST) { /* Added this check */
            req.setAttribute(key, value);
        }
        if (scope == Sp.SESSION) {
            req.getSession().setAttribute(key, value);
            ...
</code>```

It's nearly a year after this fix, and the swap didn't happen at all. So I'm confident this code fix solved the swap problem.

ContentLicense: CC BY-SA 3.0

Title: J2EE - Session swap

Body:
I found a fix for this problem. In my case, the in-house framework got the below code which caused the problem,

        ...
        req.setAttribute(key, value); /* This code gets executed for both REQUEST & SESSION */
        if (scope == Sp.SESSION) {
            req.getSession().setAttribute(key, value);
            ...

I noticed somehow the code maps session objects to incorrect jsessionid, so I tried the below code,

        ...
        if (scope == Sp.REQUEST) { /* Added this check */
            req.setAttribute(key, value);
        }
        if (scope == Sp.SESSION) {
            req.getSession().setAttribute(key, value);
            ...

It's nearly a year after this fix, and the swap didn't happen at all. So I'm confident this code fix solved the swap problem.


问:
What would be a good approach to generate a tree of folders?
Say I have an array of strings, like this:

var folders = new[]
{
    "Foo",
    "Bar",
    "Foo\Bar"
    "Foo\Bar\Baz"
};
```

<p>And that I have an object that represents a folder - something like this:</p>

<pre class="lang-cs prettyprint-override"><code>class Folder
{
    private readonly string _name;
    private readonly IEnumerable<Folder> _folders;

    public Folder(string name, IEnumerable<Folder> folders)
    {
        _name = name;
        _folders = folders;
    }

    public string Name { get { return _name; } }
    public IEnumerable<Folder> Folders { get { return _folders; } }
}
</code>```

What would be a good way to end up with an object structure like this?

```<code>- Folder {Name:Foo}
  - Folder {Name:Bar}
    - Folder {Name:Baz}
- Folder {Name:Bar}
</code>```

I'm thinking this in terms of splitting the strings on the delimiter and then grouping... and I'm thinking this wrong, I simply don't have an approach to get there, it's not going anywhere. I get the gut-feeling that I need to involve recursion somehow, but I don't see where to fit that in, I'm stuck.

The example code above is C#, but I don't need actual code, just some pseudo-code, or a line of thought, a little clue.

...I hope it's in-scope?

答:
If you look at how the file system handles folder within their structure, there is one vital difference making stuff easier for traversing and that is keeping track of the parent as well as the folders (and files).

In your case this means that you should keep track of the parent of any given Folder, and make a decision regarding the top level to either have an empty top folder, or let the folder at the top level have null as parent folder, thusly allowing the folder to be at the same level.

This means you need a constructor taking up to three parameters:

name – The name of current folder, should require a value always

parent – Link to the parent folder, preferably a weak reference to avoid strong circular reference which can throw of the garbage collectors. Can default to null

folders – List of sub-folders, or null to indicate no sub-folders, yet. Do however ensure that the constructor creates a suitable instantation of the list of folders. It can be empty, but it should be ready for adding new folders.

Regarding methods for this class, I would suggest at least the following:

GetOrCreate(folderName) – Searches through folder list, and if not found it creates a new folder with self/this as parent. Return this newly created Folder

Optionally AddPath(path) – Accepts a full path, which it splits into the folder components. Starting at the current level, do a GetOrCreate(), and change current level and repeat for next folder component.

GetFullPath() – Starting at current level prepend current level with all parent levels to give you the full path.

If not implementing the AddPath() as a separate method, you still need to do the following for the list of paths, and this could be a static method of your Folder() class:

define your top level, i.e. tree = new Folder("")

foreach path in paths:

current = tree

foreach component in split path

current = current.GetOrCreate(component, current.parent)

Hope this helps to get you started.


问:
C++ Virtual destructors used only when there are virtual functions
This is from Effective C++ (Meyers):

Classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors

I don't understand why non-polymorphic classes should not declare virtual destructors.

Assuming I have a parent class and a child class, with no virtual functions, and I have a parent-class-pointer to a child object: if I call delete on the parent-class-pointer, it will only call the parent destructor, even though I also want to call the child destructor.

答:
The keyword here is not designed

Classes not designed to be base classes or not designed to be used polymorphically

Virtual functions/destructors are not free: they cause performance overhead so you may not want to use them in all cases. However, deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in undefined behavior:

http://www.geeksforgeeks.org/g-fact-37/

So that's the trade off between performance and safety.

OwnerDisplayName: programmer


问:
Can I use an external Mustache template without Ajax?
I wrote up a site using Mustache to template it. Right now though, the template is embedded in the page, which defeats the purpose of using the template since I'll need to copy it to any other pages that need it.

I read that it's possible to store the template in an external page, then use Ajax to load the template when needed, but this is for a school project, and I'm not yet at the point where they want us using Ajax.

Is it possible to have the template externalized without the use of Ajax?

Ideally, I'd like to have the following setup:

```<code>...
PageUsingTemnplate.html
AnotherPageUsingTemplate.html
...
Template.html
</code>```

答:
You can use Partials

Partials begin with a greater than sign, like {{> box}}.

For example, this template and partial:

base.mustache:

```<code><h2>Names</h2>
{{#names}}
  {{> user}}
{{/names}}
</code>```

user.mustache:

```<code><strong>{{name}}</strong>
</code>```

Can be thought of as a single, expanded template:

```<code><h2>Names</h2>
{{#names}}
  <strong>{{name}}</strong>
{{/names}}
</code>```

Body:
You can use Partials

Partials begin with a greater than sign, like {{> box}}.

For example, this template and partial:

base.mustache:

<h2>Names</h2>
{{#names}}
  {{> user}}
{{/names}}

user.mustache:

<strong>{{name}}</strong>

Can be thought of as a single, expanded template:

<h2>Names</h2>
{{#names}}
  <strong>{{name}}</strong>
{{/names}}


问:
Is it good practice to have your C++/Qt functions always check all its arguments for null values?

Backstory

While developing with Qt Signal/Slots, I came across a few segmentation faults that had me puzzled as to what was causing it. Eventually I figured out that you could actually pass a slot function without providing it any of its arguments, which of course would cause a Segmentation Fault if the argument was used.

To avoid this pitfall, I am getting into the habit of checking all my arguments to make sure they are not NULL:

```<code>void MyClass::setMyString(QString input)
{
    if (input.isNull()) {
        qDebug() << "Error: setMyString() received NULL argument";
        return;
    }

    m_MyString = input;
    emit myStringChanged();
}
</code>```

I'm thinking I ought to do this with all my functions from now on. Part of the reasoning is that I figure that it can not hurt to do this, and that if I or someone else ever needs to re-factor my code, it is less likely they will omit a necessary null value check.

Questions:

Is this an acceptable style in all or most circumstances?

Should I be introducing a runtime error, halting the program, instead of simply returning the function?

Does this style of coding improve security?

Does this style of coding improve stability?

Are there any performance considerations, to the extent that checking for null values may take longer depending on the type?

Beyond c++ and Qt, what other languages benefit from this style?

Are there any significant drawbacks worth considering?

答:
As I commented, yes you should usually check against nullptr and always document if a public function accepts a null pointer or not (that it, document a function as accepting a null pointer, or as requiring a non-null valid pointer).

Checking against a nullptr is -on most current C++11 implementations- very quick: dereferencing a pointer might make a cache miss (always slow), but comparing it against 0 is a fast arithmetic operation (nearly free).

Use assert if a pointer should always be null and valid.

Use an if to handle the nullptr case if it is genuinely possible at runtime.

Use C++ references to convey that the address is always valid. That is, if you have void foo(int*) and you know that the address is never null and always valid, code a void foo(int&) function instead.

Compilers are permitted to optimize the null pointer test after you have dereferenced it:

```<code> void foo(struct bar_st*p) {
   int x = p->somefield;
   if (!p) return; /// test can be removed by optimization
</code>```

Body:
As I commented, yes you should usually check against nullptr and always document if a public function accepts a null pointer or not (that it, document a function as accepting a null pointer, or as requiring a non-null valid pointer).

Checking against a nullptr is -on most current C++11 implementations- very quick: dereferencing a pointer might make a cache miss (always slow), but comparing it against 0 is a fast arithmetic operation (nearly free).

Use assert if a pointer should always be null and valid.

Use an if to handle the nullptr case if it is genuinely possible at runtime.

Use C++ references to convey that the address is always valid. That is, if you have void foo(int*) and you know that the address is never null and always valid, code a void foo(int&) function instead.

Compilers are permitted to optimize the null pointer test after you have dereferenced it:

 void foo(struct bar_st*p) {
   int x = p->somefield;
   if (!p) return; /// test can be removed by optimization


问:
What do Java developers think of Scala?
I've noted that IDE support is nowhere near as good, but the language itself supports functional programming idioms much more cleanly.</p>

答: As a Java programmer, I initially found Scala interesting.  However, after dabbling with it for awhile (and running into nearly all the positives/negatives already listed by others), I was left feeling very "meh" towards it.  The language improvements are offset by the lower availability of toolsets.  I just couldn't come up with any defining reason to switch over.  It's good, but it's not "better enough" to make a case for switching.  Doesn't have that subjective excitement factor either (like Clojure seems to).</p>

ContentLicense: CC BY-SA 2.5

Title: What do Java developers think of Scala?


问:
Designing pricing table (RDBMS agnostic)
I'm designing a price list table for my database.

It will include Customer, Model, Start_date, End_date, Price, Currency, RRP

When I update a new price list, which is sent every now and then (maybe every 1~3 months), I need to update the prices but I would like to keep the records of what has already been raised.

Currently in system:

```<code>Customer  - Model - Start Date - End date  - Price - Currency - RRP
A         - Z     - 2015/10/20 - 2015-12-19- 120   - GBP      - 220
A         - Z     - 2015/12/20 - 2999-12-31- 100   - GBP      - 200
</code>```

After updating new price:

```<code>Customer  - Model - Start Date - End date  - Price - Currency - RRP
A         - Z     - 2015/10/20 - 2015-12-19- 120   - GBP      - 220
A         - Z     - 2015/12/20 - 2016-02-20- 100   - GBP      - 200
A         - Z     - 2016/02/21 - 2999-12-31-  90   - GBP      - 180
</code>```

What is the best way to update the price?

I tried to google which solved all the problems until now as most of the search results is bringing up SQL price plans :(

I have learned MySQL 9 years ago in college for a few months so I know how to interpret the SQL scripts but I am totally lost when I'm trying to create anything from scratch.

答:
There is nothing wrong how you do it, however there is alternative way as well, by using versions, the table could look like this

```<code>Customer  - Model -Version - Price - Currency - RRP
A         - Z     -1       - 120   - GBP      - 220
A         - Z     -2       - 100   - GBP      - 200
A         - Z     -3       -  90   - GBP      - 180
</code>```

The version can be used to link your records to other related tables, and it would give you better relationship without processing dates to find price for a given order.

Body:
There is nothing wrong how you do it, however there is alternative way as well, by using versions, the table could look like this

Customer  - Model -Version - Price - Currency - RRP
A         - Z     -1       - 120   - GBP      - 220
A         - Z     -2       - 100   - GBP      - 200
A         - Z     -3       -  90   - GBP      - 180

The version can be used to link your records to other related tables, and it would give you better relationship without processing dates to find price for a given order.


问:
Is there a standard way or standard alternative to packing a struct in c?
When programming in C I have found it invaluable to pack structs using GCCs __attribute__((__packed__)) attribute so I can easily convert a structured chunk of volatile memory to an array of bytes to be transmitted over a bus, saved to storage or applied to a block of registers. Packed structs guarantee that when treated as an array of bytes it will not contain any padding, which is both wasteful, a possible security risk and possibly incompatible when with interfacing hardware.

Is there no standard for packing structs that works in all C compilers? If not then I am an outlier in thinking this is a critical feature for systems programming? Did early users of the C language not find a need for packing structs or is there some kind of alternative?

答:
No all architectures are the same, just turn on the 32 bit option on one module, and see what happens when using the same source code and the same compiler. Byte order is another well known limitation. Throw in floating point representation and the problems get worse. Using Packing to send binary data is non-portable. To standardize it so it was practically usable, you would need to redefine the C Language specification. </p>

<p>Although common, using Pack to send binary data is a bad idea if you want security, portability or longevity of the data.  How often do you read a binary blob from a source into your program. How often do you check all the values are sane, that a hacker or program change has not 'got' to the data? By the time you have coded a check routine, you might as well be using import and export routines.   </p>

Body:
No all architectures are the same, just turn on the 32 bit option on one module, and see what happens when using the same source code and the same compiler. Byte order is another well known limitation. Throw in floating point representation and the problems get worse. Using Packing to send binary data is non-portable. To standardize it so it was practically usable, you would need to redefine the C Language specification.

Although common, using Pack to send binary data is a bad idea if you want security, portability or longevity of the data.  How often do you read a binary blob from a source into your program. How often do you check all the values are sane, that a hacker or program change has not 'got' to the data? By the time you have coded a check routine, you might as well be using import and export routines.


答:
Assuming I have a parent class and a child class, with no virtual functions, and I have a parent-class-pointer to a child object

Then you are using it polymorphically.

Though I don't see much point in doing that. Without virtual members, the subclass does not have much opportunity to affect the program behaviour compared to using just the base class.

A non-polymorphic class is one that will not be used to point to objects of derived classes. These are either classes that won't be derived (which in C++ is vast majority!) or classes that are used as base for purpose of code reuse without providing complete interface for anything (e.g. std::iterator; it is a public base class of most iterators, but it makes no sense to create a std::iterator *).

Title: C++ Virtual destructors used only when there are virtual functions

Body:
This is from Effective C++ (Meyers):

Classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors

I don't understand why non-polymorphic classes should not declare virtual destructors.

Assuming I have a parent class and a child class, with no virtual functions, and I have a parent-class-pointer to a child object: if I call delete on the parent-class-pointer, it will only call the parent destructor, even though I also want to call the child destructor.


问:
Making more than one instance of factory that is supposed to be singleton

However, there are some classes that should have only one instance.

Sometimes they are factories, which you can use to create the other objects in the system.

If more than one factory exist, clerical control over the created objects may be compromised.

From : Agile software development : PPP

What clerical control Uncle Bob talks about, that would be compromised?

答:
Whatever kind of "clerical control" your application needs. If you don't know what that means, chances are high your application won't need such control ;-)

For example, this could mean to keep account on the whole set of objects of a certain type which were created during the lifetime of your application, for the purpose of reiterating over them at a later point in time, or for searching for an existing object. Morevover, this could be used to create something like an "object cache" for objects where the creation is costly, like objects from a database. So the accounting will allow you to check if an object must really be newly created, or if you can reuse a former instance from the cache.

Other possible scenarios are the example of MetaFight's comment, easier ID number generation, or just counting the number of created objects of a certain type for statistical purposes.

I guess once you got the idea, you can extend that list easily by yourself.


答:
A very common alternative is "named padding" :

```<code>struct s {
  short s1;
  char  c2;
  char  reserved; // Padding
};
</code>```

This does assume the structure will not be padded to 8 bytes.

Title: Is there a standard way or standard alternative to packing a struct in c?

Body:
When programming in C I have found it invaluable to pack structs using GCCs __attribute__((__packed__)) attribute so I can easily convert a structured chunk of volatile memory to an array of bytes to be transmitted over a bus, saved to storage or applied to a block of registers. Packed structs guarantee that when treated as an array of bytes it will not contain any padding, which is both wasteful, a possible security risk and possibly incompatible when with interfacing hardware.

Is there no standard for packing structs that works in all C compilers? If not then I am an outlier in thinking this is a critical feature for systems programming? Did early users of the C language not find a need for packing structs or is there some kind of alternative?

Body:
A very common alternative is "named padding" :

struct s {
  short s1;
  char  c2;
  char  reserved; // Padding
};

This does assume the structure will not be padded to 8 bytes.


问:
Are there any compilers that attempt to fix syntax errors on their own?
I heard a while back that there used to be a compiler that attempted to fix syntax errors by analyzing context and inferring what was intended.

Does such a compiler really exist? Obviously it has little practical value, but would be very interesting to play with and learn from.

答:
The IDE for a programming language usually these days has a compiler running in the background somehow, so that it can provide analysis services like syntax colouring, IntelliSense, errors, and so on. Obviously such a compiler needs to be able to make sense of deeply broken code; most of the time when editing, code is not correct. But we still have to make sense of it.

However, usually the error recovery feature is only used during editing; it doesn't make a lot of sense to allow that for actual compilation in "mainline" scenarios.

Interestingly, we did build that feature into the JScript.NET compiler; basically it is possible to put the compiler into a mode where we allow the compiler to proceed even if an error is encountered, if the IDE would have recovered from it. You can type Visual Basic code in, run the JScript.NET compiler on it, and have a reasonable chance of a working program coming out the other end!

This is an amusing demo, but it turns out to be not a very good feature for "mainline" scenarios for a lot of reasons. A full explanation would be quite lengthy; the brief explanation is that it makes for programs that work unpredictably and by accident, and it makes it hard to run the same code through multiple compilers, or multiple versions of the same compiler. The large expenses the feature adds are not justified by the small benefits.

Peter Torr, who PM'd the feature back in the day, discusses it briefly in this blog posting from 2003.

Though we do expose this feature via the script hosting APIs of the JScript .NET engine, I don't know of any real customers that ever used it.

ContentLicense: CC BY-SA 4.0


问:
Branching and Merging Business Data
We're working on a project wherein the business users operate on a set of data that is periodically published.  We've labeled the publishing milestones as Versions, and, due to some business constraints, end up duplicating the data set for each Version that gets published.

During the work cycle, it often becomes prudent for one of the work groups to spin off a side project (which we've aptly named Project), work on that set of data for some time, then blend their changes back into the parent Version, possibly waiting until two or more Versions have been published before their changes get blended back in.

I can see the lights coming on from here.  "Ah ha!" you say, "That's the same thing that happens in [Git, SVN, TFS, etc.]; code branching and merging.  Just do that."

Right, that's a perfect lead-in to my question: how does one implement branching and merging for business data that is spread across seven or so primary objects and their representative children?  I understand clearly what I want to achieve, I just have no idea how to write the rules so that the developers can take it forward and implement successfully (I'm the solution architect for the project and a middling code writer).  I tried researching it, but am only finding articles on which Git (or Svn or whatever) commands to run to get the desired results.

By the way, we're developing on .NET 4.5 and implementing Workflow Foundation and Entity Framework if that helps matters.

Update

Per the question below, the "primary objects" are things like Model, Option, Version, Rule, and Note.  Each of those have child objects (a Rule has a set of Conditions), joining objects (RuleVersion), and of course properties (Option.Description, etc.).  One of the system's primary function is to track cost and retail price, so Price and Cost objects are hanging on the edges, each with their own set of properties (Price.Retail, Price.Calculated, etc.).

答:
My thoughts:

You should implemented objects writeTo/readFrom in some human readable text format like csv, xml, json. Advantages

Can be maintained via texteditor

Support for textual find&replace

If you have (embedded) lists of (sub-) objects make shure that they are always in the same order (i.e. sorted by name). Advantages

Windiff will only show relevant changes.

instead of importing/exporting autogenerated database-keys use symbolic key-s since the database key may varay from system to system.

We use csv-files with these constraints to maintain our testdata via git for automated integration-tests. csv files can be easily edited via libre office. Microsoft Excel as csv editor is problematic because it interprets colums as dates, Numbers, ... which may ruin content when writing back to csv.

Title: Branching and Merging Business Data


问:
How unit test service method that use repository method
For service methods that call repository methods to interact with database how could I unit test these service methods?

For example,

public function updateSlideshow($data){
    // do some logic and method calls (I can test those methods,
    // but for this method that call repository ...)

    $r = $this->blockRepo->update($data, $config, $slides);
}
```

How can I check that this method work correctly or at least send right data to update method?

And what about a scenario that method first fetch data from repository and do logic on it?

答: Assuming you are using dependency injection, then this situation is easily solved. You will be injecting blockRepo into the class/module containing updateSlideshow. So in a live environment, you inject a version of blockRepo that talks to a DB. In a test environment, you inject a version that mocks this behaviour, eg reads/writes to local variables, rather than a DB, allowing you to simulate various DB data states for the various tests.


答:
As a concrete example, assume something like this:

```<code>class Base
{
    ...
    int some_int;
};

class Derived: public Base
{
    ...
    vector<int> some_vec; // the presence of this field makes `Derived`
                          // no longer trivially destructible.
};
</code>```

Now if we do this (either directly as shown or indirectly through a smart pointer, e.g.):

```<code>Base* base = new Derived;
...
delete base;
</code>```

... then some_vec will not be destroyed unless Base defines a virtual destructor. After all, given only a base pointer, the system lacks the information at runtime to know anything about Derived unless there's a virtual table that points to its functions, allowing a dynamic dispatch to occur to get to information/functionality specific to Derived like its specific requirements for proper destruction.

To delete an object through a base pointer is polymorphic behavior, and to do it safely and correctly without running into undefined behavior requires the base class to define a virtual destructor.

The question ultimately boils down to whether you want to delete objects through a base pointer. If you do, then define a public virtual destructor:

```<code>class BaseSafeDelete
{
public:
    // Provides safe destruction through a base pointer.
    virtual ~BaseSafeDelete() {}
};
</code>```

If not, define a protected nonvirtual destructor:

```<code>class BaseNoDelete
{
protected:
    // Prevents deleting outright through a base pointer.
    /*nonvirtual*/ ~BaseNoDelete() {}
};
</code>```

And most importantly, inheritance is something to be designed and decided upfront when designing a base class. It's not suitable as an afterthought to take a class which was not designed for inheritance whatsoever (lacking either a protected nonvirtual dtor or a public virtual dtor as a first sign) and attempt to extend it. For that, see the Composite Reuse Principle.

Body:
As a concrete example, assume something like this:

class Base
{
    ...
    int some_int;
};

class Derived: public Base
{
    ...
    vector<int> some_vec; // the presence of this field makes `Derived`
                          // no longer trivially destructible.
};

Now if we do this (either directly as shown or indirectly through a smart pointer, e.g.):

Base* base = new Derived;
...
delete base;

... then some_vec will not be destroyed unless Base defines a virtual destructor. After all, given only a base pointer, the system lacks the information at runtime to know anything about Derived unless there's a virtual table that points to its functions, allowing a dynamic dispatch to occur to get to information/functionality specific to Derived like its specific requirements for proper destruction.

To delete an object through a base pointer is polymorphic behavior, and to do it safely and correctly without running into undefined behavior requires the base class to define a virtual destructor.

The question ultimately boils down to whether you want to delete objects through a base pointer. If you do, then define a public virtual destructor:

class BaseSafeDelete
{
public:
    // Provides safe destruction through a base pointer.
    virtual ~BaseSafeDelete() {}
};

If not, define a protected nonvirtual destructor:

class BaseNoDelete
{
protected:
    // Prevents deleting outright through a base pointer.
    /*nonvirtual*/ ~BaseNoDelete() {}
};

And most importantly, inheritance is something to be designed and decided upfront when designing a base class. It's not suitable as an afterthought to take a class which was not designed for inheritance whatsoever (lacking either a protected nonvirtual dtor or a public virtual dtor as a first sign) and attempt to extend it. For that, see the Composite Reuse Principle.


问:
How should a service communicate with an activity in real-time?
How should a service communicate with an activity in real-time?

BroadcastReceivers seem too slow and unreliable. Sometimes they appear too slow or stop working entirely. As an example, there was a delay of a few minutes between sending and receiving broadcasts with one of my test applications.

I can't get traditional callbacks to work reliably. I am pretty sure you're not supposed to.

There's an option to bind a service. Is that suitable for real-time communication?

I intend to send small integer updates roughly 20 (edited) times a second.

Am I looking in the right direction?

To narrow the scope of this question:

My application is an audio MediaPlayer. I need the service to host the MediaPlayer. I would like the MediaPlayer service to send updates to my GUI which mainly consist of the current position of the  audio being played.

My question is - are bound services suitable for this task? If not, what alternatives are there?

答:
In Android, a service is used to run some background task even when the user interface element which initiated that task is no more in foreground.

For example: In a social networking app where the user wants to upload a video to the server, the video should continue to get uploaded in background even when the application who requested the video to be uploaded is no more in foreground (e.g. the user receives a call in the meantime).

I am assuming in your case, you want the song to continue to play even when your user interface element (the music app) is not in foreground.

Therefore definitely service is the way to go.

In Android there are two types of services (http://developer.android.com/guide/components/services.html)

Started Service : Used for long running task where intermediate updates are not required. So for example if you want to upload a video in background and only intimate the user that the upload was a success or a failure, then you use a started service and use notifications to inform the user of the status (success or failure)

Bound Service : Used for long running task where there is a client/server relationship between the invoker (in this case the app) and the service.

In android you can create a service which is started and bound at the same time. My suggestion would be to create such a service. The started part of the service will play the song in the background and the bound part of the service will provide updates of the current position of the song being played.

In the meantime, if the app goes in background, then because the service is started the song will continue to play without providing updates of the current position of the song.


问:
Should a client check for persisted item existence before modifying it?
I'm developing a MVC Web application with a REST interface.

The REST controller performs actions on persisted items through a service class, which translates exceptions coming from the persistence layer.

When a request involves an item that not exists in the database, I would like to return 404 code, but actually this is not possible due to the exception translation operated by the service, that prevents the controller from knowing the reason of the problem.

Should the service class return a particular exception only for this case? Conversely, should the controller check for item existence before any action?

答:
In most applications, the Service would retrieve the object it needs through the data access layer (effectively loading it in memory) before it can modify it and save it back.

If the object doesn't exist, the data access object would probably return null. I would maybe not raise an exception at that point but at least return a specific error case value. The Controller would get it and respond with a 404.


问:
Creating an ASP.Net MVC web application that can work on different operating systems
I have been developing and deploying many ASP.Net MVC web applications under Windows Server 2008 R2 & Windows Server 2012 R2, and I used IIS 7 & IIS 8. At the same time I know that I can deploy my ASP.Net MVC under Linux and Unix, without the need to change my code.

Today I created a console application which is being called from my ASP.Net MVC web application. This console application represents a long running process which calls 3rd party systems and generate a report. It can be started from my ASP.Net MVC web application and it runs on timely basis as a task inside Windows tasks scheduler.

Does that mean that my web application can not run on any operating system other than Windows?

答:
As far as I know, ASP.NET MVC applications can run only on IIS, which is only available on Windows. This will change with the latest ASP.NET 5, which will run in the DNX (.NET Execution Environment). DNX supports running cross-platform console applications, so consider looking here:

http://docs.asp.net/en/latest/dnx/console.html


问:
Why is it called network "topology"? Why not network "graph"?
I want to understand why we use the term "network topology" as opposed to "network graph", or another term, to talk about the structure of networks. I'm working on a network design for a project, and want to make sure I don't use any terms that I don't truly understand.

Wikipedia defines network topology as "the arrangement of the various elements (links, nodes, etc.) of a computer network." This strikes me as interesting, because when I hear the words link and node, I immediately think of graph theory and the objects it is concerned with.

Topology, according to Wikipedia again, is "concerned with the properties of space that are preserved under continuous deformations..." And when you look at the basic examples of topological objects, you see coffee cups and Möbius strips, as opposed to the discrete vertices and edges you see with graph theory.

So why do we refer to networks as having a "topology"?

答:
Each graph is a topological object. The main properties of a graph are the nodes as well as the links between them. Those are properties which are preserved under continuous deformations. Thus the term "network graph" can surely be used in exchange for "network topology". The latter is probably more widely used; it highlights the "topological" properties a network like "which node is connected to which other node(s)", whilst ignoring properties like line length, band-width or other "non-topological" / "non-graph" properties.

However, I am pretty sure that has simply historical reasons, and not because it really fits better in a mathematical sense. And maybe "network topology" just sounds "more cool" to a lot of people than "network graph", as @CormacMullhall wrote in his comment ;-)


问:
I want to overload a function with the same type parameter; what should I do?
I'm creating an API, and I want to overload a function for strip:

```<code>QString MyClass::strip();
QString MyClass::strip(QRegularExpression open);
QString MyClass::strip(QRegularExpression close);
QString MyClass::strip(QRegularExpression open, QRegularExpression close);
</code>```

Obviously the second and third conflict.

What is the recommended style for C++ and Qt programmers to restructure this?

答:
I would suggest

```<code>QString MyClass::strip();
QString MyClass::strip(QRegularExpression regex, bool opening=false);
QString MyClass::strip(QRegularExpression open, QRegularExpression close);
</code>```

and perhaps

```<code>QString MyClass::strip_open(QRegularExpression regex);
QString MyClass::strip_close(QRegularExpression regex);
</code>```

or replace the bool opening with e.g.

```<code>enum stripping_mode {Strip_Open, Strip_Close};;
</code>```

or make even it a class enum

Body:
I would suggest

QString MyClass::strip();
QString MyClass::strip(QRegularExpression regex, bool opening=false);
QString MyClass::strip(QRegularExpression open, QRegularExpression close);

and perhaps

QString MyClass::strip_open(QRegularExpression regex);
QString MyClass::strip_close(QRegularExpression regex);

or replace the bool opening with e.g.

enum stripping_mode {Strip_Open, Strip_Close};;

or make even it a class enum


问:
How have you found, refined and maintained your coding style?
Recently, I've been switching between several projects and development environments. The expectations for coding style in each is different.

Now, my question is three part, the first, just of curiosity:

How did you define and find your coding style?

How do you keep augmenting and improving it?

How do you maintain it? (From mental notes, keeping a document, using a tool like StyleCop etc.)

答:
I worked in a team with a closed source game that I loved and the lead developer mentored me, and helped me improve my skills after I asked him too.

He suggested, and I adopted the Zend Framework's Coding Style (http://framework.zend.com/manual/en/coding-standard.html)


答: What about creating a class to hold your arguments? This class would contain both open and close parameters and either of them could be NULL. Then, there will be only one strip method with above class as argument and method will decide if it wants to use open/close if they are set.

Title: I want to overload a function with the same type parameter; what should I do?

Body:
I'm creating an API, and I want to overload a function for strip:

```<code>QString MyClass::strip();
QString MyClass::strip(QRegularExpression open);
QString MyClass::strip(QRegularExpression close);
QString MyClass::strip(QRegularExpression open, QRegularExpression close);
</code>```

Obviously the second and third conflict.

What is the recommended style for C++ and Qt programmers to restructure this?


答:
You're right, if you've written a Windows-only console you need to port the code in it to Linux or Mac. How hard that is depends a lot on what you wrote it in, and how you wrote it. Note that it is possible to run the console on Windows and connect to it via a network connection (if you wrote it to have this capability).

As for ASP.NET, this is a Microsoft-only technology that cannot run (at the moment at least) on non-Windows platforms. You can write your web site using different frameworks (eg PHP and Laravel, or Python and Django, etc) to get the same functionality that is cross-platform and will work on all 3 OSes you want.

Title: Creating an ASP.Net MVC web application that can work on different operating systems

Body:
I have been developing and deploying many ASP.Net MVC web applications under Windows Server 2008 R2 & Windows Server 2012 R2, and I used IIS 7 & IIS 8. At the same time I know that I can deploy my ASP.Net MVC under Linux and Unix, without the need to change my code.

Today I created a console application which is being called from my ASP.Net MVC web application. This console application represents a long running process which calls 3rd party systems and generate a report. It can be started from my ASP.Net MVC web application and it runs on timely basis as a task inside Windows tasks scheduler.

Does that mean that my web application can not run on any operating system other than Windows?


答:
The Service layer can translate exception received from lower layers to avoid coupling between the controller and the persistence layer. But in doing that translation, the Service layer should not throw away/obscure information that could be relevant for dealing with the reported error.

So, the Service layer should in general have a one-to-one mapping between persistence exceptions and the exceptions they get translated into. You should only deviate from that if the persistence layer, for legacy reasons, throws two different exceptions for one and the same problem.

Title: Should a client check for persisted item existence before modifying it?

Body:
I'm developing a MVC Web application with a REST interface.

The REST controller performs actions on persisted items through a service class, which translates exceptions coming from the persistence layer.

When a request involves an item that not exists in the database, I would like to return 404 code, but actually this is not possible due to the exception translation operated by the service, that prevents the controller from knowing the reason of the problem.

Should the service class return a particular exception only for this case? Conversely, should the controller check for item existence before any action?


答:
I ended up adopting characteristics of different styles - including styles reflected on MSDN. I then set up templates in VS that provide my #region/#endregion blocks and anything else that is preferable.

I continue to study other styles that I encounter through research and reading. If I think there is something that stands out and could improve my style in readability, maintenance, or organization, I try it out. If a new style adjustment is in order, I will update templates in VS or make mental notes.

Title: How have you found, refined and maintained your coding style?

Body:
Recently, I've been switching between several projects and development environments. The expectations for coding style in each is different.

Now, my question is three part, the first, just of curiosity:

How did you define and find your coding style?

How do you keep augmenting and improving it?

How do you maintain it? (From mental notes, keeping a document, using a tool like StyleCop etc.)


问:
Algorithm to get all paths in a tree
I have a tree that has n-levels. For example here I have four levels:

Each node has two children (except for the last one), however everyone except for the first and last node of each row has two parents. I'm trying to figure out a scalable way to get all paths into a List of Lists, so that for this example, I will have a List of Lists of chars:

```<code>A,B,D,G

A,B,D,H

A,B,E,H
</code>```

etc.

Can anyone help steer me to the right direction of finding an algorithm for this regardless of how many levels?

答:
The fact that a node can have two parents shouldn't prevent you from using a standard depth first search. As you describe it, a child with two parents is still independently part of two "solutions". The fact that there are at most two edges leaving each node simplifies things further.

```<code>search(node):

    if node is null: // maybe a non-terminal parent's left or right was null
        return  // that or someone gave you a null graph

    add node to "discovered" list

    if node is terminal:
        print the list //[A,B,D,G], [A,B,D,H], etc
        remove node from the list
        return // done at this level

    search(node.left)
    search(node.right)
    remove node from the list // all done at this level
</code>```

You can change the order of discover by going right before you go left.

Title: Algorithm to get all paths in a tree

Body:
The fact that a node can have two parents shouldn't prevent you from using a standard depth first search. As you describe it, a child with two parents is still independently part of two "solutions". The fact that there are at most two edges leaving each node simplifies things further.

search(node):

    if node is null: // maybe a non-terminal parent's left or right was null
        return  // that or someone gave you a null graph

    add node to "discovered" list

    if node is terminal:
        print the list //[A,B,D,G], [A,B,D,H], etc
        remove node from the list
        return // done at this level

    search(node.left)
    search(node.right)
    remove node from the list // all done at this level

You can change the order of discover by going right before you go left.


问:
Why is Eclipse platform dependent?
When Eclipse is written in Java and Java is platform independent, why does Eclipse offer different versions according to platforms?

I assume it should be write once, use anywhere code.

答:
Although Eclipse IDE is written in Java, the graphical control elements use Standard Widget Toolkit (SWT), whereas most Java applications use the Java standard Abstract Window Toolkit (AWT) or Swing.

To display GUI elements, the SWT implementation accesses the native GUI libraries of the operating system using JNI (Java Native Interface) in a manner that is similar to those programs written using operating system-specific APIs. Programs that call SWT are portable, but the implementation of the toolkit, despite part of it being written in Java, is unique for each platform.

SWT must be ported to every new GUI library that needs supporting. Unlike Swing and AWT, SWT is not available on every Java-supported platform since SWT is not part of the Java release.

Therefore the Eclipse distribution must include different SWT implementation for each supported platform.

Title: Why is Eclipse platform dependent?


问:
Is it effective to review code in language I don't know?
I'm an experienced developer, but have not done many code reviews. I'm being asked to review code written in Python but I do not know Python.

Does it make any sense at all to review code in a language I don't know?

答:
Any sense? Yes. Even if you know nothing about the semantics of a programming language, you can still read characters and notice inconsistent formatting, missing comments, badly chosen identifiers, obvious duplication etc.

Much sense, or enough sense to repay the cost of your time? I'm not sure. This depends on your position, the importance of code reviews in the workflow of your team, and several other factors that we can't quantify well enough.


答:
Code review is not about searching for variables with invalid spelling and wrong formatting. If you use code review to find such things, then stop wasting your time and use a tool.

Code review is about improving design and detecting common mistakes by a novice programmers.

Since I program in C++, and I don't know Python well enough, I wouldn't dare to review Python code. However I could help with a Java code review.

You didn't say in which language you program, but I do not see what you could contribute in a code review, if you do not know the language it is programmed in.

Title: Is it effective to review code in language I don't know?

Body:
I'm an experienced developer, but have not done many code reviews. I'm being asked to review code written in Python but I do not know Python.

Does it make any sense at all to review code in a language I don't know?


答:
Code reviews (in addition to actually looking for flaws) are a good introduction from one team member to others for the code being added or changed.  If you are an experienced developer, you should be able to read through enough to mostly understand what is going on.

Look at a code review from a team leader's point of view: there is someone there who understands what the application should be doing (business logic), there is someone there who understands the code is doing (implementation logic), and possibly several other people there who need to have an idea of how all of that fits together.


问:
Explanation on how "Tell, Don't Ask" is considered good OO
This blogpost was posted on Hacker News with several upvotes. Coming from C++, most of these examples seem to go against what I've been taught.

Such as example #2:

Bad:

```<code>def check_for_overheating(system_monitor)
  if system_monitor.temperature > 100
    system_monitor.sound_alarms
  end
end
</code>```

versus good:

```<code>system_monitor.check_for_overheating

class SystemMonitor
  def check_for_overheating
    if temperature > 100
      sound_alarms
    end
  end
end
</code>```

The advice in C++ is that you should prefer free functions instead of member functions as they increase encapsulation. Both of these are identical semantically, so why prefer the choice that has access to more state?

Example 4:

Bad:

```<code>def street_name(user)
  if user.address
    user.address.street_name
  else
    'No street name on file'
  end
end
</code>```

versus good:

```<code>def street_name(user)
  user.address.street_name
end

class User
  def address
    @address || NullAddress.new
  end
end

class NullAddress
  def street_name
    'No street name on file'
  end
end
</code>```

Why is it the responsibility of User to format an unrelated error string? What if I want to do something besides print 'No street name on file' if it has no street? What if the street is named the same thing?

Could someone enlighten me on the "Tell, Don't Ask" advantages and rationale? I am not looking for which is better, but instead trying to understand the author's viewpoint.

答:
These answers are very good, but here's another example just to emphasize: note that it's usually a way to avoid duplication. For example, let's say you have SEVERAL places with a code like:

```<code>Product product = productMgr.get(productUuid)
if (product.userUuid != currentUser.uuid) {
    throw BlahException("This product doesn't belong to this user")
}
</code>```

That means you'd better have something like this:

```<code>Product product = productMgr.get(productUuid, currentUser)
</code>```

Because that duplication means most clients of your interface would use the new method, instead of repeating the same logic here and there. You give your delegate the work you want done, instead of asking for the info you need in order to do it yourself.

Body:
These answers are very good, but here's another example just to emphasize: note that it's usually a way to avoid duplication. For example, let's say you have SEVERAL places with a code like:

Product product = productMgr.get(productUuid)
if (product.userUuid != currentUser.uuid) {
    throw BlahException("This product doesn't belong to this user")
}

That means you'd better have something like this:

Product product = productMgr.get(productUuid, currentUser)

Because that duplication means most clients of your interface would use the new method, instead of repeating the same logic here and there. You give your delegate the work you want done, instead of asking for the info you need in order to do it yourself.


答:
Reading the DOOM source code.

Reading everything else I could lay my hands on, picking out the parts that worked.

Functioning alcoholism.

When coding alone, I aim for brevity; Spartan Programming may be complete, batshit insanity... But it's probably the closest familiar thing to my creed.

When coding with others, especially maintenance coding, I aim to be a chameleon - my changes should improve what they modify, without looking out of place.


答:
A few observations:

1) If you are an experienced developer, you will pick up Python (or at least as much as you need to know), just by working with it. It will be a case of "learning by doing." It will be hard at first, but will get easier as you pick up the language. Think of this as an opportunity to learn another language (people often learn "foreign" languages through "immersion.")

2) There are a number of valuable people on SE sites that are "non-technical," but are skilled with grammar, communications and logic. Such people bring a "fresh eye" to subjects, and make a number of "no brainer" fixes that others miss, because they are too "tied up" in the material. You are being consulted presumably for your non "technical" (i.e. non Python) skills such as logic and overall programming savvy.

And if you haven't done a lot of code review, almost any code review experience will help you as a developer. This looks like a good match between your skills and needs and the team's.


问:
Confusion over Node as a "script" vs Node as a "server"
As I was beginning to tool around a bit with node, I was told that I needed to undergo a little bit of a paradigm shift since I was coming from a PHP background. I would ask questions like, "I have my script working in terminal, now how can I upload it to the server and access through an AJAX request?". I was told that "it doesn't work like that" and that "Node scripts aren't just that magically work like PHP when you upload them to a server. Node IS a server".

So I thought to myself, "Okay. Let's just put this on the shelf for a while." I basically only use node for scripts that I run locally anyway, so if I have to type node server.js in terminal to use my script, it wasn't that inconvenient, and it allowed me to happily learn it without having to worry about shifting any of my paradigms.

Then, last week I made a small front end that worked with some node scripts I was writing and I realized that I needed members of another team to use it. I guessed that they weren't going to have Node installed or be comfortable enough with a CLI to type node server.js. I found out about Heroku. And I uploaded all my scripts to it, and you know what: it magically works! Paradigm shift avoided AGAIN.

I feel like continually having avoided this paradigm shift is hurting me. So I need to figure it out. How node can be a server? Yet also node files can be uploaded to something like Heroku (/Docker? Another "container" I've heard discussed) and work in the same way as I'm used to server-side PHP running? Yet, it seems, at the same time not: I can't upload them to an Apache server I don't think and expect them to work. Also, since I've mentioned Docker, once I understand exactly what Heroku is, is Docker basically the same thing?

(I felt this question is correct for this SE site, but please let me know if you think it would be a better fit on SO or somewhere else)

答:
Node is a javascript execution environment.  Node can act as a server (by executing a script that performs server functions).

Heroku is an operating system (sitting in the cloud) that supports (among others) Node scripts. You can think of it like your desktop sitting on the internet, running a Node environment.

When you run a server type of script in Heroku, it isn't any different than you running it on one your companies public facing servers.

One of the nice things about Heroku over Apache, is that Heroku is designed to allow users to upload applications without an admin being required to deploy it.


答:
As a regular contributor over at Code Review Stack Exchange, I encounter a lot of questions suffering from Language-agnostic issues, for example:

Formatting, indentation

Scope

Loops

Type operations

and the list goes on. However, while I don't need to know the language, I can still review those issues / points.

A few of our top users have top answers in languages they either don't actively use, or don't know. Even two of my top ten are in languages I neither know nor can compile / run on my machine.

I'd even say it'd be the same as reviewing someone's pseudo code. As long as you can observe and comment on things relevant to things you understand, you'll be fine, and it'll be relevant.


问:
How useful are function points?
How useful is it to measure function points?

We use function points at my new job.  I've heard of function points but haven't had any training or experience... but I don't have much confidence in things that cannot be explained succinctly.

答: They seem to be marginally useful at expressing the complexity of a given system/component, and can help managers/team leads apportion work, but they're not really any more useful than any other synthetic/arbitrary metrics (SLOC, Cyclomatic Complexity, etc.)  That is, they may give an indication of the relative amount of effort required for specific parts of a system, but there's no way to map them to concrete estimates.</p>

Title: How useful are function points?


答:
There are many options, it's your tradeoff which to take:

Decision at runtime:

Add a defaulted bool argument:

```<code> QString MyClass::strip(QRegularExpression regex, bool close=false);
 // Mimic the two-regex-variants interface as good as possible
</code>```

Use scoped enum's and no default as a variant on 1 which is more descriptive:

```<code> enum class option { open, close };
 QString MyClass::strip(QRegularExpression regex, option open_close);
</code>```

Use std::experimental::optional or something like that, maybe from boost.

Find out that a specific regex does nothing, and document that as the no-op default.

Decision at compiletime:

Use overloads replacing one argument with std::nullptr_t:

```<code> QString MyClass::strip(std::nullptr_t open, QRegularExpression close);
 QString MyClass::strip(QRegularExpression open, std::nullptr_t close = {});
</code>```

Use tags to avoid any overhead:

```<code> constexpr struct open_t {} open;
 constexpr struct close_t {} close;
 QString MyClass::strip(open_t, QRegularExpression regex);
 QString MyClass::strip(close_t, QRegularExpression regex);

 // Call it like this:
 object.strip(object.open, regex);
</code>```

Bite the bullet and name those functions differently:

```<code> QString MyClass::strip_open(QRegularExpression regex);
 QString MyClass::strip_close(QRegularExpression regex);
</code>```

Consider whether making the open-regex and the close-regex different types makes sense. To be truthful, I doubt it here, but where appropriate that's the best option.

Body:
There are many options, it's your tradeoff which to take:

Decision at runtime:

Add a defaulted bool argument:

 QString MyClass::strip(QRegularExpression regex, bool close=false);
 // Mimic the two-regex-variants interface as good as possible

Use scoped enum's and no default as a variant on 1 which is more descriptive:

 enum class option { open, close };
 QString MyClass::strip(QRegularExpression regex, option open_close);

Use std::experimental::optional or something like that, maybe from boost.

Find out that a specific regex does nothing, and document that as the no-op default.

Decision at compiletime:

Use overloads replacing one argument with std::nullptr_t:

 QString MyClass::strip(std::nullptr_t open, QRegularExpression close);
 QString MyClass::strip(QRegularExpression open, std::nullptr_t close = {});

Use tags to avoid any overhead:

 constexpr struct open_t {} open;
 constexpr struct close_t {} close;
 QString MyClass::strip(open_t, QRegularExpression regex);
 QString MyClass::strip(close_t, QRegularExpression regex);

 // Call it like this:
 object.strip(object.open, regex);

Bite the bullet and name those functions differently:

 QString MyClass::strip_open(QRegularExpression regex);
 QString MyClass::strip_close(QRegularExpression regex);

Consider whether making the open-regex and the close-regex different types makes sense. To be truthful, I doubt it here, but where appropriate that's the best option.


问:
Anonymous namespaces make code untestable
Here is a typical C++ code:

foo.hpp

```<code>#pragma once

class Foo {
public:
  void f();
  void g();
  ...
};
</code>```

foo.cpp

```<code>#include "foo.hpp"

namespace {
    const int kUpperX = 111;
    const int kAlternativeX = 222;

    bool match(int x) {
      return x < kUpperX || x == kAlternativeX;
    }
} // namespace

void Foo::f() {
  ...
  if (match(x)) return;
  ...
</code>```

It looks like a decent idiomatic C++ code - a class, a helper function match which is used by the methods of Foo, some constants for that helper function.

And then I want to write tests.

It would be perfectly logical to write a separate unit test for match, because it's quite non-trivial.

But it resides in an anonymous namespace.

Of course I can write a test which would call Foo::f(). However it won't be a good test if Foo is heavy and complicated, such test won't isolate the testee from other unrelated factors.

So I have to move match and everything else out of the anonymous namespace.

Question: what's the point of putting functions and constants into the anonymous namespace, if it makes them unusable in tests?

答:
If you want to unit-test the private implementation-details, you do the same sort of dodge for unnamed namespaces as for private (or protected) class-members:

Break in and party.

While for classes you abuse friend, for unnamed namespaces you abuse the #include-mechanism, which doesn't even force you to change the code.

Now that your test-code (or better only something to expose everything) is in the same TU, there's no problem.

A word of caution: If you test the implementation-details, your test will break if those change. Be really sure to only test those implementation-details which will leak anyway, or accept that your test is unusually ephemeral.


答:
General advice

Here's the bottom line, in my opinion:

If you don't know the language well enough to know the features and common idioms, you are probably not going to contribute much to the review.

If you want to learn the language's features and idioms, you could participate in the review. Your focus should be observing the idioms and asking questions about patterns and organization that don't make sense to you. This may help identify problem areas, but only in the sense that you might force the developer to defend what they've done. Ask your questions in a way that leaves room for your gap in knowledge. Note that this may end up being a net cost in the review itself, but that cost is an investment in your knowledge.

Your ability to contribute until you have familiarized yourself with the language's features, idioms, and standards will be limited. I would not expect this to change until you have actually written a significant amount of code in the language.

Python specific considerations and examples

For the specific situation of not knowing Python, I would be especially wary of this. Python has a lot of idioms and standard practices that end up making good Python look very different from what you might expect in other languages. (Indeed, I think the things Python emphasizes have made my code look better in other languages, and not the other way around.) Beyond PEP8 has a good example of how you might completely miss the mindset Python encourages.

Let's look at a simple example. Take this code:

f = open('/home/me/something.txt')
try:
    content = f.read()
finally:
    f.close()
```

<p>See the problem with this code? If you haven't worked with Python, you probably don't. The problem is that there is a <em>much</em> preferred style in Python that does <em>exactly</em> the same thing:</p>

<pre class="lang-python prettyprint-override"><code>with open('/home/me/something.txt') as f:
    content = f.read()
</code>```

This is a context manager. Do you know what they're good for? Do you know when it would be appropriate to use one? Do you know when it would be appropriate to create your own? No? Then you're probably not ready to review Python.

Let's look at another example.

def add_fifty(other_list):
   result = list()
   for i in other_list:
       result.append(i + 50)
   return result

x = range(10)
y = add_fifty(x)
```

<p>See the problem? The problem is this method is <em>completely unnecessary</em>. You should probably just use a comprehension in place, when the operation is this simple:</p>

<pre class="lang-python prettyprint-override"><code>x = range(10)
y = [i + 50 for i in x]
</code>```

If you didn't see that, you're not familiar with Python's features and idioms.

Body:
General advice

Here's the bottom line, in my opinion:

If you don't know the language well enough to know the features and common idioms, you are probably not going to contribute much to the review.

If you want to learn the language's features and idioms, you could participate in the review. Your focus should be observing the idioms and asking questions about patterns and organization that don't make sense to you. This may help identify problem areas, but only in the sense that you might force the developer to defend what they've done. Ask your questions in a way that leaves room for your gap in knowledge. Note that this may end up being a net cost in the review itself, but that cost is an investment in your knowledge.

Your ability to contribute until you have familiarized yourself with the language's features, idioms, and standards will be limited. I would not expect this to change until you have actually written a significant amount of code in the language.

Python specific considerations and examples

For the specific situation of not knowing Python, I would be especially wary of this. Python has a lot of idioms and standard practices that end up making good Python look very different from what you might expect in other languages. (Indeed, I think the things Python emphasizes have made my code look better in other languages, and not the other way around.) Beyond PEP8 has a good example of how you might completely miss the mindset Python encourages.

Let's look at a simple example. Take this code:

f = open('/home/me/something.txt')
try:
    content = f.read()
finally:
    f.close()

See the problem with this code? If you haven't worked with Python, you probably don't. The problem is that there is a much preferred style in Python that does exactly the same thing:

with open('/home/me/something.txt') as f:
    content = f.read()

This is a context manager. Do you know what they're good for? Do you know when it would be appropriate to use one? Do you know when it would be appropriate to create your own? No? Then you're probably not ready to review Python.

Let's look at another example.

def add_fifty(other_list):
   result = list()
   for i in other_list:
       result.append(i + 50)
   return result

x = range(10)
y = add_fifty(x)

See the problem? The problem is this method is completely unnecessary. You should probably just use a comprehension in place, when the operation is this simple:

x = range(10)
y = [i + 50 for i in x]

If you didn't see that, you're not familiar with Python's features and idioms.


问:
Convention to where to declare module.exports on Javascript files
Is there any convention to where we should declare the module.exports no Javascript/Node.js module files?

Should it be in the beginning of the file like:

```<code>module.exports = Foo;

function Foo() {
    this.bar = 'bar';
}

Foo.prototype.getBar = function() {
    return this.bar;
}
</code>```

Or should it be in the end of the file:

```<code>function Foo() {
    this.bar = 'bar';
}

Foo.prototype.getBar = function() {
    return this.bar;
}

module.exports = Foo;
</code>```

I know that there is no technical difference. The first example is perfectly valid because of declaration hoisting.

So I was wondering if there are some kind of best practices.

答:
There are certainly lots and lots of options, which are all commonly used. But that's terribly annoying. I like to put it at  the end, because that works under all circumstances. Whenever I find myself doing something fancy with module.exports, there is probably a better way to do it.

Most importantly, as always, be consistent. And be consistent in your team.

EDIT: On the same notion, I like to have all require statements at the beginning. My Node.js files always look like this:

```<code>"use strict";

const fs = require("fs");
const MyClass = require("./MyClass");

class MyOtherClass extends MyClass {}

module.exports = MyOtherClass;
</code>```

Nothing fancy, just the way you would expect it. One class per file, one file per class. Files named after the class they contain, with consisten upper/lowercasing. Have a look at this node module, for some examples: yaioc (disclaimer: I'm the author, and this is shameless advertising)

Body:
There are certainly lots and lots of options, which are all commonly used. But that's terribly annoying. I like to put it at  the end, because that works under all circumstances. Whenever I find myself doing something fancy with module.exports, there is probably a better way to do it.

Most importantly, as always, be consistent. And be consistent in your team.

EDIT: On the same notion, I like to have all require statements at the beginning. My Node.js files always look like this:

"use strict";

const fs = require("fs");
const MyClass = require("./MyClass");

class MyOtherClass extends MyClass {}

module.exports = MyOtherClass;

Nothing fancy, just the way you would expect it. One class per file, one file per class. Files named after the class they contain, with consisten upper/lowercasing. Have a look at this node module, for some examples: yaioc (disclaimer: I'm the author, and this is shameless advertising)


问:
How can we rollback a database synchronized over multiple systems?
On a mobile device, a set of operations has been saved in the local DB with a wrong date (because the system date was set in the future). Then the device regularly doing synchronisation with a server DB, the erroneous operations have been propagated to the server.

Later the wrong date has been detected by the mobile user, and the system date set back correctly, and the user resumed his normal flow of work, pushing even more data to the server.

What should be the best strategy to clean the data from this incorrect state. As suggested in Accountants Don't Use Erasers, a wrong entry (invoice for example) should be compensated by a negative corresponding entry (credit note).

Then what if the problem is with the date of the entry ? How to compensate a wrong date ?

More generally what is the best strategy to rollback a database longtime after data have been committed ? and how to rollback when database is synchronized over multiple systems ?

NB : I posted first in stackoverflow.com but I believe here is a more appropriate place.

答:
First you need to decide how to make this change. Either update all the necessary invoice date fields or cancel the invoice and copy/rebuild all the data with a different date and possibly invoice number.

Once you can code making this change, you can then decide on how to apply it to many invoices. If you think the problem is going to continue to stem from mobile app imports, start attaching some sort of Batch ID to all the records imported from each device at each import. Date and time stamp along with any other device and/or user indicator you can include. You'll probably end up with a batch table and a batch id as a foreign key in your invoice table.

Ideally, you could just filter a group of invoices out by user and some sort of date range and change them all from Date A to Date B.

Someone with domain knowledge needs to get involved in this process on what to do and the ramifications and then some manager gets to make a decision.


问:
how to evaluate own project
I am working on a open source project in pure C, that I have started some time ago, but only recently found time to add some features. I can clearly some weaknesses of my old design, so I am trying to refactor my old code. I have no idea however, how to evaluate properly my new code. Do you know about any techniques or tools for code evaluation? I am pretty good with object oriented design, but for about three years I had no contact with purely structural one. Therefore I don't have enough experience, to be able to discern between good and bad design choices.

答:
Somewhat of a second answer...

@MainMa Of course there is, actually there are many ways to evaluate and assess software quality, those are software development processes that go from the highly regarded Scrum, to the less practical and more rigid (but perhaps more objective) PSP (for personal code) & TSP (for team code).

First, one must define the type of software quality factor one is seeking, then pursue it with the right tools. For personal code, try the Personal Software Process but ditch the fugly paper forms for modern documentation such as UML, BPMN, etc., or even apply Scrum in a personal fashion.

@gruszczy Perhaps with your case, I'd seek a code repository hosting site that support a good code review workflow, such as github.

Code reviews and TDD, I think, are some of the best practices happening in open source projects right now, because they both keep the code alive and healthy

OwnerDisplayName: gruszczy

Title: how to evaluate own project


问:
Javascript Closure Style Similar to Java Class Structure
PROBLEM: There is a coding imperative (S. McConnel, Code Complete) that one shouldn't code on language, but by means of it, e.g. doing right style things even if language doesn't have some possibilities. Javascript is a script language in its heart, but it pretends being OOP very much. I want my Javascript and Java coding styles be better agreed on that basis.

QUESTION ONE: In Javascript methods I split code for simplicity and do encapsulation using closures. One large method turns into multiple inside its scope. Is it a bad practice?

QUESTION TWO: In Javascript method I declare variables first, then declare a method-constructor with a name of its parent-method, then go other methods-resources - like in Java classes. No script is floating directly in the body, except for one-line constructor call in the end of parent-method (void or return). When you open a closure method its main operations are atop. Any reasons why shouldn't I do that?

```<code>function parentFunction() {
  var myVariable;
  var scope = this; // Keep scope stable inside enclosed methods.

  function parentFunction() {
    // A pointless action to demonstrate an approach:
    return (
      sonFunction() ||
      daughterFunction());
  }

  function sonFunction() {
    return scope.name;
  }

  function daughterFunction() {
    return scope.name;
  }

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

答:
Where this style starts to be a little awkward is when you introduce public methods:

```<code>function ParentFunction() {
  var myVariable;
  var scope = this; // Keep scope stable inside enclosed methods.

  function parentFunction() {
    sonFunction(); // no 'this'/'scope'
    this.daughterFunction(); // needs 'this'/'scope'
  }

  function sonFunction() {
    return scope.name;
  }

  scope.daughterFunction = function() {
    return scope.name;
  };

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

Or define public methods like this, avoids "sometimes use this/scope, sometimes not":

```<code>function daughterFunction () {
  return scope.name;
}
scope.daughterFunction = daughterFunction;
</code>```

But that's even more boilerplate. My advice is: Go with the language. There is no privacy, there is no classes (yet). But a pretty powerful prototype system:

```<code>function ParentFunction() {
  // ...
}

ParentFunction.prototype = {

  sonFunction: function () {
    return this.name;
  },

  daughterFunction: function() {
    return this.name;
  }

};
</code>```

Which is very much like Java classes

```<code>class ParentFunction {

  public ParentFunction() {
    // ...
  }

  public string sonFunction() {
    return this.name;
  }

  // ...

}
</code>```

Or (near future) JavaScript classes:

```<code>class ParentFunction {

  constructor() {
    // ...
  }

  sonFunction() {
    return this.name;
  }

  // ...

}
</code>```

Body:
Where this style starts to be a little awkward is when you introduce public methods:

function ParentFunction() {
  var myVariable;
  var scope = this; // Keep scope stable inside enclosed methods.

  function parentFunction() {
    sonFunction(); // no 'this'/'scope'
    this.daughterFunction(); // needs 'this'/'scope'
  }

  function sonFunction() {
    return scope.name;
  }

  scope.daughterFunction = function() {
    return scope.name;
  };

  return parentFunction();
}

Or define public methods like this, avoids "sometimes use this/scope, sometimes not":

function daughterFunction () {
  return scope.name;
}
scope.daughterFunction = daughterFunction;

But that's even more boilerplate. My advice is: Go with the language. There is no privacy, there is no classes (yet). But a pretty powerful prototype system:

function ParentFunction() {
  // ...
}

ParentFunction.prototype = {

  sonFunction: function () {
    return this.name;
  },

  daughterFunction: function() {
    return this.name;
  }

};

Which is very much like Java classes

class ParentFunction {

  public ParentFunction() {
    // ...
  }

  public string sonFunction() {
    return this.name;
  }

  // ...

}

Or (near future) JavaScript classes:

class ParentFunction {

  constructor() {
    // ...
  }

  sonFunction() {
    return this.name;
  }

  // ...

}


问:
Is there a generally accepted definition of "Secondary Index" independent of DB product?
Is the definition for "Secondary Index" anything more specific than just "Any index that is not the primary index"?

EDIT: Here is some research I have done:

Search Google. I evaluated the first 20 results. These included:

a) links to websites for priopetary DB products such as DynamoDB, Oracle, MySQL, etc. (and therefore not valid answers IMO because I'm asking about definitions independent of DB product)

b) the opinion of someone named Devang Savaliya[1] who identifies as a Footballista and whose expertise I'm less than 100% confident in.

c) Course notes from universities such as Simon Fraser University[2] and UC Davis[3], which don't seem to be specifically about database indices

d) A defintion from TutorialsPoint.com[4]

Refer to the Wikipedia entry for database indexes[5] which does not contain the word "secondary"

[1] https://www.quora.com/What-is-difference-between-primary-index-and-secondary-index-exactly-And-whats-advantage-of-one-over-another/answer/Devang-Savaliya
[2] http://www.cs.sfu.ca/CourseCentral/354/zaiane/material/notes/Chapter11/node8.html
[3] http://web.cs.ucdavis.edu/~green/courses/ecs165a-w11/7-indexes.pdf
[4] http://www.tutorialspoint.com/dbms/dbms_indexing.htm
[5] https://en.wikipedia.org/wiki/Database_index

答:
Usually a 'secondary index' is an index which is not used to enforce the primary key constraint. This seems to be a pretty widely-accepted term in the world of relational DBMSes.

In non-relational world, I don't know.


问:
What is wrong with this substring-matching algorithm?
At a recent interview I was asked to write an algorithm which:

Given a string text, and string subtext, finds the starting character positions of each subtext found within the text.

```<code>"hey hi how are you hi" = 5, 20
</code>```

I was forbidden to use any System.String functions (Substring, IndexOf etc).

I wrote this in C#:

```<code>IEnumerable<int> CalculateSubtextPositions(string text, string subtext)
{
    var charIndexToMatch = 0;
    for (int i = 0; i < text.Length; i++)
    {
        if (text[i] != subtext[charIndexToMatch])
            charIndexToMatch = 0;

        if (text[i] == subtext[charIndexToMatch])
        {
            charIndexToMatch++;
            if (charIndexToMatch == subtext.Length)
            {
                yield return i - charIndexToMatch + 2;
                charIndexToMatch = 0;
            }
        }
    }
}
</code>```

Which was described as 'disappointing'. It may well be I've missed something, but I can't see what's hugely wrong with the above. It works, it's efficient, and reasonably easy to read compared to many approaches (at least in my opinion, please correct me if I'm wrong).

Would people be able to suggest where I might have messed up? It may have been because I was asked to make the code 'reusable', but I'm not sure to what extent that can be applied when you're only asked to write an algorithm.

Please do criticise! :)

答:
Your code isn't correct enough.

When you detect a match failure, resetting your match counter to 0 is too aggressive; as kevin pointed out, this can miss valid matches if the text is constructed misleadingly. You have to reset to the last possible global match start position, and that isn't easy to do. In an interview, I'd probably go for the obvious double-loop solution instead.


答:
You should definitely not be the only reviewer, but there are lots of good reasons for you to be one of the reviewers.  Not knowing the language is not much of a hindrance for a lot of questions that need answering in a code review.  As an example, I'm one of the top 20 answerers in the C# tag on this site, and I've not so much as compiled hello world in C#.

Some expertise you can share without knowing the language:

Domain knowledge.

General object-oriented design.

General programming practices:  naming, clarity, and so forth.

It's also a good way to come up to speed on a new product.  I just joined a new team, where I know the languages used quite well, but don't know the domain.  Participating in code reviews has helped me learn the domain side better, even though I haven't been able to contribute much along those lines yet.

In your case, it will be a good way to learn the idioms of a new language, as you see the comments other reviewers leave.  These are the kinds of things that are very difficult to learn any other way, because your interpreter doesn't care if your code is pythonic or not.


问:
How are head first books?
I have never read any of them but I find their style interesting and unique.  I am not sure if they are worth giving money/time?</p>

答:
I'm not terribly fond of them personally: I prefer denser texts that allow me to absorb information very quickly.  However, I've been coding since age 6 and am accustomed to picking up new skills/languages on the fly.  The exercises are a waste on me (if I'm learning foo, it's because I need to use foo for something -- that is my exercise).

Many newbies I know swear by the Head First series, for exactly the reasons I dislike it: the language isn't very dense, so (to the newbie) it feels more approachable, and there are plenty of exercises to practice with.

So, it comes down to your learning style: do you like to wander around a subject to get your bearings, try some exercises, and take it slow, or do you want a dense manual from which to launch into some project-at-hand?  Head First books are good for the former, not for the latter.

Title: How are head first books?


问:
JIT based on precompiled code templates
This is a crazy idea that I just came up with, and I'm interested in knowing if it would be workable, or if someone already wrote about or implemented it.

Imagine you are on a platform (a game console, iOS, ...) where you cannot implement a JIT compiler due to technical reasons1 - you cannot make writable memory executable. You can write an interpreter, but you'd like to make it faster. Now, memory is fairly cheap and code is relatively small compared to other assets, so you can always add more pre-compiled code.

What if you just add lots of (ahead-of-time) compiled code pieces to your binary - one for every sequence of instructions you're likely to need? You can make the pieces configurable by passing arguments in through registers or memory. One trivial example is replacing a simple loop (pseudocode)

```<code>for i in range(100000):
    array[i] = 0;
</code>```

with memset(&array, 0, 100000). But you can do a lot better. Compile some typical programs, take the 1000 top N-grams of instructions, and put them in your binary. Now string them together - either using computed jumps (I don't know if they would be available in a typical locked-down system) - or by wrapping the larger ones in functions, or by using some return-based-programming trickery.

There are a few trade-offs here:

One is that there is much overhead since you have to compile in a lot more code than you actually will use. However, it might be that performance-critical code (for a given platform and use case) has a lot of common pieces. Think graphics code for example.

Another one is that, while executing the compiled code bits is faster than interpreting them, you have some overhead due to jumping around between the code bits. I also have a hunch that the lack of cache locality between far-apart code pieces might be bad. Both these should be especially true on modern processors.

So, I'm wondering if someone smarter than me already thought about this, and can tell me about these trade-offs, and how well this would work in reality.

1) Note I'm not asking about the legal aspects, which is beyond the scope of the site anyway. Someone might forbid you from writing a JIT compiler, and then you invent something that is technically not a JIT, but the same thing in spirit, and you've just created a lot of work for lawyers. This question is about technical aspects - say you want something JIT-like on a Havard architecture computer.

答:
This idea is... less crazy than I'd have said at first glance. To cast it in more sober language, this would mean:

Identifying common patterns in the interpreted code

Writing or generating native code equivalent to those patterns

Replacing instances of these patterns with calls to the native code

Minus the third step, which is often left to users of the language, this is a very popular way to make dynamic languages faster. Well, they don't grab random N-grams out of the code, they choose meaningful operations for which a separate function makes semantic sense, but still, they speed up (e.g.) Python code by writing common operations in C and calling it in their Python program.

With this prior art in mind, your concerns seem unfounded to me. It will be just like any other natively implemented function, and calling those is usually quite efficient. There is a tiny bit of overhead from the jump (but keep in mind that you have at least one jump per bytecode instruction), and some more from the icache pressure, but if the function was worth optimizing in the first place then the speedup will far outweigh those concerns.

But as always, the devil is in the details. Here are just a few:

You probably don't want to go by which patterns occur most often, but by which patterns take the most time, which puts you into the realm of profile-guided optimizations. Certainly doable, but quite a hassle in practice.

If the pattern writes to variables used outside of the pattern or does complicated control flow like returning from the surrounding function, you either need to include the surrounding code in the pattern (and lose opportunities for applying it) or do complicated, problem-specific rewriting of the surrounding code.

Unless you do the second step manually, the translation to native code can probably not do much better than simply chaining together the dynamically-typed, late-bound operations that the interpreter would perform while interpreting the original code. This often gives a nice speedup, but it's rarely anywhere as drastic as going from an interpreted loop to memset.

It may be quite hard to choose the appropriate boundaries for the patterns automatically. Maybe you want to assume some inputs are constant, maybe you want to generalize other parts to apply the optimization more generally, etc.

Dynamic languages usually have quite extensive capabilities to break optimizations.

Oh my god don't even get me started on how hard it is to statically optimize dynamic languages.

Really, don't.

It's so hard you wouldn't believe.

At the very least you'd have to assume all values involved have one concrete type (and ideally a built-in one that can't be modified) and bail out of the pattern if you find yourself with different types. And even that can break in languages like Ruby where you can even redefine even arithmetic on numbers.

(Of course you could stomp your foot and declare that these things are not permitted, but then it's not the same language any more and you could get much greater wins across the board by optimizing the interpreter for this new restriction, or perhaps even make it a static compiler.)

Maybe you can fix some of these problems by getting more inspiration by JIT compilers, specifically tracing ones. That is, run the program, let the JIT compiler identify hot code paths (including assumptions made during optimization) and statically insert these optimized traces into the program. Tracing JIT compilers already know how to handle all these things. It would be mostly an engineering challenge (making data structures and machine code suitable for a static binary).

Another variant on the same idea is to give up on automating the second and third step: Use tools to find patterns that might benefit from optimization, then optimize them manually. Less shiny, but also more likely to actually work.

Conclusion: Nice idea for a thesis, but I wouldn't bet on it working out in its current form.

Title: JIT based on precompiled code templates


答:
They may have asked you to review Python code precisely because you don't know Python.  There's a management theory that it's useful to have a "fool" on a team.  I'm not calling you a bad name :)  The idea is that a team may suffer from group think and develop tunnel vision.  One way to break out of this is to include someone on the team who the other team members would consider a "fool", that is, someone who doesn't know the subject matter.  You'll ask questions to inform yourself, and the questions will come from a point-of-view that the other team members likely never considered.

You don't know Python, so what may seem ordinary to the Python coders may seem strange to you.  You might suggest an improvement that the team never considered.