问:
An embedded C developer wishing to interface some code with a web page
Okay, so as the title says, I'm an embedded C/C++ developer.

Right now, I'm working on a project that involves a client/server C application.  The server side of the application is running on multiple SoC nodes that are deployed in random locations (they run off a battery and use a cellular modem for communication).

Right now, I would like to poll information about these nodes.  So I have a central computer that I call my server, but that is running the client-side application of the project (bear with the nomenclature here).  I run my program from the command line with an IP address, and other parameters as an input.  It establishes a TCP connection with a node, sends it a request packet, and the node answers with a response packet.  I then write this data to a CSV file on the server computer (the one who initiated the request).  The socket is closed, and that's it.

One of the modes it runs in is "live mode", in which the client instantiates a TCP connection to one of the nodes (running the server portion of the application), and returns data once a second.  When data is returned, a CSV file is appended to.  Once the program receives an interrupt signal, it gracefully shuts down.

Now I'd like to do a little more.  I would like a user to be able to control this application via a web browser.

The hacky solution I came up with is to have a button on a page.  When this button is pressed, I do a shell_exec(/srv/bin/myApp_cli <parameters> &).  Then through AJAX Javascript, the page starts reading from its output file once a second.  It looks at the last line of the CSV file and posts it on the screen.  When I want to stop this application, I do shell_exec(killall -2 myApp_cli).

It works, but my god is that a hacky way of doing something that should be easy.  These two parts of the larger project: the web portion and the C client server portion; are extremely independent of one another.

