答:
Okay, I'll bite, but a small disclaimer: I don't have any sources backing me up (at least that I can link to, they might be out there) and this is written purely from my understanding/interpretation of the original intentions of MVC which might very well not be correct.

Originally MVC made sense because heavily managed event-driven GUI engines (such as a window manager or DOM) didn't exist. You had a model, a view (monitor), and a controller (keyboard). Now, whenever something was triggered on your input device (keyboard) you needed to alter your model and subsequently update the view. This was the usual UI paradigm at this point in time - then along came window managers.

Window managers abstracted the input device away some, by tying the view and the controller together for you. You no longer received a "keyboard y was pressed"-event but rather a "textbox1 had an y applied to it"-event, or in the case of a mouse it was no longer "mouse clicked at point(400, 500)", but "mouse clicked on top of button1". The UI was now interactive, and I'm sure most Window managers use pure MVC under the hood and keep a model of where on the screen button1 is and which element has focus etc. etc.

Fast forward; people kept using the word "MVC" in interactive GUI programming, but it sort of lost its meaning. I remember when I was a student and we learned about MVC, and I tried to somehow fit the pattern onto java swing. I never fully understood why we had to do that, as it made absolutely no sense ... What was the input now? Why should I separate the buttons appearance from its input-options when both of these was already tied together for me in the jButton class? This is where I think a lot of confusion comes from...

Now, another small and popular way of programming a UI is leveraging HTTP and the world wide web. Server-side MVC has been reborn with a ton of frameworks popping up embracing the pattern in its original intention. Something happens as an input (a HTTP request) which alters the model and finally updates the view (by doing a response of some html).

All well and good. We got Interactive GUIs using window managers (like WPF, JavaFX, Qt, etc) and we got non-interactive GUIs (like HTTP or embedded MMIs).

So which of these is client-side MVC on the web? I'd say they look a lot more like interactive GUIs than non-interactive ones. You got a DOM which handles both appearance and behaviours and you got a closely tied view/controller (at least according to MVCs original definition). In my opinion this leads to the same conclusion as for desktop programming; original MVC just doesn't fit, and something like MVP (which a lot of 'MVC-implementations' actually look a lot like) or MVVM makes more sense.

So, back to your original questions:

In other words, does the fact that we're ususing

JavaScript, a loosely typed and very different language from the ones
  used when the MVC pattern was designed

and use the DOM + CSS, a predefined simplified method of rendering
  content, whereas before web development, applications used their own
  rendering engines or rendering libraries to display content, perhaps
  making the MVC pattern more necessary

change the way we should define and use the MVC pattern in a web
  development environment? Are there any fundamental differences in the
  original usage of MVC in a non web environment and using MVC in web
  development?

IMHO, yes. There's fundamental differences in the original usage of MVC in a non web environment and using MVC in web development, and we probably should change the way we define it, but at this point I think it's too late. Let the buzzer's keep saying MVC, while the rest of us refer to "Original MVC" or "Buzzword MVC" :)

Title: How does the usage of MVC in web development fundamentally differ from the original usage of the pattern?

Body:
I recently read an answer regarding MVC and web development, mostly about how it was originally designed for older systems and has since been applied poorly in web development. That being said, I'm sure every pattern has by now been used poorly in web development. But I'd still like to make sure that I don't make the same mistakes in applying this pattern to web development, leading myself and potentially my team into having the same bad experience with MVC.

We now deal with an obscene web-mvc hybrid that, with its awful
  buzzword status, ill definition, and having
  semi-illiterate-programmers as a target demographic, makes a really
  bad publicity to software patterns in general.

MVC, thus, became separation of concerns distilled for people who
  don't really want to think too much about it.

As someone learning about MVC and considering using it in a web application, I'd like to know from an objective perspective how the MVC pattern should be applied to web development.

It's occurred to me that web development, having pre-existing methods for rendering content via the DOM, and with JavaScript being a loosely typed language, MVC probably relates very differently to web development than it does to older systems used when it was first popularized.

Fundamentally speaking, how does the usage of the MVC pattern's (proper) usage in web development differ from its usage in a non-web environment, with strictly typed languages and no DOM and browser rules for easy GUI rendering and alteration? In other words, does the fact that we're ususing

JavaScript, a loosely typed and very different language from the ones used when the MVC pattern was designed

and use the DOM + CSS, a predefined simplified method of rendering content, whereas before web development, applications used their own rendering engines or rendering libraries to display content, perhaps making the MVC pattern more necessary

change the way we should define and use the MVC pattern in a web development environment? Are there any fundamental differences in the original usage of MVC in a non web environment and using MVC in web development?


问:
How does the usage of MVC in web development fundamentally differ from the original usage of the pattern?
I recently read an answer regarding MVC and web development, mostly about how it was originally designed for older systems and has since been applied poorly in web development. That being said, I'm sure every pattern has by now been used poorly in web development. But I'd still like to make sure that I don't make the same mistakes in applying this pattern to web development, leading myself and potentially my team into having the same bad experience with MVC.

We now deal with an obscene web-mvc hybrid that, with its awful
  buzzword status, ill definition, and having
  semi-illiterate-programmers as a target demographic, makes a really
  bad publicity to software patterns in general.

MVC, thus, became separation of concerns distilled for people who
  don't really want to think too much about it.

As someone learning about MVC and considering using it in a web application, I'd like to know from an objective perspective how the MVC pattern should be applied to web development.

It's occurred to me that web development, having pre-existing methods for rendering content via the DOM, and with JavaScript being a loosely typed language, MVC probably relates very differently to web development than it does to older systems used when it was first popularized.

Fundamentally speaking, how does the usage of the MVC pattern's (proper) usage in web development differ from its usage in a non-web environment, with strictly typed languages and no DOM and browser rules for easy GUI rendering and alteration? In other words, does the fact that we're ususing

JavaScript, a loosely typed and very different language from the ones used when the MVC pattern was designed

and use the DOM + CSS, a predefined simplified method of rendering content, whereas before web development, applications used their own rendering engines or rendering libraries to display content, perhaps making the MVC pattern more necessary

change the way we should define and use the MVC pattern in a web development environment? Are there any fundamental differences in the original usage of MVC in a non web environment and using MVC in web development?

答:
The typing or the language makes no impact whatsoever, so ignore that.

The Model is the same, as its the holder for all data that is passed on for display.

There's difference in the View - where the original constructed a GUI that was persistent, the Web equivalent constructs a GUI each time a request is made from the client browser. However, both are doing the same kind of work (roughly) - constructing a view, its just that one is persistent and the other transient. Operations on one directly call the controller to manipulate elements, whereas the other has a browser as a 'proxy' for this, only calling the controller when links are clicked that require a refreshed view.

This suggests the Controller part is the main difference - whereas the original used this to route messages to event handlers to manipulate the GUI elements, the web version is more concerned with routing the request for a view.

So I would say there's little difference from a conceptual point of view, though big differences in implementation, but then you could say this about a MVC system created using C++ MFC and another created using Swift and Cocoa for example. I imagine you could create a MVC desktop system that recreated the GUI display every time a link was pressed (and could say this happens anyway, if you click a button that pops up a dialog, its creating a brand new view for you). Similarly, persistence of data is the same - lots of thick GUIs write directly to a database, and although they don't fetch state for every request, using session state or not isn't exactly a fundamental aspect of MVC.

ContentLicense: CC BY-SA 3.0


问:
Simple explanation of MVC needed
I am trying to understand MVC, but for most of the Q&A's I have seen, the description is great but I cannot quite understand it, I think it works like this scenario I thought of:

User Registration (sorry for the wrong order):

Controller: The user, they input the data (username & password)

Model: The UserRegistration class - Takes in the username and password and deals with the request

View: A success message passed to the user (just an example!)

Am I right in thinking that it goes the same for any language; C#, C++, PHP etc.?

I have tried for ages to understand this and what I am looking for is: talk to me like I am a child or a monkey.

I have looked here (What is MVC, really?) and found it didn't help me

答:
As your example of user registration:

Model: This would be your "User" class which is populated at the end of registration, that stores the Username, Email, Password, etc. This would then be put into the database.

View: The HTML page which allows the user to input their desired Username, Email, Password, and click submit.

Controller: Gives the View to the User initially so they can fill out the registration form. Then takes the details from the View, uses them to populate the Model and create a record in the database.

An easy way of looking at it is that the Controller acts as a bridge between Model and View. If you wish to retrieve data from a db, the Controller accesses the Model layer, and passes the data down into the view. If you want to store data, the data you enter into the view is passed to the Controller which runs logic (validation, modification) on the user submitted data, creates the Model using that data, and stores it in the database.

Title: Simple explanation of MVC needed


问:
How can I represent a flowchart, complete with conditional logic using JSON or XML?
One part of a project I'm working on is interactive scripts for call centre staff. Pretty much every possibility I can think of in this case can be represented on paper as a flowchart, which is why I'll be making an interactive "script builder" that is essentially a flowchart builder in HTML5/JS. This will let me add conditional logic to the scripts, so the agent could be prompted to say something specific based on the reply from the person being called.

Currently I'm stuck in the planning phase: how do I represent each script/flowchart in my system? I need something that can be completely represented using either JSON or XML, as the system is web based.

答:
Effectively, a flow chart is just a fancy graph.  So, you will have nodes and edges.  Nodes will have text, (optionally) position/size, and unique ids.  Edges will have a pair of nodes and a name.

So, suppose we have, "Ask user their name.  If their name is Bob, compliment them.  Otherwise, hang up on them."

Something like this:

