答:
The summary I give below is based on "Compilers, Principles, Techniques, & Tools", Aho, Lam, Sethi, Ullman, (Pearson International Edition, 2007), pages 1, 2, with the addition of some ideas of my own.

The two basic mechanisms for processing a program are compilation and interpretation.

Compilation takes as input a source program in a given language and outputs a target program in a target language.

```<code>source program --> | compiler | --> target program
</code>```

If the target language is machine code, it can be executed directly on some processor:

```<code>input --> | target program | --> output
</code>```

Compilation involves scanning and translating the entire input program (or module) and does not involve executing it.

Interpretation takes as input the source program and its input, and produces the source program's output

```<code>source program, input --> | interpreter | --> output
</code>```

Interpretation usually involves processing (analyzing and executing) the program one statement at a time.

In practice, many language processors use a mix of the two approaches. E.g., Java programs are first translated (compiled) into an intermediate program (byte code):

```<code>source program --> | translator | --> intermediate program
</code>```

the output of this step is then executed (interpreted) by a virtual machine:

```<code>intermediate program + input --> | virtual machine | --> output
</code>```

To complicate things even further, the JVM can perform just-in-time compilation at runtime to convert byte code into another format, which is then executed.

Also, even when you compile to machine language, there is an interpreter running your binary file which is implemented by the underlying processor. Therefore, even in this case you are using a hybrid of compilation + interpretation.

So, real systems use a mix of the two so it is difficult to say whether a given language processor is a compiler or an interpreter, because it will probably use both mechanisms at different stages of its processing. In this case it would probably more appropriate to use another, more neutral term.

Nevertheless, compilation and interpretation are two distinct kinds of processing, as described in the diagrams above,

To answer the initial questions.

A compiler would create machine language which runs on the physical
  hardware directly?

Not necessarily, a compiler translates a program written for a machine M1 to an equivalent program written for a machine M2. The target machine can be implemented in hardware or be a virtual machine. Conceptually there is no difference. The important point is that a compiler looks at a piece of code and translates it to another language without executing it.

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

If by producing you are referring to the output, then a compiler produces a target program which may be in machine language, an interpreter does not.

Body:
The summary I give below is based on "Compilers, Principles, Techniques, & Tools", Aho, Lam, Sethi, Ullman, (Pearson International Edition, 2007), pages 1, 2, with the addition of some ideas of my own.

The two basic mechanisms for processing a program are compilation and interpretation.

Compilation takes as input a source program in a given language and outputs a target program in a target language.

source program --> | compiler | --> target program

If the target language is machine code, it can be executed directly on some processor:

input --> | target program | --> output

Compilation involves scanning and translating the entire input program (or module) and does not involve executing it.

Interpretation takes as input the source program and its input, and produces the source program's output

source program, input --> | interpreter | --> output

Interpretation usually involves processing (analyzing and executing) the program one statement at a time.

In practice, many language processors use a mix of the two approaches. E.g., Java programs are first translated (compiled) into an intermediate program (byte code):

source program --> | translator | --> intermediate program

the output of this step is then executed (interpreted) by a virtual machine:

intermediate program + input --> | virtual machine | --> output

To complicate things even further, the JVM can perform just-in-time compilation at runtime to convert byte code into another format, which is then executed.

Also, even when you compile to machine language, there is an interpreter running your binary file which is implemented by the underlying processor. Therefore, even in this case you are using a hybrid of compilation + interpretation.

So, real systems use a mix of the two so it is difficult to say whether a given language processor is a compiler or an interpreter, because it will probably use both mechanisms at different stages of its processing. In this case it would probably more appropriate to use another, more neutral term.

Nevertheless, compilation and interpretation are two distinct kinds of processing, as described in the diagrams above,

To answer the initial questions.

A compiler would create machine language which runs on the physical
  hardware directly?

Not necessarily, a compiler translates a program written for a machine M1 to an equivalent program written for a machine M2. The target machine can be implemented in hardware or be a virtual machine. Conceptually there is no difference. The important point is that a compiler looks at a piece of code and translates it to another language without executing it.

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

If by producing you are referring to the output, then a compiler produces a target program which may be in machine language, an interpreter does not.


问:
Folder structure for app with Symfony 2, React, Webpack, and Sass?
I am creating an app that uses some components of Symfony2 along with React, Webpack and Sass. We will mostly code in PHP, with the other things adding functionality to our app. I'm having a hard time figuring out how to make my folder structure.

Please note that I don't want to make an app entirely dependent on Symfony, but an app that uses only parts of it.

Inspiration taken from Symfony, Html5 Boilerplate, and Ryan Florence.

```<code>root
├── app
│   ├── console
│   ├── cache
│   ├── config
│   ├── logs
│   └── Resources
│       └── views (Twig files)
│       └── sass
├── src
│   └── AppBundle
├── vendor (Composer dependencies)
│   └── phpUnit
├── components (Bower dependencies)
│   └── Foundation
└── web
    ├── css
    │   ├── main.css
    │   └── normalize.css
    ├── doc
    ├── img
    ├── js
    │   ├── config
    │   │   └── routes.js
    │   ├── screens
    │   │   └── App
    │   │       ├── components
    │   │       ├── screens
    │   │       │   ├── Admin
    │   │       │   │   ├── components
    │   │       │   │   ├── screens
    │   │       │   │   │   ├── Reports
    │   │       │   │   │   │   ├── components
    │   │       │   │   │   │   ├── stores
    │   │       │   │   │   │   │   └── ReportsStore.js
    │   │       │   │   │   │   └── index.js
    │   │       │   │   │   └── Users
    │   │       │   │   │       ├── components
    │   │       │   │   │       └── index.js
    │   │       │   │   ├── shared
    │   │       │   │   │   └── stores
    │   │       │   │   │       ├── AccountStore.js
    │   │       │   │   │       └── UserStore.js
    │   │       │   │   └── index.js
    │   │       ├── shared
    │   │       │   └── components
    │   │       │       ├── Avatar.js
    │   │       │       └── Icon.js
    │   │       └── index.js
    │   └── shared
    │       └── util
    │           └── createStore.js
    ├── index.js
    ├── .editorconfig
    ├── .htaccess
    ├── 404.html
    ├── apple-touch-icon.png
    ├── browserconfig.xml
    ├── index.html
    ├── humans.txt
    ├── robots.txt
    ├── crossdomain.xml
    ├── favicon.ico
    ├── tile-wide.png
    └── tile.png
</code>```

Update to make question more clear

I want to have an app that uses Symfony as the backend and React, Webpack, etc. for the frontend. I want to keep the frontend and backend separated. I am not totally against Symfony's suggested folder structure, but by using it, the frontend and backend are not separated.

I know that other people have made apps that use Symfony but keep it completely separate from their frontend. What folder structure do others suggest and/or use to make separating their Symfony backend from their frontend possible?

I do realize that separating the dependencies of your code goes beyond just the folder structure, but I also think it's rather difficult to have one without the other. Also, just looking at another person's folder structure that has successful separation will give me an idea of how they did that without going into lengthy detail.

答:
Please note that I don't want to make an app entirely dependent on Symfony, but an app that uses only parts of it.

My suggestion would be to make your Symfony2 application an independent RESTful back end. Build your front entirely separate.

However if you wish to combine the two, I would probably make a folder under "app/Resources", eg, client. Put your js/scss in there. A rough example:

```<code>app/Resources/client/app.js
app/Resources/client/styles/*.scss
app/Resources/client/components/component1/main.js
</code>```

Put webpack.config.js in the root folder of the Symfony2 application along with your package.json. Have your webpack entry point to the app/Resources/client folder. Then have the target build to something like "web/dist/app.bundle.js". You can then just include that in app/Resources/layout.html.twig. You can even have multiple bundles if it's not a single page application.

We had to add in Backbone late to our already established Symfony2 project and this is how we approached it. Webpack and CommonJS were a HUGE help to organizing our JavaScript and keeping our front end code organized and easy to deploy.

Here is our webpack config. You can ignore the externals section since we had to add this to an existing project we decided to load certain libraries externally since they were already being required.

```<code>var path = require('path');
var webpack = require('webpack');

var commonsPlugin = new webpack.optimize.CommonsChunkPlugin({
    name: 'common',
    filename: 'common.bundle.js'
});

var uglifyPlugin = new webpack.optimize.UglifyJsPlugin({
    compress: {
        warnings: false
    }
});

var providePlugin =
    new webpack.ProvidePlugin({
        Backbone: 'backbone'
});

var modulePlugins = [commonsPlugin, providePlugin];
if (process.env.NODE_ENV === 'prod') {
    modulePlugins.push(uglifyPlugin);
}

module.exports = {
  entry: {
    app: path.resolve(__dirname, 'app/Resources/modules/layout/app'),
    primers: path.resolve(__dirname, 'app/Resources/modules/primer/app'),
    // sample: path.resolve(__dirname, 'app/Resources/modules/sample/app'),
    cnv_batches: path.resolve(__dirname, 'app/Resources/modules/cnv/app_batches'),
    cnv_samples: path.resolve(__dirname, 'app/Resources/modules/cnv/app_samples'),
    ngs_batches: path.resolve(__dirname, 'app/Resources/modules/ngs/app_batches'),
    ngs_sample: path.resolve(__dirname, 'app/Resources/modules/sample/app_ngs'),
    sample_cnv: path.resolve(__dirname, 'app/Resources/modules/sample/app_cnv')
  },
  resolve: {
    root: path.resolve(__dirname, 'app/Resources/modules'),
    extensions: ['', '.js', '.css', '.scss', '.html']
  },
  output: {
    path: path.resolve(__dirname, 'web/dist'),
    filename: "[name].bundle.js"
  },
  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel' },
      { test: /\.css$/, loader: 'style!css' },
      { test: /\.scss$/, loader: 'style!css!sass' },
      { test: /\.html$/, loader: "underscore-template-loader" }
    ]
  },
  externals: {
    "jquery": "jQuery",
    "datatables": "$.fn.DataTable",
    "lodash": "_",
    "Routing": "Routing"
  },
  plugins: modulePlugins
};
</code>```