My question is.. how can I interface my simple little C program with PHP, or any web language easily (I chose PHP because that's the only real back-end language I know).  What would be the best approach to achieve what I would like to do?  Especially in the case in which I run a program indefinitely until I want to send it a signal to stop?

答:
The best back end webserver language for an embedded C program is... C!

There are plenty of embedded C webservers that are trivially easy to use,  I added civetweb to my service a while ago and it was too easy. Civetweb is a non-GPL fork of Mongoose, but there are others such as NxWeb.

Civetweb has some examples, including ones that include Lua support and websockets if you need push responses to the web browser, all in a handful of lines of code.


问:
How do you check that code has been covered automatically?
I am in the process of setting up a Bamboo server for some new projects for a push to TDD in a CI/CD workflow. Sure, unit testing is great, but only as log as it is there.

Now this might be better off in a GIT pre-recieve hook on certain branches (i.e: develop and main release branches) but how should code coverage be enforced, if at all. I am happy to trust committers to ensure code is covered, but how are these things upheld without any slippage apart from diligence and consistency?

In short, I would like to see how others enforce test coverage as an automatic process during either commit or build stages.

答:
Noone has mentioned mutation tests. The idea behind them is quite practial and intuitive.

They work by modifying source code randomly (eg. switching ">" into "<") - hence mutation - and checking whether these haphazard changes break any test.

If they don't, then either a) the code in question might be unnecessary, or b) (more likely) this piece of code isn't covered by a test, since breaking it goes undetected.

ContentLicense: CC BY-SA 3.0


答:
Test coverage is a useful metric for the overall health of your project. A high test coverage lets you do an informed decision on whether the software will work as expected when deployed; with a low test coverage implying you're merely guessing. Tools exist to measure coverage automatically, these usually work by running the program in a debugging context or by injecting bookkeeping operations into the executed code.

There are different kinds of tests, and different kinds of coverage metrics. Common coverage metrics include function coverage, statement coverage, branch coverage, and condition coverage, although there are more.

Unit tests check whether the implementation of one conceptual unit (module, class, method, …) conforms to its specification (in TDD, the test is the specification). Units without their own unit tests are a red flag, though they might be covered by integration-style tests.

Unit tests should imply near-total function coverage – since the unit test exercises the whole public interface of that unit, there should be no functionality that isn't touched by these tests. If you're introducing unit testing to an existing code base, function coverage is a rough progress indicator.

A unit test should strive for good (75%–100%) statement coverage. Statement coverage is a quality metric for an unit test. Total coverage is not always possible, and you probably have better uses of your time than to improve coverage beyond 95%.

Branch and condition coverage are more tricky. The more complicated or important one piece of code is, the higher should these metrics be. But for unspectacular code, high statement coverage tends to be enough (and already implies a branch coverage of at least 50%). Looking at the condition coverage report of one unit can help to construct better test cases.

Integration tests check whether multiple units can correctly work with each other. Integration tests can be very useful without scoring high in any coverage metric. While integration tests would usually exercise a large part of their unit's interfaces (i.e. have high function coverage), the internals of these units have already been covered by the unit tests.

Running tests before code gets merged into a main branch is a good idea. However, calculating test coverage metrics for the whole program tends to take a lot of time – this is a nice job for a nightly build. If you can figure out how to do this, a good compromise would be to only run changed tests or unit tests on changed units in a Git hook. Test failures are not acceptable for anything other than “work in progress”-commits. If selected coverage metrics drop below some threshold (e.g. statement coverage below 80%, or the introduction of new methods without any corresponding tests), then these problems should be treated as a warning, with an opportunity for the developer to fix these potential issues. However, sometimes there are good reasons to ignore these warnings, and developers should be able to do so.

Testing is good, but too much of it can get annoying. Quick, relevant feedback can help to foster attention to quality, but you don't want it to get in the way of producing value. I personally prefer running tests manually, since it allows me to get faster feedback on the part I'm working on. Before release, I'll do a quality focus where I use static analysis, profilers, and code coverage tools to find problem zones (with some of these steps being part of a pre-release test suite).

Title: How do you check that code has been covered automatically?

Body:
I am in the process of setting up a Bamboo server for some new projects for a push to TDD in a CI/CD workflow. Sure, unit testing is great, but only as log as it is there.

Now this might be better off in a GIT pre-recieve hook on certain branches (i.e: develop and main release branches) but how should code coverage be enforced, if at all. I am happy to trust committers to ensure code is covered, but how are these things upheld without any slippage apart from diligence and consistency?

In short, I would like to see how others enforce test coverage as an automatic process during either commit or build stages.


问:
Best practices for lookup tables in the application - by id or value
I have a complex database application. There are a lot of lookup tables containing a few values, in particular one contains pass / fail / waiting / unknown.

In the application I find many of the queries depend on the pass/fail status of a model. So I want to display everything with a pass. Or everything that isn't a fail.

I am using Django (though I am sure the question is relevant outside of Django).

So when I am querying via the ORM, I can join the extra table in and say for example.

```<code>Model.objects.filter(passfail__status='pass')
</code>```

Alternatively I can use the ID.

```<code>Model.objects.filter(passfail_id=1)
</code>```

The first example will join in the passfail table and query based on the "status" field - the actual text 'pass' / 'fail' / 'waiting' text.

Is either of these considered good / bad practice?

Using the ID should be slightly better performance, as there is one less join. And it will avoid the problem of the passfail status changing (it shouldn't but I never know what users will do).

Using the status field should make the code more readable and more obvious what we are trying to achive. Though I don't expect the passfail table to change.

答:
Use enums. Good ORM framework can easily handle mapping of enums to IDs. Then you benefit two ways:

Simple use in code and clear business logic - you operate (compare, etc.) on descriptive names, so business logic is clear.

Performance efficiency: No joins for descriptive names in db queries (ORM will operate on Ids only)

If you can't - you can fallback to named constants just to make your code clear. You unfortunately won't benefit in ORM then.


问:
Staying productive by keeping focus on a feature while developing
As a hobbyist developer I'm quite keen on the git-flow way of working.

But I keep having a problem that I can only blame myself for: while developing a new feature, I keep getting sidetracked by small things that I can "quickly" do. Such things range from small refactoring, writing a particular piece of code in a more pythonic way, adding comments, decoupling, writing an extra test, etc.

Of course, next to the fact that these small things are unrelated to the feature I'm developing, they also tend to grow in size. What appears to be a small thing to do turns out to be something that you spend 2 hours on.

Are there any best practices to keep myself from doing this? I have tried forcing myself to switch to the development branch and do the fixes in a seperate hotfix branch, but I always fool myself into thinking that "for this little change, it's unnecessary to bother with a new branch". Is this just a question of discipline?

(Bonus question: I'm a sole developer, but how on earth would a team of developers handle someone like me? In other words: I'd be changing code all over the place, all the time, which would mean my co-developers would have to keep checking out code and keep trying to get their heads around the new changes).

答:
Those sorts of tasks are distracting because they're hard to get out of your head, so get them out of your head.  I keep an interruptions.txt file open that I put stuff like that into, or if it's small, I add a TODO comment (which I search for and remove before code review).  Then instead of it interrupting my main task just to get it out of my head, I can address it in an objective manner when I get to an appropriate place to do so.

When I address it objectively, there might be several outcomes:

I decide it's not that important.

I decide to put it in a user story on the backlog.

I decide to do it right then.

Deciding to do something right then is not necessarily a bad thing, if the decision was made objectively and not just because it was distracting you.  Team members don't like bad code getting perpetuated any more than lone developers do.  Just yesterday, I noted as a defect in a code review that the author failed to refactor code to remove duplication, even though I knew he didn't create the duplication.  Also, certain refactorings actually save you time, because they make it easier to spot defects before they go through a more expensive testing cycle.


问:
Data inter-exchange with C
I'm developing a system in which a C coded TCP server is listening for new connections from clients, on connection parse the data & store into database.

I'm familiar with JSON, and would like to use this as the data-interexchange between client & server. My issue here is the additional complexity of parsing json using C, in context to using a dynamic language such as php or java.

Before i start venturing in JSON headers/libraries (i'm currently looking at json-c), i thought it best to check with the community if JSON was a reasonable choice of format for this purpose? I've only worked with data inter-exchanges with higher level languages, so ease of parsing was always taken for granted.

答:
Don't see why not, its juts another format you have to handle, and there are thousands of them in the wild already. At least JSON is a well-known format.

A quick google says libjso, cJSON, and NxJSON are available as libraries to help parse and manage your data payloads so there shouldn't be much issue with the complexity of parsing it, no ore so than XML or text, say.

One thing I would suggest is to use an embedded webserver instead of a plain socket, if you're using JSON I might guess you may want web clients in the future (as there are plenty of these to chose from and they're really simple to add to your project)

Title: Data inter-exchange with C


答:
Parsing chunks from a stream is usually an issue.

One of the issues is that you often need to know the size of the packet to allocate the buffer needed to hold it while parsing. Most text based formats don't have that instead they are delimited by a special set of characters (JSON it's the closing brace/bracket).

If you elect for a binary transmission I suggest a fixed header with size and a integer denoting what message it is.

Title: Data inter-exchange with C

Body:
I'm developing a system in which a C coded TCP server is listening for new connections from clients, on connection parse the data & store into database.

I'm familiar with JSON, and would like to use this as the data-interexchange between client & server. My issue here is the additional complexity of parsing json using C, in context to using a dynamic language such as php or java.

Before i start venturing in JSON headers/libraries (i'm currently looking at json-c), i thought it best to check with the community if JSON was a reasonable choice of format for this purpose? I've only worked with data inter-exchanges with higher level languages, so ease of parsing was always taken for granted.


问:
Best practice to include XSD in C# project
I have an XSD schema I need to include within my program, to validate some user input XML. The schema will need to be regularly updated. (By the programmer.)

My current method to include this is hold a reference to it within Resources.resx - however, this doesn't seem ideal as it requires me to duplicate all my enum's between the XSD and the C#.

I've also looked at converting the XSD file to a runtime class using xsd.exe - however, as I understand, this requires running a separate process outside of Visual Studio, which makes it more complex to update, and requires the process being detailed for future authors.

I can't imagine this is an unusual situation - is there a method by which this is commonly done, where I can remove the duplication in my current method, but still not have the need to manually process the schema on each update?

答:
Create a pre-build step to run XSD.EXE before each build.

I found 2 other answers on SO that explain how to automate this:
https://stackoverflow.com/questions/14897750/automate-xsd-exe-during-build
https://stackoverflow.com/questions/2990684/automatically-generate-xsd-to-c-sharp-in-visual-studio-ide

The second one refers to a tool called XSD2code which is on codeplex.  I don't see a nuget package for it though.


问:
Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far

答:
Personally, I prefer camelCase, but in some fonts I think underscores are easier to read.

I would suggest that if you need to use prefixes to differentiate sets of variables, you should use a language that lets you make namespaces or objects or something to hold that information.

```<code>myName   = 7
bobsName = 8   // :(

me.name  = 7
bob.name = 8   // :D
</code>```

Likewise, if you need to differentiate types, why not use a language that allows them?

```<code>var intThingy = 7; // :(

int thingy = 7;    // :)
</code>```

Once you have that straight, and you're not just using the name as meta-data, then you won't have enough long names that it matters very much whether you prefer that extra keypress or not.

ContentLicense: CC BY-SA 2.5

Body:
Personally, I prefer camelCase, but in some fonts I think underscores are easier to read.

I would suggest that if you need to use prefixes to differentiate sets of variables, you should use a language that lets you make namespaces or objects or something to hold that information.

myName   = 7
bobsName = 8   // :(

me.name  = 7
bob.name = 8   // :D

Likewise, if you need to differentiate types, why not use a language that allows them?

var intThingy = 7; // :(

int thingy = 7;    // :)

Once you have that straight, and you're not just using the name as meta-data, then you won't have enough long names that it matters very much whether you prefer that extra keypress or not.


问:
Do I need to use cloud services (EC2 / GAE) for my web app?
Noobie to deploying any kind of web app. I have a Java (Play Framework) and MySQL server app running locally. I know that I can deploy it to EC2 (have once as a test), and that I can download some kind of module to get it to run on Google App Engine. But my question is -- do I need to?

I suppose I don't understand what my other options are -- are there other options besides these typical cloud offerings where I get my own server VM, get SSH access and run a Java application / install MySQL with admin access? If so, why would I choose EC2 / GAE over these other options?

I know that they are robust (mainly Amazon) and that's one reason. But I am fairly certain I do not need hardly anything that Amazon offers with their cloud packages other than the ability to run an EC2 instance. But then, I do need some level of customization, as I'm running a custom Java application and will need root level admin access, so from what I'e heard of GAE I probably would not use it.

答:
The main alternative to AWS EC2 would be a dedicated server. Having dedicated hardware can be beneficial if the following are true:

You have a good sense of your capacity requirements.

Performance is important for your application.

You expect that the resource needs of your application will be fairly constant over time.

You expect that traffic will be non-trivial from the start.

With all of this in mind, a cloud provider will be best for most situations, for different reasons.

If the site is a startup, or new line of business for an existing company, you want the freedom to adjust your expenses as the site grows.

If the site is a hobby project, you will not be able to get a dedicated server for the amount that a low-end EC2 instance costs ($10/month, after 1 year free trial.)

But if a key part of your site's value is performance, and you don't care about the easy of changing capacity, then you would want to do some testing to determine if dedicated machines will perform better than cloud instances.


问:
"Read user input": Could it be a step of an algorithm?
Based on this definition of algorithm from Wikipedia:

In mathematics and computer science, an algorithm is a self-contained step-by-step set of operations to be performed. Algorithms exist that perform calculation, data processing, and automated reasoning.

An algorithm is an effective method expressed as a finite list of well-defined instructions for calculating a function. Starting from an initial state and initial input (perhaps empty), the instructions describe a computation that, when executed, proceeds through a finite number of well-defined successive states, eventually producing "output" and terminating at a final ending state.

Is "Wait for user input" or simply read() counted an step of algorithm?

I thought for the following reasons it may not fit in the definition:

It seems it's not an step which can be executed as an operation is executed.

It should wait for an external signal to get finished, it could be against of the self-contained in the definition.

Moreover the definition talks about an initial input, so I suppose the input should be already provided.

Am I correct?

Update: If it's not an step, then how would you represent the following sequence, is it an algorithm?

X = 5

Y = X + 4

if ( Y > 10) Z = Read() // get the user input

else Z = 1

if (Z > 2) Z = Z + X

Please note reading occurs conditionally, then we may not suppose the input should be already provided.

答:
That definition of "algorithm" is extremely narrow. It applies only to non-interactive deterministic digital small-step algorithms.

However, algorithms need not be digital (consisting of discrete steps and operating on discrete values). They can also be continuous (consisting of discrete steps and operating on continuous values) or analog (continuous progress and operating on continuous values). They can be non-deterministic (actually, it turns out that non-determinism is just a form of interactivity). They can be interactive (i.e. interacting with an environment). They can be parallel (i.e. wide-step).

For example, the simple "bucket-of-rain" algorithm. This is an interactive digital small-step algorithm:

every morning at 8:00 am you put a bucket in the yard.

every evening at 8:00 pm you measure the amount of rain in the bucket, in grams, truncated down to an integer.

This is a perfectly valid algorithm. It even has steps and operates on discrete values (which isn't even necessarily required for it to be considered an algorithm).

It is, however, interactive. It depends on some environment outside of the algorithm. Mathematically, in algorithm theory, this is modeled as an oracle.

So, to answer your question: yes, what you have there, is an interactive algorithm, and the reading is definitely a part of it.


答: There are also some other libraries used for data exchange, e.g. protobuf or MessagePack. These libraries can better fit your needs - depends on data you plan to exchange</p>

Title: Data inter-exchange with C


答:
You have to apply some judgment to the situation.

If you go off all over the place on dis-related features, that is wrong and not very productive. Also, I once had a co-worker who did that and every checkout from version control was a nightmare for me.

If it's dis-related, you should generally log it for later. (I admit, sometimes, I tend to fix it right then but only if it takes seconds or is a serious bug.)

On the other hand, as you are developing a feature you will discover points, that were not necessarily thought of in planning, but that would greatly improve the software. There is nothing wrong with these. As a matter of fact I find that these little refinements developers add that make the difference between mediocre software and amazing software.

However, when you encounter the latter you have three options:

If it's simple and you can just do it now, without sidetracking too much, then do it right now.

If it's simple but would just complicate things right this moment, put a TODO and fix it before committing next time.

If it would throw you off track and really is a new User Story, log it for later.

So the key thing to focus is to have a log. This can be a piece of paper or a sophisticated issue tracking system or anything between.

When first implementing this you will notice that the "backlog" in the log increases rapidly. Don't worry this is only normal. There is a stage in the development process were all your core features are in place and you will start reducing this backlog.

Title: Staying productive by keeping focus on a feature while developing

Body:
As a hobbyist developer I'm quite keen on the git-flow way of working.

But I keep having a problem that I can only blame myself for: while developing a new feature, I keep getting sidetracked by small things that I can "quickly" do. Such things range from small refactoring, writing a particular piece of code in a more pythonic way, adding comments, decoupling, writing an extra test, etc.

Of course, next to the fact that these small things are unrelated to the feature I'm developing, they also tend to grow in size. What appears to be a small thing to do turns out to be something that you spend 2 hours on.

Are there any best practices to keep myself from doing this? I have tried forcing myself to switch to the development branch and do the fixes in a seperate hotfix branch, but I always fool myself into thinking that "for this little change, it's unnecessary to bother with a new branch". Is this just a question of discipline?

(Bonus question: I'm a sole developer, but how on earth would a team of developers handle someone like me? In other words: I'd be changing code all over the place, all the time, which would mean my co-developers would have to keep checking out code and keep trying to get their heads around the new changes).


问:
How to handle initial state in an event-driven architecture?
In an event-driven architecture each component only acts when an event is sent through the system.

Imagine a hypothetical car with a brake pedal and a brake light.

The brake light turns on when it receives a brake_on event, and off when it receives a brake_off event.

The brake pedal sends a brake_on event when it is pressed down, and a brake_off event when it is released.

This is all well and good, until you have the situation where the car is turned on with the brake pedal already pressed down. Since the brake light never received a brake_on event, it will stay off - clearly an undesirable situation. Turning the brake light on by default only reverses the situation.

What could be done to resolve this 'initial state problem'?

EDIT: Thank you for all the responses. My question was not about an actual car. In cars they solved this problem by continuously sending the state - therefore there is no startup issue in that domain. In my software domain, that solution would use many unnecessary CPU cycles.

EDIT 2: In addition to @gbjbaanb's answer, I'm going for a system in which:

the hypothetical brake pedal, after initialization, sends an event with its state, and

the hypothetical brake light, after initialization, sends an event requesting a state event from the brake pedal.

With this solution, there are no dependencies between components, no race conditions, no message queues to go stale, and no 'master' components.

答:
You can have an initialize event which sets states appropriately upon load/startup. This can be desirable for simple systems or programs not including multiple hardware pieces, however for more complicated systems with multiple physical components as you run the same risk as not initializing at all - if a "brake on" event is missed or lost along your communication system (for example, a CAN based system) you may inadvertently set your system backwards as if you started it with the brake depressed. The more controllers you might have, such as with a car, the higher likelihood something is missed.

To account for this, you can have the "brake on" logic repeatedly send out "brake on" events. Perhaps every 1/100 second or something. Your code containing the brain can listen for these events and trigger "brake on" while it is receiving the them. After 1/10sec of not receiving "brake on" signals it triggers an internal "brake_off" event.

Different events will have considerably different timing requirements. In a car, your brake light needs to be much faster than say your check fuel light (where a multisecond delay is probably acceptable) or other less important systems.

Complexity of your physical system will dictate which of these approaches is more appropriate. Given your example is a vehicle, you probably would want something similar to the latter.

Either way, with a physical system, you do NOT want to rely on a single event being received/processed correctly. Connected microcontrollers on a networked system often have a "I'm alive" timeout for this reason.


问:
Indexers in C# for single objects
I was wondering whether it was possible to also use indexers for single objects. So,

```<code>class A<T>
{
public T this[int index]
{
//get, set using index
}
private T _t;
}
</code>```

I was wondering whether the following was possible? (or something that looks like it)

```<code>class A<T>
{
public T this
{
//no indexer? essentially get { return _t; } set ...
}
private T _t;
}
</code>```

Thanks!

答:
You can use implicit conversion operators to do this sort of thing where one type acts like another type.

The only limitation is that you can only have a getter or a setter, not both for a given other type.

Title: Indexers in C# for single objects


答:
As most people have mentioned - Use the existing standard. If it's a new project, use the standard for the language and frameworks you will be using.

And don't get confused, this is not about readability (which is subjective), it's about being consistent and professional. Anyone who has worked in a codebase with numerous 'standards' going on will understand.

Title: Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?

Body:
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far


答:
In this case, I would not model the brake as a simple on/off.  Rather, I would send "brake pressure" events.  For example, a pressure of 0 would indicate off and a pressure of 100 would be fully depressed.  The system (node) would constantly send break pressure events (at a certain interval) to the controller(s) as needed.

When the system was started it would start to recieve pressure events until it was turned off.

Title: How to handle initial state in an event-driven architecture?

Body:
In an event-driven architecture each component only acts when an event is sent through the system.

Imagine a hypothetical car with a brake pedal and a brake light.

The brake light turns on when it receives a brake_on event, and off when it receives a brake_off event.

The brake pedal sends a brake_on event when it is pressed down, and a brake_off event when it is released.

This is all well and good, until you have the situation where the car is turned on with the brake pedal already pressed down. Since the brake light never received a brake_on event, it will stay off - clearly an undesirable situation. Turning the brake light on by default only reverses the situation.

What could be done to resolve this 'initial state problem'?

EDIT: Thank you for all the responses. My question was not about an actual car. In cars they solved this problem by continuously sending the state - therefore there is no startup issue in that domain. In my software domain, that solution would use many unnecessary CPU cycles.

EDIT 2: In addition to @gbjbaanb's answer, I'm going for a system in which:

the hypothetical brake pedal, after initialization, sends an event with its state, and

the hypothetical brake light, after initialization, sends an event requesting a state event from the brake pedal.

With this solution, there are no dependencies between components, no race conditions, no message queues to go stale, and no 'master' components.


问:
Is it acceptable to refactor a collaborator's code?
When working with other people in a project, is it acceptable to refactor some of their code?

I'm working with another developer and I notice a lot of duplicate code. To make things easier for myself, I will locate the duplicate logic or notice a similar pattern that can be used. I will then put the repeated code in a loop, DRYING up the code.

I work with Rails, so DRY is an important principle. I will also make trivial edits on the code. For example, I would change things like

```<code>unless @user.nil?
</code>```

to

```<code>if @user
</code>```

I'm working on the project as well, and I find repeated blocks of code really annoying, so I take the lead to refactor his code. Is this acceptable?

答:
Short answer: No.

Longer answer:  If your refactorings are truly improvements, then you're engaging in Codependent behaviour - you're supporting your collaborator's bad habits & not giving him/her the opportunity to improve.

If your refactorings are trivial, then you're probably wasting your time and/or risking the possibility of falling into an edit loop where you refactor the code to A, they refactor it back to B, then you fix it back to A, and so on.

At the very least, talk to your collaborator at least once about this issue.

Some folks may improve their practices and thus solve the problem.  Others may use you as a safety net, and continue to write sloppy code (or worse, get even sloppier knowing you're backing them up).  A few immature souls may take offense at you changing 'their' code.


答:
Yes, but I recommend changing how to go about doing it.

Rather than refactoring on your own, do a code review. Work on refactoring and cleaning up the code as a group. You clearly know there are better ways to write the code, so share! Maybe your coworker will learn and start writing better code. In the future, maybe you will not need to spend so much time improving his code.

The key here is to mentor your coworker. Most software is built by a team. There is more to a team than simply having each person do his own job in isolation. Collaborate, work together, and help each other to become better developers.

Title: Is it acceptable to refactor a collaborator's code?

Body:
When working with other people in a project, is it acceptable to refactor some of their code?

I'm working with another developer and I notice a lot of duplicate code. To make things easier for myself, I will locate the duplicate logic or notice a similar pattern that can be used. I will then put the repeated code in a loop, DRYING up the code.

I work with Rails, so DRY is an important principle. I will also make trivial edits on the code. For example, I would change things like

```<code>unless @user.nil?
</code>```

to

```<code>if @user
</code>```

I'm working on the project as well, and I find repeated blocks of code really annoying, so I take the lead to refactor his code. Is this acceptable?


问:
What does that mean? SOAP operation represents logic and REST Resources that represent data
I am trying to understand the different between SOAP and REST so one of these differences is. SOAP exposes operation that represents logic and REST exposes Resources that represent data. What does that mean? Can someone clarify that with examples?</p>

答:
SOAP follows the Remote Procedure Call paradigm. REST follows, well the REST paradigm. A better question is difference between SOAP and HTTP (SOAP uses HTTP completely wrong)

In simple terms RPC is when a client makes a call over the network to a server in order to issue a command on the server. So a client might say "Hey server, update stock price to be 10 euro a share" or "Hey server, compute the fibonati sequence"

A problem with RPC is that it couples the client and server quite strongly together. The client must know what calls it can make to the server, and if you update the server you must update the clients as well, even if are just changing the name of a remote procedure.

REST is a different way to thinking about communication between servers that implements strict restrictions that ironically increase flexibility.

With REST the communication between client and server is concerned ONLY with transferring the state of a resource between the client and the server. HTTP protocol is a REST protocol and you will notice there are only a handful of actual commands you can call on the sever (GET, PUT, POST, DELETE etc). You cannot (or should not) ask the server to run any other commands.

In REST a client says "Hey I want to do something with resource X, so give me a copy of it". The client then does what ever it wants to do and then says to server "Hey I'm done with updating that resource, here is it's new state please update yourself"

The advantage of this is that clients and servers have to know very little about each other, they just need to know that both support the REST protocol such as HTTP 1.1, and they have to understand the Content Type of the resources, at least on the client side (sometimes on server side as well if you want server to validate new state before it saves it).


答:
If your only means of passing state information is through events, then you are in trouble.  Instead, you need to be able to both:

query the current state of the brake pedal, and

register for "state changed" events from the brake pedal.

The brake light can be seen as an observer of the brake pedal. In other words, the brake pedal does not know anything about the brake light, and can operate without it. (This means that any notion of the brake pedal proactively sending an "initial state" event to the brake light is ill-conceived.)

Upon instantiation of the system, the brake light registers with the brake pedal to receive braking notifications, and also reads the current state of the brake pedal and turns itself on or off.

Then, the braking notifications can be implemented in one of three ways:

as parameterless "braking pedal state changed" events

as a pair of "braking pedal is now depressed" and "braking pedal is now released" events

as a "new breaking pedal state" event with a "depressed" or "released" parameter.

I prefer the first approach, which means that upon receiving the notification, the brake light will simply do what it already knows how to do: read the current state of the brake pedal and turn itself on or off.


问:
Using Facebook to authenticate, how to link to user record in my app? Email?
I'm using Facebook to authenticate users. We also have conventional username/ password login and registration form too. Anyway, when a user chooses to login with Facebook, we use the following procedure:

Redirect to Facebook, user is authenticated, returneded from Facebook to the app - email, name, facebook ID etc is provided from FB .. but ofcourse, no password

We look in our system for any existing user by the email address. If a user is found, then that is the currently logged in user; otherwise, create a new user with the user info returned from FB.

Email kinda makes sense as we don't want duplicate email addresses (also the database currently won't allow it due to unique index) so if a user has signed up already with that email address, it won't attempt to create a new user for them. Instead it will pull the previously registered user.

Is this the sound approach though? Exploring all possibilities, I was wondering what happens in the event that the user tries to register by our conventional registration form, but as they have already created an account with that email from their initial Facebook login, we wouldn't allow the duplicate email. So having made the decision to use their Facebook to login, they are stuck with that method. Is this a common/ok approach?

Also without intention, if they use the conventional registration form first, and setup their account that way, we have their password, so they could login using our form or login with FB and the user account will just be pulled by email. However, if they choose to login with FB first time, and their account is created that way (we won't obtain the pw), they must always use FB only. I've absolutely no idea whether this could be problematic or not, I kinda want to go with the option of - whatever means you chose to login/register first time round - then that's what you stick with :)

I'm a little new to having users sign up with multiple logins so heads a bit full of "what ifs" etc. Would appreciate any advise on this, and common approaches. Thanks

Alternatively, we loose the index on the email field, add a field somewhere to store the facebook ID, and at the application level decide whether to permit duplicate email address and more distinction between users of different login methods (therefor allowing a user to have a conventionally registered user account, and/or a seperate facebook login auth/created user account, both with the same email address - but different methods of login - least if the user deletes their Facebook account, they can create an account with their email through our register form)

答:
Some sites (e.g.: Asana) employ the same tactic as you do: If you register using a 3rd party and then try registering again using their own login, you will be politely reminded that you are already registered and redirected to the 3rd party login. If you go about it the other way around, you will still be able to log in using your own password.

Other sites (e.g. Wunderlist) will make you create a password even if you register using a 3rd party.

So both approaches exist out there. Which one you use is up to you.

The first approach makes registering more straightforward. The login experience may be different for different users, but it is just as simple for all of them.

The second approach gives your users a uniform experience at login. It also gives them a choice of login, in case they get paranoid about Facebook.


答:
There are many ways to do this, but I prefer to keep a message-based system as decoupled as possible. This means the overall system cannot read the state of any component, nor any component read the state of any other (as that way lies spaghetti ties of dependancies).

So, while the running system will look after itself, we need a way to tell each component to start itself up, and we already have such a thing in the component registration, ie at startup the core system has to inform each component that it is now registered (or will ask each component to return its details so it can be registered). This is the stage at which the component can perform its startup tasks, and can send messages as it would do in normal operation.

So the brake pedal, when the ignition is started, would receive a registration/check message from the car management and it would return not only a "I'm here and working" message, but it would then check its own state and send the messages for that state (eg a pedal depressed message).

The problem then becomes one of startup dependancies, as if the brake light is not yet registered then it will not receive the message, but this is easily resolved by queuing all of these messages until the core system has completed its startup, registration and check routine.

The biggest benefit is that there is no special code required to handle initialisation except that you already have to write (ok, if your message-sending for brake pedal events is in a brake-pedal handler you will have to call that in your initialisation too, but that's usually not a problem unless you've written that code tied heavily to the handler logic) and no interaction between components except those that they already send to each other as normal. Message passing architectures are very good because of this!


问:
How can I ask my boss (in a polite way) to comment his code?
I am being taught by my boss (I just finished school and he wanted someone with a little programming experience, so he chose me to train me on what that company specializes in) and started working with ASP.NET MVC applications, some HTML and CSS. I'm fine with the web design stuff he gives me (it is pretty simple to understand without clarification).

But for instance, he gives me a task to do with ASP.NET MVC, he explains it really well. But he doesn't explain anything in the code he has just given me. (We use source control in Visual Studio 2013), so it's literally hundreds of lines of code, without any background on what it is supposed to do. The kind of code that I'm seeing is code I've never seen before, so it is really difficult to try and figure out.

I would try and ask him more questions, but he is always working (it's his own business), and I feel as though he might get annoyed with all these questions I have on my hands.

So just something that will help my out until I get a grip on things, how can I ask my boss to put comments into his code that he gives me, but politely?

答:
As others have mentioned, this is quite common, but that doesn't mean you just have to suck it up and plow through.  You don't need to understand as much of the code in as much depth as you think you do, and there are concrete strategies for making the "deep end" a lot shallower:

Find something in the code related to the task at hand.  Usually the easiest to search for is something user visible, like the label of the button on the GUI.  Write down where you found it.  This will be your anchor point.

Now search for code one step away and write that down.  Who creates the button?  What code gets called when the button is clicked?

Source control is often useful for finding code that's one step away.  Find when the code you're looking at was added or changed, and look at what else was checked in at the same time, and why.

Repeat until you understand just enough to make your change, plus one level deeper to make sure you aren't missing anything.

If you get stuck at any point, you now have a very specific question to ask.  For example,  "I can't figure out where this button gets instantiated from."


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
It depends.

If I am coding in Javascript or jQuery, I use the first form:

```<code>jQuery(function($) {
    if ($ instanceOf jQuery) {
        alert("$ is the jQuery object!");
    }
});
</code>```

But if I am coding in C#, I use the second form, because that is the canonical way to do it in C#.

```<code>public int CalculateAge(DateTime birthDate, DateTime now)
{
    int age = now.Year - birthDate.Year;
    if (now.Month < birthDate.Month
        || (now.Month == birthDate.Month && now.Day < birthDate.Day))
        age--;
    return age;
}
</code>```

Note that your example can be written

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

in C#.

Body:
It depends.

If I am coding in Javascript or jQuery, I use the first form:

jQuery(function($) {
    if ($ instanceOf jQuery) {
        alert("$ is the jQuery object!");
    }
});

But if I am coding in C#, I use the second form, because that is the canonical way to do it in C#.

public int CalculateAge(DateTime birthDate, DateTime now)
{
    int age = now.Year - birthDate.Year;
    if (now.Month < birthDate.Month
        || (now.Month == birthDate.Month && now.Day < birthDate.Day))
        age--;
    return age;
}

Note that your example can be written

if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();

in C#.


问:
What is a good design pattern for generating an Excel (xlsx) file in code?
See my Update at the bottom for more.

I occasionally have projects where I have to output some data as an Excel file (xlsx format).  The process is usually:

User clicks some buttons in my application

My code runs a DB query and processes the results somehow

My code generates an *.xlsx file using either the Excel com interop libraries or some third-party library (e.g., Aspose.Cells)

I can easily find code examples for how to do this online, but I am looking for a more robust way to do this.  I'd like my code to follow some design principles to ensure that my code is maintainable and easily understandable.

Here is what my initial attempt to generate an xlsx file looked like:

```<code>var wb = new Workbook();
var ws = wb.Worksheets[0];
ws.Cells[0, 0].Value = "Header";
ws.Cells[1, 0].Value = "Row 1";
ws.Cells[2, 0].Value = "Row 2";
ws.Cells[3, 0].Value = "Row 3";
wb.Save(path);
</code>```

Pros: Not much.  It works, so that's good.

Cons:

Cell references are hardcoded, so I have magic numbers littered throughout my code.

It's difficult to add or remove columns and rows without updating many cell references.

I need to learn some third-party library.  Some libraries are used like other libraries, but there can still be problems.  I had a problem where the com interop libraries use 1-based cell referencing whereas Aspose.Cells uses 0-based cell referencing.

Here is one solution that addresses some of the cons I listed above.  I wanted to treat a table of data as its own object that can be moved around and changed without digging into cell manipulation and disturbing other cell references.  Here is some pseudocode:

```<code>var headers = new Block(new string[] { "Col 1", "Col 2", "Col 3" });
var body = new Block(new string[,]
    {
        { "Row 1", "Row 1", "Row 1" },
        { "Row 2", "Row 2", "Row 2" },
        { "Row 3", "Row 3", "Row 3" }
    });

body.PutBelow(headers);
</code>```

As a part of this solution, I'll have some BlockEngine object that takes a container of Blocks and performs the cell manipulations required to output the data as an *.xlsx file.  A Block object can have formatting attached to it.

Pros:

This removes most of the magic numbers that my initial code had.

This hides a lot of cell manipulation code, although cell manipulation is still required in the BlockEngine object that I mentioned.

It's much easier to add and remove rows without effecting other parts of the spreadsheet.

Cons:

It's still difficult to add or remove columns.  If I wanted to swap the position of columns two and three, I'd have to directly swap the cell contents.  In this case that'd be eight edits, and thus eight opportunities to make a mistake.

If I have any formatting in place for those two columns, I have to update that as well.

This solution doesn't support horizontal block placement; I can only place one block below another.  Sure I could have tableRight.PutToRightOf(tableLeft), but that would cause problems if tableRight and tableLeft had different numbers of rows.  To place tables, the engine would have to be aware of every other table.  This seems unnecessarily complicated to me.

I still need to learn third-party code, though through a layer of abstraction via Block objects and a BlockEngine the code will be less tightly-coupled to the third-party library than my initial attempt.  If I wanted to support lots of different formatting options in a loosely-coupled way, I'd probably have to write a lot of code; my BlockEngine would be a huge mess.

Here is a solution that takes a different route.  Here's the process:

I take my report data and generate an xml file in some format that I choose.

I then use an xsl transformation to convert the xml file to an Excel 2003 XML Spreadsheet file.

From there I simply convert the xml Spreadsheet to an xlsx file using a third party library.

I found this page that describes a similar process and includes code examples.

Pros:

This solution requires almost no cell manipulation.  You instead use xsl/xpath to do your manipulations.  In order to swap two columns in a table, you move the whole columns in the xsl file unlike my other solutions which would require cell-swapping.

While you still need a third-party library that can convert an Excel 2003 XML Spreadsheet to an xlsx file, that's about all you'll need the library for.  The amount of code you need to write that would call into the third-party library is tiny.

I think this solution is the easiest to understand and requires the least amount of code.

The code that creates the data in my own xml format will be simple.

The xsl file will be complicated only because the Excel 2003 XML Spreadsheet is complicated.  However it's easy to check the output of the xsl file: just open the output in Excel and check for error messages.

It's easy to generate sample Excel 2003 XML Spreadsheet files: just create a spreadsheet that looks like your desired xlsx file, and then save it as an Excel 2003 XML Spreadsheet.

Cons:

Excel 2003 XML Spreadsheets don't support certain features.  You can't autofit column widths for instance.  You can't include images in headers or footers.  If you're going to export the resultant xlsx file to pdf, you can't set pdf bookmarks.  (I hacked together a fix for this using cell comments.).  You have to do this using your third-party library.

Requires a library that supports Excel 2003 XML Spreadsheets.

Uses an 11-year old MS Office file format.

Note: I realize that xlsx files are actually zip files containing xml files, but the xml formatting seems too complicated for my purposes.

Finally, I've looked into solutions involving SSRS, but it seems too bloated for my purposes.

Back to my initial question, what is a good design-pattern for generating Excel files in code?.  I can think of a few solutions, but none seem to stick out as ideal.  Each has drawbacks.

Update: So I tried both my BlockEngine solution and my XML Spreadsheet solution for generating similar XLSX files.  Here are my opinions of them:

The BlockEngine solution:

This simply requires too much code considering the alternatives.

I found it too easy to overwrite one block with another if I had an offset wrong.

I originally stated that formatting could be attached at the block level.  I found this to be not much better than doing the formatting separately from the block content.  I can't think of a good way to combine the content and the formatting.  Nor can I find a good way to keep them separate.  It's just a mess.

The XML Spreadsheet solution:

I'm going with this solution for now.

It bears repeating that this solution requires much less code.  I'm effectively replacing the BlockEngine with Excel itself.  I still do need a hack for features like bookmarks and page breaks.

The XML Spreadsheet format is finicky, but it's easy to make a small change and compare the results to an existing file in your favorite Diff program.  And once you figure out some idiosyncrasy, you can put it in place and forget about it from there.

I'm still concerned that this solution relies on an older Excel file format.

The XSLT file I created is easy to work with.  Dealing with formatting is much simpler here than it is with the BlockEngine solution.

答:
Here is a solution I have used often in the past:

create a regular Excel document (typically in xlsx format) as as template, containing all column headers, including their title and a default formatting for the columns and maybe formatting for title cells.

embed that template into the resources of your program. At runtime, the first step is to extract the template as a new file and place it into the destination folder

use Interop or a third party library to fill the data into the newly created xlsx. Do not refer to hardcoded column numbers, instead use some metadata (for example the column headers) to identify the correct columns.

Pros:

something like your Block approach now works better. For example, column swapping: no need to change anything in your block code, since the the correct columns are identified by their headers

as long as your columns have a unique formatting, most of the formatting can be done directly in Excel, by manipulating your template. That gives you a WYSIWYG feeling, together with the freedom to use any formatting option available in Excel without the need of writing code for it

Cons:

you still need to make use of a third party lib or Interop. Did I mention that Interop is slow?

when the column headers change in your template, you need to adapt also your code (but that can easily detected by having a validation routine which signals if there are expected columns missing)

when you need dynamic formatting of different cells in the same column, you still have to deal with that in code

As a general hint, whatever approach you choose: it has advantages to separate layout from content and to make use of declarative solutions.


问:
Bridging the gap between abstract machines and computer achitectures?
I always feel disconnected between abstract machines (such as Turing machines) and computer architectures (including virtual machines' architectures, Von Neumann's achitecture).
So I would like to know how they are related? How do one influence the other?
References are also appreciated. Thanks.</p>

答:
Turing machines and similar "machines" are models of computation, they are intended to investigate problems such as:

What can be computed

The complexity class of problems

Relations among complexity classes

The equivalence of various ways to compute something

For that purpose, the machine itself must be as simple as possible. Programmer convenience or pesky implementation concerns do not matter, since these are mathematical objects and only very few programs are ever written directly for them.

Conversely, virtual machine architecture and actual silicon-based machine architecture is centered on executing a given program. The machine is made more complicated than strictly necessary for the above concerns, and in turn it takes fewer (and more obvious) instructions to do interesting things. Not too complicated, as they still have to be comprehensible (and efficiently implementable), but more complicated.

So the two approaches are fundamentally at odds. Besides both being in the field of computer science, they don't have a lot to do with each other.


答:
In an event-driven system (which I currently use and love), I find it important to keep things as decoupled as possible. So with that idea in mind, let's delve right in.

It's important to have some default state. Your brake light would take the default state of 'off' and your brake pedal would take the default state of 'up'. Any changes after that would be an event.

Now to address your question. Imagine your brake pedal being initialized and pressed down, the event fires, but there's no brake lights yet to receive the event. I have found it easiest to separate the creation of the objects (where the event listeners would get initialized) as a separate step before initializing any logic. That will prevent any race conditions as you've described.

I also find it awkward to use two different events for what is effectively the same thing. brake_off and brake_on could be simplified into e_brake with a parameter bool on. You can simplify your events this way by adding supporting data.


答:
The main relationship is that you can simulate the theoretical construct in the physical one.

The fact that the physical one is capable of all things the theoretical one is gives rise to the ability for theoretical testing and analysis of the theoretical machine to be recognized as implementable in the real world.

The halting problem is a perfect example of something that was shown on a turing machine to be unsolvable, and by proof on the turing machine it can thus be known to be unsolvable on a real machine that abides the laws of the turing machine.

It's the difference between summing things by counting and doing it by writing it on paper, it's been proven that the reality of counting fulfills the same rules as doing the summation on a piece of paper. So when you simulate the physical counting of things, your results are recognized as applicable to real world - thus you know how much two candy bars will cost by mentally simulating the counting without needing to count the physical money to come up with the result.

People are currently working out analysis and testing of a theoretical model known as a "Quantum Turing Machine" to see what facilities will be available with quantum computing machines. It makes sense people would work with these models when the physical version of their model is both excessively expensive, rare, and current implementations are still very lacking. The theoretical models are used to show what we may be able to do when our physical implementations improve.

Title: Bridging the gap between abstract machines and computer achitectures?

Body:
I always feel disconnected between abstract machines (such as Turing machines) and computer architectures (including virtual machines' architectures, Von Neumann's achitecture).
So I would like to know how they are related? How do one influence the other?
References are also appreciated. Thanks.</p>


答:
They are related in roughly the same way that the space shuttle is related to a balloon that you inflate with your breath and then let go of and watch fly away.

The fundamental principle of expelling something in one direction to propel something in the opposite direction is there.

That's where the similarities end.


问:
What does "issue or start an instruction" mean?
From Section 2.1.3 RISC vs CISC from Structured Computer Organization by Tanenbaum,

While the initial emphasis was on simple instructions that could be
  executed quickly, it was soon realized that designing instructions that  could be issued (started) quickly was the key to good
  performance. How long an instruction actually took mattered less
  than how many could be started per second.

what does "issue or start an instruction" mean? Does it refer to step 1, 2, 3, 4 and 5 in the fetch-decode-execute cycle?

Does "execute an instruction" mean only step 6 in the fetch-decode-execute cycle ?

Thanks.

Note:

The CPU executes each instruction in a series of small steps. Roughly
  speaking, the steps are as follows:

Fetch the next instruction from memory into the instruction register.

Change the program counter to point to the following instruction.

Determine the type of instruction just fetched.

If the instruction uses a word in memory, determine where it is.

Fetch the word, if needed, into a CPU register.

Execute the instruction.

Go to step 1 to begin executing the following instruction.

This sequence of steps is frequently referred to as the
  fetch-decode-execute cycle.

答:
It probably refers to pipelining, that is, parallel (or semi-parallel) execution of instructions.  That's the only scenario I can think of where it does not really matter how long something takes, as long as you can have enough of them running in parallel.

So, the CPU may fetch one instruction, (step 1 in the table above,) and then as soon as it proceeds to step 2 for that instruction, it can at the same time (in parallel) start with step 1 for the next instruction, and so on.

Let's call our two consecutive instructions A and B.  So, the CPU executes step 1 (fetch) for instruction A.  Now, when the CPU proceeds to step 2 for instruction A, it cannot yet start with step 1 for instruction B, because the program counter has not advanced yet. So, it has to wait until it has reached step 3 for instruction A before it can get started with step 1 for instruction B.  This is the time it takes to start another instruction, and we want to keep this at a minimum, (start instructions as quickly as possible,) so that we can be executing in parallel as many instructions as possible.

CISC architectures have instructions of varying lengths: some instructions are only one byte long, others are two bytes long, and yet others are several bytes long. This does not make it easy to increment the program counter immediately after fetching one instruction, because the instruction has to be decoded to a certain degree in order to figure out many bytes long it is.  On the other hand, one of the primary characteristics of RISC architectures is that all instructions have the same length, so the program counter can be incremented immediately after fetching instruction A, meaning that the fetching of instruction B can begin immediately afterwards.  That's what the author means by starting instructions quickly, and that's what increases the number of instructions that can be executed per second.

In the above table, step 2 says "Change the program counter to point to the following instruction" and step 3 says "Determine the type of instruction just fetched."  These two steps can be in that order only on RISC machines.  On CISC machines, you have to determine the type of instruction just fetched before you can change the program counter, so step 2 has to wait. This means that on CISC machines the next instruction cannot be started as quickly as it can be started on a RISC machine.


问:
Object Oriented Analysis and Design workflow for developer working alone
Studying about OOAD I've found a simple workflow based on five steps. I don't work with a team, so what I'm interested in is a workflow that can be used by a developer working alone. The workflow I found is:

Gather requirements for the application

Describe the application with use cases

Based on the use cases identify the main objects

Identify the relationships between the objects found

Write a class diagram

Now, there are two things about this workflow that makes me a little confused: first it seems oversimplified, and second it seems to deal only with the domain layer, but I'm not sure.

So, my questions are:

Is this workflow ok, or is it oversimplified?

If that's the case, which more information could be added to it in order to make it more clear the way to proceed from the requirements all the way to the class diagram?

Am I right in that this is all about the domain model?

When we do OOAD do we include on the model and on the class diagrams other classes that might be needed to connect the domain model to the technologies? Or on this step we are just concerned with modeling the domain of the application?

答:
This work flow does seem rather simplistic and in some ways unhelpful to me:

It assumes that all requirements of your application can be captured as use cases, but use cases are abstract descriptions of operations that need to be performed on stored data that (a) do not describe user interface and (b) do not describe storage mechanisms. I would, along with the use cases, produce a user interface sketch and a data storage plan, as these will influence the design of your solution too.

I rarely see the benefit in producing a class diagram before code. Class diagrams are useful to describe a system to other people, but when working alone or in small teams that communication tends not to be needed until much later, and the design usually changes enough to render diagrams produced before code obsolete before they're useful. Go straight to code.

Your work flow appears to assume you can analyse and then implement the entire application in a single pass. For anything other than the simplest of applications, this is unrealistic. Design and implement a portion of it, then repeat until finished.


问:
Can Fluent DSL's exist in big data environments?
The way I understand Fluent Domain Specific Languages I am able to use method chaining to have a conversation with the code.  For example, if the business requirement is to call the database in order to "Get all customers with InActive accounts" I could use:

Customers().WithInActiveAccount()

Customers has millions of rows.  Pulling all customers into memory is not efficient when I only need a subset of customers (and maybe not even possible given memory constraints).  I suspect ORM's solve this problem by treating code as data, lazy-loading and building a complete query based off the entire expression.  So the final query may be

SELECT * CUSTOMERS WHERE InActive = true

IME, when dealing with highly normalized tables ORM's produce inefficient DB queries.  Rolling yet another custom ORM to solve such an issue feels like a death march waiting to happen.  And stored procedures written by a DB professional are going to be efficient.

In this simple case I can simply change customers to an object:

Customers.WithInactiveAccount()

What if I need to do something more complex?

Customers.WithInactiveAccount().BornAfter(October 1, 1990)

How do I efficiently build up queries as I build more advanced expressions that potentially draw in other entities?  This is a question I'm sure every ORM asks themselves right in the early stages of development.  Do I have to limit myself to "dumb queries" to maintain performance?  If this a technique that exists?

These are the types of questions I find myself getting from developers like me that have experienced across the board performance problems with ORM's in the big data world.

So when dealing with these types of normalized Databases is a fluent DSL a practical option?  (I'm assuming a fluent DSL for DB access requires an underlying ORM to function)

答:
First, let's clarify terms a little...

The term DSL is enormously wide. SQL, HTML, LOGO, Mathematica, are all DSLs. You are talking about referring\ querying your data model according to its actual structure in a strongly typed manner.

Fluent means method chaining so your source looks more like English and less like a programming language. like so: Noun().Adjective().Verb().Adverb(). This is not the only or even the best way to form queries.

Big-Data usually refers to data that can not be efficiently stored and queried using RDBMS. This means Big-data and "normalized" are mostly mutually exclusive.

Now regarding your question. First of all I'm answering based on my experiance of several years you using C#, F#, some C++, and some Java, NHibernate, MS-SQL, PostgreSQL, and some MongoDB, and some Hadoop, mostly on pretty big data-sets.

"Fluent" is a bad idea. It's usually harder to write, and tends to be misleading to the reader. it's also a lot less "discoverable" you need to learn an entire vocabulary to use and understand a given "fluent" API.

Using an ORM (NHibernate, Hibernate, Entity Framework), is better than manipulating data by yourself. This is not always true, and you should always test, optimize, and understand what your ORM is doing and why. This involves a pretty significant learning curve, you need to understand your ORM, you need to understand how to create a correct mapping, and how to control the way queries are generated. On the other hand if you know what you are doing about ~98% of the time using an ORM is the fastest way to create the best and most performant solutions, with the least effort. ~2% of the time you end up going to the DBA, you write a stored procedure or some SQL, and you use it from within the ORM...

You should have a proper DAL layer, handling data manipulation. Using an ORM doesn't remove the need to build DAL.

Writing queries and manipulating data in your programming language, in a strongly typed way is a great idea. It's fast, verified by the compiler, and very convenient. C# has a special feature called LINQ that enables querying various data sources, these include: C#'s collections, XML, RDBMSes, ODATA sources, many other structured, non structured, real big-data (MongoDB, Cassandra(?), Hadoop), and ORMs such as NHibernate and Entity Framework. Hibernate\NHibernate also have a "Fluent" quarry language called Criteria, and a special non-strongly typed (strings) language called HQL. NHibernate's Linq provider also has some limitations. Usually the strongly typed options are preferable, but still it's very important to understand them thoroughly.

You seem to not "believe" in ORMs... I think this comes from not being familiar, and lacking experience of working with them. I assure you all of the questions you are asking have been considered, and addressed, by some of the best developers in the industry.


问:
When to use controllers in mvc
I am studying mvc5 in asp.net and wondering if there is a general rule when to use a controller. If I have a business object like Employee will I create a controller named Employeecontroller? But why and what is the benefits of having a controller in the first place?

I want to understand when to create a controller and what the benefits is. I have been looking in mvc5 tutorials but they don't say when to create controllers.

答:
A controller is the mediator between the model and the view. Essentially, the controller reads the user input from the view, and updates the model in accordance to the changes.

Without a controller, the view will be too tightly coupled with the data model. If you were to change one small thing in the model, it could completely screw up the view. Whereas if you have a controller, a change to the model does not do anything until you wire it into the controller and view.

The whole point is separation of concerns. You can mentally think of the view as the user interface, the controller as the place where you place business rules etc., and the model as the data you want to interface with. Without such a separation, you will have controller logic in both the view and the model, and the code will become hell to maintain and enhance.

Title: When to use controllers in mvc


答:
The whole point of MVC is decoupling layers from each other.  UI work can be done independent of business rules.  Business rules can be crafted independently of the UI or data access.  And the Model can mine away all the data it wants independently of the Business rules.

Notice that the UI and Model shouldn't ever know of each other.

"Business logic" about the Employee is what should go into EmployeeController.  And when do you create a controller?  When you have business logic to capture about a system object.  Well, what's business logic?  Essentially it's the rules about acting upon Employee or other object that aren't artifacts of the UI or artifacts of the persistence layer.

The advantage of this is that each layer is easier to test as they are providing, in essence, a contract to the other layers.  Another advantage is that multiple UIs can utilize the same controller without requiring a rewrite (or a copy & paste) of the existing controller.

Title: When to use controllers in mvc

Body:
I am studying mvc5 in asp.net and wondering if there is a general rule when to use a controller. If I have a business object like Employee will I create a controller named Employeecontroller? But why and what is the benefits of having a controller in the first place?

I want to understand when to create a controller and what the benefits is. I have been looking in mvc5 tutorials but they don't say when to create controllers.


答:
You use a controller when you have a need to access a resource externally. So if you're building an interface to modify employee information, then you have a need for a controller there.

Just because you have a resource, though, doesn't mean you need a controller for it. Suppose you have a location class/model that refers to addresses. Maybe an employee has many locations but those locations are all manipulated through the employee views. Well in this case, the employee is still the resource being accessed so you don't need a LocationController. You will need a view to represent that model probably, but that would be accomplished with partial views.

Controllers should be used to govern the actions necessary within an application to control access to resources. The trick is really to define: What is a resource and what is simply a supporting class?

Title: When to use controllers in mvc


答: It's really a matter of opinion.  In the standard MVC pattern for web applications, you have one controller per action the user performs, but like many other modern implementations of the pattern, Asp.net MVC allows you to have multiple actions in a single controller class. Grouping them by entity they affect is one option, as is having a class for each action, and I'm sure there are other patterns you could use too. I  suspect the only important thing is to pick a strategy and be consistent about it, otherwise you'll struggle to find your controller implementations.</p>

Title: When to use controllers in mvc


问:
What are subdomains, really?
In studying domain-driven design (DDD), I've come across the concept of subdomain, but I think I don't get it yet. My first understanding of this was that a subdomain is a subset of the domain of the application. In other words, it's a partition of the problem space. I've read that there are three types of subdomain:

core subdomains

supporting subdomains

generic subdomains.

My understanding was somewhat like this: We pick the domain of the application, and it is quite complex. Then we look at it and we figure out a way to partition it into simpler pieces, some of which would be core subdomains and some of which would be supporting, while others would be generic.

In searching for more information, I've found some people saying something different: That just one core subdomain exists, along with some generic subdomains and no supporting subdomain whatsoever.

So my questions are:

What are subdomains, really? Is my first understanding the correct one, or is it the second thing I read?

How is this idea of subdomains useful?

What are some good criteria for identifying subdomains? What should we have in mind when deciding on subdomains in order to make better use of this idea?

EDIT: Searching a little more, I found the following:

Think of an e-Commerce system. Initially you can tell that it is an application of a shopping context. If you look more closely, you will see there are other contexts too, such as Inventory, Delivery, Accounts, etc.

This is what I initially thought a subdomain was. We pick a domain (the shopping domain) and break it down into simpler subdomains (inventory, delivery, accounts, and so on). But in the text in question, they refer to these as contexts. So is my former understanding not subdomains but contexts?

I've found one question here on this site about the difference between a subdomain and a bounded context. The answer states that subdomains are a partition of the problem space, while contexts are partitions of the solution space. Yet, separating the shopping context into inventory, delivery, accounts, etc, is not a conceptual partition. That is, is it in the problem space rather than the solution space?

答:
Disclaimer: I'm not a DDD expert, but I'm going to do my best here to answer your questions.

Let's use an Online Book Retailer as an example. A book seller is offering to sell books on his website, but he doesn't print the books himself. Instead, he has a long list of "Book Suppliers" who print and ship the books to his warehouse, were he packages them and ships them to the customers all around the world.

Could you imagine the teams working in that company?

The listing team: The team that selects which books they should list on the Website, depending on the stock of the suppliers.

The fulfillment team: responsible for collecting the orders from the Website and managing the orders' life cycle.

The commercial team: these are the guys who handle adding or removing suppliers from the system.

The marketing team: responsible for the campaigns and offers.

The warehouse team: responsible for collecting books from the suppliers and shipping them.

Each team will use its own terms to describe what it is doing. Teams will use the domain language or the "Ubiquitous Language", as Eric Evans calls it. Normally, each team will have a different mental model of what an entity is. For example:

```<code>Listing team: BOOK(book_id, ISBN, title, price, weight, length, width )
Fulfillment team: BOOK(book_id, totalPrice, sold_quantity)
Shipping team: ITEM(book_id, delivery_date) --> they refer to the book entity as "item"
</code>```

A sub-domain is one particular part of the domain, in which some users use a certain Ubiquitous Language. When the language changes, this is an indication the you are crossing into another sub-domain.

What if two teams use the same terms? Both the fulfillment and listing teams call book "book". You will have to ask them, "what is a book for you? What are its key attributes? How is it used?"

Answers to these question will result in two different or similar domain models. The greater the difference between the two models, the more indication that these are two different Bounded Contexts/sub-domains. The opposite is also true. The more similar the two models are, the more likely that they should be part of the same sub-domain.

This may result in very interesting findings in your model. You may discover that inside the fulfillment sub-domain, the orders pass through different states (new -> requested -> shipped). Maybe each of these states requires complex management and different attributes, so you may divide this sub-domain into several other sub-domains.

This brings out a question of what the size of the sub-domain(s) should be. The answer is "let the domain model decide that". Whenever you see a change in the UL and model, then draw a boundary for that sub-domain.

Remember that DDD is all about the business, the people and the communication(s) between them. Let that drive your model.

Title: What are subdomains, really?

Body:
Disclaimer: I'm not a DDD expert, but I'm going to do my best here to answer your questions.

Let's use an Online Book Retailer as an example. A book seller is offering to sell books on his website, but he doesn't print the books himself. Instead, he has a long list of "Book Suppliers" who print and ship the books to his warehouse, were he packages them and ships them to the customers all around the world.

Could you imagine the teams working in that company?

The listing team: The team that selects which books they should list on the Website, depending on the stock of the suppliers.

The fulfillment team: responsible for collecting the orders from the Website and managing the orders' life cycle.

The commercial team: these are the guys who handle adding or removing suppliers from the system.

The marketing team: responsible for the campaigns and offers.

The warehouse team: responsible for collecting books from the suppliers and shipping them.

Each team will use its own terms to describe what it is doing. Teams will use the domain language or the "Ubiquitous Language", as Eric Evans calls it. Normally, each team will have a different mental model of what an entity is. For example:

Listing team: BOOK(book_id, ISBN, title, price, weight, length, width )
Fulfillment team: BOOK(book_id, totalPrice, sold_quantity)
Shipping team: ITEM(book_id, delivery_date) --> they refer to the book entity as "item"

A sub-domain is one particular part of the domain, in which some users use a certain Ubiquitous Language. When the language changes, this is an indication the you are crossing into another sub-domain.

What if two teams use the same terms? Both the fulfillment and listing teams call book "book". You will have to ask them, "what is a book for you? What are its key attributes? How is it used?"

Answers to these question will result in two different or similar domain models. The greater the difference between the two models, the more indication that these are two different Bounded Contexts/sub-domains. The opposite is also true. The more similar the two models are, the more likely that they should be part of the same sub-domain.

This may result in very interesting findings in your model. You may discover that inside the fulfillment sub-domain, the orders pass through different states (new -> requested -> shipped). Maybe each of these states requires complex management and different attributes, so you may divide this sub-domain into several other sub-domains.

This brings out a question of what the size of the sub-domain(s) should be. The answer is "let the domain model decide that". Whenever you see a change in the UL and model, then draw a boundary for that sub-domain.

Remember that DDD is all about the business, the people and the communication(s) between them. Let that drive your model.


问:
What to do when time estimation goes wrong?
Let’s say you estimated time for a case to be 3 days.
In day two you notice that the case is growing and new scenarios are popping up which were not counted when the time estimation where done.  The new finding leads to 2 days extra (total 5 days). This is a typical problem that you will face sooner or later as developer.

Which strategy can be used when you are going to notify project leader the new time of delivery?

Often you get the question why? How do you motivate the new time of delivery?

The fact is that many projects don’t put much time on analysis & design during SDLC.

EDIT:
In very complex projects no matter how much reasonable time you put on Analysis & Design there are always surprises since the business rules are too complex. However in such cases I believe the project leader must be aware of the complexity and have right attitude when unexpected surprises comes up. The question is how to tackle project leaders who don’t understand the complexity.

答:
Always keep the relevant stakeholders aware of your progress, including (especially!) the fact that your estimates were overly optimistic. They won't be happy, but they'll know where the project really stands and can plan accordingly.

Ideally your list of features will have been MoSCoWed - Must, Should, Could, Won't.

When you're heading for overrun, cut the Coulds, then the Shoulds. Cut features so you can ship on time: your project usually doesn't live in isolation, and you going past release date means the downstream projects will now also overrun their schedule.

Ideally you'll only have ~60% Musts. If you have to cut those you're in very deep trouble (having a very serious overrun), in which case you'll have to cut corners.

Make sure that you give yourself enough time after release to clean up the mess made by cutting corners!


问:
Enterprise application object oriented modeling for user and role
Generally in the Enterprise Applications like ERP or ERM, CRM, BP etc. we see two things a lot, one of them is Role and the other one is User. What happens is that in the real world we have some persons as the Audiences of the Organization and also we have some roles that each person do his duty as that role. Actually each person has his own information in his file, dependent on the role that he has. Notice that one person can has more than one role.

The question is that How can we model this topic as the OO (Object Oriented) viewpoint?

One way is that we have an Inheritance Hierarchy of Users which each one has his own data and his own behaviors (for example in one clinic we have doctor, patient and Secretary that all of them are derived of the user.) User has list of roles. In this case roles are more likely to Enum and does not have any behavior and the main use of them is Access Control.

The problem of this method is that if a real person wants to have different roles and this issue is completely dynamic, modeling of this wouldn’t be clear.

Second method is that we have one user and an Inheritance Hierarchy   of roles that each role has his own duty. We assign this roles to the users. Actually we see the roles in the program and the main operant for us are the roles.

The problem of this method is that for some roles it is necessary that users have other personal information (for example about the doctor the field of study should be defined.) and it is not clear that where we should store these data.

The third method that is not obvious for us is a combination of the two method above.

答:
Why don't you separate the concepts?

Have one bounded context to handle the user identity. This BC will have all data related to the person itself. This should answer "Who is that user?"

Have another BC to control the roles which each user have. This BC will be responsible for answering "Is this user allowed to do that?"

And a 3rd BC for the operations that you need the entity to do. Now you have 3 models for the same concept, but in different contexts. This may sound really complicated, but each BC has a clear definition of what the entity is (different attributes) and what it can do (its responsibilities)

What is dangerous about your approach is that an entity will have many responsibilities. This violates the Single Responsibility Principle and will go out of hands really fast once the applications grows significantly.


答:
One way is that we have an Inheritance Hierarchy of Users which each one has his own data and his own behaviors (for example in one clinic we have doctor, patient and Secretary that all of them are derived of the user.)

That's IMHO not a good approach. You have persons (IMHO a better term than "users"), and "doctor", "patient", and "secretary" are clearly roles of a person, because a person can be simultanously a doctor, a patient, and / or a secretary.

Second method is that we have one user

I would call it a person ...

and an Inheritance Hierarchy of roles

... yes if your roles are derived from a common "role" class. Now you can have a 1:n relationship between persons and roles.

... The problem of this method is that for some roles it is necessary that users have
  other personal information (for example about the doctor the field of study should be
   defined.) and it is not clear that where we should store these data.

This depends. At a first glance, a "field of study" is a personal qualification. You gain it independently of beeing a Doctor, maybe at a different point in time. So the natural solution seems to be a 1:n relationship between "person" and a qualification object (or a "Field of Study" object, if that is the only form of qualification you ever need to store).

If you really need that information exclusively for doctors, and only as long as the "Doctor" role is assigned to a specific person, then you can assign it to the Doctor object instead, but I would not recommend it. The functional dependency "each doctor needs to have a field of study" can be enforced by the surrounding application, as part of the role assignment process, it is not mandatory to make "Field of Study" an attribute of "Doctor" for that purpose.

EDIT: here is an example class diagram as a rough scetch, probably some details don't match your exact requirements, but I hope you get the general idea:

Title: Enterprise application object oriented modeling for user and role

Body:
Generally in the Enterprise Applications like ERP or ERM, CRM, BP etc. we see two things a lot, one of them is Role and the other one is User. What happens is that in the real world we have some persons as the Audiences of the Organization and also we have some roles that each person do his duty as that role. Actually each person has his own information in his file, dependent on the role that he has. Notice that one person can has more than one role.

The question is that How can we model this topic as the OO (Object Oriented) viewpoint?

One way is that we have an Inheritance Hierarchy of Users which each one has his own data and his own behaviors (for example in one clinic we have doctor, patient and Secretary that all of them are derived of the user.) User has list of roles. In this case roles are more likely to Enum and does not have any behavior and the main use of them is Access Control.

The problem of this method is that if a real person wants to have different roles and this issue is completely dynamic, modeling of this wouldn’t be clear.

Second method is that we have one user and an Inheritance Hierarchy   of roles that each role has his own duty. We assign this roles to the users. Actually we see the roles in the program and the main operant for us are the roles.

The problem of this method is that for some roles it is necessary that users have other personal information (for example about the doctor the field of study should be defined.) and it is not clear that where we should store these data.

The third method that is not obvious for us is a combination of the two method above.