```<code>var JsonGraph = {
    Root: 1,
    Nodes: {
        1: {Text: "Ask user their name.  Is their name Bob?"},
        2: {Text: "Compliment the user."},
        3: {Text: "Hang up on the user."}
    },
    Edges: [
        {Source:1,Destination:2,Text:"yes"},
        {Source:1,Destination:3,Text:"no"}
    ]
}
</code>```

The Edge text turns into a button within the wizard.  The node text turns into the text within the wizard.

Body:
Effectively, a flow chart is just a fancy graph.  So, you will have nodes and edges.  Nodes will have text, (optionally) position/size, and unique ids.  Edges will have a pair of nodes and a name.

So, suppose we have, "Ask user their name.  If their name is Bob, compliment them.  Otherwise, hang up on them."

Something like this:

var JsonGraph = {
    Root: 1,
    Nodes: {
        1: {Text: "Ask user their name.  Is their name Bob?"},
        2: {Text: "Compliment the user."},
        3: {Text: "Hang up on the user."}
    },
    Edges: [
        {Source:1,Destination:2,Text:"yes"},
        {Source:1,Destination:3,Text:"no"}
    ]
}

The Edge text turns into a button within the wizard.  The node text turns into the text within the wizard.


问:
Vertical alignment: yea or nay?
For instance, non-vertically aligned:

```<code>Name:   Hamt
Version:  0.1.0
Cabal-Version:  >= 1.2
License:  BSD3
Author:  Jason Baker
</code>```

Or vertically aligned:

```<code>Name:           Hamt
Version:        0.1.0
Cabal-Version:  >= 1.2
License:        BSD3
Author:         Jason Baker
</code>```

Which do you prefer and why?

答:
I prefer a hybrid:

```<code>Name    : Hamt
Version : 0.1.0
Cabal-Version :  >= 1.2
License : BSD3
Author  : Jason Baker
</code>```

Which is essentially number 2 with exceptions for occasional lines that are longer than the surrounding lines - to prevent the majority of lines being spaced far over.

ContentLicense: CC BY-SA 2.5

Title: Vertical alignment: yea or nay?

Body:
I prefer a hybrid:

Name    : Hamt
Version : 0.1.0
Cabal-Version :  >= 1.2
License : BSD3
Author  : Jason Baker

Which is essentially number 2 with exceptions for occasional lines that are longer than the surrounding lines - to prevent the majority of lines being spaced far over.


问:
Which scenarios to use .NET Concurrent Collections effectively?
I am investigating how to introduce parallelism into an application to improve performance. In particular, I am looking at parallel for loops and their variants and my initial experiments show significant overhead to using collections from the System.Collections.Concurrent namespace.

Typical scenario

Want to iterate over a collection in Parallel, perform some computations per iteration and then route/add the results into an appropriate collection depending on the details of the iteration.