If I could start over I would totally separate the two and build a RESTful Syfmony2 application completely separate from our front-end and that is my ultimate recommendation if it's a choice.

Good luck.

ContentLicense: CC BY-SA 3.0

Body:
Please note that I don't want to make an app entirely dependent on Symfony, but an app that uses only parts of it.

My suggestion would be to make your Symfony2 application an independent RESTful back end. Build your front entirely separate.

However if you wish to combine the two, I would probably make a folder under "app/Resources", eg, client. Put your js/scss in there. A rough example:

app/Resources/client/app.js
app/Resources/client/styles/*.scss
app/Resources/client/components/component1/main.js

Put webpack.config.js in the root folder of the Symfony2 application along with your package.json. Have your webpack entry point to the app/Resources/client folder. Then have the target build to something like "web/dist/app.bundle.js". You can then just include that in app/Resources/layout.html.twig. You can even have multiple bundles if it's not a single page application.

We had to add in Backbone late to our already established Symfony2 project and this is how we approached it. Webpack and CommonJS were a HUGE help to organizing our JavaScript and keeping our front end code organized and easy to deploy.

Here is our webpack config. You can ignore the externals section since we had to add this to an existing project we decided to load certain libraries externally since they were already being required.

var path = require('path');
var webpack = require('webpack');

var commonsPlugin = new webpack.optimize.CommonsChunkPlugin({
    name: 'common',
    filename: 'common.bundle.js'
});

var uglifyPlugin = new webpack.optimize.UglifyJsPlugin({
    compress: {
        warnings: false
    }
});

var providePlugin =
    new webpack.ProvidePlugin({
        Backbone: 'backbone'
});

var modulePlugins = [commonsPlugin, providePlugin];
if (process.env.NODE_ENV === 'prod') {
    modulePlugins.push(uglifyPlugin);
}

module.exports = {
  entry: {
    app: path.resolve(__dirname, 'app/Resources/modules/layout/app'),
    primers: path.resolve(__dirname, 'app/Resources/modules/primer/app'),
    // sample: path.resolve(__dirname, 'app/Resources/modules/sample/app'),
    cnv_batches: path.resolve(__dirname, 'app/Resources/modules/cnv/app_batches'),
    cnv_samples: path.resolve(__dirname, 'app/Resources/modules/cnv/app_samples'),
    ngs_batches: path.resolve(__dirname, 'app/Resources/modules/ngs/app_batches'),
    ngs_sample: path.resolve(__dirname, 'app/Resources/modules/sample/app_ngs'),
    sample_cnv: path.resolve(__dirname, 'app/Resources/modules/sample/app_cnv')
  },
  resolve: {
    root: path.resolve(__dirname, 'app/Resources/modules'),
    extensions: ['', '.js', '.css', '.scss', '.html']
  },
  output: {
    path: path.resolve(__dirname, 'web/dist'),
    filename: "[name].bundle.js"
  },
  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel' },
      { test: /\.css$/, loader: 'style!css' },
      { test: /\.scss$/, loader: 'style!css!sass' },
      { test: /\.html$/, loader: "underscore-template-loader" }
    ]
  },
  externals: {
    "jquery": "jQuery",
    "datatables": "$.fn.DataTable",
    "lodash": "_",
    "Routing": "Routing"
  },
  plugins: modulePlugins
};

If I could start over I would totally separate the two and build a RESTful Syfmony2 application completely separate from our front-end and that is my ultimate recommendation if it's a choice.

Good luck.


问:
How to write maintainable, not brittle, unit tests for a GUI?
I tried writing UI unit tests for my GUI apps and I face the problem that, while they work well when I initially write them, they turn out to be brittle and they break whenever the design changes (that is, quite often). I'm struggling to find a set of guidelines that would lead me to having maintainable unit tests for the GUI.

For now, one thing that I discovered is that tests saying "this component should show its input data somewhere" are good (and that's very easy with HTML). Tests checking for a specific state of a specific part of the component are usually brittle. Tests going like click-click-click-expect, that try to follow the user behaviour and the underlying business logic (which is the most important part) usually turn out to be brittle. How do I write good tests?

To be more precise, I'd like to know some patterns about what could I test in my UI, not exactly how to test it. Naming conventions and fixed identifiers are good, but don't solve the core problem, which is, that GUIs change a lot. I'd like to test the behaviours that are most unlikely to change. How to find the right thing to test?

答:
GUI interaction tests should be no more or less brittle than any other kinds of tests. That is; if your application is changing in some way, the tests need to be updated to reflect that.

As a comparison:

Unit Test

Original: validateEmail() should throw an InvalidData exception. Which is correctly covered in your unit test.

Change: validateEmail() should throw an InvalidEmail exception. Now your test is incorrect, you update it, and everything is green again.

GUI Test

Original: Entering an invalid email will result in a popup error box containing "Invalid data entered". Correctly detected by your tests.

Change: Entering an invalid email will result in an inline error containing "Invalid email entered". Now your test is incorrect, you update it, and everything is green again.

Remember that you're testing for inputs and outputs - some well defined behaviour. Regardless of if it's a GUI test or a Unit test or an Integration test, etc.


问:
Design pattern for large amounts of overflowing data?
Our current queues publish messages that consumed by 3rd party services with rate limits. Currently the messages are retried with exponential back-off. However there could be cases where data is coming in so fast that the retries will never catch up.

Most of the 3rd party services offer alternative batch imports, and the solution I've come up with so far is to write the data to file(s) to be processed out of band.

Are there any design patterns for storing overflowing data?

答:
The ideal situation would be to have your queue store its messages indefinitely, provide you with message position as it delivers messages to you, and allow you to resume your subscription from a certain position (instead of only from now forward). That way, your subscriber can keep track of the last message it successfully processed and start from that position forward when it restarts. EventStore does this. It is an append-only database which also behaves as a queue that you can subscribe to.

Assuming your current queue only gives subscribers messages from now forward, you will have to store the messages as they come in (file or database or whatever). As you successfully send messages to 3rd parties, you will have to record the last successful one (per 3rd party) so you can resume from there if it gets too far behind or crashes. Periodically, I assume you will want to delete old messages which all 3rd parties have processed.

Checkpointing

You can either save the checkpoint (id of last successfully processed message) before or after delivering the message.

Saving checkpoint before delivery is called At Most Once Delivery, because it's possible that the message never gets delivered. For example: Checkpoint gets saved, but before delivery the computer crashes. Upon reboot, the loaded checkpoint says that message was already processed and loads next one.

Saving checkpoint after delivery is called At Least Once Delivery, because it's possible to deliver the message multiple times. For example: Message is sent, but computer crashes before checkpoint is saved. Upon reboot, checkpoint is pointing at same message that was sent, which will get resent again.

At Least Once Delivery (saving checkpoint after successful delivery) is safer so long as messages do not induce side effects (i.e. they are idempotent). For instance, if the message is CountIncreasedBy:5, then it has a side effect because it's new value depends on the old value, and processing this message more than once is going to skew the value on the receiver. However, if the message says NewCountSetTo:37, then you can process that any number of times in a row and it will always have the same effect.

However, with "at least once" you also have to watch for poison messages. These are messages which always crash when they are attempted to be delivered, thus you are not able to proceed any further. They will get retried infinitely unless you put something in place to watch for that.

Also note that if there are no circumstances in which the 3rd parties can catch up (i.e. it's not just burst traffic, but average traffic that overwhelms the 3rd party), then you are going to run into the same overflow problem on your hard drive. At that point, you will have to use offline methods or just skip messages once processing gets too far behind.


答:
As I understand, there are components of three types in the system at issue.

```<code>                                         |
         ,----> [Message Translator] ----|---> [3rd Party Endpoint]
        /                                |
  [Queue] ----> [Message Translator] ----|---> [3rd Party Endpoint]
        \                                |
         `----> [Message Translator] ----|---> [3rd Party Endpoint]
                                         |

    [type] - component of type
    -----> - data flow
         | - internal/external component boundary
.
</code>```

First thing that comes to mind is replacing message translators with aggregators, that store messages and send them in batch. Batch data can be stored in some fast (nosql) database or even in flat file if your requirements allow it. If 3rd party endpoints require raw data, not much more can be done. Generally, check out Enterprise Integration Patterns.

Event Sourcing techniques (and all databases based on them) can be useful, especially if your problem can be described in terms of Domain Objects and Domain Events (Domain Driven Design).

Title: Design pattern for large amounts of overflowing data?

Body:
Our current queues publish messages that consumed by 3rd party services with rate limits. Currently the messages are retried with exponential back-off. However there could be cases where data is coming in so fast that the retries will never catch up.

Most of the 3rd party services offer alternative batch imports, and the solution I've come up with so far is to write the data to file(s) to be processed out of band.

Are there any design patterns for storing overflowing data?

Body:
As I understand, there are components of three types in the system at issue.

                                         |
         ,----> [Message Translator] ----|---> [3rd Party Endpoint]
        /                                |
  [Queue] ----> [Message Translator] ----|---> [3rd Party Endpoint]
        \                                |
         `----> [Message Translator] ----|---> [3rd Party Endpoint]
                                         |

    [type] - component of type
    -----> - data flow
         | - internal/external component boundary
.

First thing that comes to mind is replacing message translators with aggregators, that store messages and send them in batch. Batch data can be stored in some fast (nosql) database or even in flat file if your requirements allow it. If 3rd party endpoints require raw data, not much more can be done. Generally, check out Enterprise Integration Patterns.

Event Sourcing techniques (and all databases based on them) can be useful, especially if your problem can be described in terms of Domain Objects and Domain Events (Domain Driven Design).


问:
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?

答:
While the lines between compilers and interpreters has gotten fuzzy over time, one can still draw a line between them by looking at the semantics of what the program should do and what the compiler/interpreter does.

A compiler will generate another program (typically in a lower-level language like machine code) which, if that program is run, will do what your program should do.

An interpreter will do what your program should do.

With these definitions, the places where it gets fuzzy are the cases where your compiler/interpreter can be thought of as doing different things depending on how you look at it. For example, Python takes your Python code and compiles it into a compiled Python bytecode. If this Python bytecode is run through a Python bytecode interpreter, it does what your program was supposed to do. In most situations, however, Python developers think of both of those steps being done in one big step, so they choose to think of the CPython interpreter as interpreting their sourcecode, and the fact that it got compiled along the way is considered an implementation detail. In this way, it's all a matter of perspective.


问:
Switching CSS to use asset pipeline in Rails?
I have a lot of legacy CSS files from what was a Rails 2.x app that got upgraded to Rails 3.2.8, and I want to switch over to using the Rails asset pipeline for stylesheets. The issue is, the CSS stuff is messy in terms of huge lines of code, duplicate file names, and unorganized folder structure.

After looking through individual pages, and trying to add individual stylesheets and folders into the asset pipeline and spending some cycles debugging, I realized there's probably a better approach.

Is there a way to test to make sure the old CSS matches up with the asset pipeline CSS? What are some good tools for testing and debugging CSS?

答:
Warning: You man not like this answer.

Even though rails gives you CSS file for each controller - the're not included only for this controller. If you put *= require_tree . in your application.css - the all are going to be included.

So if your legacy project used approach to include different files for different pages - ouch. There's some substantial work for you to do.

What you can do is to implement such solution in your layout:

```<code><%= stylesheet_link_tag 'application' %>
<%- (@extra_css || []).each do |css| %>
  <link rel="stylesheet" type="text/css" href="/legacy_csses/<%= css %>" />
<% end %>
</code>```

(I write in HAML, so this erb might need some polishing to work ;))

And in your controllers you can

```<code>def index
  @extra_css = ['one.css', 'two.css']
end
</code>```

so you can have specific css'es per controller or action. But keep in mind those styles are not in assets pipeline. This is temporary solution. From now on you can start to refactor. You can do it one @extra_css file at a time. https://github.com/Huddle/PhantomFlow can be helpful, it can test your styling against reference screenshot so you can see quickly what you've messed up.

Nevertheless there's some refactoring for you to do before you can move all styles into assets pipeline. But you'll get there. It will feel good. I envy you a little :)

Body:
Warning: You man not like this answer.

Even though rails gives you CSS file for each controller - the're not included only for this controller. If you put *= require_tree . in your application.css - the all are going to be included.

So if your legacy project used approach to include different files for different pages - ouch. There's some substantial work for you to do.

What you can do is to implement such solution in your layout:

<%= stylesheet_link_tag 'application' %>
<%- (@extra_css || []).each do |css| %>
  <link rel="stylesheet" type="text/css" href="/legacy_csses/<%= css %>" />
<% end %>

(I write in HAML, so this erb might need some polishing to work ;))

And in your controllers you can

def index
  @extra_css = ['one.css', 'two.css']
end

so you can have specific css'es per controller or action. But keep in mind those styles are not in assets pipeline. This is temporary solution. From now on you can start to refactor. You can do it one @extra_css file at a time. https://github.com/Huddle/PhantomFlow can be helpful, it can test your styling against reference screenshot so you can see quickly what you've messed up.

Nevertheless there's some refactoring for you to do before you can move all styles into assets pipeline. But you'll get there. It will feel good. I envy you a little :)


问:
Is Python Interpreted or Compiled?
This is just a wondering I had while reading about interpreted and compiled languages.

Ruby is no doubt an interpreted language since the source code is processed by an interpreter at the point of execution.

On the contrary C is a compiled language, as one have to compile the source code first according to the machine and then execute. This results is much faster execution.

Now coming to Python:

A python code (somefile.py) when imported creates a file (somefile.pyc) in the same directory. Let us say the import is done in a python shell or django module. After the import I change the code a bit and execute the imported functions again to find that it is still running the old code. This suggests that *.pyc files are compiled python files similar to executable created after compilation of a C file, though I can't execute *.pyc file directly.

When the python file (somefile.py) is executed directly ( ./somefile.py or python somefile.py ) no .pyc file is created and the code is executed as is indicating interpreted behavior.

These suggest that a python code is compiled every time it is imported in a new process to create a .pyc while it is interpreted when directly executed.

So which type of language should I consider it as? Interpreted or Compiled?
And how does its efficiency compare to interpreted and compiled languages?

According to wiki's Interpreted Languages page, it is listed as a language compiled to Virtual Machine Code, what is meant by that?

答:
Compiled vs. interpreted can be helpful in some contexts, but when applied in a technical sense, it is a false dichotomy.

A compiler (in the broadest sense) is a translator. It translates program A to program B and for future execution it using a machine M.

An interpreter (in the broadest sense) is an executor. It is a machine M that executes program A. Though we typically exclude from this definitions physical machines (or non-physical machines that act just like physical ones). But from theoretic perspective, that distinction is somewhat arbitrary.

For example, take re.compile. It "compiles" a regex to an intermediate form, and that intermediate form is interpreted/evaluated/executed.

In the end, it depends on what level abstraction you are talking about, and what you care about. People say "compiled" or "interpreted" as broad descriptions of the most interesting parts of the process, but really most every program is compiled (translated) and interpreted (executed) in one way or another.

CPython (the most popular implementation of the Python language) is mostly interesting for executing code. So CPython would typically be described as interpreted. Though this is a loose label.

ContentLicense: CC BY-SA 4.0

Title: Is Python Interpreted or Compiled?


问:
What license can I choose for a shallow fork of a recently abandoned project?
So I need a bootloader for an avr chip and after some research, I selected this one.

License

OpenSource, base on GPL license.

It needed minor modifications to compile without the dedicated AvrStudio. Namely:

conformance to c99

writing a makefile

custom configuration for my PCB and chip.

I would like to push the modified project to GitHub, mainly as means to archive it in case of hard disk failure. The bootloader is going to be a part of my final year project, which I would like to publish as MIT/BSD/any-non-copyleft license.

The project seems to have been abandoned during 2012 and the author is not returning my emails.

After this background, my question. What is supposed to be the content of the LICENSE file, that GitHub recommends? Should I put a large "I DO NOT OWN THIS CODE", should I select a GPL version or do I have more options?

And another question. How is my project supposed to be called? Do I have the right to name it the same as the original? Do I have the right to change the name?

Related, but the original project is MIT:

Licensing on forked projects

答:
I'm not sure that the single statement of "OpenSource, base on GPL license" is actually a valid license:  we can say informally that a program is GPL, but it's supposed to actually include a copy of the license containing the real legal terms.  The source code for this project (avrubd_src_v45.zip) doesn't seem to contain any sort of license file.

However, it sounds like the author intended to apply (some unspecified version of) the GPL to the program.  That would require that any modified versions must also be distributed on the same terms.

To be really sure, you should talk to a lawyer, but it sounds to me like if it's legal to fork the program at all, the GPL is the only license you're allowed to use.  You could potentially use a BSD-type license specifically for any new code that you add, but the complete program (containing the original author's code, even with modifications) has to be GPL.


答:
If you fork a GPL project, you need to keep the same GPL license (unless the original copyright owner gives you permission to change it).

BTW, I strongly suggest to contact and interact with the original authors of the project. They will probably be happy of you working on their code (and they could help you, maybe give you permission for relicensing, etc...).

Regarding naming, if you want (and I recommend that) to fork the original repository on GitHub, you'll keep the same name.

I would suggest to keep the same name anyway, or at least to have a similar name.

Title: What license can I choose for a shallow fork of a recently abandoned project?

Body:
So I need a bootloader for an avr chip and after some research, I selected this one.

License

OpenSource, base on GPL license.

It needed minor modifications to compile without the dedicated AvrStudio. Namely:

conformance to c99

writing a makefile

custom configuration for my PCB and chip.

I would like to push the modified project to GitHub, mainly as means to archive it in case of hard disk failure. The bootloader is going to be a part of my final year project, which I would like to publish as MIT/BSD/any-non-copyleft license.

The project seems to have been abandoned during 2012 and the author is not returning my emails.

After this background, my question. What is supposed to be the content of the LICENSE file, that GitHub recommends? Should I put a large "I DO NOT OWN THIS CODE", should I select a GPL version or do I have more options?

And another question. How is my project supposed to be called? Do I have the right to name it the same as the original? Do I have the right to change the name?

Related, but the original project is MIT:

Licensing on forked projects


答:
Other answers have hinted at this, but just to clarify:

You don't really have any legal right to use, develop, or redistribute the code based on the quoted statement.

A statement that the author intends to make the code open source is not enough.  There needs to be an actual license that outlines what you are allowed to do.  You have nothing you can point to that actually proves the author granted you rights to this code.  Furthermore, the vague wording "based on GPL" leaves it unclear even what the author might actually intend.

Given the facts that the code was published on the internet and the statement of intent to make it open source, I wouldn't mind using and adapting this code for my own personal use.

However, I would not redistribute this code without a license or at least some form of written agreement from the author.  Doing so probably wouldn't ever cause a problem, given the author's statement, but there is a risk.  What if your version became popular and widely used?  The author could have a change of heart and decide to take legal action to regain control or make some money off it.  You wouldn't have a very good defense against this.

The author's seeming unconcern over licensing also makes me worry that the author may have taken someone else's code without paying proper attention to the license.  If this work contains someone else's code (even if that code was released under an open source license), I think you would be at risk of redistributing it inappropriately.

Caveat: consult a lawyer for an authoritative answer.


答:
A compiler would create machine language

No. A compiler is simply a program which takes as its input a program written in language A and produces as its output a semantically equivalent program in language B. Language B can be anything, it doesn't doesn't have to be machine language.

A compiler can compile from a high-level language to another high-level language (e.g. GWT, which compiles Java to ECMAScript), from a high-level language to a low-level language (e.g. Gambit, which compiles Scheme to C), from a high-level language to machine code (e.g. GCJ, which compiles Java to native code), from a low-level language to a high-level language (e.g. Clue, which compiles C to Java, Lua, Perl, ECMAScript and Common Lisp), from a low-level language to another low-level language (e.g. the Android SDK, which compiles JVML bytecode to Dalvik bytecode), from a low-level language to machine code (e.g. the C1X compiler which is part of HotSpot, which compiles JVML bytecode to machine code), machine code to a high-level language (any so-called "decompiler", also Emscripten, which compiles LLVM machine code to ECMAScript), machine code to low-level language (e.g. the JIT compiler in JPC, which compiles x86 native code to JVML bytecode) and native code to native code (e.g. the JIT compiler in PearPC, which compiles PowerPC native code to x86 native code).

Note also that "machine code" is a really fuzzy term for several reasons. For example, there are CPUs which natively execute JVM byte code, and there are software interpreters for x86 machine code. So, what makes one "native machine code" but not the other? Also, every language is code for an abstract machine for that language.

There are many specialized names for compilers that perform special functions. Despite the fact that these are specialized names, all of these are still compilers, just special kinds of compilers:

if language A is perceived to be at roughly the same level of abstraction as language B, the compiler might be called a transpiler (e.g. a Ruby-to-ECMAScript-transpiler or an ECMAScript2015-to-ECMAScript5-transpiler)

if language A is perceived to be at a lower level level of abstraction than language B, the compiler might be called a decompiler (e.g. a x86-machine-code-to-C-decompiler)

if language A == language B, the compiler might be called an optimizer, obfuscator, or minifier (depending on the particular function of the compiler)

which runs on the physical hardware directly?

Not necessarily. It could be run in an interpreter or in a VM. It could be further compiled to a different language.

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

An interpreter doesn't produce anything. It just runs the program.

A compiler produces something, but it doesn't necessarily have to be machine language, it can be any language. It can even be the same language as the input language! For example, Supercompilers, LLC has a compiler that takes Java as its input and produces optimized Java as its output. There are many ECMAScript compilers which take ECMAScript as their inputs and produce optimized, minified, and obfuscated ECMAScript as their output.

You may also be interested in:

Understanding the differences: traditional interpreter, JIT compiler, JIT interpreter and AOT compiler

Which components/phases of a JIT compiler are different from a traditional ahead of time compiler?

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?


问:
How much configurability to give to users regarding concurrency?
This question is a narrowing-down of these related questions:

How much effort should we spend to programming for multiple cores?

Concurrency: How do you approach the design and debug the implementation?

Given that each user's computers may have different performance characteristics with respect to calculations, memory, disk I/O bandwidth and network I/O bandwidth, and that it is difficult to implement an automated self-tuning system in your software, how much configurability should we give to the end-users so that they can find ways (by trial-and-error?) to improve our software's efficiency?

If we give users the ability to change these settings, how do we give visual feedback to users so they can measure the performance changes?

答:
I don't think that giving the user control over these options is a good idea. Of course this depends on the software and target user demographic, but I can't imagine a common application where the average user is interested in tweaking that sort of stuff. They just want the application to work. Incrementally adjusting performance options through trial and error is probably too much.

If you have performance problems, fix them. If you don't, don't worry about it and don't complicate the app and potentially confuse the user with options they may don't understand. You could open yourself up to a lot of support tickets along the lines of "I changed some options and now your application is too slow. Fix it.", if they even admit that they changed any settings.

ContentLicense: CC BY-SA 2.5


问:
How to store various sized values in a vector?
I want to separate the communication protocol from the communication medium in a project.  For example, I want to have a serial class and whatever other medium class and separately have a checksum protocol class and a crc protocol class and so forth.  That way, a device class can have a member base class pointer to the medium and another to the protocol and via that device class's constructor child classes of both can be passed.

Pseudo code

```<code>class CDevice
{
public:
CDevice( CCommunicationDriver * drvr, CProtocol * protocol ) :
    drvr_     ( drvr ),
    protocol_ ( protocol )
{}

private:
CCommunicationDriver * drvr_;
CProtocol *            protocol_;
};

class CCrcProtcol : public CProtocol
{};

class CSerial : public CCommunicationDriver
{};

CDevice  a_device( new CSerial, new CCrcProtocol );
</code>```

The idea is that if the difference between 2 devices is solely the medium and/or protocol a simple change can have a profound impact.  The goal is minimal code rewrite for a change of this nature.

Ultimately, I envision the communication driver taking in a CPacket which is a thin wrapper around a std::vector.  That way the interface for communicationdriver doesn't have to change going forward.  I plan for the vector to hold unsigned char's ( bytes ) since ultimately everything going over a wire/medium is bytes.

This leads to commands that are decoupled from the medium and protocol albeit not completely decoupled.  So, a command to turn on a light might have an ID 1 and a sub-ID 2.  What I think I need to do is to pass child commands to the driver's transmit function [ tx( CCommand * ) ] and have that function apply the protocol's decoration ( not sure on how that'll work yet ) and then get a vector of bytes to have the child communication driver push out over the wire.

Thus, I have 2 questions I could use help with.
1. ( main question ) Since ultimately everything ends up in the std::vector< unsigned char > what's a flexible way to add data to that vector?  I.e. a command has an id 2 bytes long due to one protocol but for another it's 4 bytes.  How do I pass id and 2 or 4 to some function that will split it up into single bytes?  Assume there's a lot sizes ( 1, 2, 3, 4, 8, etc. length ).  I've thought about a template function that you specify the type with and then the value passed will be interpreted as that type's size.
    template< typename T >
    void addData( T data )
    {
    // determine data's type, parse somehow?
    }

```<code>and also
template <typename T >
void addData( T data, int size )
{
// size is known but won't I have to specialize every size?
}
</code>```

Would you have the protocol class be a member of the driver class or keep them separate?

I hope this long explanation of what I'm trying to achieve is more helpful than annoying and that someone has a bright idea.

Thanks.
-G-

答:
Firstly, command classes are decoupled from the medium and protocol. That means you can design the command classes for your own programming convenience, rather than having to design it to match exactly to the specifics of each protocol (which would be impossible, since different protocols may have different bit widths for the same command and field).

When I mention convenience, what I mean is that you can use the maximum bit width you'll ever need for each command's fields.

However, you may still need to have device- or protocol-specific validation code, since each device or protocol imposes its own limits to what values can be in those fields. Unless you don't plan to implement any validation at all.

When it comes to validation, there are several choices:

Not doing it at all, if you will be doing all of the programming yourself, and if it is a hobby project such that mistakes do not result in damages.

Validating it eagerly, i.e. in the command class. This may be difficult, since a command class might not know which device or protocol it will be sent to.

Validating it late, i.e. in the protocol class where the command values are being converted into bytes.

For example, even if a validation rule says that a particular field can only have a value in the range 0 - 100, it doesn't stop you from using a uint32_t or int32_t for that field in the command class.

To the second question of having an overloaded method that takes in various built-in number types and append the bytes to an internal byte vector, do notice the caveats.

In my opinion, if you only needs to work with the fundamental integer types, you don't need templates. Instead, you simply provide function overloads for each of the types, and you call the functions with a value of the appropriate type.

```<code>void CPacket::addData(uint32_t data) { ... }
void CPacket::addData(int32_t data) { ... }
void CPacket::addData(uint16_t data) { ... }
void CPacket::addData(int16_t data) { ... }
...
</code>```

Regarding the code inside, there are several choices:

Type punning with union. This assumes that your code will work exclusively with one byte-endianness, thus not needing to consider the possibility of porting to a different byte-endianness.

```<code>union
{
    uint32_t value;
    uint8_t bytes[4];
} pun = { data };
// after that, add the bytes to the vector one-by-one, according to the byte endianness of the communication.
</code>```

Explicitly extracting the bytes with endian-agnostic bitwise arithmetic: (see note on casting)

```<code>// only if value is unsigned. For signed value, it must first be cast to unsigned
uint8_t byte0 = (uint8_t)value;
uint8_t byte1 = (uint8_t)(value >> 8ul);
uint8_t byte2 = (uint8_t)(value >> 16ul);
uint8_t byte3 = (uint8_t)(value >> 24ul);
</code>```

Body:
Firstly, command classes are decoupled from the medium and protocol. That means you can design the command classes for your own programming convenience, rather than having to design it to match exactly to the specifics of each protocol (which would be impossible, since different protocols may have different bit widths for the same command and field).

When I mention convenience, what I mean is that you can use the maximum bit width you'll ever need for each command's fields.

However, you may still need to have device- or protocol-specific validation code, since each device or protocol imposes its own limits to what values can be in those fields. Unless you don't plan to implement any validation at all.

When it comes to validation, there are several choices:

Not doing it at all, if you will be doing all of the programming yourself, and if it is a hobby project such that mistakes do not result in damages.

Validating it eagerly, i.e. in the command class. This may be difficult, since a command class might not know which device or protocol it will be sent to.

Validating it late, i.e. in the protocol class where the command values are being converted into bytes.

For example, even if a validation rule says that a particular field can only have a value in the range 0 - 100, it doesn't stop you from using a uint32_t or int32_t for that field in the command class.

To the second question of having an overloaded method that takes in various built-in number types and append the bytes to an internal byte vector, do notice the caveats.

In my opinion, if you only needs to work with the fundamental integer types, you don't need templates. Instead, you simply provide function overloads for each of the types, and you call the functions with a value of the appropriate type.

void CPacket::addData(uint32_t data) { ... }
void CPacket::addData(int32_t data) { ... }
void CPacket::addData(uint16_t data) { ... }
void CPacket::addData(int16_t data) { ... }
...

Regarding the code inside, there are several choices:

Type punning with union. This assumes that your code will work exclusively with one byte-endianness, thus not needing to consider the possibility of porting to a different byte-endianness.

union
{
    uint32_t value;
    uint8_t bytes[4];
} pun = { data };
// after that, add the bytes to the vector one-by-one, according to the byte endianness of the communication.

Explicitly extracting the bytes with endian-agnostic bitwise arithmetic: (see note on casting)

// only if value is unsigned. For signed value, it must first be cast to unsigned
uint8_t byte0 = (uint8_t)value;
uint8_t byte1 = (uint8_t)(value >> 8ul);
uint8_t byte2 = (uint8_t)(value >> 16ul);
uint8_t byte3 = (uint8_t)(value >> 24ul);


问:
The burndown suffers due to "technical" dependency between tasks - should we focus more on each task, and accept additional overhead?
We have a new piece of functionality coming up. It comprises of 9 different user stories, covering the functions needed. Three of these are listed below:

As a user I should be able to add a person so that...

As a user I should be able to edit a person so that...

As a user I should be able to delete a person so that...

These three issues make out about 20 sp's each.

The challenge is that these three issues are in practice treated as one issue. So, instead of having a nice burndown with 20 sp's burned on Tuesday, 20 sp's burned on Thursday and 20 on the following Monday, I get to see 60 sp's burned on the last day (e.g. Monday).

In theory, (I believe) this is wrong. Each issue implemented should be "atomic" in the way that you can deploy this in production once the issue is done. This makes sense, and in my scenario above, you can deploy "add" to production without having edit and delete.

However, from a technical perspective, it makes sense to "combine" the implementation of the three. Or at least add and edit. They share a lot of logic, and you might have to "pay more" if you first complete "add" and then start on "edit" the day after.

Question is if we should continue as this, and have a rotten burndown in these cases, or if we should allow for more overhead and focus on the theoretical part - e.g. "atomic" issues.

Or should we consider something else?

答:
The best thing to do would be to stick to the atomic nature, i.e. working on one user story at once instead of all at the end.

Doing several related but atomic stories at once can have several problems. It makes testing more difficult and takes more time, as there can be a dip in stories to test, then a sudden flood, leading to irregular test workloads. It also means that finding which story a bug relates to becomes more difficult.

In your example however, this is not always possible. The story to add a user would most likely have to be completed prior to the other two stories, as it would be difficult to debug the editing/deletion of a user without being able to add one.


答:
The significance of atomic stories is that your application should be in a state that can be deployed after a story is completed: build is not broken, all tests pass, etc. That does not mean that your application at that point is feature complete, it just means that a single story is finished but the feature as a whole does not necessarily work yet. Would you really WANT to deploy add without having edit or remove? Probably not... You deploy when a FEATURE (which can be comprised of multiple STORIES) is completed. Sometimes 1 feature = 1 story, sometimes 1 feature = 12 stories.

Atomic stories also mean that multiple stories can be worked on simultaneously, which is important in bigger teams. In that sense, add and edit cannot be considered atomic because they depend on each other. Nothing wrong with that, and also nothing wrong with writing the code for your first 'add' story taking the fact into account that you need to do an 'edit' story next.

For these kinds of features, we often have estimations that are heavy on the 'add' story. In this story, we create database tables, create new domain objects, new pages, and so on. The 'edit' story is a lot less story points because we already have the tables, object, pages and so on. We factor this into account when estimating.

Concerning your burndown: you don't draw a burndown based on storypoints. Unless you are doing hundreds of stories in a sprint it makes more sense to burn down based on tasks. Stories are estimated in story points to indicate the amount of work a team thinks it will take which allows some amount of planning ('how many stories can we fit into a sprint'). Teams then divide stories for a sprint into tasks and burndown on those. You can burn down on story points when you are doing things like a yearly status report.

Title: The burndown suffers due to "technical" dependency between tasks - should we focus more on each task, and accept additional overhead?

Body:
We have a new piece of functionality coming up. It comprises of 9 different user stories, covering the functions needed. Three of these are listed below:

As a user I should be able to add a person so that...

As a user I should be able to edit a person so that...

As a user I should be able to delete a person so that...

These three issues make out about 20 sp's each.

The challenge is that these three issues are in practice treated as one issue. So, instead of having a nice burndown with 20 sp's burned on Tuesday, 20 sp's burned on Thursday and 20 on the following Monday, I get to see 60 sp's burned on the last day (e.g. Monday).

In theory, (I believe) this is wrong. Each issue implemented should be "atomic" in the way that you can deploy this in production once the issue is done. This makes sense, and in my scenario above, you can deploy "add" to production without having edit and delete.

However, from a technical perspective, it makes sense to "combine" the implementation of the three. Or at least add and edit. They share a lot of logic, and you might have to "pay more" if you first complete "add" and then start on "edit" the day after.

Question is if we should continue as this, and have a rotten burndown in these cases, or if we should allow for more overhead and focus on the theoretical part - e.g. "atomic" issues.

Or should we consider something else?


问:
What are good/common practices to manage disabling/enabling functionality items in GUI applications for different licenses/permissions?
I have worked on two different desktop applications and both had the problem of enabling/disabling functionality and associated GUI elements depending on available licenses or "user-roles".

In the first application I worked on, a mess was created by cluttering the code with conditionals that checked for certain licenses. I now work on another application for which work has just recently started and where a similar problem occured. Now I am looking for a good way to solve the problem in a "better" way.

The problems with the system we had were:

We had many many places in the code that looked like

if( !check_license( MY_LICENSE ) ) myWidget->setVisible(false);

or

if( !check_license( MY_LICENSE ) ) return;

These kind of lines cluttered the code in many places and were hard to maintain when a piece of functionality should be disabled/enabled for a certain license.

Sales people often asked: "Can I do this and that with licence xy?"
We had a table in a wiki that tried to solve that problem but it was rather coarse grained so we often had to look into the code to find the answer.

So here is the question:

How can one reduce the "clutter-effect" and what are the best ways to have a central register for functionality items.

I think the sollution should contain the following concepts.

The notion of a functionality item, that is explicitly mentioned in the code.

The notion of a functionality block to which multiple functionality items can be asigned.

An entity "FunctionalityRegister" that allows registering functionality items with functionality blocks that can print a list of functionality items for each functionality block

An entity that can be asked if a functionality item is currently enabled

I have not concrete ideas how one can reduce the number of places where the program asks if an functionality item is enabled. I would like to here your ideas on that problem.

I would also like to see sugestions for techniques that reduces the "code-size" of one enabledness request to a minium. This is dependent on the used technology so I have to mention that we use C++/Qt.

How was the problem solved in the applications you know and what where the advantages and disadvantages?

答:
I have not concrete ideas how one can reduce the number of places where the program asks if an functionality item is enabled.

That isn't needed. If a functionality involves changes to the user interface in 7 places, then there must be 7 places that check haveFeature(Bit.TIME_TRAVEL) in the code base. This is not a violation of DRY.

What should be reduced, preferably to 1, is the number of places that determine the behaviour of haveFeature(). Ideally, both the code base and your user support pople will take this knowledge from one and the same authoritative document. For instance, you could maintain a list/spread sheet/interpretive dance choreography/whatever in your version-controlled repository and auto-generate both the internal user-support web page and the decision code within haveFeature() from it, as a normal part of your build process.


问:
Starting on Web Project now - Do we choose HTML5/JS over Silverlight?
we are about to start on a Web Development project (the planning starts early 2011).

Do we choose HTML5/JS over Silverlight?

Are there any applications which now run on HTML5? Samples?

A simple Google Search led me here. Those look great (especially the Star Wars one!), but they are not what you call proper applications as such.

答:
A simple Google Search led me here. Those look great (especially the Star Wars one!), but they are not what you call proper applications as such.

What would you call "proper applications?"

That is what you need to ask yourself before you commit to a language set.

Notice: I've never done work with Silverlight. Plus I might be a bit HTML5 biased.

Silverlight

Flash-like Microsoft product. Requires a plug-in. Might require other Microsoft tools for development.

HTML5

HTML5 is a buzzword for a suite of new technologies that encourage fast, involved, web based applications. There is easy feature detection available as well as libraries to help split the difference between older browsers and newer ones.


问:
What is the preferred way of preparing data in automatic testing
Lets say I want to test a method of a class representing a user account. I have a fixture which contains several user records from which I want to choose one. What is the preferred method here?

Pick user record by unique ID ("pick user with ID=X")

Pick user record by some readable date like name or email address ("pick user with email='name@example.com'").

Pick user record by properties that are related to the test I make, e.g. if I want to test if a user with the role "admin" can access a specific method, I could pick the first admin user I can find ("pick user with role='admin'").

答:
If you are doing unittesting, you declare the objects you test on in your fixture. There is no 'loading' involved whatsoever. You simply create an instance of an object if you need it, set the fields so that the state of the object matches the state needed in your test and use the variable you assigned it to in your test.

```<code>[Test]
public void AdminUserShouldHaveBackUpAccess()
{
    var user = new User { IsAdmin = true };
    Assert.That(user.CanAccess("backup"), Is.True);
}

[Test]
public void RegularUserShouldNotHaveBackUpAccess()
{
    var user = new User { IsAdmin = false };
    Assert.That(user.CanAccess("backup"), Is.False);
}
</code>```

Body:
If you are doing unittesting, you declare the objects you test on in your fixture. There is no 'loading' involved whatsoever. You simply create an instance of an object if you need it, set the fields so that the state of the object matches the state needed in your test and use the variable you assigned it to in your test.

[Test]
public void AdminUserShouldHaveBackUpAccess()
{
    var user = new User { IsAdmin = true };
    Assert.That(user.CanAccess("backup"), Is.True);
}

[Test]
public void RegularUserShouldNotHaveBackUpAccess()
{
    var user = new User { IsAdmin = false };
    Assert.That(user.CanAccess("backup"), Is.False);
}


答:
The main problem as described is that Producers are faster than the consumers.  This reminds me a lot of http://ferd.ca/queues-don-t-fix-overload.html . Reactive streams are an initiative that I noticed recently to provide some solution to this kind of setting.

You can have a look at any Queue oriented software products like:

Akka (letitcrash.com is their blog with some interesting general posts) or

ZeroMQ (Their guide offers some setups applicable to any Queue system)

to see how you can deal with overachieving producers.

However the main question remains how you want to deal with it from your business point of view? Since your consumers (3rd party) are limited in the amount of messages they can handle, your approach to batch import your buffered messages seems reasonable. Aggregating or even dropping messages might also be viable depending on your scenario.

No matter how you want to react to overflow, your queue should be made aware of this fact ( i.e. introducing back-pressure) and then you can apply your own strategy which will depend on your requirements.

In my last project I ended up pulling messages from a consumer through the queue system:

The producers were not hogging resources that could be used to work through the existing message pile.

The workers processing the messages could fetch new messages when they were ready without the need for scheduled pushing of new messages onto them.

I had a guaranteed downtime at specific intervals of the producers that allowed me to catch up since I could not drop any messages.

I hope this provides some handles that allow you to find your own solution.


答:
I think you should drop the notion of "compiler versus interpreter" entirely, because it's a false dichotomy.

A compiler is a transformer: It transforms a computer program written in a source language and outputs an equivalent in a target language. Usually, the source language is higher-level that the target language - and if it's the other way around, we often call that kind of transformer a decompiler.

An interpreter is an execution engine. It executes a computer program written in one language, according to the specification of that language. We mostly use the term for software (but in a way, a classical CPU can be viewed as a hardware-based "interpreter" for its machine code).

The collective word for making an abstract programming language useful in the real world is implementation.

In the past, a programming language implementation often consisted of just a compiler (and the CPU it generated code for) or just an interpreter - so it may have looked like these two kinds of tools are mutually exclusive. Today, you can clearly see that this isn't the case (and it never was to begin with). Taking a sophisticated programming language implementation, and attempting to shove the name "compiler" or "interpreter" to it, will often lead you to inconclusive or inconsistent results.

A single programming language implementation can involve any number of compilers and interpreters, often in multiple forms (standalone, on-the-fly), any number of other tools, like static analyzers and optimizers, and any number of steps. It can even include entire implementations of any number of intermediate languages (that may be unrelated to the one being implemented).

Examples of implementation schemes include:

A C compiler that transforms C to x86 machine code, and an x86 CPU that executes that code.

A C compiler that transforms C to LLVM IR, an LLVM backend compiler that transforms LLVM IR to x86 machine code, and an x86 CPU that executes that code.

A C compiler that transforms C to LLVM IR, and an LLVM interpreter that executes LLVM IR.

A Java compiler that transforms Java to JVM bytecode, and a JRE with an interpreter that executes that code.

A Java compiler that transforms Java to JVM bytecode, and a JRE with both an interpreter that executes some parts of that code and a compiler that transforms other parts of that code to x86 machine code, and an x86 CPU that executes that code.

A Java compiler that transforms Java to JVM bytecode, and an ARM CPU that executes that code.

A C# compiler that transforms C# to CIL, a CLR with a compiler that transforms CIL to x86 machine code, and an x86 CPU that executes that code.

A Ruby interpreter that executes Ruby.

A Ruby environment with both an interpreter that executes Ruby and a compiler that transforms Ruby to x86 machine code, and an x86 CPU that executes that code.

...and so on.


问:
How to split a class that is an implementation of interface?
Let's say there is class called AccountingService.
Using this class I fetch all kinds of ecommerce records like products, customers, etc. The fetching happens inside a controller action. Once fetched, I should process and save these records to some kind of ecommerce shop.

What I want to do is create an implementation of Shop

```<code>namespace PrestaShop;

use Shop\ShopInterface;

class Shop implements ShopInterface
{
    public function saveProduct(array $products)
    public function saveProductQuantities(array $productQuantities)
    public function saveCustomers(array $customers)
    public function getOrder($orderReference)
}
</code>```

The problem is that the methods are incredibly long, because many foreign keys, pivot tables, relations need to be saved to MySQL tables. I would like to extract product, customer, quantitiy methods into seperate classes/components that work as dependencies for this class.

I am using array because the fetched records are in bulk (lets say 10k), so I can't instantiate an object for each record and save it via active record.

Using separate Repository pattern objects doesn't make sense to me, because all these objects product, customer, quantity are related and have connected tables.

I'm looking for advice on how to split up the implementation PrestaShop\Shop into smaller classes.

Any other advice on hwo to structure this app logic is welcomed.

答:
You should split up the interface. Customers and products are not related so having an interface with saveProduct-methods and one with saveCustomer-methods will reduce the amount of code in your implementations.

If you can't split the interface up (because it is not under your control, for example), simply create a couple of classes that contain the different implementations split up, inject these classes into the class that implements the interface and route your calls to those classes. These can again have classes with specific roles injected into them (if a customer contains products, a CustomerSaver can have a ProductSaver injected so it can use the methods on that class).

All code that is generic (ie common to those classes) can be put in a base class that all sub-saving classes derive from.

```<code>namespace PrestaShop;

use Shop\ShopInterface;

class ProductSaver
{
    public function saveProduct(array $products)
    {
         //implement here
    }
}

class Shop implements ShopInterface
{
    function __construct($productSaver, $customerSaver)
    {
        $this->productSaver = $productSaver;
        $this->customerSaver = $customerSaver;
    }

    public funtion saveProduct(array $products)
    {
        $this->productSaver->saveProduct($products);
    }

    //and so on...
}
</code>```

Body:
You should split up the interface. Customers and products are not related so having an interface with saveProduct-methods and one with saveCustomer-methods will reduce the amount of code in your implementations.

If you can't split the interface up (because it is not under your control, for example), simply create a couple of classes that contain the different implementations split up, inject these classes into the class that implements the interface and route your calls to those classes. These can again have classes with specific roles injected into them (if a customer contains products, a CustomerSaver can have a ProductSaver injected so it can use the methods on that class).

All code that is generic (ie common to those classes) can be put in a base class that all sub-saving classes derive from.

namespace PrestaShop;

use Shop\ShopInterface;

class ProductSaver
{
    public function saveProduct(array $products)
    {
         //implement here
    }
}

class Shop implements ShopInterface
{
    function __construct($productSaver, $customerSaver)
    {
        $this->productSaver = $productSaver;
        $this->customerSaver = $customerSaver;
    }

    public funtion saveProduct(array $products)
    {
        $this->productSaver->saveProduct($products);
    }

    //and so on...
}


问:
State Machine Memory Management Problems
My state machine handles requests and returns the next state. In the below simplification, I've got two states here, CreatedState and RunningState. Running state is the end state, and just returns itself. Running state has state (as in memebers) that need to be preseved, I'll use the integer count to represent them.

```<code>std::unique_pointer<StateBase> handle();

// Caller
void Call(){
    _currentState = _currentState->handle();
}

// Created State Implementation
std::unique_pointer<StateBase> CreatedState::handle(){
    return std::make_unique<RunningState>();
}

// Running State Implementation (option 1: create a new one)
std::unique_pointer<StateBase> RunningState::handle(){
    return std::make_unique<RunningState>(RunningState(int count));
}
</code>```

The problem here is that creating a new RunningState with a memento/all-of-the-private-members of the old RunningState is messy and probably inefficient(?).

In a managed language I might just return this, but if I did something like that: return std::make_unique<RunningState>(&this) I would have two pointers to the same object and the destruction of the lhs _currentState in the Call() would leave me with nothing to point at.

How can I cleanly and efficiently leave _currentState unchanged?

答:
My potential solution:

Pass the pointer as a reference. Alter it in the handle as needed. I'm not a big fan of mutating parameters in general, but I think this might be the way to go?

```<code>#include <iostream>
#include <memory>

void handle2(std::unique_ptr<int>& current, bool changePtr)
{
    *current = *current + 5 ;
    if(changePtr){
    auto foo = std::make_unique<int>(200);
    (*foo)++;
    current = std::move(foo); //destruction of current only happens if I want to change state
    }
}

int main()
{
    auto currentState = std::make_unique<int>(50);

    handle2(currentState, false);
    std::cout << *currentState << std::endl; // 55
    // Guard against nullptr in caller

    handle2(currentState, true);
    std::cout << *currentState << std::endl; // 201

    handle2(currentState, false);
    std::cout << *currentState << std::endl; // 206
}
</code>```

Incidently, here is the state machine I was designing:
https://github.com/mikeyjkmo/ableton-freetime-looper

Body:
My potential solution:

Pass the pointer as a reference. Alter it in the handle as needed. I'm not a big fan of mutating parameters in general, but I think this might be the way to go?

#include <iostream>
#include <memory>

void handle2(std::unique_ptr<int>& current, bool changePtr)
{
    *current = *current + 5 ;
    if(changePtr){
    auto foo = std::make_unique<int>(200);
    (*foo)++;
    current = std::move(foo); //destruction of current only happens if I want to change state
    }
}

int main()
{
    auto currentState = std::make_unique<int>(50);

    handle2(currentState, false);
    std::cout << *currentState << std::endl; // 55
    // Guard against nullptr in caller

    handle2(currentState, true);
    std::cout << *currentState << std::endl; // 201

    handle2(currentState, false);
    std::cout << *currentState << std::endl; // 206
}

Incidently, here is the state machine I was designing:
https://github.com/mikeyjkmo/ableton-freetime-looper


问:
Is a function immediately impure if it takes a function as a parameter?
Since the purity of an input parameter is an unknown until runtime, is a function immediately considered impure if it takes a function as an input parameter?

Related: if a function applies a pure function that is defined outside of the function, but is not passed in as a parameter, is it still pure if it fulfills the criteria of having no side effects and output depends solely on input?

For context, I'm writing functional code in JavaScript.

答:
As long as all values used in the function are defined solely by its parameters, it's a pure function.

The facet that output is the same each time for the same input is controlled by whether the parameters are pure. If you assume the parameters (like a function argument) are also pure, then it is pure.

In a language like Javascript where purity isn't enforced, this means that it's possible to make an otherwise pure function have impure behavior by invoking an impure function passed as a parameter.

This effectively means that for languages that don't enforce purity (ie almost all), it's impossible to define a pure function which invokes functions passed as arguments. It's still useful to write them as pure as possible, and to reason about them as pure functions, but you have to exercise caution because the assumption that it's pure will be broken if you pass in the wrong arguments.

In my experience in practice this isn't usually a big deal - I find it rare to have impure functions be used as function arguments to pure functions.


问:
Can functional programming be used to develop a full enterprise application?
I am just beginning to learn Functional programming (FP). I come from a OOP world, where everything are objects, and most of them are mutable. I have a hard time wrapping around the concept that  functions don't have side effects.

If something is not mutable, how are common things objects like Employee or Person represented in FP.

Can FP be used to create a full fledged enterprise application?

答:
Yes, FP can be used in enterprise applications. Clojure is one example of an FP language with success in enterprise: http://cognitect.com/clojure#successstories

Representing state can be a challenge in FP and changing paradigms to fit FP can be a bit of a mind warp.  Some FP languages completely disallow side affects and mutable state.  Clojure allows both but discourages or isolates those paradigms.

In short, state representation may be very similar to OO.  It's state modification that is very different.  So for instance, in FP state may be represented by lists and maps.  A list of employees may look like:

```<code>[[name: "James Brown" address: "Barnwell, SC"]
 [name: "Elvis Presley" address: "Tupelo, MS"]]
</code>```

There are two ways I know of to handle state modification in FP.  One is something like functional reactive programming.  In this paradigm all state is handled at the highest level only... for instance, an HTML view of your application has state in the view (like the person's name, address, etc.).  Now when you click "update name" a function is called that handles every thing about a name update except actually changing the name.  This may sound weird... but bear with me.  The changed name would then be returned by the function and the view (or persistent data store, etc.) will show the new name.  Or, alternatively, an entire new structure with the updated name will be returned.  So what does the function do?  It validates the name and returns the new name if it is valid, an error if it is not, and possibly a new view or navigation link to follow.  For something more complex than a name change it may do a lot more.

So for FRP the object returned by the function is the new state and can be given directly to the view or whatever is at the high level.  In some cases FRP takes the whole state passes it to the function and gets the whole state back.

With this paradigm, the container or framework needs to handle the update of the display, database, or whatever else needs updating from the new state.  So you can imagine a framework that draws the application on screen.  When a user clicks something functions are invoked and the new state is returned.  The framework then updates the screen by either redrawing everything or intelligently redrawing parts of the display.  See http://blog.getprismatic.com/om-sweet-om-high-functional-frontend-engineering-with-clojurescript-and-react/

Clojure uses the second paradigm that I've come across and that is to isolate state changes but not necessarily restrict them to the highest level.  With Clojure all mutable state must be "held" (unless you're using Java objects for state) by an atom, agent, or reference.  The way this works is the object held or pointed to or referenced (however you want to call it) by the atom/agent/ref is immutable, but the atom/agent/ref can change to point to a new object.  In this case you use special methods on the atom/agent/ref that say "update the object here by doing such and such and reassigning the atom/agent/ref to a new object".

Why is this beneficial you may ask?  Because the immutable object referenced by these Clojure constructs may be passed to a function that does something and while that function is running its reference to the object is guaranteed not to change.  That is, the atom/agent/ref isn't passed to the function but the immutable object pointed to by them is passed.  Atoms, agents, and refs have special properties that handle updates and concurrency in ways that are safe and part of the language.  See http://clojure.org/state

I hope this helps.  I suggest reading more about Clojure state and FRP to get a better understanding for how employees and persons can be represented in FP.  Though, the actual representation would be similar to object oriented programming... it's the mutability that is really different.

Body:
Yes, FP can be used in enterprise applications. Clojure is one example of an FP language with success in enterprise: http://cognitect.com/clojure#successstories

Representing state can be a challenge in FP and changing paradigms to fit FP can be a bit of a mind warp.  Some FP languages completely disallow side affects and mutable state.  Clojure allows both but discourages or isolates those paradigms.

In short, state representation may be very similar to OO.  It's state modification that is very different.  So for instance, in FP state may be represented by lists and maps.  A list of employees may look like:

[[name: "James Brown" address: "Barnwell, SC"]
 [name: "Elvis Presley" address: "Tupelo, MS"]]

There are two ways I know of to handle state modification in FP.  One is something like functional reactive programming.  In this paradigm all state is handled at the highest level only... for instance, an HTML view of your application has state in the view (like the person's name, address, etc.).  Now when you click "update name" a function is called that handles every thing about a name update except actually changing the name.  This may sound weird... but bear with me.  The changed name would then be returned by the function and the view (or persistent data store, etc.) will show the new name.  Or, alternatively, an entire new structure with the updated name will be returned.  So what does the function do?  It validates the name and returns the new name if it is valid, an error if it is not, and possibly a new view or navigation link to follow.  For something more complex than a name change it may do a lot more.

So for FRP the object returned by the function is the new state and can be given directly to the view or whatever is at the high level.  In some cases FRP takes the whole state passes it to the function and gets the whole state back.

With this paradigm, the container or framework needs to handle the update of the display, database, or whatever else needs updating from the new state.  So you can imagine a framework that draws the application on screen.  When a user clicks something functions are invoked and the new state is returned.  The framework then updates the screen by either redrawing everything or intelligently redrawing parts of the display.  See http://blog.getprismatic.com/om-sweet-om-high-functional-frontend-engineering-with-clojurescript-and-react/

Clojure uses the second paradigm that I've come across and that is to isolate state changes but not necessarily restrict them to the highest level.  With Clojure all mutable state must be "held" (unless you're using Java objects for state) by an atom, agent, or reference.  The way this works is the object held or pointed to or referenced (however you want to call it) by the atom/agent/ref is immutable, but the atom/agent/ref can change to point to a new object.  In this case you use special methods on the atom/agent/ref that say "update the object here by doing such and such and reassigning the atom/agent/ref to a new object".

Why is this beneficial you may ask?  Because the immutable object referenced by these Clojure constructs may be passed to a function that does something and while that function is running its reference to the object is guaranteed not to change.  That is, the atom/agent/ref isn't passed to the function but the immutable object pointed to by them is passed.  Atoms, agents, and refs have special properties that handle updates and concurrency in ways that are safe and part of the language.  See http://clojure.org/state

I hope this helps.  I suggest reading more about Clojure state and FRP to get a better understanding for how employees and persons can be represented in FP.  Though, the actual representation would be similar to object oriented programming... it's the mutability that is really different.


问:
How to query Aggregate Root to react to event from other AR
I want to create a little GPS tracking program. Simplified: Users can create Tracks.
To make things scale Track and User are two separate AR's. Track contains an AuthorUser which it refers to by UserID.

The following rules apply:

A User can create an unlimited amount of Tracks.

Users can be removed from the system. In that case all the created Tracks of the User need to be removed.

I want to use DDD+ES for this. Knowing the AR's can only be created/loaded by ID, how should I delete/modify all Tracks when a UserRemovedEvent is triggered?

Please note the query model is completely decoupled and might lag in time since it is async event-based updated.

答:
From what I can see, the answer to what you asked is a Saga -- you are creating transactions for multiple different Aggregate Roots, so no one AR has the responsibility for all of it.  The Saga uses the userId to query the TracksRepository/Projection for the list of tracks to be removed, and enumerates them.  Note that the Saga is relying only on model api -- it listens to the events, and sends commands to the Tracks, but has no knowledge of the internals of either.

Note the assumption here -- if these are different aggregate roots, then they are going to be modified in different transaction boundaries, and you're only getting "eventual" consistency.  So make sure that you and your domain experts agree what the real latency requirement is.


问:
How do you separate view from logic in a Winform application?
I know there are patterns like MVC to separate view from logic, however, I don't know how common they are in Winform applications.

For a C# Winform application, I may start with a Form and gradually add UI components to it, then for the events of components, (click, textchanged...) I call my functions, or directly write my logic there!

I know that is a bad habit, but I don't know what is the best way to start such a project in Visual Studio (a template, a framework, starting point),  Does MVC the only solution? Should I do it for any project?!

I would like to receive some guidelines or lightweight framework to get started.

答:
MVVM(Model-View-ViewModel) Pattern can be used in the Winforms

Model

```<code>public class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
}
</code>```

ViewModel

```<code>public class PersonViewModel : INotifyPropertyChanged
{
    private Person _Model;

    public string FirstName
    {
        get { return _Model.FirstName; }
        set(string value)
        {
            _Model.FirstName = value;
            this.NotifyPropertyChanged("FirstName");
            this.NotifyPropertyChanged("FullName"); //Inform View about value changed
        }
    }

    public string LastName
    {
        get { return _Model.LastName; }
        set(string value)
        {
            _Model.LastName = value;
            this.NotifyPropertyChanged("LastName");
            this.NotifyPropertyChanged("FullName");
        }
    }

    //ViewModel can contain property which serves view
    //For example: FullName not necessary in the Model
    public String FullName
    {
        get { return _Model.FirstName + " " +  _Model.LastName; }
    }

    //Implementing INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}
</code>```

View

```<code>public class PersonView: Form
{
    //Add two textbox and one label to the form
    //Add BindingSource control which will handle
    //ViewModel and Views controls changes

    //As viewmodel you can use any type which of course have same named properties
    public PersonView(Object viewmodel)
    {
        this.InitializeComponents();

        this.ViewModelBindingSource.DataSource = viewmodel;
        this.InitializeDataBindings();
    }

    private void InitializeDataBindings()
    {
        this.TextBoxFirstName.DataBindings.Add("Text", this.ViewModelBindingSource, "FirstName", true);
        this.TextBoxLastName.DataBindings.Add("Text", this.ViewModelBindingSource, "LastName", true);
        this.LabelFullName.DataBindings.Add("Text", this.ViewModelBindingSource, "FullName", true);
    }
}
</code>```

Read more about databinding in Winforms from MSDN

Body:
MVVM(Model-View-ViewModel) Pattern can be used in the Winforms

Model

public class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

ViewModel

public class PersonViewModel : INotifyPropertyChanged
{
    private Person _Model;

    public string FirstName
    {
        get { return _Model.FirstName; }
        set(string value)
        {
            _Model.FirstName = value;
            this.NotifyPropertyChanged("FirstName");
            this.NotifyPropertyChanged("FullName"); //Inform View about value changed
        }
    }

    public string LastName
    {
        get { return _Model.LastName; }
        set(string value)
        {
            _Model.LastName = value;
            this.NotifyPropertyChanged("LastName");
            this.NotifyPropertyChanged("FullName");
        }
    }

    //ViewModel can contain property which serves view
    //For example: FullName not necessary in the Model
    public String FullName
    {
        get { return _Model.FirstName + " " +  _Model.LastName; }
    }

    //Implementing INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

View

public class PersonView: Form
{
    //Add two textbox and one label to the form
    //Add BindingSource control which will handle
    //ViewModel and Views controls changes

    //As viewmodel you can use any type which of course have same named properties
    public PersonView(Object viewmodel)
    {
        this.InitializeComponents();

        this.ViewModelBindingSource.DataSource = viewmodel;
        this.InitializeDataBindings();
    }

    private void InitializeDataBindings()
    {
        this.TextBoxFirstName.DataBindings.Add("Text", this.ViewModelBindingSource, "FirstName", true);
        this.TextBoxLastName.DataBindings.Add("Text", this.ViewModelBindingSource, "LastName", true);
        this.LabelFullName.DataBindings.Add("Text", this.ViewModelBindingSource, "FullName", true);
    }
}

Read more about databinding in Winforms from MSDN


答:
Since the purity of an input parameter is an unknown until runtime, is a function immediately considered impure if it takes a function as an input parameter?

Technically, yes, unless there is some way in your language to guarantee that the input function is also pure.

if a function applies a pure function that is defined outside of the function, but is not passed in as a parameter, is it still pure if it fulfills the criteria of having no side effects and output depends solely on input?

Yes. So let's focus on what matters here. Calling a function pure or not isn't in and of itself useful. Pure functions are useful because producing the same output for any input and not depending on state or having side effects is a very useful set of properties. It means that once your function has been run, you can "remember" the answer for that input and it will always be true. You also don't need to run the function again to generate side effects. And you can run that function in parallel (or out of order) with other functions and know that they won't have any hidden interactions that behave badly.

Those useful properties still hold if the function uses other pure read-only functions to do its work, regardless of how it references them.

Title: Is a function immediately impure if it takes a function as a parameter?

Body:
Since the purity of an input parameter is an unknown until runtime, is a function immediately considered impure if it takes a function as an input parameter?

Related: if a function applies a pure function that is defined outside of the function, but is not passed in as a parameter, is it still pure if it fulfills the criteria of having no side effects and output depends solely on input?

For context, I'm writing functional code in JavaScript.


问:
Rich Model vs God Class
I have a legacy code containing some behaviour classes, like services and controllers. My model is pretty anaemic. It's just a repository of getters and setters, and I want to refactor it. There is a thin line between Rich Model and God Class. I'm afraid to refactor my anaemic model into a god class.

I want some opinion about how many lines is acceptable into a model class, and how many methods should I use without separating.

I know it's a unique perception from project to project, but I want to know some global opinions.

答:
Whether or not you have a god class has nothing to do with how many lines of code the class is, although that can certainly be used as an indication of a code smell of some sort.

A god class is one that does way too much (i.e., it has more than one main responsibility). If this is the case, it should be split into smaller classes which each have their own responsibility.

As an example, if you have a single class which handles a bunch of different things like file IO, business logic, and displaying a GUI, chances are it's a god class and needs to be refactored.

For more reading, see the Single Responsibility Principle or God Object.

Title: Rich Model vs God Class