[If you don't use the Concurrent Collections you get errors due to the usual multi-threading & synchronization issues so you appear to be forced into using the Concurrent collections.]

Unfortunately my tests mostly/often show that the single-threaded simple solutions perform faster due to the overhead of using the Concurrent Collections - is this to be expected?

Tentative Conclusions

You would need to be doing a "very large" piece of work per iteration for the Concurrent Collections to perform better than a single threaded solution?

Code Example

As per requests in the comments:

open System.Collections.Generic
open System.Collections.Concurrent
open FSharp.Collections.ParallelSeq

type Data = {
    Name:string
    mutable Age:int
    Description:string
}

[<EntryPoint>]
let main argv =

    let xs = ResizeArray<Data>()
    let n = 1000000

    let rand = System.Random()

    // create some random data
    for i in 0..n do
        let f1 = rand.NextDouble()
        let f2 = rand.NextDouble()
        let data = {Name = "My Name" + f1.ToString() + f2.ToString(); Age = 38; Description = "Happy"}
        xs.Add(data)

    // single-threaded example
    let normalCollection = Dictionary<string,Data>()
    let stopWatch = System.Diagnostics.Stopwatch()
    stopWatch.Start()
    xs |> Seq.iter (fun x ->
        x.Age <- x.Age + rand.Next()
        normalCollection.[x.Name] <- x
        )
    stopWatch.Stop()
    printfn "Single Threaded: %A" stopWatch.Elapsed

    System.GC.Collect(2)

    // single-threaded + concurrent Collection example
    let concurrentCollection = ConcurrentDictionary<string,Data>()
    let stopWatch = System.Diagnostics.Stopwatch()
    stopWatch.Start()
    xs |> Seq.iter (fun x ->
        x.Age <- x.Age + rand.Next()
        concurrentCollection.[x.Name] <- x
        )
    stopWatch.Stop()
    printfn "Single Threaded + Concurrent Collection: %A" stopWatch.Elapsed

    concurrentCollection.Clear()

    System.GC.Collect(2)

    // multi-threaded example
    let concurrentCollection = ConcurrentDictionary<string,Data>()
    let stopWatch = System.Diagnostics.Stopwatch()
    stopWatch.Start()
    xs |> PSeq.iter (fun x ->
        x.Age <- x.Age + rand.Next()
        concurrentCollection.[x.Name] <- x
        )
    stopWatch.Stop()
    printfn "Multi-Threaded: %A" stopWatch.Elapsed

    // Functional Style
    normalCollection.Clear()
    System.GC.Collect(2)
    let stopWatch = System.Diagnostics.Stopwatch()
    stopWatch.Start()
    let ys =
        xs
        |> PSeq.map (fun x -> {x with Age = x.Age + rand.Next()} )
        |> Seq.iter (fun x -> normalCollection.[x.Name] <- x)
    stopWatch.Stop()
    printfn "Functional Style: %A" stopWatch.Elapsed

    printfn "%A" argv
    0 // return an integer exit code
```

Timing

Consistent over multiple runs...

n = 10,000 (small data set)

Single Threaded: 00:00:00.0048328

Single Threaded + Concurrent Collection: 00:00:00.0053433

Multi-Threaded: 00:00:00.0197919

Functional Style: 00:00:00.0073613

n = 10,000,000 (large data set)

Single Threaded: 00:00:04.0683213

Single Threaded + Concurrent Collection: 00:00:13.6469918

Multi-Threaded: 00:00:10.9768615

Functional Style: 00:00:04.6633076

答:
What you are measuring is the speed of adding a fixed set key-value pairs to a Dictionary in the reduce part of a map-reduce operation.

The ConcurrentDictionary is meant for a more general use-case: concurrent readers+writers, no coordination between any of the participants, writes to the same keys, reads to the same keys. There is a performance cost to each of those features, so it is no surprise the ConcurrentDictionary isn't competitive in your benchmark.

Two ways to explore from here could be:

How to implement a Dictionary that gains from multiple threads in your benchmark?

What is a realistic benchmark that requires the features ConcurrentDictionary provides and how does it's performance compare in that case?


问:
Searching for 2 numbers that equal 10
During an interview today I was asked to write a function that accepted an array of integers and return the positions of two values in the array that the sum was 10.

My code was

C#

```<code>public string ReturnIntegers(int[] arrayOfIntegers)
{
   for(int j = 0; j < arrayOfIntegers.Length - 1; j++)
   {
      for(int k = j + 1; k < arrayOfIntegers.Length; k++)
      {
          sum = arrayOfIntegers[j] + arrayOfIntegers[k];
          if(sum == 10)
             return j + "," + k;
      }

}
</code>```

Assuming the array entered has more than 2 values. My interviewer said that this had a magnitude of n^2 if the array contained a billion values. What is a better solution (performance) to support a large number of values.

答:
There are really two questions here

could the algorithm have been implemented in a better/cleaner manner

is there a better algorithm.

Two things leap out at me your implementation. Firstly there is nothing to handle the case where there is no soloution. The function just reaches the end without reachign a return statement. In some languages this is a compile error, in others it gives undefined behaviour. I don't know about C# specifically. The other is you are returning the result as a String, that usually isn't a very efficient way of doing things.

Regarding the algorithm the algorithm you have chosen has a complexity of order n² . So for large lists it will be slow. On the other hand it doesn't allocate any aditional memory/create any new objects and for small lists I expect it is actually the fastest soloution.

For large lists it may be better to do something like (note: this is untested and I don't code in c#)

```<code>public string ReturnIntegers(int[] arrayOfIntegers)
{
   Dictionary d<int,int> = new Dictionary<int,int>

   for(int j = 0; j < arrayOfIntegers.Length - 1; j++)
   {
      d.add(10-arrayOfIntegers[j]),j)
   }
   for(int k = 0; k < arrayOfIntegers.Length; k++)
   {
       if (d.ContainsKey(arrayOfIntegers[k])) {
           j = d[arrayOfIntegers[k]]
           return j + "," + k;
       }
   }
   return null;
}
</code>```

Title: Searching for 2 numbers that equal 10

Body:
There are really two questions here

could the algorithm have been implemented in a better/cleaner manner

is there a better algorithm.

Two things leap out at me your implementation. Firstly there is nothing to handle the case where there is no soloution. The function just reaches the end without reachign a return statement. In some languages this is a compile error, in others it gives undefined behaviour. I don't know about C# specifically. The other is you are returning the result as a String, that usually isn't a very efficient way of doing things.

Regarding the algorithm the algorithm you have chosen has a complexity of order n² . So for large lists it will be slow. On the other hand it doesn't allocate any aditional memory/create any new objects and for small lists I expect it is actually the fastest soloution.

For large lists it may be better to do something like (note: this is untested and I don't code in c#)

public string ReturnIntegers(int[] arrayOfIntegers)
{
   Dictionary d<int,int> = new Dictionary<int,int>

   for(int j = 0; j < arrayOfIntegers.Length - 1; j++)
   {
      d.add(10-arrayOfIntegers[j]),j)
   }
   for(int k = 0; k < arrayOfIntegers.Length; k++)
   {
       if (d.ContainsKey(arrayOfIntegers[k])) {
           j = d[arrayOfIntegers[k]]
           return j + "," + k;
       }
   }
   return null;
}


问:
Should I use a mock or create a new instance of an object in unit tests?
I have to write a unit test for a method like:

```<code>void doSomethingWith(Country country) {...}
</code>```

There are the following classes:

Interface:

```<code>public interface Country {
  String getName();
  ... // and a lot of other methods, more than 20
}
</code>```

Class, implementing the interface:

```<code>public class CountryInst implements Country {
  ...
}
</code>```

For my test I'm choosing between the following options:

1) Pass a mock as a parameter:

```<code>Country country = Mockito.mock(Country.class);
Mockito.doReturn("Canada").when(country).getName();
doSomethingWith(country);
</code>```

2) Or create a new instance of CountryInst and override the needed method:

```<code>Country country = new CountryInst {
  @Override
  String getName() {
    return "Canada";
  }
}
doSomethingWith(country);
</code>```

Which one is preferable?

答: It largely depends on whether doSomethingWith uses every single field of Country. If yes, then the two approaches would be equivalent and it would be up to you to decide which one is more readable. Otherwise, it's  much cleaner to create a mock object that only stubs the methods that are interacted with, leaving out those that are not relevant. This would make it easier to understand what's being tested by  clearly stating the given/when/then parts.


问:
Performing a username lookup before registering a User while conforming to REST philosophy
I have a REST Service based on Spring MVC. JSON is the only interchange format for any client to talk to this service.

I'm working on implementing a user registration workflow. So I have created an endpoint (/register, payload=User object in JSON) that accepts the User entity and does it's thing. So I'm transferring the state of an object which makes me content about adhering to the REST philosophy (I think).

My question is: Before I can register a user, I need to check if ther username is already used up. So I can create a new endpoint /register/username/
But this idea sounds bad and not RESTful at all as I'm using the endpoint to perform an action, not transfer of state. And this sounds like I'm invoking a method to perform an action (remote RPC). How can I re think this in terms of REST?

答:
When a client attempts to add a duplicate, I would return a 409 Conflict.  A 400 bad request (with explanation error in response) would also be fine and is probably more common practice.

However, the jury is out on this one.  REST doesn't make it clear what to do in these situations.  See
https://stackoverflow.com/questions/3290182/rest-http-status-codes-for-failed-validation-or-invalid-duplicate


答:
I'm using the endpoint to perform an action, not transfer of state.

Actually, you are transferring state.  The client is sending the proposed new user entity to the server.  The server has its own rules to enforce, however, so it must refuse to create a user if their unique identifier already exists.

There is already an HTTP error code for that.  As @tom pointed out, the 409 Conflict response code is acceptable for that.  It basically means What you asked me to do is perfectly legal in from your standpoint.  I am simply unable to fulfill your request because it is in conflict with something outside of your control versus some of the other response codes which focus on inappropriate client requests.

As far as your concern about using REST to perform an action in this case, I don't agree, but I am glad you are thinking about that.  I have seen developers create "REST services" named things like GET /whatever/updateWidget, which is clearly not a RESTful way of thinking.

You are performing an action only in the sense that you are creating a new resource.  But that resource is based on the state you transferred.  You have to create it somehow.

As long as you return a meaningful error code like 409, I do not see any problems with your approach whatsoever.

Title: Performing a username lookup before registering a User while conforming to REST philosophy

Body:
I have a REST Service based on Spring MVC. JSON is the only interchange format for any client to talk to this service.

I'm working on implementing a user registration workflow. So I have created an endpoint (/register, payload=User object in JSON) that accepts the User entity and does it's thing. So I'm transferring the state of an object which makes me content about adhering to the REST philosophy (I think).

My question is: Before I can register a user, I need to check if ther username is already used up. So I can create a new endpoint /register/username/
But this idea sounds bad and not RESTful at all as I'm using the endpoint to perform an action, not transfer of state. And this sounds like I'm invoking a method to perform an action (remote RPC). How can I re think this in terms of REST?


答:
For starters, and I think you're onto this already, don't invent new verbs and stuff them into the tree.  If you find yourself wanting to do that, stop and ask yourself where in the model the data should fit, then POST it there.

Creating a new user should be an operation you do against the same part of the tree you use to get at the ones that already exist.  For example, you'd GET /users/lanceboyle to retrieve Lance Boyle's user information, so you should be POSTing to the same place to create a new one (e.g., POST /users/duanepipe).

Your situation seems to hit the major points for a return code of 409.  From RFC 7231 (emphasis mine):

The request could not be completed due to a conflict with the current state of the resource.

If there's already data in /users/warrenpease, then its state is "existing."  Trying to POST a second copy to the same location conflicts with that state because you can't create a new one of what already exists.

This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request.

Again, the user (requester) can resolve this problem by picking a different user name and POSTing it to a location that doesn't exist.


问:
Accessing data in widget
Background

I started to get involved in a project written in python and wxPython (for the GUI). My task is to debug and add a few features to the GUI.

The widgets are organised mainly with sizers, and the application as a whole only looks good at a certain screen size and resolution.
First thing I did was to group some elements under some panels and separate them with splitter (wx.SplitterWindow). But the hierarchy of the widgets changed; in one line of code I had to change from:

```<code>class CustomGrid(wx.grid.Grid):
    def __init__(self, parent, name, config):
        # ...
        self.data = self.GetParent().data
</code>```

to:

```<code>class CustomGrid(wx.grid.Grid):
    def __init__(self, parent, name, config):
        # ...
        self.data = self.GetParent().GetParent().GetParent().data
</code>```

That's ugly. In another instance a widget class get inserted in two different places and the data is not located at the same parent level.

Questions

I am suspecting that there is something wrong with the architecture here.
How to/Should I separate the data from the GUI?

Any tips and/or links to blogs or other questions would be nice to get started with. Also how to state my question better? (I'm looking forward to learning the proper lingo and perhaps edit the title!)

答:
Relative (parent-children) widget resolution is... ugly. It makes your code set in stone and GUI unchangeable. All your widgets must be isolated from each other as much as possible.

I suggest keeping track of all relevant objects in a dictionary.

```<code>_widget_dict = {"oranges_grid": oranges.grid, "apples_window": apples.mywindow}
</code>```

This is akin to **GtkBuilder in GTK+ - by keeping a reference in a book you are able to easily access them by supplying a name.

```<code>def get_widget(widget_id):
    return _widget_dict[widget_id]
</code>```

Title: Accessing data in widget

Body:
Relative (parent-children) widget resolution is... ugly. It makes your code set in stone and GUI unchangeable. All your widgets must be isolated from each other as much as possible.

I suggest keeping track of all relevant objects in a dictionary.

_widget_dict = {"oranges_grid": oranges.grid, "apples_window": apples.mywindow}

This is akin to **GtkBuilder in GTK+ - by keeping a reference in a book you are able to easily access them by supplying a name.

def get_widget(widget_id):
    return _widget_dict[widget_id]


问:
Is there any merit for using beginning iterator instead of reference to a std::vector?
I'm working on our company's lib. I see a lot of code like:

```<code>std::vector<int>::iterator it = market.vec.begin();
for (size_t i = 0; i < market.vec.size(); ++i)
    it[i] = i + 1;
</code>```

I think a reference should be better:

```<code>std::vector<int>& ref_vec = market.vec;
for (size_t i = 0; i < market.vec.size(); ++i)
    ref_vec[i] = i + 1;
</code>```

Since if we do

```<code>market.vec.resize(20);
</code>```

somewhere, it will be invalid.

So, is there any benefit that I don't know for using iterator instead of reference?

Thanks.

答:
Using iterators has several advantages:

It makes your code container-agnostic. The "C++ way" is to accept a pair of iterators. The first points to the first element, the second points to an invalid element (generally one past the final element) with the guarantee that incrementing the "begin" iterator will eventually make it equivalent to the "end" iterator which tells you when you are done processing container data.

In your case you are using a vector, which has an index. What if you were using a different data structure such as a set? You can still iterate a set, but cannot get an index. This is closely related to my previous point.

You can write reusable code to use arbitrary containers with arbitrary ranges. In fact, one could say you could write... algorithms...


问:
Include Testers inside the Team or Create a Tests Area?
I've become a leader of a group of 30 developers. We run Scrum and we have different teams for each Product Backlog.

We have no testers across the teams and I'd like add them.

My main question is:

1. Creating a different backlog and a Testing Team, where they would be shared among all Product Teams?

Pros: We could hire less testers

Cons: We could create a bottleneck to Tests Team

2. Hiring Testers for each Product Backlog

Pros: We have no bottleneck cause each Tester is allocated to a specific product

Cons: We have to hire more people.

Our goal is: Deploy the code developed in the sprints strongly tested.

Based on your experiences, which option do you think should work better under which circumstances?

答:
We could hire less testers /  We have to hire more people

That is a misconception. The total amount of testing work is still the same in both scenarios. And if in scenario two a tester dedicated to one product would run "out of work" because there is not enough to test to give him 8 hours work per day, you would probably assign him testing work from a different product either (at least, temporarily).

We have no bottleneck cause each Tester is allocated to a specific product

Same as above - you can still get a bottleneck because there could be too much to test in one product for a single person to meet your schedule.

What you should ask yourself instead is: are the different products mostly independent from each other so they can be tested individually? And do the different products need very specific knowledge to test them well (which means testers have to specialize for each product)? Then it makes sense to assign each product one or more testers as "experts" for this product.

On the other hand, if your different products are just parts of an application system, with heavy interaction between them, then assigning different people strictly to different products does not make much sense (remark: that might not only be true for your testers, but also for your devs). And even if not, if the products do not need specific user knowledge so anyone with a test plan can start testing the thing immediately, the option of shifting testers between products makes your team more flexible and helps to avoid bottlenecks.

Shifting people between different teams, however, comes always for the cost of more communication and organizational overhead - when a team can work completely on its own, it might be much more efficient as when when some of them have to work on different things in parallel. You will have to decide for yourself what works best in your case.


答:
If you're actually doing scrum, rather than something with a few Agile principles which you're calling scrum, then this is easy as there are only three roles in scrum: the product owner, the scrum master and the development team. You can't have a separate "test team" because a feature isn't finished until it's been tested, so your test function has to be part of the specific scrum team.

If you're not actually doing scrum, then do whatever works best for you. I don't actually understand how you're doing product development at all without some testers, but that's a different issue.

Title: Include Testers inside the Team or Create a Tests Area?

Body:
I've become a leader of a group of 30 developers. We run Scrum and we have different teams for each Product Backlog.

We have no testers across the teams and I'd like add them.

My main question is:

1. Creating a different backlog and a Testing Team, where they would be shared among all Product Teams?

Pros: We could hire less testers

Cons: We could create a bottleneck to Tests Team

2. Hiring Testers for each Product Backlog

Pros: We have no bottleneck cause each Tester is allocated to a specific product

Cons: We have to hire more people.

Our goal is: Deploy the code developed in the sprints strongly tested.

Based on your experiences, which option do you think should work better under which circumstances?


答:
There a limited containers in the C++ library that are required to be implemented with contiguous memory. vector is one of them, so given a reference to the first element, it is well known where the next element is in memory and the way to get there is also well known.

For other containers, it is not known how it is laid in memory, where all the elements are and how to traverse from one element to the next. Iterators provide that mechanism;

Where is the next element (++), possibly where is the previous element (--) and even, get the element 3 places away from the current one (+= 3)

It knows how to get to the value of the element being referenced (dereferencing the iterator)

It also knows when it gets to the end of the container (when compared to .end())

Once the above semantics are established, it becomes very easy to write general algorithms that are agnostic of the container being used and the memory layout.

The general algorithms can also apply some optimisations knowing the nature of the iterators (random iterators vs. forward iterators) and getting to that iterator type is embedded in the iterator itself. Sure, more specialised algorithms that know the memory layout and can be optimised further are present, but they generally land up being members of the containers.

Note: elements can be accessed by reference with members such as .front(), .back() and .at() etc. as supported by the container. Support for these is defined per container, and the front and back only get to the first and last elements, general algorithm support and usage of these members is limited.

Note on the resize: the call to resize the vector could invalidate both the iterators and element references (depending on the whether a reallocation takes place) and should generally be assumed that the resize does invalidate them.

A common technique when using iterators is to loop from the beginning to the end, given the for loop in your sample, as follows;

```<code>// auto used for the sample
// if the container is non-const, then "it" is of type
// std::vector<int>::iterator
for (auto it = market.vec.begin(); it != market.vec.end(); ++it)
    // code
</code>```

Additionally, indexes etc. could be added as required. Given the code sample, std::iota could be a good replacement for it as well.

```<code>std::iota(market.vec.begin(), market.vec.end(), 0);
</code>```

Giving more consideration to the exact sample code provided, there is little reason to use the iterator or the reference, just access the element in the vector using the index operator []. I don't see any synchronisation code so the vector won't be resized whilst the for loop runs.

That said, favour working with iterators and dereference them to get to the element's value.

Title: Is there any merit for using beginning iterator instead of reference to a std::vector?

Body:
I'm working on our company's lib. I see a lot of code like:

```<code>std::vector<int>::iterator it = market.vec.begin();
for (size_t i = 0; i < market.vec.size(); ++i)
    it[i] = i + 1;
</code>```

I think a reference should be better:

```<code>std::vector<int>& ref_vec = market.vec;
for (size_t i = 0; i < market.vec.size(); ++i)
    ref_vec[i] = i + 1;
</code>```

Since if we do

```<code>market.vec.resize(20);
</code>```

somewhere, it will be invalid.

So, is there any benefit that I don't know for using iterator instead of reference?

Thanks.

Body:
There a limited containers in the C++ library that are required to be implemented with contiguous memory. vector is one of them, so given a reference to the first element, it is well known where the next element is in memory and the way to get there is also well known.

For other containers, it is not known how it is laid in memory, where all the elements are and how to traverse from one element to the next. Iterators provide that mechanism;

Where is the next element (++), possibly where is the previous element (--) and even, get the element 3 places away from the current one (+= 3)

It knows how to get to the value of the element being referenced (dereferencing the iterator)

It also knows when it gets to the end of the container (when compared to .end())

Once the above semantics are established, it becomes very easy to write general algorithms that are agnostic of the container being used and the memory layout.

The general algorithms can also apply some optimisations knowing the nature of the iterators (random iterators vs. forward iterators) and getting to that iterator type is embedded in the iterator itself. Sure, more specialised algorithms that know the memory layout and can be optimised further are present, but they generally land up being members of the containers.

Note: elements can be accessed by reference with members such as .front(), .back() and .at() etc. as supported by the container. Support for these is defined per container, and the front and back only get to the first and last elements, general algorithm support and usage of these members is limited.

Note on the resize: the call to resize the vector could invalidate both the iterators and element references (depending on the whether a reallocation takes place) and should generally be assumed that the resize does invalidate them.

A common technique when using iterators is to loop from the beginning to the end, given the for loop in your sample, as follows;

// auto used for the sample
// if the container is non-const, then "it" is of type
// std::vector<int>::iterator
for (auto it = market.vec.begin(); it != market.vec.end(); ++it)
    // code

Additionally, indexes etc. could be added as required. Given the code sample, std::iota could be a good replacement for it as well.

std::iota(market.vec.begin(), market.vec.end(), 0);

Giving more consideration to the exact sample code provided, there is little reason to use the iterator or the reference, just access the element in the vector using the index operator []. I don't see any synchronisation code so the vector won't be resized whilst the for loop runs.

That said, favour working with iterators and dereference them to get to the element's value.


答:
I think it depends what you want your testers to do. In some cases a tester is a developer, writing unit and other automated tests. In some cases they are manual testers who write and/or run through test scripts. In some cases they are implementation engineers who test that the product delivery does what the requirements actually wanted.

In these cases you need a different deployment of testers. In the dev-tester, he needs to be part of the dev team with knowledge of the development changes. In the requirements-tester he needs to be part of the product team with knowledge of the product delivery.

QA is another interesting aspect - in this case its more of a deployment/production team that are very disconnected from the development process. (ie you drop them the final shrink-wrap product that will, if passed, be given to production).

So - as with so many things - a bit of a mix is appropriate. I found a tester per team works very well as they need the knowledge of the product the team is working on to help test it efficiently. But the testers who are assigned to the product are also very important as they're the ones who tend to know all the social, configuration and customer history of the product that often gets lost between developments.


问:
Do Rails Join Models Get Controllers?
I have a rails app where my users can buddy up with other users.  Since that relationship can have a status (approved/rejected/pending), I decided to go with a join model (UserRelationship) so now I have the attribute.

To handle state for that join model, I have a controller (UserRelationshipsController) with actions/RESTful endpoints for changing the state of the relationship.  Is this bad practice?  If so, where should I handle state-changes for the relationship?  In the User model?

答:
You can treat UserRelationship as a separate resource (as you proposed in your question) or you can use Nested resources (http://guides.rubyonrails.org/routing.html#nested-resources)
to have something like this

POST user/9/relationship (POST/PATCH: user_id: 10, status: 'confirmed')

to set/get relationship statuses for specific user.

Title: Do Rails Join Models Get Controllers?


答:
Your first code example does not really utilize the strengths of an iterator. If one wants to take advantages of an iterator, the code should probably look like this:

```<code>std::vector<int>::iterator it = market.vec.begin();
int i=0;
while(it != market.vec.end())
{
    *it = i + 1;
    ++i;
    ++it;
}
</code>```

Now it is easier to refactor the second part out to a generic function which works on arbitrary iterators, not just vector iterators:

```<code>template<class iterator_type>
void AssignIncreasingValues(iterator_type it, iterator_type end)
{
    int i=0;
    while(it != end)
    {
        *it = i + 1;
        ++i;
        ++it;
    }
}
</code>```

and call it like this:

```<code>    AssignIncreasingValues(market.vec.begin(),market.vec.end());
</code>```

However, note this has some drawbacks:

it is more complex, maybe an overgeneralization

as you already spotted by yourself, there should be no resize during the lifetime of your iterators (but is this really a problem?)

this does not bring you any real benefit if you need a full random access iterator

So use the first variant (in the form I showed above) if it makes your code more DRY, and the second variant if you have no use case for this kind of generalization - YAGNI principle tells you to use the most simple variant which suffers your needs.

Body:
Your first code example does not really utilize the strengths of an iterator. If one wants to take advantages of an iterator, the code should probably look like this:

std::vector<int>::iterator it = market.vec.begin();
int i=0;
while(it != market.vec.end())
{
    *it = i + 1;
    ++i;
    ++it;
}

Now it is easier to refactor the second part out to a generic function which works on arbitrary iterators, not just vector iterators:

template<class iterator_type>
void AssignIncreasingValues(iterator_type it, iterator_type end)
{
    int i=0;
    while(it != end)
    {
        *it = i + 1;
        ++i;
        ++it;
    }
}

and call it like this:

    AssignIncreasingValues(market.vec.begin(),market.vec.end());

However, note this has some drawbacks:

it is more complex, maybe an overgeneralization

as you already spotted by yourself, there should be no resize during the lifetime of your iterators (but is this really a problem?)

this does not bring you any real benefit if you need a full random access iterator

So use the first variant (in the form I showed above) if it makes your code more DRY, and the second variant if you have no use case for this kind of generalization - YAGNI principle tells you to use the most simple variant which suffers your needs.


问:
Where does `this` go in a x64 thiscall?
So I understand that thiscall doesn't really exist in x64 programming. However, I can't really find any definitive explanation as to where the this pointer is put to be passed to the callee.

Is a x64 thiscall like a true cdecl call, where this is put on to the 'stack' last (on both GCC and MSVC compilers)?

EDIT: Running through GDB, it appears so. rdi held the this pointer and rsi held the one parameter that particular method had. Is this how it always works?

答:
According to https://msdn.microsoft.com/en-us/library/windows/hardware/ff561499%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396

"the [this pointer] is passed as an implicit first parameter." So in X64 __fastcall convention [this pointer] should always be set in the RCX register.

Title: Where does `this` go in a x64 thiscall?


问:
Explaining concepts
How can I explain a concept when I don't know its name or any formal reason for it? The reason I ask is this...

A new programmer has entities with a property title in his system. He uses the title to derive image paths. Then we discovered that the titles weren't the same case as the actual paths. His environment (more specifically his server) serve the images case insensitive and my lamp stack doesn't. This was basically the problem.

When I explained to him that it would be wise to not derive the images name from the title but instead he should include a property entity.image-path he didn't get it and was annoyed that I told him to change his program. He says he can just lower case the title while deriving the images path. He hadn't yet noticed that all his titles are upper case words and some of the images upper case and some lower so his idea of transforming the title won't work.

But how do I explain the general idea that he should never have been trying to derive an image file name from a string that is used for a html page title and could be changed for seo or usability reasons without sounding in anyway patronising. This accusation made at me when I said "now I've been programming a while and I'm sure it should be done the way I know it should be done."

答:
In the concrete case, the thing to do is to point out that a solution is incorrect by supplying a case where it does the wrong thing. This is what you did.

But what if someone then adds ad-hoc trickery that fixes this case but will obviously fail for the next slightly different case you could come up with? You're right that to explain why an ad-hoc solution doesn't work in the general case, oyu should usually try to find the name of the concept you're talking about, and use that in your argument.

In your case, the problem seems to be with subtly different data types. This is a problem that occurs particularly often with character strings and things that are almost, but not quite, like strings. In this case, the fact that some components of the system distinguish case and others don't was the problem. At other places it might be the fact that only a certain subset of the defined characters is actually permissible, and things won't blow up until someone introduces one of the "rare" characters. (For instance, UNIX has a deep-seated problem with strings that work fine as long as there's no whitespace in them, and an even deeper-seated problem with strings that work fine as long as neither \0 nor / is in them.)

Because such subtle problems almost always occur when you model something that isn't really a fully general string as a string, it is almost always a good idea to create a special-purpose type that does all the checking that is actually required to use a piece of data safely, and use that in place of a raw string. Unfortunately, the only technical term I know for the issue is "stringly typed", but that describes the problem rather than the solution!

Title: Explaining concepts


问:
Should I create a class for functions that uses of the database?
I have a PHP application which is pretty simple: It allows the user to create, edit and read a post. Basic stuff.

I have a Database class which handles the connection and the queries execution. The thing is that I want my models (I am using a self-built MVC framework) to be clean, so I created in Database some functions such as CreatePost(), EditPost() etc., which contains all the SQL needed, so I can call them nicely from the model: $database->CreatePost(/* post data */);.

Should I keep those functions in the Database class, or should I put them elsewhere (let's say, a class)? Maybe I should even give up on the functions idea and write the code explicitly in the model?

EDIT:

the answer is probably opinion-based, but still - I am trying to figure out what most of the people would do according to well-accepted modern conventions.

答:
The way I look at this, the Database class should not know about what model the application uses. Also the Model should not be aware of the Database class. The class combining the two should be the Controller. It should contain code that would tell the Database class to create and edit stuff, based on the Model.
The Model should contain business logic (in this case stuff like validations, etc).</p>


问:
Class design for writing multiple versions of multiple files
I am writing a web service in Java which reads some information from a DB and generates multiple JSON files which are written to S3. For each type of file, I have a POJO which is serialized to JSON using jackson.

The schema of the files can change over time - new fields can be added, existing fields can be removed etc. Any change in schema will require a new version of the file to be created. Therefore at any point in time, there might be multiple versions of a file in S3.

The current architecture is pretty simple - There is a Controller class which calls a couple of classes to get data from DB. After that it passes that data to a FileGenerator class which creates multiple POJOs and writes them to S3 through a Repository class.

I need to change this design to make it more modular and handle multiple versions of files.

Till now this is what I have come up with:

A generator class for generating each type of file (or POJO) (File1Generator, File2Generator etc)

A FileManager class for each type of file , which calls the generator and serializes the POJO and then writes it to the data-store. (File1Manager, File2Manager etc)

The Controller class will now all the File managers one by one.

However, I am not sure how to design the system in a way that multiple versions of the files can be handled. For the POJOs, I have to have a separate POJO for each version - File1POJO_V1, File1POJO_V2. But then I will also have additional generators and additional managers.  The information passed to generators might vary from one version to another. Same with managers. I am struggling to create a nice class hierarchy such that the code is easily extensible.
Following is a skeleton of the code as I have thought:

```<code>class File1POJOV1{
 private String prop1;
 private String prop1;
 ..........
 public setProp1(){}
 public setProp2(){}
}

class File1Generator_V1{
  public File1POJOV1 createFile(String prop1, String prop2 ...){
        //Perform manipulations and create File1POJO_V1
  }
}

class File1Manager_V1{
  private File1Generator_V1 fileGenerator;
  private Serializer serializer; //JSON serializer
  public void createFile(String prop1, String prop2,.., String directory){
      File1POJOV1 file = fileGenerator.createFile(prop1, prop2 ...);
      byte[] data = serializer.serialzer(data);
      String path  = generateFilePath(); //dynamic based on properties
      writeToS3(data, path, directory); //write data to S3 bucket
  }
}

class Controller{
   File1Manager_V1 manager1_V1;
   File2Manager_V1 manager2_V1;
   generateFile(String prop1, prop1..., directory){
      manager1.createFile(prop1, prop2..,directory);
      manager2.createFile(prop3, prop4.. directory)
   }
}
</code>```

The problem is that when there is new version of a file, there will be a separate POJO for that which will have more(or less) fields than the previous version. This change will be propagated to the Generators and Managers as the input parameters to the methods will change. I am not able to figure out, how to have an elegant design for this system which makes maintenance easy.

EDIT:
I have got some good suggestions for not removing fields in successive versions of a file. But my question remains: assuming that I don't remove fields and that each new version is a subclass of the older one, I will still have to write a separate generator and a manager for each subclass. Can this be avoided ? What would be a better design ?

答:
I think the answer will depend on what you are trying to achieve other than writing files.

Lets leave out the POJOs for the moment, you read data from a DB and write it out to a specific file format via your fileManger class. The DB read returns some generic data reader type, so as long as the needed columns exist you are fine.

If you want to write the same DB data in a different format, you can create another fileMangerV2 class and you are good to go.

If you want to add fields to the DB, again you are fine.

If you remove fields, then things break and you have a backwards compatibility issue you just can't get around if you go ahead and delete that data.

So really this is about the underlying data. If that is the same across all your file versions then you just need the one POJO which matches that data structure and one fileManager per file Format to handle the reading and writing to that format

However, if you want to expose the file format to code with a matching POJO and the underlying data struct is the same, you can create new classes which either inherit (if you don't mind exposing all the base class properties), or wrap the base POJO

Converting from one POJO to the other is then relatively straight forward, just expose the underlying base class, and this code can be included in the object itself rather than the fileManager. This will enable you to have a single fileManager class which is able to output any file format, either by reflection, or better, by having all the POJOs implement a common interface ICanBeWrittenToAFile which exposes GetFieldsForWritingToFile() or something similar.

Your Controllers and fileManager can then take an ICanBeWrittenToAFile as input rather than a specific POJO and you only need to inject the one fileManager

Now say you have some business logic X which you want to be able to perform on the data regardless of the file version. You can extend the same concept by having the POJOs implement ICanPerformLogicX etc


答:
Keep the need for versioning low

I assume here that the JSON files are generated for someone other component/service/client to consume. So try not removing fields. If you only add new fields, then there is no need to create a new version, so long as consumers of the JSON files ignore fields they don't know.

An interface where consumers ignore features they don't know about is more robust. Imagine for example if I consume your data at V0 and then for a year you add new fields on a biweekly basis, arriving at V26 after a year. Then in V27 you add a field that I want to consume also. Should I be bothered by updating my code to handle the fields added between V1 through V26 even though I don't use them? I don't think so.

Removing fields on the other hand is a different beast. You should do that rarely, and in bulk. The whole idea of major and minor versions in semantic versioning is about that. If you add something, it is a minor version and it should not affect users, if you remove things, it is a major update, that can break dependent code.

This also coincides with the notion of subtypes, polymorphism and substitutability. Essentially, to add a new field to a FirstPOJO, you could modify it, or you could subclass it to SubPOJO, that extends FirstPOJO by adding someField. Code written against FirstPOJO will be able to handle SubPOJO transparently. Of course if you start removing things, then code can break.

I know this doesn't exactly answer your question. But your basic problem is that you have a code architecture, that doesn't scale. Reducing the need to scale in the first place, does circumvent the problem.

Title: Class design for writing multiple versions of multiple files

Body:
I am writing a web service in Java which reads some information from a DB and generates multiple JSON files which are written to S3. For each type of file, I have a POJO which is serialized to JSON using jackson.

The schema of the files can change over time - new fields can be added, existing fields can be removed etc. Any change in schema will require a new version of the file to be created. Therefore at any point in time, there might be multiple versions of a file in S3.

The current architecture is pretty simple - There is a Controller class which calls a couple of classes to get data from DB. After that it passes that data to a FileGenerator class which creates multiple POJOs and writes them to S3 through a Repository class.

I need to change this design to make it more modular and handle multiple versions of files.

Till now this is what I have come up with:

A generator class for generating each type of file (or POJO) (File1Generator, File2Generator etc)

A FileManager class for each type of file , which calls the generator and serializes the POJO and then writes it to the data-store. (File1Manager, File2Manager etc)

The Controller class will now all the File managers one by one.

However, I am not sure how to design the system in a way that multiple versions of the files can be handled. For the POJOs, I have to have a separate POJO for each version - File1POJO_V1, File1POJO_V2. But then I will also have additional generators and additional managers.  The information passed to generators might vary from one version to another. Same with managers. I am struggling to create a nice class hierarchy such that the code is easily extensible.
Following is a skeleton of the code as I have thought:

```<code>class File1POJOV1{
 private String prop1;
 private String prop1;
 ..........
 public setProp1(){}
 public setProp2(){}
}

class File1Generator_V1{
  public File1POJOV1 createFile(String prop1, String prop2 ...){
        //Perform manipulations and create File1POJO_V1
  }
}

class File1Manager_V1{
  private File1Generator_V1 fileGenerator;
  private Serializer serializer; //JSON serializer
  public void createFile(String prop1, String prop2,.., String directory){
      File1POJOV1 file = fileGenerator.createFile(prop1, prop2 ...);
      byte[] data = serializer.serialzer(data);
      String path  = generateFilePath(); //dynamic based on properties
      writeToS3(data, path, directory); //write data to S3 bucket
  }
}

class Controller{
   File1Manager_V1 manager1_V1;
   File2Manager_V1 manager2_V1;
   generateFile(String prop1, prop1..., directory){
      manager1.createFile(prop1, prop2..,directory);
      manager2.createFile(prop3, prop4.. directory)
   }
}
</code>```

The problem is that when there is new version of a file, there will be a separate POJO for that which will have more(or less) fields than the previous version. This change will be propagated to the Generators and Managers as the input parameters to the methods will change. I am not able to figure out, how to have an elegant design for this system which makes maintenance easy.

EDIT:
I have got some good suggestions for not removing fields in successive versions of a file. But my question remains: assuming that I don't remove fields and that each new version is a subclass of the older one, I will still have to write a separate generator and a manager for each subclass. Can this be avoided ? What would be a better design ?


答:
I would strongly recommend having the testers part of the development teams rather than as a separate function. This is for three main reasons, based on my own experience managing teams organised in both ways.

Testing can be done as part of the sprint (you say you're doing Scrum) meaning a more complete Definition of Done for your teams and less chance of rework down the line.

Testers can work more closely with the development team which can actually reduce the amount of testing which needs to be done. This can be because a tester and developer pair up to test and fix something in parallel. Or, testers are involved in the planning so can guide developers as to edge cases they should consider. And finally, testers being part of the planning and working closely with the developer lets them more easily work out what does and doesn't need re testing after each change is made.

Finally, you maintain a nice team focus rather than any us vs them feeling between the development teams and the testing team. This is not guaranteed to occur with the other set up but having your teams split like this can lend itself to such behaviour.


答:
Your way of handling it is the common solution (in my opinion). But there are also other styles of design e.g. the domain-driven design. It's the basic paradigm for developing typo3 extensions and considering your problem you could build sth like this:

Model: These are your model object classes

Controller:This contains your controllers

View: Basically your frontend/your views

Repository: This contains a class which handles all db operations e.g. Database(it is used by a controller)

Title: Should I create a class for functions that uses of the database?

Body:
I have a PHP application which is pretty simple: It allows the user to create, edit and read a post. Basic stuff.

I have a Database class which handles the connection and the queries execution. The thing is that I want my models (I am using a self-built MVC framework) to be clean, so I created in Database some functions such as CreatePost(), EditPost() etc., which contains all the SQL needed, so I can call them nicely from the model: $database->CreatePost(/* post data */);.

Should I keep those functions in the Database class, or should I put them elsewhere (let's say, a class)? Maybe I should even give up on the functions idea and write the code explicitly in the model?

EDIT:

the answer is probably opinion-based, but still - I am trying to figure out what most of the people would do according to well-accepted modern conventions.


答:
In my experience testing a feature usually takes longer than developing that feature. So if you have pure test roles you are going to need more testers than developers.

However, this can vary greatly depending on how much test automation you have in place and how specific your feature requirements are. Similarly, if you have very tight specs, the amount of product specific knowledge needed to test a feature is less, you can test it just from the description. Whereas with a looser spec you would expect the tester to use product specific knowledge to fill in the gaps. ie 'ahh but when the app is in state X the feature fails'

Given that you are worried about resourcing and bottlenecks I would suggest that you modify your scrum process to include some of the concepts from KANBAN.

Here you assign a volume to each stage of development, and only move a task into the next phase when there is available capacity. This makes it very clear where the bottlenecks in your process are and gives you a rough idea of how much more resource you need to assign to that area to clear them.


答:
Requirement Documents and Unit tests.

You can argue until the end of days about architecture and best practice, but its all basically opinion unless you agree on some fundamental principle you can argue from.

The thing you cant argue about is 'does the program fulfil the requirement?' this is simply provable one way or the other as long as the requirement is well defined.

In this case you might have a requirement which says:

'The Title should be able to contain any UTF8 character, including spaces,
single quotes, new lines, foreign languages and accents'

and another which says :

'The file path must only contain ASCII characters excluding white-space etc etc and must be less than 256 characters'

You can then write a test case or cases to prove the solution matches the requirements. If it fails you need to change it. If the 'crazy' ad-hoc trick works, you don't.

Title: Explaining concepts

Body:
How can I explain a concept when I don't know its name or any formal reason for it? The reason I ask is this...

A new programmer has entities with a property title in his system. He uses the title to derive image paths. Then we discovered that the titles weren't the same case as the actual paths. His environment (more specifically his server) serve the images case insensitive and my lamp stack doesn't. This was basically the problem.

When I explained to him that it would be wise to not derive the images name from the title but instead he should include a property entity.image-path he didn't get it and was annoyed that I told him to change his program. He says he can just lower case the title while deriving the images path. He hadn't yet noticed that all his titles are upper case words and some of the images upper case and some lower so his idea of transforming the title won't work.

But how do I explain the general idea that he should never have been trying to derive an image file name from a string that is used for a html page title and could be changed for seo or usability reasons without sounding in anyway patronising. This accusation made at me when I said "now I've been programming a while and I'm sure it should be done the way I know it should be done."


答:
Having the model creation process in your database class may look like a good idea now, but it will be a problem when you decide to change the place where your models are stored.

The database class should only provide basic interface, such as querying it, creating transactions, and/or fetching the data in multiple ways (single, multi, associative,...).

You then make a class (preferably implementing a generic interface), which will be using your database class and its interface to query the db, and in your app use this newly created class so your application will be database independent.

Also, your database class should implement a generic database interface, so you can potentially swap out the implementation, if you ever need to.


问:
MVC Best practice mixing Partial View and JavaScript
I searched the internet and really can't find a good answer to this question.

Imagine there is a View that contains a simple tab-element. Each tab-content is loaded dynamically (via ajax) when the tabs header is clicked. The View itself has the document.ready-handler to do things when the View (not the partial) is loaded. (e.g. init the Views javascript module).

One partial contains a list of elements which can be deleted. Clicking the Delete button should open a modal dialog to let the user confirm the deletion.

What would be the best way to handle this?

The View does not know about the Partial which has been loaded and vice versa.

The View has some kind of module which will have a function

deleteElement(id){ //... }
How should this be called from within the partial?

Should the partial know about the deleteElement? What if it is called inside another View which module does not have such a function?

Should the deleteElement be declared global? Does this make sense when only needed in some specific context?

Or is the whole idea of splitting into single javascript-modules per View already the wrong decision I've made? (My thoughts was to keep a single .js file which is only loaded when really needed, keep code clean, separation of concerns, ...)

Any links, hints, workarounds or ideas would be greatly appreciated.

答:
Practical solution :

Jquery and other frameworks will allow you to bind to events for which the element which fires them has not been loaded yet.

So your View, or js module or whatever, can bind to the deleteButton.Click event even though there are no delete buttons yet loaded on the page.

Philosophical thoughts :

When you start doing single page apps with lots of JavaScript logic in them, I feel that you have to shift your perception from the point of view of the website server side being the 'app' to the JavaScript being the app and the server a service which the app can call.

This view helps you resolve these kind of 'where should I put X' questions, the 'View' becomes a ViewModel from the point of view of the JavaScript. Which logically moves you to making it JSON and having the JS update the HTML with some sort of template.

Once you get to this point you might as well start using a framework like angular to do the templating and binding, which gives you a nice clear separation of concerns.

The other point of view I think would be to keep the JavaScript as just a decorative thing. This keeps it firmly in the view, but then you page should run equally well with JavaScript turned off. Which your dynamic loading of the tabs would not do.


问:
How to include estimating and its effect on prioritization with Kanban?
I've read in several sources about Kanban. Using Atlassian's description as my current main source of information about how it works, I wonder how the effects of estimations on prioritization should be included in the flow.

Mentioned description suggest a Kanban board with these lanes:

To do

In progress

Ready for review

Done

The Product Owner then makes sure everything in lane 1 is prioritized. However, priority often depends on estimated effort (something might get higher prio if a quick fix is available, pushed back if it turns out to be a lot of work, etc), and estimating (a) takes time and (b) is best done by those that'll be doing the work.

I'm familiar with Scrum, where the team sits down to estimate on set times. There is no such thing with Kanban it seems. How would this typically work? I can see several options:

The PO guesses, and the team learns to give feedback if the guesses are off;

Introduce a "Lane 0" with "To Estimate" items;

The PO mixes estimating him/herself and interrupting a team member's work to get an estimate;

Introduce fixed moments for estimations (e.g. 0900 and 1300 hours);

I've searched and found some opinions like this one ("estimation is optional"), but am curious if there's any canonical advice at all?

答:
One of the things Agile tries to achieve is the concept of 'doing it trumps talking about doing it', estimating is one of these things where you spend too much time worrying about how long it'd take you to do something if you eventually got on and did it. And generally, whatever estimate you come up with, you're wrong regardless!

So scrap estimates.

Kanban can tell you the cycle time for the tasks you put through it, and you can plot them on a graph to get a distribution curve of times actually taken (ie from when the ticket was placed on the board in progress to when it was removed).

Dennis Stevens suggests t-shirt sizing your tasks to get an understanding of whether to perform the or not, but t-shirting is a 10 second task in most cases - if I ask you how big a task is, you'll be able to say "trivial", "about average" or "mhmhmhmhhh.. that's gonna cost you g'vnor". Waste about that long on this kind of process, and then get on with working those tasks. Do not try to estimate every task, just those you're concerned about.

With Kanban I think the canonical answer is this: don't bother with estimates.

For prioritisation, there is a concept in Kanban called Classes of Service that you can use for those tasks you want to alter the prioritisation for - if something is not a priority (a task that is lengthy-but-important is still important, a task that is quick-but-unimportant is still unimportant after all) you can put it in as a slow-burn or intangible task that will be done after all the higher-priority tasks are complete and someone has time to devote to the task.


答:
Your team should be doing regular Backlog refinement regardless of whether you're doing kanban or scrum. This will include the team providing some level of estimate. Try for relative sizing (fibonacci values) at first to provide enough information for the Product Owner to prioritize without spending too much time on the estimate.

Once the PO has estimates, take a look at Weighted Shortest Job First to help prioritize. This method should take some of the guess-work out of the prioritization.

Title: How to include estimating and its effect on prioritization with Kanban?

Body:
I've read in several sources about Kanban. Using Atlassian's description as my current main source of information about how it works, I wonder how the effects of estimations on prioritization should be included in the flow.

Mentioned description suggest a Kanban board with these lanes:

To do

In progress

Ready for review

Done

The Product Owner then makes sure everything in lane 1 is prioritized. However, priority often depends on estimated effort (something might get higher prio if a quick fix is available, pushed back if it turns out to be a lot of work, etc), and estimating (a) takes time and (b) is best done by those that'll be doing the work.

I'm familiar with Scrum, where the team sits down to estimate on set times. There is no such thing with Kanban it seems. How would this typically work? I can see several options:

The PO guesses, and the team learns to give feedback if the guesses are off;

Introduce a "Lane 0" with "To Estimate" items;

The PO mixes estimating him/herself and interrupting a team member's work to get an estimate;

Introduce fixed moments for estimations (e.g. 0900 and 1300 hours);

I've searched and found some opinions like this one ("estimation is optional"), but am curious if there's any canonical advice at all?


问:
Handling Upload Of Unknown File types
A support ticket has been raised whereby a mac user saved a file from an email, then uploaded it to our web based system. By default, when doing this the mac does not save the file with a 3 letter file extension.

While this caused our system some initial problems (it looks at the file extension to work out what kind of icon to show), these can be worked around easily.

However, I just know if we patch this behaviour, we will soon end up getting a ticket complaining that these files cannot be opened on a Windows based machine.

I think we have 3 options:

Allow users to upload files with no extensions, and leave them to deal with the mess

If a file with no extension is uploaded, show a dropdown and ask the user to pick what kind of file it is, then rename it for them. The downside of this, is if the user picks the wrong option, the file will open in the wrong application on Windows.

Block uploading of files with no extensions, and insist they rename the file, adding the correct extension, then upload.

What is the best option for dealing with a situation like this?

答:
I don't think that any of those options sound particularly good (at least as a first line of defense).  No one is going to want to deal with the mess of either remembering what kind of files those things are later or being stopped all the time to rename files.

A different approach would be to use some software or a library to try to figure out what the file is without having to involve the user.  After looking at these questions on the Stack network (Q1, Q2, Q3, Q4) it looks like there are at least a few solutions.  One uses a program called TrID to identify the files (you could possibly shell out to it if it doesn't have a way to integrate directly into your code).  Another listed a C# library (Urlmon) that seems to do an ok, but kind of limited job of identifying files.

I would try to identify the files by one of these means first.  Only if that failed would I prompt the user to pick a file type or rename it.  That should make it fairly user friendly and only bother them when you just can't do any more.

Title: Handling Upload Of Unknown File types


问:
C++ returning persistent objects
I'm currently trying to learn best practices in C++ after coming from a C# background. I understand that there are three ways of handling objects:

By value (objects are copied or moved when passed into and out of functions)

By reference

By shared or unique pointer (raw pointers are frowned upon unless you really need them)

In general I see it as good practice to avoid using shared pointers but as I'm developing a lot of code recently I'm finding that I initial define something as a value type and then end up having to make it a shared pointer. This situation occurs so frequently that almost every object in my system is in a shared pointer! This seems wrong.

Most of my classes look somewhat like this:

```<code>class Container
{
public:
    // ...other functions

    std::shared_ptr<Thing> GetThing() const;
    std::vector<std::shared_ptr<Thing>> GetThings() const;

private:
    std::shared_ptr<Thing> thing;
    std::vector<std::shared_ptr<Thing>> things;
}
</code>```

Initially this class would have contained value objects of type Thing, but then other classes need access to these objects and so to avoid copying them when they get returned from the 'getter' functions I've put them into shared pointers. This means that if any changes occur to these objects their state will be consistent to the container and those objects currently accessing the 'things'.

Why does this feel wrong, and how can I improve this approach? What is the correct 'C++' way of doing this?

答:
Return/pass by const ref before turning to shared_ptr. They let you pass by reference without allowing them to change the object. This requires that you take care to maintain const-correctness throughout.

```<code>class Container
{
public:
    // ...other functions

    const Thing& GetThing() const;
    Thing& GetThing();

    const std::vector<Thing>& GetThings() const;
    std::vector<Thing>& GetThings();

private:
    Thing thing;
    std::vector<Thing> things;
}
</code>```

What is important is reasoning about ownership. With store-by-value and pass-by-reference you know exactly what owns the object and know who is responsible for destroying it.

Title: C++ returning persistent objects

Body:
Return/pass by const ref before turning to shared_ptr. They let you pass by reference without allowing them to change the object. This requires that you take care to maintain const-correctness throughout.

class Container
{
public:
    // ...other functions

    const Thing& GetThing() const;
    Thing& GetThing();

    const std::vector<Thing>& GetThings() const;
    std::vector<Thing>& GetThings();

private:
    Thing thing;
    std::vector<Thing> things;
}

What is important is reasoning about ownership. With store-by-value and pass-by-reference you know exactly what owns the object and know who is responsible for destroying it.


答:
It is not clear what you do with those objects.

If you want to copy the non-copyable class, then using shared_ptr is fine as you did.

If you want to copy objects, then return a value.

If you just want to provide access to those objects, then use references :

```<code>class Container
{
public:
    // ...other functions

    const Thing& GetThing() const;
    const std::vector<Thing>& GetThings() const;

private:
    Thing thing;
    std::vector<Thing> things;
};
</code>```

Title: C++ returning persistent objects

Body:
I'm currently trying to learn best practices in C++ after coming from a C# background. I understand that there are three ways of handling objects:

By value (objects are copied or moved when passed into and out of functions)

By reference

By shared or unique pointer (raw pointers are frowned upon unless you really need them)

In general I see it as good practice to avoid using shared pointers but as I'm developing a lot of code recently I'm finding that I initial define something as a value type and then end up having to make it a shared pointer. This situation occurs so frequently that almost every object in my system is in a shared pointer! This seems wrong.

Most of my classes look somewhat like this:

```<code>class Container
{
public:
    // ...other functions

    std::shared_ptr<Thing> GetThing() const;
    std::vector<std::shared_ptr<Thing>> GetThings() const;

private:
    std::shared_ptr<Thing> thing;
    std::vector<std::shared_ptr<Thing>> things;
}
</code>```

Initially this class would have contained value objects of type Thing, but then other classes need access to these objects and so to avoid copying them when they get returned from the 'getter' functions I've put them into shared pointers. This means that if any changes occur to these objects their state will be consistent to the container and those objects currently accessing the 'things'.

Why does this feel wrong, and how can I improve this approach? What is the correct 'C++' way of doing this?

Body:
It is not clear what you do with those objects.

If you want to copy the non-copyable class, then using shared_ptr is fine as you did.

If you want to copy objects, then return a value.

If you just want to provide access to those objects, then use references :

class Container
{
public:
    // ...other functions

    const Thing& GetThing() const;
    const std::vector<Thing>& GetThings() const;

private:
    Thing thing;
    std::vector<Thing> things;
};


答:
It sounds like you are doing this because you want to modify the internal values inside Container. So you are doing something like:

```<code>void foo(Container &container) {
   container.GetThing().SetFoo(12);
}
</code>```

The problem is that you are not supposed to be modifying Container's internal state this way. Only methods on Container should modify it. So this function should probably be a method insider Container.

```<code>void Container::foo() {
    thing.SetFoo(12);
}
</code>```

If you really must modify thing outside of Container, you should prefer something more explicit:

```<code>void foo(Container &container) {
    Thing thing = container.GetThing();
    thing.SetFoo(12);
    container.SetThing(thing);
}
</code>```

But having Get/Set methods for internal pieces of state in Container is a code smell. It suggests you've got other code that really should be part of Container.

Title: C++ returning persistent objects

Body:
It sounds like you are doing this because you want to modify the internal values inside Container. So you are doing something like:

void foo(Container &container) {
   container.GetThing().SetFoo(12);
}

The problem is that you are not supposed to be modifying Container's internal state this way. Only methods on Container should modify it. So this function should probably be a method insider Container.

void Container::foo() {
    thing.SetFoo(12);
}

If you really must modify thing outside of Container, you should prefer something more explicit:

void foo(Container &container) {
    Thing thing = container.GetThing();
    thing.SetFoo(12);
    container.SetThing(thing);
}

But having Get/Set methods for internal pieces of state in Container is a code smell. It suggests you've got other code that really should be part of Container.


问:
Does an interpreter produce machine code?
I study the topics of compilers and interpreters intensively. I want to check if my base understanding is right, so let's assume the following:

I have a language called "Foobish" and its keywords are

```<code><OUTPUT> 'TEXT', <Number_of_Repeats>;
</code>```

So if I want to print to the console 10 times, I would write

```<code>OUTPUT 'Hello World', 10;
</code>```

Hello World.foobish-file.

Now I write an interpreter in the language of my choice - C# in this case:

```<code>using System;

namespace FoobishInterpreter
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            analyseAndTokenize(Hello World.foobish-file)//Pseudocode
            int repeats = Token[1];
            string outputString = Token[0];
            for (var i = 0; i < repeats; i++)
            {
                Console.WriteLine(outputString);
            }
        }
    }
}
</code>```

On a very easy interpreter level, the interpreter would analyze the script-file, etc. and execute the foobish-language in the way of the interpreter's implementation.

Would a compiler create machine language which runs on the physical hardware directly?

So an interpreter doesn't produce machine language, but does a compiler do it for its input?

Do I have any misunderstandings in the basic way how compilers and interpreters work?

答:
The terms "interpreter" and "compiler" are much more fuzzy than they used to be.  Many years ago it was more common for compilers to produce machine code to be executed later, while interpreters more or less "executed" the source code directly.  So those two terms were well understood back then.

But today there are many variations on the use of "compiler" and "interpreter."  For example, VB6 "compiles" to byte code (a form of Intermediate Language), which is then "interpreted" by the VB Runtime.  A similar process takes place in C#, which produces CIL that is then executed by a Just-In-Time Compiler (JIT) which, in the old days, would have been thought of as an interpreter.  You can "freeze-dry" the output of the JIT into an actual binary executable by using NGen.exe, the product of which would have been the result of a compiler in the old days.

So the answer to your question is not nearly as straightforward as it once was.

Further Reading

Compilers vs. Interpreters on Wikipedia


问:
TDD - Outside In developemnt
I'm pretty comfortable with the core concepts of Outside In (especially from this question). However one thing eludes me concerning the mocks you created at each level which then lead to creating the real implementation that the solution requires...

Do you keep using the mocks in the higher-level (outside) tests, and then create another suite of Integration Tests that check all of the production components are working as expected?

Or do you gradually replace the mocks in the higher-level (outside) tests with the working production components and then throw the mocks away?

答:
Keep the mocks

While the mocks happen to allow testing before the production components are written, that isn't the only reason to use them.

Mocks give you explicit control over their behavior.

For any injected object whose sibling production object is stateful or relies upon an external system (like a disk drive, database, etc.), it is far easier to control the mocked object's behavior.  In some cases, it may even be the only way to make the object return consistent, exact values (e.g., an object which returns the current time versus a mock which can return a pre-specified time).

Keeping the mocks in your tests forces the test object to remain loosely-coupled.

If your tests started using the production objects directly, there is little stopping someone from modifying the tested object to rely on those concrete types.  This, in turn, makes it much easier for a lazy maintainer to update the tested object in a way which makes it more difficult in the future to swap out the dependency later.

Title: TDD - Outside In developemnt


问:
How can I represent a flowchart, complete with conditional logic using JSON or XML?
One part of a project I'm working on is interactive scripts for call centre staff. Pretty much every possibility I can think of in this case can be represented on paper as a flowchart, which is why I'll be making an interactive "script builder" that is essentially a flowchart builder in HTML5/JS. This will let me add conditional logic to the scripts, so the agent could be prompted to say something specific based on the reply from the person being called.

Currently I'm stuck in the planning phase: how do I represent each script/flowchart in my system? I need something that can be completely represented using either JSON or XML, as the system is web based.

答:
JSON documents consist of: Dictionaries (aka key-value pairs), Arrays, Strings, Numbers, Boolean values, and Null values, where the values in the dictionaries and items in the arrays are the same objects again. </p>

<p>Once you organise your data that way, translating into JSON is trivial (usually you have a library that makes it a single call). </p>

Body:
JSON documents consist of: Dictionaries (aka key-value pairs), Arrays, Strings, Numbers, Boolean values, and Null values, where the values in the dictionaries and items in the arrays are the same objects again.

Once you organise your data that way, translating into JSON is trivial (usually you have a library that makes it a single call).


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
I was asked by my TL to connect the phone line directly to USB (no MODEM type converter in between).

I tried to explain him that it is not possible technically (the connecting of phone to USB directly). but he didn't want to listen.

Then, I had to write him a 20 page document explaining that phone is analog while USB is digital so a converter is very much required. Then he dropped the idea altogether.

OwnerDisplayName: Manish Dalal


问:
Azure CloudServices: Having more than just staging and production slots?
We're using Azure Cloud Services and would like to have a workflow where deployments flow as

Cloud Service #1: testing/QA => staging => production

Currently Azure Cloud Services only have staging and production environments where you can swap the deployments. How are folks accommodating a more traditional 3 stage approach as shown above?

We currently do the following

Cloud Service #1: testing/QA =>
Cloud Service #2: staging => production

but this is painful and feels kludgy since going from Cloud Service A => Cloud Service B is essentially a full redeploy rather simply switching IPs or swapping behind the load balancer.

答:
We are developing a number of services hosted as azure web apps. Some of the services have testing, staging and production web apps. These are different web apps. In addition each of these have preview and production slots for deployment with no or minimal downtime. In addition to this we have primary and failover instances behind a traffic manager so to sum up. One logical service can have up to 12 web apps. This is all streamlined with deployment through git triggered from teamcity with a clear hierarchy enforced where a commit must have been deployed to testing and staging before hitting production. </p>

<p>All this is possible because web apps are same price for one or multiple. I realize you are using cloud services and not web apps but the same applies where they are seperate services. We don't use the slot feature for staging. </p>

Body:
We are developing a number of services hosted as azure web apps. Some of the services have testing, staging and production web apps. These are different web apps. In addition each of these have preview and production slots for deployment with no or minimal downtime. In addition to this we have primary and failover instances behind a traffic manager so to sum up. One logical service can have up to 12 web apps. This is all streamlined with deployment through git triggered from teamcity with a clear hierarchy enforced where a commit must have been deployed to testing and staging before hitting production.

All this is possible because web apps are same price for one or multiple. I realize you are using cloud services and not web apps but the same applies where they are seperate services. We don't use the slot feature for staging.


答:
Here's a simple conceptual disambiguation between compilers and interpreters.

Consider 3 languages: programming language, P (what the program is written in); domain language, D (for what goes on with the running program); and target language, T (some third language).

Conceptually,

a compiler translates P to T so that you can evaluate T(D); whereas

an interpreter evaluates P(D) directly.

Title: Does an interpreter produce machine code?

Body:
I study the topics of compilers and interpreters intensively. I want to check if my base understanding is right, so let's assume the following:

I have a language called "Foobish" and its keywords are

```<code><OUTPUT> 'TEXT', <Number_of_Repeats>;
</code>```

So if I want to print to the console 10 times, I would write

```<code>OUTPUT 'Hello World', 10;
</code>```

Hello World.foobish-file.

Now I write an interpreter in the language of my choice - C# in this case:

```<code>using System;

namespace FoobishInterpreter
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            analyseAndTokenize(Hello World.foobish-file)//Pseudocode
            int repeats = Token[1];
            string outputString = Token[0];
            for (var i = 0; i < repeats; i++)
            {
                Console.WriteLine(outputString);
            }
        }
    }
}
</code>```

On a very easy interpreter level, the interpreter would analyze the script-file, etc. and execute the foobish-language in the way of the interpreter's implementation.

Would a compiler create machine language which runs on the physical hardware directly?

So an interpreter doesn't produce machine language, but does a compiler do it for its input?

Do I have any misunderstandings in the basic way how compilers and interpreters work?


问:
What's the name of the algorithm to balance an acyclic graph?
Algorithms class was a such a long time ago and I can't remember the name of the algorithm to balance an acyclic graph.

Let's start with a graph that looks like this:

```<code>        1
        |
        2
        |
        3
      /   \
     4     7
    / \    |
   5   6   8
</code>```

The solution to balancing this out would be:

```<code>        2                             3
       /  \                         / |  \
      1    3                       2  4   7
          /  \        =>          /  / \  |
        4     7                  1  5   6 8
      /   \   |
     5     6  8
</code>```

You rotate until the you have a root node whose branch's are the same length and your tree is at a minimum height.

What algorithm am I describing?

答:
You might want to provide some more details in your description. Also, the example you give does not seem to be consistent (e.g. node 3 suddenly takes three children), whereas all other nodes seem to maintain at most two children.

Based on the little detail you provide, your rotation operations are similar to what's described in AVL tree rotations. See e.g. the wikipedia page for more details.