问:
.NET mulithreading and quad core processors
I have a single threaded application that runs on a machine with a quad core processor.  The scheduled tasks that run VB.NET forms are too slow.

I am new to multi threading and parallel computing.  If you have a single threaded application that runs on a server with a multi core processor then does the application only ever use one of the processors?  What happens if you have multiple scheduled tasks and multiple instances are in memory at the same time?

I have read this question on Stackoverflow: https://stackoverflow.com/questions/607775/how-to-write-net-applications-that-utilize-multi-core-processors, but I am still not clear.

答:
"If you have a single threaded application that runs on a server with a multi core processor then does the application only ever use one of the processors?" You don't state how many processors the server has so it could be that there is just one processor but with multiple cores and thus only one processors is getting used as there aren't other processors to use.  The warning here is to beware of the difference between the number of cores and the number of processors as there is something to be said for which perspective are you asking the question.  For example, a single quad-core processor isn't quite the same as 2 dual-core processors and thus I'd advise caution in your word choice as core and processor aren't interchangeable terms for me.

If there are multiple instances in different processes then they should run in different address spaces in memory would be my guess but that is more up to the OS than anything else.

Something to consider here is what kind of forms are you using here:  Winforms or Webforms?  If the latter, even though each page may use a single thread, the application pool used by IIS may have multiple threads and thus the code is executed on multiple cores.  If it is a Winforms application, I don't know the answer.

Introducing Threading may or may not encourage the OS to use other processors, as there is the concept of Concurrent computing which can complicate the question as there can be the appearance of parallel execution.  Thus one could bring in multiple threads but this still gets executed on the same processor possibly.


答:
A process will have one thread, unless you tell it otherwise. Two processes then have two threads total. Each core on a processor can run one thread at a time. So, if you have a processor with 2 cores (or 2 processors with 1 core each):

If you have one process with one thread, it will only ever run on
one of the cores at a time (note that it can switch between cores,
but will never use both at the same time).

If you have two processes with one thread each, they can (but might not) both run at the same time (on different cores and/or different processors).

If you have one process with two threads, both threads can (but might not) run at the same time (on different cores and/or different processors).

ContentLicense: CC BY-SA 3.0

Title: .NET mulithreading and quad core processors

Body:
I have a single threaded application that runs on a machine with a quad core processor.  The scheduled tasks that run VB.NET forms are too slow.

I am new to multi threading and parallel computing.  If you have a single threaded application that runs on a server with a multi core processor then does the application only ever use one of the processors?  What happens if you have multiple scheduled tasks and multiple instances are in memory at the same time?

I have read this question on Stackoverflow: https://stackoverflow.com/questions/607775/how-to-write-net-applications-that-utilize-multi-core-processors, but I am still not clear.


答:
It will depend on server hardware, OS and environment where your code runs.

In another words, it's up to the OS where a thread is scheduled. There are advantages to keeping a thread on the same core if possible, in terms of cache coherency etc. And forcing it to stay on the same core is usually over restrictive.

There are core differences in approach for single threaded and multi-threaded application development that have to be taken into account. For .NET platform developers, here is a really good article that unfolds essentials to be aware of - Multi-threading in .NET: Introduction and suggestions

That post has very important points to enlighten understanding of .NET threading processes.


答:
A single-threaded application can only run on a single core, it well never fully utilize a processor. If you perform concurrent work within that application, for each thread you create, it can be assigned to a different core. Intels current generation of multi-core processors tend to have hyper threading on them as well. So for example a quad core with hyper-threading has 8 virtual cores, (if you view the task manager performance tab, you will see the CPU usage divided into 8 columns). This means that windows will run 8 separate threads at the same time.

The simplest path to making your application multi-thread is to use the Task Parallel Library which is available for .NET 4 and above.


问:
How can I  really master a programming language?
I know that learning a language, you can simply buy a book, follow the examples, and whenever possible try the exercises. But what I'm really looking is how to master the language once you've learned it.

Now I know that experience is one major factor, but what about learning the internals of the language, what is the underlying structure, etc.

There are articles out there saying read this book, read that book, make this game and that game.
But to me this doesn't mean to master a language. I want to be able to read other people's code and understand it, no matter how hard that is. To understand when to use a function and when another, etc etc.

The list could go on and on but I believe I've made the point. :)

And finally, take whatever language as an example if needed, though best would be if C was taken as an example.

答:
Programming languages reflect the ideas behind the programming paradigms that were developed targeting general-purpose software development or for developing special-purpose software. For example, a program language like Java represents the object-oriented program paradigm, but AspectJ (an extension of Java) is used to program according to aspect-oriented programming.

Given this short introduction, in order to really master a language, buying and reading a book by itself wouldn't be much helpful. You'd need to understand the environment in which you can program using the desired language, learn about the paradigm, and more importantly build a meaningful application using the language. Building a small application that can give you a taste of various tools provided by the language is a really helpful learning approach.

I have seen people coming from the pure C community without learning anything about object-orientation and struggle in learning Java or objective-c. I also have seen people struggle with programming user interfaces when they haven't really gone through understanding of user interface elements, event-driven programming, etc...

I hope this helps!


答:
I would add two items to Glen's list

Try to solved hard problem that others have e.g. give answers on SO

Read language designers blogs/book. That's the best resource of deep knowledge. You would know what's the design decision behind reason X.

Title: How can I  really master a programming language?

Body:
I know that learning a language, you can simply buy a book, follow the examples, and whenever possible try the exercises. But what I'm really looking is how to master the language once you've learned it.

Now I know that experience is one major factor, but what about learning the internals of the language, what is the underlying structure, etc.

There are articles out there saying read this book, read that book, make this game and that game.
But to me this doesn't mean to master a language. I want to be able to read other people's code and understand it, no matter how hard that is. To understand when to use a function and when another, etc etc.

The list could go on and on but I believe I've made the point. :)

And finally, take whatever language as an example if needed, though best would be if C was taken as an example.


问:
Copy-and-Pasted Test Code: How Bad is This?
My current job is mostly writing GUI test code for various applications that we work on. However, I find that I tend to copy and paste a lot of code within tests. The reason for this is that the areas I'm testing tend to be similar enough to need repetition but not quite similar enough to encapsulate code into methods or objects. I find that when I try to use classes or methods more extensively, tests become more cumbersome to maintain and sometimes outright difficult to write in the first place.

Instead, I usually copy a big chunk of test code from one section and paste it to another, and make any minor changes I need. I don't use more structured ways of coding, such as using more OO-principles or functions.

Do other coders feel this way when writing test code? Obviously I want to follow DRY and YAGNI principles, but I find that test code (automated test code for GUI testing anyway) can make these principles tough to follow. Or do I just need more coding practice and a better overall system of doing things?

EDIT: The tool I'm using is SilkTest, which is in a proprietary language called 4Test. As well, these tests are mostly for Windows desktop applications, but I also have tested web apps using this setup as well.

答:
One Big Procedure

One thought: It sounds like you are trying to avoid cut-n-paste code by making methods like:

```<code>testScreen(title, fieldList, linkList, param1, param2, param3,...) {
    test that the layout at the top of the screen is correct
    test if PageTitle == title?
    for each field in fieldList:
        check that it appears in order on the screen
    for each field in linkList:
        check that it appears in order on the screen
    test if param1 is whatever...
    test if param2 is whatever...
    etc.
    test that the bottom of the screen is correct
}
</code>```

Many Little Procedures (toolkit)

Have you also considered the opposite approach?  Instead of passing a million parameters to one big testScreen() procedure, maybe make your own framework or tool-kit of little helper procedures that you whip out as you need them.  Like:

```<code>testScreenTop()
verifyLinks(list)
testScreenBottom()
</code>```

You still cut and paste these procedures into every screen, but you are cutting and pasting smaller chunks of code and carving out chunks of commonality that are not cut and pasted (the contents of each little procedures).

Cut and Paste

The only time cut-and-pasted code hasn't bitten me was when the code was thrown away before I had to change it.  My biggest concern with UI tests is how quickly they become obsolete.  If you find you throw all your code away before you change it, then maybe you have found a niche where cutting and pasting is OK!  Also, it's not so bad when there is no code downstream from the cut-and-pasted code (e.g. in the UI of an application).  If you are pasting more than 3 lines, I'd really look into doing something about it.  At least take steps to minimize it!

Automated UI Testing

Heck, if you can prove greater productivity with automated UI testing than manual testing using any technique (the cost of writing/maintaining automated tests is lower than testing manually every time, yet quality is the same) I think you should write a paper.  I would read it!  I can see the title now, "Cut-and-paste Code a Net Win for UI Testing!"

Body:
One Big Procedure

One thought: It sounds like you are trying to avoid cut-n-paste code by making methods like:

testScreen(title, fieldList, linkList, param1, param2, param3,...) {
    test that the layout at the top of the screen is correct
    test if PageTitle == title?
    for each field in fieldList:
        check that it appears in order on the screen
    for each field in linkList:
        check that it appears in order on the screen
    test if param1 is whatever...
    test if param2 is whatever...
    etc.
    test that the bottom of the screen is correct
}

Many Little Procedures (toolkit)

Have you also considered the opposite approach?  Instead of passing a million parameters to one big testScreen() procedure, maybe make your own framework or tool-kit of little helper procedures that you whip out as you need them.  Like:

testScreenTop()
verifyLinks(list)
testScreenBottom()

You still cut and paste these procedures into every screen, but you are cutting and pasting smaller chunks of code and carving out chunks of commonality that are not cut and pasted (the contents of each little procedures).

Cut and Paste

The only time cut-and-pasted code hasn't bitten me was when the code was thrown away before I had to change it.  My biggest concern with UI tests is how quickly they become obsolete.  If you find you throw all your code away before you change it, then maybe you have found a niche where cutting and pasting is OK!  Also, it's not so bad when there is no code downstream from the cut-and-pasted code (e.g. in the UI of an application).  If you are pasting more than 3 lines, I'd really look into doing something about it.  At least take steps to minimize it!

Automated UI Testing

Heck, if you can prove greater productivity with automated UI testing than manual testing using any technique (the cost of writing/maintaining automated tests is lower than testing manually every time, yet quality is the same) I think you should write a paper.  I would read it!  I can see the title now, "Cut-and-paste Code a Net Win for UI Testing!"


问:
What norms/standards should I follow when writing a functional spec?
I would like to know what documents (ISO?) should I follow when I write a functional specification. Or what should designers follow when creating the system design? I was told that there was a progress in last years but was not told what the progress was in (college professor). Thank you

EDIT: I do not speak about document content etc. but about standards for capturing requirements, for business analysis.

答:
I can endorse following the ISO12207 life-cycle model referred to above

Specifically, to answer the question though, the IEEE are the answer with IEEE Std 830-1998 - this is written with 12207 in mind

@Peter is quite dismissive of ISO12207, but for anything safety critical, documentation is paramount... but I accept for many applications it will be OTT.

Update 2012-11-12

Re-reading the question, ISO12207 is the Software Development Life-Cycle process model which covers all phases (as does CMMI)... the question specifically asks about writing a functional specification.

There is, naturally, an ISO standard for that too: ISO/IEC/IEEE 29148:2011 Systems and software engineering -- Life cycle processes -- Requirements engineering, quoting the Abstract:

ISO/IEC/IEEE 29148:2011 contains provisions for the processes and
  products related to the engineering of requirements for systems and
  software products and services throughout the life cycle. It defines
  the construct of a good requirement, provides attributes and
  characteristics of requirements, and discusses the iterative and
  recursive application of requirements processes throughout the life
  cycle.

ISO/IEC/IEEE 29148:2011 provides additional guidance in the
  application of requirements engineering and management processes for
  requirements-related activities in ISO/IEC 12207:2008 and ISO/IEC
  15288:2008.

Information items applicable to the engineering of requirements and
  their content are defined. The content of ISO/IEC/IEEE 29148:2011 can
  be added to the existing set of requirements-related life cycle
  processes defined by ISO/IEC 12207:2008 or ISO/IEC 15288:2008, or can
  be used independently.


问:
Should you document everything or just most?
It seems a bit of a controversial subject to document everything, including the "JavaBean" syntax of getters and setters for fields: People say its needlessly long and repetitive breaking DRY (don't repeat yourself), that the naming convention should explain everything, and it clutters code/documentation. Sometimes those arguments work. But other times, you end up with this:

Above is common to open source projects that do boldly follow those principles. You're left with entirely useless documentation. That doesn't explain anything about what's going on underneath, the possible effects, or even what the expected value is (could it be null or never null? I don't know; the Javadoc doesn't tell me).

So when should I document? Do I document everything even if it occasionally clutters code? Or do I document nothing since in my eyes it's "obvious"?

答:
In simple terms, documentation is there to help the developers now, and the maintainers in the future.

If you remember that simple maxim, then the level of documentation should be self-defining.

Documentation, for the sake of documentation, is a waste of time... but explaining today what you are doing is more helpful than someone having to reverse-engineer your code in five years time.


答:
To build on what @TMN said. I've had great success in learning languages by writing the same program in a different language.

For example writing a program that reads in a CSV file, parses the text and then writes it back to a second CSV with the columns in reverse order.

Like this,

Column1,Column2,Column3

to

Column3,Column2,Column1

This will get you a basic understanding or the language. Then see what else you can do. Maybe allow for value substitution or reordering or reading from the command-line. Make it as complex as you want.

Also I think what @GlenPeterson said about,

Learn a very different language. A great compliment to C would be a functional language like Lisp. This will turn the way you think about your procedural language inside out.

Is a great Idea. I'd suggest a language like Haskell because in the latest versions you can program using all four programming paradigms of OO, procedural, logical or functional. Even though it's actually a functional language you can with some effort implement the other paradigms which would be a good learning experience.

Great language to play around with.


问:
Webservice Return Generic Result Type or Purposed Result Type
I'm building a webservice which returns JSON / XML / SOAP at the moment.. and I'm not entirely sure which approach for returning results is best.

The Client Consuming the Services will generally be Web Applications / Mobile Web Applications. But could be from various WordPress and other social media Plugin type systems.

Which would be a better return value?

A generic "transfer" type structure, which carries Generic properties or a purposed type with distinct properties:

```<code>class GenericTransferObject{
    public string returnVal;
    public string returnType;
}
</code>```

VS

```<code>class PurposedTransferObject_1{
  public string Property1;
}

//and then building additional "types" for additional values
class PurposedTransferObject_2 {
  public string PropertyA;
  public string PropertyB;
}
</code>```

Now, this would be the serialized and returned from a web service call via some client technology, JQuery in this example. SO if I called:

/GetDaysInWeek/

I would either get back:

{"returnType": "DaysInWeek",
"returnVal": "365"
 }

OR

{"DaysInWeek": "365"}

And then it would go from there.

On the one hand there's flexibilty with the 1st example. I can add "returnTypes" without needing to adjust the client other than referencing an additional "index"..

but if I had to add a property, now i'm changing a structure definition..

Is there an obvious choice in this situation?

答:
I would think for the most part you would be better off with the distinct and typed properties in the for-purpose objects for several reasons:

It makes it easier for some clients to consume your entities. For example there are JSON and XML parsers that will automatically create the representations of your objects from existing tools. It puts more of a burden on that side with the more generic non-standard representation (similar to the problem with EAV in SQL databases).

Consuming clients may be less trusting of the implied contract of the API to deliver non-breaking changes with the looser representations and it would be easy to accidentally create breaking changes that are hard to troubleshoot.

It will be more difficult to represent other data value types if everything is a string. You would have to add another property called "returnValuetype" and then it starts getting overly messy as you will have to check that in your parser as well. There are enough problems with date-time representations already.


答:
I'm more of a CMMI fan, but that might be because I've gone through the pain of getting to level 3 -- on what was originally a research project. "If we knew what we were doing we wouldn't call it research." That's a bit counter to the concepts of to any those software quality / process improvement efforts. I've also been with organizations that became ISO 9001 certified.

Both CMMI and ISO can be a bit (more than a bit!) burdensome. Getting certified at CMMI-DEV 3 is costly, in dollars and in time. Quality is not free. (At least that silly management mantra went out the door.) IMO, CMMI level 2 is a reasonable target for most organizations; CMMI 3 is where you start to need to be very sure the product is right. CMMI 4 and beyond: I wouldn't want to work there. The stuff I work on, if done wrong, could lead to hundred of million dollar catastrophes. Research project quality, or even CMMI 2, was not good enough. CMMI 4 was (thankfully) deemed too counterproductive.

Title: What norms/standards should I follow when writing a functional spec?

Body:
I would like to know what documents (ISO?) should I follow when I write a functional specification. Or what should designers follow when creating the system design? I was told that there was a progress in last years but was not told what the progress was in (college professor). Thank you

EDIT: I do not speak about document content etc. but about standards for capturing requirements, for business analysis.


答: It's really not that bad. In fact, if you find certain code patterns are being used very often and the changes are very routine (such as a few strings, or parameter values), you could even write a code generator that generates repetitive test code based on a small(-ish?) input list of values that change. I've done this (generated test code) many times, using batch files, SQLPlus scripts, even Excel macros (it sounds ugly, but the variables for the different test scripts were already in a spreadsheet) and it can be a great time saver. The thing is that if anything changes in the overall structure of the repetitive test case code, you can just regenerate whatever you need.</p>

Title: Copy-and-Pasted Test Code: How Bad is This?

Body:
My current job is mostly writing GUI test code for various applications that we work on. However, I find that I tend to copy and paste a lot of code within tests. The reason for this is that the areas I'm testing tend to be similar enough to need repetition but not quite similar enough to encapsulate code into methods or objects. I find that when I try to use classes or methods more extensively, tests become more cumbersome to maintain and sometimes outright difficult to write in the first place.

Instead, I usually copy a big chunk of test code from one section and paste it to another, and make any minor changes I need. I don't use more structured ways of coding, such as using more OO-principles or functions.

Do other coders feel this way when writing test code? Obviously I want to follow DRY and YAGNI principles, but I find that test code (automated test code for GUI testing anyway) can make these principles tough to follow. Or do I just need more coding practice and a better overall system of doing things?

EDIT: The tool I'm using is SilkTest, which is in a proprietary language called 4Test. As well, these tests are mostly for Windows desktop applications, but I also have tested web apps using this setup as well.


问:
Review before or after code commit, which is better?
Traditionally we performed code review before commit, I had an argument with my colleague today, who preferred code review after commit.

First, here's some background,

We have some experienced developers and we also have new hires with almost zero programming experience.

We'd like to perform fast and short iterations to release our product.

All team members are located at the same site.

The advantages of code review before commit I've learned:

Mentor new hires

Try to prevent errors, failures, bad designs early in the development cycle

Learn from others

Knowledge backup if someone quits

But I've also had some bad experiences:

Low efficiency, some changes may be reviewed over days

Hard to balance speed and quality, especially for newbies

One team member felt distrust

As to post-commit review, I know little about this, but the thing I'm most worried about is the risk of losing control due to lack of review.
Any opinions?

UPDATE:

We're using Perforce for VCS

We code and commit in the same branches (trunk or bug fixing branches)

To improve efficiency, we've tried to split code into small changes. We've also tried some live dialog review, but not everyone followed the rule. This is another problem though.

答:
Reviews benefit from both pre- and post- commits.

Pre-review commit

Gives reviewers confidence they are reviewing the author's latest revision.

Helps ensure everyone reviews the same code.

Gives a reference for comparison once revisions made from review items are complete.

No Running Commits During the Review

I have used Atlassian tools and have seen running commits occur during the review.  This is confusing to reviewers, so I recommend against it.

Post Review Revisions

After reviewers complete their feedback, verbally or in writing, the moderator should ensure the author makes the requested changes.  Sometimes reviewers or the author may disagree as to whether to designate a review item as a fault, suggestion, or an investigation.  To resolve disagreements and ensure investigation items are cleared correctly, the review team depends on moderator judgment.

My experience with around 100 code inspections is that when reviewers can reference an unambiguous coding standard, and for most kinds of logic and other programming faults, review results are generally clear cut.  Occasionally there is a debate about nit-picking or a point of style can degenerate to argument.  However, giving decision power to the moderator avoids stalemate.

Post-Review Commit

Gives the moderator and other reviewers a data point to compare against the pre-review commit.

Provides metrics for to judge both the value and success of the review at defect removal and code improvement.


问:
Where to put business logic in MVC design?
I have created a simple MVC Java application that adds records through data forms to a database.

My app collects data,  it also validates it and stores it. This is because the data is being sourced online from different users. the data is mostly numeric in nature.

Now on the numeric data being stored into database (SQL server), I want my app to perform computations and display the results. The user is not interested in how computations are done so they must be encapsulated. The user must only be able to view the simple computed data (for example, A column data minus B Column data divided by C column data). I know how to write stored procedures for same but I want a three-tier app.

I want the data that I put into the database as a record, worked upon by performing calculations on it. The original data should remain unaffected, while the new data, post-calculations, must be stored as a new entity record into the database.

Where should I write the code for this background calculation? As it is the rules and business logic, should I put it in new JavaBeans files?

答:
The business logic should be placed in the model, and we should be aiming for fat models and skinny controllers.

As a start point, we should start from the controller logic. For example: on update, your controller should direct your code to the method/service that delivers your changes to the model.

In the model, we may easily create helper/service classes where the application business rules or calculations can be validated.

A conceptual summary

The controller is for application logic. The logic which is specific to how your application wants to interact with the "domain of knowledge" it belongs.

The model is for logic that is independent of the application. This logic should be valid in all possible applications of the "domain of knowledge" it belongs.

Thus, it is logical to place all business rules in the model.


答:
For the code review itself, my vote is for 'during' the commit.

A system like gerrit or clover (I think) can stage a change and then have the reviewer commit it to the source control (push in git) if it's good. That's the best of both world.

If that's not practical, I think that after commit is the best compromise. If the design is good then only the most junior developers should have things bad enough you don't want them committed ever. (Make a pre-commit review for them).

Which leads to design review - while you can do it at code review time (or for that matter at customer deployment time), finding design issues should be done earlier than that - before the code is actually written.

Title: Review before or after code commit, which is better?

Body:
Traditionally we performed code review before commit, I had an argument with my colleague today, who preferred code review after commit.

First, here's some background,

We have some experienced developers and we also have new hires with almost zero programming experience.

We'd like to perform fast and short iterations to release our product.

All team members are located at the same site.

The advantages of code review before commit I've learned:

Mentor new hires

Try to prevent errors, failures, bad designs early in the development cycle

Learn from others

Knowledge backup if someone quits

But I've also had some bad experiences:

Low efficiency, some changes may be reviewed over days

Hard to balance speed and quality, especially for newbies

One team member felt distrust

As to post-commit review, I know little about this, but the thing I'm most worried about is the risk of losing control due to lack of review.
Any opinions?

UPDATE:

We're using Perforce for VCS

We code and commit in the same branches (trunk or bug fixing branches)

To improve efficiency, we've tried to split code into small changes. We've also tried some live dialog review, but not everyone followed the rule. This is another problem though.


问:
Confusion related to sigwait in multiprocess system
I am having difficulty in understanding IPC in multiprocess system. I have this system where there are three child processes that send two types of signals to their process group. There are four types of signal handling processes responsible for a particular type of signal.

There is this monitoring process which waits for both the signals and then processes accordingly. When I run this program for a while, the monitoring process doesn't seem to pick up the signal as well as the signal handling process. I could see in the log that the signal is only being generated but not handled at all.

My code is given below

```<code>#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

using namespace std;

double timestamp() {
  struct timeval tp;
  gettimeofday(&tp, NULL);
  return (double)tp.tv_sec + tp.tv_usec / 1000000.;
}

double getinterval() {
  srand(time(NULL));
  int r = rand()%10 + 1;
  double s = (double)r/100;
}

int count;
int count_1;
int count_2;
double time_1[10];
double time_2[10];

pid_t senders[1];
pid_t handlers[4];
pid_t reporter;

void catcher(int sig) {
  printf("Signal catcher called for %d",sig);
}

int main(int argc, char *argv[]) {

  void signal_catcher_int(int);

  pid_t pid,w;
  int status;

  if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) {
    perror("1");
    return 1;
  }

  if(signal(SIGUSR2 ,SIG_IGN) == SIG_ERR) {
    perror("2");
    return 2;
  }

  if(signal(SIGINT,signal_catcher_int) == SIG_ERR) {
    perror("3");
    return 2;
  }

  //Registering the signal handler
  for(int i=0; i<4; i++) {
    if((pid = fork()) == 0) {
      cout << i << endl;
      //struct sigaction sigact;
      sigset_t sigset;
      int sig;
      int result = 0;

      sigemptyset(&sigset);

      if(i%2 == 0) {

        if(signal(SIGUSR2, SIG_IGN) == SIG_ERR) {
          perror("2");
          return 2;
        }

        sigaddset(&sigset, SIGUSR1);
        sigprocmask(SIG_BLOCK, &sigset, NULL);
      } else {
            if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) {
          perror("2");
          return 2;
        }

        sigaddset(&sigset, SIGUSR2);
        sigprocmask(SIG_BLOCK, &sigset, NULL);
      }

      while(true) {
        int result = sigwait(&sigset, &sig);
        if(result == 0) {
          cout << "The caught signal is " << sig << endl;
        }
      }
      exit(0);

    } else {
      cout << "Registerd the handler " << pid << endl;
      handlers[i] = pid;
    }
  }

  //Registering the monitoring process
  if((pid = fork()) == 0) {
    sigset_t sigset;
    int sig;
    int result = 0;

    sigemptyset(&sigset);
    sigaddset(&sigset, SIGUSR1);
    sigaddset(&sigset, SIGUSR2);

    sigprocmask(SIG_BLOCK, &sigset, NULL);

    while(true) {
      int result = sigwait(&sigset, &sig);
      if(result == 0) {
        cout << "The monitored signal is " << sig << endl;
      } else {
        cout << "error" << endl;
      }
    }

  } else {
    reporter = pid;
  }

  sleep(3);
  //Registering the signal generator
  for(int i=0; i<1; i++) {
    if((pid = fork()) == 0) {

      if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) {
        perror("1");
        return 1;
      }

      if(signal(SIGUSR2, SIG_IGN) == SIG_ERR) {
        perror("2");
        return 2;
      }
      srand(time(0));
      while(true) {
        volatile int signal_id = rand()%2 + 1;
        cout << "Generating the signal " << signal_id << endl;
        if(signal_id == 1) {
          killpg(getpgid(getpid()), SIGUSR1);
        } else {
              killpg(getpgid(getpid()), SIGUSR2);
        }
        int r = rand()%10 + 1;
        double s = (double)r/100;
        sleep(s);
      }

      exit(0);
    } else {
      cout << "Registered the sender " << pid << endl;
      senders[i] = pid;

    }

  }

  while(w = wait(&status)) {
    cout << "Wait on PID " << w << endl;
  }

}

void signal_catcher_int(int the_sig) {
  //cout << "Handling the Ctrl C signal " << endl;
  for(int i=0; i<1; i++) {
    kill(senders[i],SIGKILL);
  }

  for(int i=0; i<4; i++) {
    kill(handlers[i],SIGKILL);
  }

  kill(reporter,SIGKILL);

  exit(3);
}
</code>```

Any suggestions?

Here is  a sample of the output as well

In the beginning

```<code>Registerd the handler 9544
Registerd the handler 9545
1
Registerd the handler 9546
Registerd the handler 9547
2
3
0
Registered the sender 9550
Generating the signal 1
The caught signal is 10
The monitored signal is 10
The caught signal is 10
Generating the signal 1
The caught signal is 10
The monitored signal is 10
The caught signal is 10
Generating the signal 1
The caught signal is 10
The monitored signal is 10
The caught signal is 10
Generating the signal 1
The caught signal is 10
The monitored signal is 10
The caught signal is 10
Generating the signal 2
The caught signal is 12
The caught signal is 12
The monitored signal is 12
Generating the signal 2
Generating the signal 2
The caught signal is 12
The caught signal is 12
Generating the signal 1
The caught signal is 12
The monitored signal is 10
The monitored signal is 12
Generating the signal 1
Generating the signal 2
The caught signal is 12
Generating the signal 1
Generating the signal 2
10
The monitored signal is 10
The caught signal is 12
Generating the signal 1
The caught signal is 12
The monitored signal is GenThe caught signal is TheThe caught signal is 10
Generating the signal 2
</code>```

Later on

```<code>The monitored signal is GenThe monitored signal is 10
Generating the signal 1
Generating the signal 2
The caught signal is 10
The caught signal is 10
The caught signal is 10
The caught signal is 12
Generating the signal 1
Generating the signal 2
Generating the signal 1
Generating the signal 1
Generating the signal 2
Generating the signal 2
Generating the signal 2
Generating the signal 2
Generating the signal 2
Generating the signal 1
The caught signal is 12
The caught signal is 10
The caught signal is 10
Generating the signal 2
Generating the signal 1
Generating the signal 1
Generating the signal 2
Generating the signal 1
Generating the signal 2
Generating the signal 2
Generating the signal 2
Generating the signal 1
Generating the signal 2
Generating the signal 1
Generating the signal 2
Generating the signal 2
The caught signal is 10
Generating the signal 2
Generating the signal 1
Generating the signal 1
</code>```

As you can see initially, the signal was generated and handled both by my signal handlers and monitoring processes. But later on the signal was generated a lot, but it was not quite processes in the same magnitude as before. Further I could see very less signal processing by the monitoring process

Can anyone please provide some insights. What's going on?

答:
Are you certain that the monitoring code is not being executed?

In your section above: Later On

```<code>The monitored signal is GenThe monitored signal is 10
</code>```

Appears that the std::out that the monitoring process is being overwritten by your other forked process.  I would suggest that you write your output to separate files, perhaps named with the PIDs and timestamps to fully understand the behavior you are seeing.

The second issue that I could see happening, is that the forked monitoring process has (for some reason) unexpectedly quit.  For this to see what is happening in the OS, I would suggest running top and watching the behavior of your program and its forked processes.

Body:
Are you certain that the monitoring code is not being executed?

In your section above: Later On

The monitored signal is GenThe monitored signal is 10

Appears that the std::out that the monitoring process is being overwritten by your other forked process.  I would suggest that you write your output to separate files, perhaps named with the PIDs and timestamps to fully understand the behavior you are seeing.

The second issue that I could see happening, is that the forked monitoring process has (for some reason) unexpectedly quit.  For this to see what is happening in the OS, I would suggest running top and watching the behavior of your program and its forked processes.


问:
Which VCS is efficient for storing small changes to big text files?
A government agency publishes a text file with thousands of records. The entire file is about 60MB. Every day the file has about 60 new or changed records.

We need to validate some info against that file, and for auditing purposes, we may need to recover the file as it was in certain date.

I thought I could use a VCS to store the file using git, but I understand git stores the entire text file gzipped, so the 60BM file will still need about 30MB to store everyday version.

I wonder if one of the free VCS stores only diff/patch files.

答:
I understand git stores the entire text file gzipped,

That's what happens immediately. But it frequently reorganizes this into sets of changes that are compressed.

I wonder if one of the free VCS stores only diff/patch files.

All of them do. Every single one. Even SCCS from 1972 did, and probably others before it.


问:
What is the right way to group this project into classes?
I originally asked this on SO, where it was closed and recommended that I ask it here instead.  I'm trying to figure out how to group all the functions necessary for my project into classes. The goal of the project is to execute the following process:

Get the user's FTP credentials (username & password).

Check to make sure the credentials establish a valid connection to the FTP server.

Query several Sharepoint lists and join the results of those queries to create a list of items that need to have action taken on them.

Each item in the list has a folder. For each item:

Zip the contents of the folder.

Upload the folder to the FTP server using SFTP

Update the item's Sharepoint data.

Email the user an Excel report showing, e.g.,

Items without folder paths

Items that failed to zip or upload

Steps 2-5 are performed on a periodic basis; if step 2 returns an invalid connection, the user is alerted and the process returns to step 1. If at any point the user presses a certain key, the process terminates.

I've defined the following set of classes, each of which is in its own .cs file:

SFTP: file transfer processes

DataHandler: Sharepoint data retrieval/querying/updating processes. Also makes and uploads the zip files.

Exceptions: Not just one class, this is the .cs file where I have all of my exception classes.

Report: Builds and sends the report.

Program: The main class for running the program.

I recognize that the DataHandler class is a god object, but I don't have a good idea of how to refactor it. I feel like it should be more fine-grained than just breaking it into Sharepoint, Zip, and Upload, but maybe that's it.

Also, I haven't yet worked out how to combine the periodic behavior with the "wait for user input at any point in the process" part; I think that involves threads, which means other classes to manage the threads...

I'm not that well-versed in design patterns, but is there one that fits this project well?

If this is too big of a topic to neatly explain in an SO answer, I'll also accept a link to a good tutorial on what I'm trying to do here.

答: DataHandler, is not following SRP. It is doing several different things. You may be missing a class (or more) that would be responsible for maintaining user credentials(create, update, delete) of a user. Also, you may want to handle Excel reporting separate from Emailing the report (2 classes not 1) since reporting is the process of sending an Excel report, these are 2 different responsibilities.</p>


答:
It is true that Git stores only full revisions of entire files. However, it does not simply store them in the file system as individual files. Instead, it stores them in a pack file.

A pack file is, broadly speaking, every revision of every file of the entire history of the entire repository concatenated into a single file and then compressed. Because of the enormous amount of redundancy this compresses incredibly well, since compressors love redundancy.

This will not only compress different revisions of individual files (since revision n and n+1 will usually be mostly identical), this will even compress identical blocks of content in unrelated files, such as GPL license headers (which is something patch-based storage formats cannot do with the same ease).

In general, a Git repository will end up smaller than a Subversion repository, even though the latter only stores patches.

Title: Which VCS is efficient for storing small changes to big text files?

Body:
A government agency publishes a text file with thousands of records. The entire file is about 60MB. Every day the file has about 60 new or changed records.

We need to validate some info against that file, and for auditing purposes, we may need to recover the file as it was in certain date.

I thought I could use a VCS to store the file using git, but I understand git stores the entire text file gzipped, so the 60BM file will still need about 30MB to store everyday version.

I wonder if one of the free VCS stores only diff/patch files.


问:
Build/deployment tools for a small (1) development effort
What build or deployment tools are available for a 1 person development effort, in the .NET space, that are capable of producing project outputs?

I'm not looking necessarily looking for a CI server (though I can't think of anything else that does what I'm looking for) but I am looking for it to:

produce and publish documentation from xml comments

produce and publish the project (web and/or clickonce app)

handle basic versioning (automatic build number incrementing)

work from a sln file

be easy to setup (< 8-16 hrs for someone who knows little to nothing about the tool(s))

do this at the push of a button (after configuration obviously)

Things I don't need:

source control integration : I can point it to a sln if need be. Not a huge deal.

unit testing : I run test suite before commits

static analysis : again, I also run these before commits

I know that msbuild is capable of most or all of this, and I do have my msbuild book(s) with me, but I'm still very new to it and I don't have the time at the moment to learn it well enough to do what I want.

答:
I don't have a comprehensive answer to all of your points, but I can point you to a software that I found extremely useful. It's called CruiseControl.Net

Google it and check it out :D

ContentLicense: CC BY-SA 2.5


问:
Learning about security and finding exploits
First things first: I have absolutely no interest in learning how to crack systems for personal enrichment, hurting other people or doing anything remotely malicious.

I understand the basis of many exploits (XSS, SQL injection, use after free etc.), though I've never performed any myself. I even have some idea about how to guard web applications from common exploits (like the aforementioned XSS and SQL injection)

Reading this question about the Internet Explorer zero-day vulnerability from the Security SE piqued my curiosity and made me wonder: how did someone even find out about this exploit? What tools did they use? How did they know what to look for?

I'm wary about visiting hacker dens online for fear of getting my own system infected (the Defcon stories make me paranoid). So what's a good, safe place to start learning?

答: If you're really interested in security, take a look at Open Web Application Security Project. It covers a lot of what is happening in the web security world, with lots of resources. I've only scratches the surface of this, but there's lots of good stuff there. </p>


答:
how did someone even find out about this exploit? What tools did they use? How did they know what to look for?

As it was also may come up from your question - it starts with curiosity and interest to learn or hack. In addition there are special interest groups and forums where this individuals are sharing the knowledge.

As a reference, there are few official and informative web resources where you may get abundance of essential and advance security tricks and tips. I have listed some top once below:

csrc.nist.gov

ISF - information security Forum

Security Web Resources

Web Security and Encryption Resources

W3C Security Home

Title: Learning about security and finding exploits

Body:
First things first: I have absolutely no interest in learning how to crack systems for personal enrichment, hurting other people or doing anything remotely malicious.

I understand the basis of many exploits (XSS, SQL injection, use after free etc.), though I've never performed any myself. I even have some idea about how to guard web applications from common exploits (like the aforementioned XSS and SQL injection)

Reading this question about the Internet Explorer zero-day vulnerability from the Security SE piqued my curiosity and made me wonder: how did someone even find out about this exploit? What tools did they use? How did they know what to look for?

I'm wary about visiting hacker dens online for fear of getting my own system infected (the Defcon stories make me paranoid). So what's a good, safe place to start learning?


问:
Branching strategy for parallel development that won't be in the same release?
My team is working on a product, which for business reasons needs to be released on a regular schedule. An issue has arisen where we want to do development in parallel for the upcoming release, as well as the 'next' release. This is to become standard practice, so it's not as straightforward as cutting a feature branch for the new work. We'll continually have 2+ teams working on different releases of the same product.

Is there an SCM best practice for this sort of arrangement?

答:
I believe this post would be of help to you.

From experience, it also helps not to think of version numbers until the actual release build has been made. In other words, don't associate your branch names with version numbers.

The reason you don't want that is that it gives you the flexibility to change the order of release of the versions you're working on. It also means that you don't end up with branches with version numbers in their names ("rel_0_9", "rel_1_0" ).


问:
Good Practices for development team in large projects
Since I started learning C a few years ago, I have never been a part of a team that worked on a project. I am very interested to know what are the best practices for writing large projects in C.

One of the things I want to know, is when (not how) do I split my project into different source files?  My previous experience is with writing a header-source duo (the functions defined in the header are written in the source).

I want to know what are the best practices for splitting a project, and some pointers on important things when writing a project as part of a team?

答:
Important thing to mention is a team spirit, communication and approach to eliminate the technical dept/gap that team members may know/have. Here you are some suggestions that you may consider and follow:

Bring a continual flow of new knowledge in.  Once a week you should have somebody from outside come and speak for an hour on a technical topic.  Provide food, and make an effort to get good speakers.  Bring in people from your sister development organization and from completely outside your company or different project.  When you bring people in, ask them who is doing the most interesting work related to your project or area of expertise.  This process will help build knowledge and skills into your group and will eventually get you connected to the world experts in whatever you are doing.

Have you own team members speak at least once or twice a month.  If you are constantly researching best practices and you are successful, you will eventually be asking for more resources or asking a development team to adopt your work.  The more people you have who can speak articulately about the work, the greater your chance of success.

Have short, frequent meetings whose primary goal is to keep the whole team connected.  When I was running a group of 6 to 8 people building a compiler, we met twice a week for 45 to 90 minutes.  Everybody including me, talked about what have you done since the last meeting, what do you hope to achieve by the next meeting, and what is the next step you will take today (aka, Scrum methodology of daily stand-up meetings). These meetings served three purposes:

Kept everybody on the team aware of the big picture.

Enabled the junior people to learn from the senior people.

Got people unstuck quickly, before they went off the rails.

It's a great privilege to be in a big team, learn good practices from each other and to have some say in setting your own direction!


答:
@Emmad has hit the nail on the head on the note about Single Responsibility.

If you follow a Behaviour Driven approach to class design (ignoring all the unit testing stuff for the moment and thinking more along the lines of the Behaviours which your program needs to support), you might start with entities which represent individual areas of functionality, for example, you may end up with individual classes for each of the following

User Input Handler

User Credentials (simple data object or struct?)

User Credentials Validator

Sharepoint Query

Folder Compressor

Folder Sender

FTP Connection

Sharepoint Updater

Sharepoint Connection

Report (simple data object or struct?)

Report Builder

Report Sender

Email Connection

The reason for using these as a starting point is not necessarily to model exactly what will appear in your final code, but to provide you loose coupling until you have some code in front of you which gives you a better understanding of the problem and how everything fits together.

In general, it is easier to add complexity to a simple class than it is to simplify something which started out complex in the first place;  Similarly, if you end up with a working solution and decide that some of the classes should be merged together, then this is also easier to do than splitting up a single class which had started out doing too much.

(Remember that problems are seldom as trivial as they seem at first, especially not when you start thinking about error flow control, debug logging, disposable resources, etc - something which starts out as "Oh, we can do this with one line of code" might turn out to be a lot more than one line)

Doing this you might also notice patterns in the kinds of method names you're using which may lend themselves to interfaces and abstractions which previously weren't obvious from looking at the original problem.

Title: What is the right way to group this project into classes?

Body:
I originally asked this on SO, where it was closed and recommended that I ask it here instead.  I'm trying to figure out how to group all the functions necessary for my project into classes. The goal of the project is to execute the following process:

Get the user's FTP credentials (username & password).

Check to make sure the credentials establish a valid connection to the FTP server.

Query several Sharepoint lists and join the results of those queries to create a list of items that need to have action taken on them.

Each item in the list has a folder. For each item:

Zip the contents of the folder.

Upload the folder to the FTP server using SFTP

Update the item's Sharepoint data.

Email the user an Excel report showing, e.g.,

Items without folder paths

Items that failed to zip or upload

Steps 2-5 are performed on a periodic basis; if step 2 returns an invalid connection, the user is alerted and the process returns to step 1. If at any point the user presses a certain key, the process terminates.

I've defined the following set of classes, each of which is in its own .cs file:

SFTP: file transfer processes

DataHandler: Sharepoint data retrieval/querying/updating processes. Also makes and uploads the zip files.

Exceptions: Not just one class, this is the .cs file where I have all of my exception classes.

Report: Builds and sends the report.

Program: The main class for running the program.

I recognize that the DataHandler class is a god object, but I don't have a good idea of how to refactor it. I feel like it should be more fine-grained than just breaking it into Sharepoint, Zip, and Upload, but maybe that's it.

Also, I haven't yet worked out how to combine the periodic behavior with the "wait for user input at any point in the process" part; I think that involves threads, which means other classes to manage the threads...

I'm not that well-versed in design patterns, but is there one that fits this project well?

If this is too big of a topic to neatly explain in an SO answer, I'll also accept a link to a good tutorial on what I'm trying to do here.


答:
First and foremost, get familiar with C and assembly! It can't be stressed over too much how important these are, because they build the whole foundation on which our vulnerable software runs.

There are a few resources I can recommend from personal experience. First the theory: Hacking: The Art of Exploitation which is good especially accompanied with Reversing: Secrets of Reverse Engineering which is not so much about vulnerabilities and exploits, but much more about reverse engineering software in general to learn how it works, which is a central part in vulnerability assessment.

Then there are things like IO wargame in the SmashTheStack wargame network. It should be pretty easy to figure how to get started with it, although some knowledge of Unix is required(namely how to connect via SSH, what setuid executables are, what is the purpose of privilege escalation and so on). In essence the idea is to login at levelN(where N is the current level number), find a vulnerability in an setuid executable and exploit it to gain the privileges to read the password file for the password for the level(N+1) login. And yes, you get to write your own shellcode to exploit buffer overflow and format string vulnerabilities from scratch, as well as do some cryptanalysis and reverse engineering too. Note that the SmashTheStack wargame network has other wargames too apart from IO one, but I have no experience with them and as such can't vouch much for them.


问:
If immutable objects are good, why do people keep creating mutable objects?
If immutable objects¹ are good, simple and offer benefits in concurrent programming why do programmers keep creating mutable objects²?

I have four years of experience in Java programming and as I see it, the first thing people do after creating a class is generate getters and setters in the IDE (thus making it mutable). Is there a lack of awareness or can we get away with using mutable objects in most scenarios?

¹ Immutable object is an object whose state cannot be modified after it is created.

² Mutable object is an object which can be modified after it is created.

答:
In Java immutable objects require a constructor that will take all the properties of the object (or the constructor creates them from other arguments or defaults). Those properties should be marked final.

There are four problems with this mostly having to do with data binding:

Java Constructors reflection meta-data does not retain the argument names.

Java Constructors (and methods) do not have named parameters (also called labels) thus it gets confusing with many parameters.

When inheriting another immutable object proper order of constructors must be called. This can be rather tricky to the point of just giving up and leaving one of the fields non-final.

Most binding technologies (like Spring MVC Data Binding, Hibernate, etc...) will only work with no-arg default constructors (this was because annotations did not always exist).

You can mitigate #1 and #2 using annotations like @ConstructorProperties and creating another mutable builder object (usually fluent) to create the immutable object.


答:
Check out Sandcastle and Sandcastle Help File Builder for compiling your XML docs. It works pretty well, but the documentation isn't so hot.

http://sandcastle.codeplex.com/

http://shfb.codeplex.com/

Title: Build/deployment tools for a small (1) development effort

Body:
What build or deployment tools are available for a 1 person development effort, in the .NET space, that are capable of producing project outputs?

I'm not looking necessarily looking for a CI server (though I can't think of anything else that does what I'm looking for) but I am looking for it to:

produce and publish documentation from xml comments

produce and publish the project (web and/or clickonce app)

handle basic versioning (automatic build number incrementing)

work from a sln file

be easy to setup (< 8-16 hrs for someone who knows little to nothing about the tool(s))

do this at the push of a button (after configuration obviously)

Things I don't need:

source control integration : I can point it to a sln if need be. Not a huge deal.

unit testing : I run test suite before commits

static analysis : again, I also run these before commits

I know that msbuild is capable of most or all of this, and I do have my msbuild book(s) with me, but I'm still very new to it and I don't have the time at the moment to learn it well enough to do what I want.


答:
As always, it depends on the complexity of the project.

In trivial applications, where the domain model complexity is relatively small, you can put the logic in the models and call it a day.

However, for non trivial applications with complex models and lots of business rules, it's better to separate things a little bit more.

If you put the business logic that involves more than one model in a model, you are introducing a tight coupling between those models. As applications continues to grow, these models tends to turn into god models, knowing too much. And this will quickly turns into a big mess that is hard to test and maintain. So in that case, it is beneficial to put the logic in a separate layer.

When deciding about abstraction, always take your app complexity and purposes into account, and avoid over-engineering. For trivial/small applications, introducing more layers than it needs increases complexity instead of reducing it.

Robert Martin(Uncle Bob) has a good blog post on this subject: The Clean Architecture.

Title: Where to put business logic in MVC design?

Body:
I have created a simple MVC Java application that adds records through data forms to a database.

My app collects data,  it also validates it and stores it. This is because the data is being sourced online from different users. the data is mostly numeric in nature.

Now on the numeric data being stored into database (SQL server), I want my app to perform computations and display the results. The user is not interested in how computations are done so they must be encapsulated. The user must only be able to view the simple computed data (for example, A column data minus B Column data divided by C column data). I know how to write stored procedures for same but I want a three-tier app.

I want the data that I put into the database as a record, worked upon by performing calculations on it. The original data should remain unaffected, while the new data, post-calculations, must be stored as a new entity record into the database.

Where should I write the code for this background calculation? As it is the rules and business logic, should I put it in new JavaBeans files?


问:
How to handle "porting" software that's still in development
My company is building an iOS version of an Android app that our client is developing (but has not yet released). We have access to the latest builds and source, however since the software is frequently re-structured and refactored, we're doing a lot of unnecessary re-work. In addition, the due date on the contract will likely be passed before the client's application is even ready for release. In other words, we're supposed to build the iOS version before the original Android version is even complete. Luckily the client tossed out the original deadline, but now we may have to renegotiate pricing... never a fun situation.

Are we handling this incorrectly? How are "ports" (especially between mobile platforms) normally done? Is there a correct way to pipeline development for multiple platforms without so much re-work?

Thanks in advance! :)

答:
If your only source of information for the application is it's unfinished android source, there is no way to escape this mess other than waiting for it's finish.

A good way is this case is having a requirements file etc. that describes the work. For contract work, if what needs to be done is unclear, you WILL encounter lots of problems regarding the delivery date and pricing.

Talk with the client, and formalize what needs to be done before you do more work. Use acceptance tests/use cases/requirements file/user stories/whatever to document what needs to be delivered and work on that. This way, you will know what you are responsible for(instead of an ever changing requirements when the android version changes) and you can talk in even terms with the client.


问:
What is the correct order to read these books?
I'm a junior C# developer, I learned at home and now I got my first job :)

I want to buy these books. But what is the correct order to read these books?

Code Complete: A Practical Handbook of Software Construction

Clean Code: A Handbook of Agile Software Craftsmanship

Pragmatic Programmer

答:
These books have high merit.

Often times developers enter into the work knowing mostly what without much detail about why.  The three books you picked offer a lot to improve what you do as a programmer, and are good at providing descriptions to back up their prescriptions.

Reading these books will open you to a lot of ideas you might have never imagined.  Later, as you gain experience, you will get even more out of these books, relating what you have seen to what they describe.

Together, these books total over 1500 pages.  That's a lot of reading, and you are right to prioritize and map out a sequence.  I suggest you download the table of contents for all three and score the chapters in each by what you most need now for your job.  You could compare and contrast their advice on variable and class naming, but I think if your read about naming once, it would be enough.  Similarly, if your team or manager have guidelines, follow them.

Perhaps you can borrow these from a friend or library before buying them.  Or maybe even spending a few hours at your local bookstore.  If you time box your reading, threading through all three based on your priorities, taking notes on a blank piece of paper, you will find vocabulary and concepts you can apply at work today.

Pragmatic is a great description of the learning approach you want when using these books.  There is a lot of overlap between the three, and I think much has been revisited in web accessible sources.  There are many things you may find you need that are either not in these books, or are barely touched upon.  Consider adding more topics that go beyond the scope of these books:

Programming language tutorials.

Your organizations specific source control and build tools.

Concepts and implementations of data structures in C#.

Standard C# class libraries.

Coding standards specific to your organization.

Testing, probably with MS Test tools.

UI / UX design guidelines for your platforms.

Applicable design patterns which for C#, I would expect MVVM to be the most critical.

Another consideration I think might help is to consider the publication date, context, and goals of each book.  Oldest to newest: Pragmatic 1999, Code Complete 2nd Ed. 2004, Clean Code 2008.  Context: Pragmatic lists C, C++, Java in its index but not C#.  Code complete is Microsoft Press, written by an ex-Microsoft guy, and because you are working with a Microsoft language, there might be some affinity there, but the index has one entry for C# and it gets less love than Fortran on page 64.

The Robert Martin book is more steeped in the Agile approach than the other two, is the newest, and has some pretty great descriptions of naming, class design, and probably a lot more help with concurrency than the others.  It may be a little unfair, but the later books can talk about more stuff and newer stuff, and their context is generally more like what we do today.

Each of these books to some extent competes in a similar range of topics.  Kind of makes you want to ask, "What newer, broadly scoped programming books are competing in the same space?"


答:
A 1-dev project could do all this within Visual Studio, since it has builtin tools to do all of this.  If you want script it though, then the tools you want to look at are:

produce and publish documentation from xml comments produce and publish

Sandcastle: http://broadcast.oreilly.com/2010/09/build-html-documentation-for-y.html, http://sandcastle.codeplex.com/

the project (web and/or clickonce app)

http://codingcockerel.co.uk/2008/05/18/how-to-publish-a-web-site-with-msbuild/, or calling the Publish target on the solution

handle basic versioning (automatic build number incrementing)

AssemblyInfo task from http://msbuildtasks.tigris.org.  This won't automatically increment the version because that would mean tracking the version number each time.  You can have something like CruiseControl.NET pass one in, or you can generate one based on the date and time using the Time task (as an example).

work from a sln file

MSBuild will use a .sln as a project file.  If you want to wrap your .sln with another MSBuild script, you can use the MSBuild task


问:
OS choice for functional developing
I'm mainly a .NET developer so I normaly use Windows/VisualStudio (that means: I'm spoiled) but I'm enjoying Haskell and other (mostly functional) languagues in my spare time.

Now for Haskell the windows-support is ok (you can get the Haskell-Platform) but latley I tried to get a basic Clojure/Scheme environment set up and it's just a pain on windows.

So I'm thinking about trying out another OS for better tooling and languague support.
Of course that leaves me with MacOS or some Linux distribution.

I never used MacOS before and of course Linux would be cheaper (free) and I don't think I can parallel-boot MacOS on your normal PC-Hardware (can you?).
PLUS: I don't have a clue about the tools you can use on those (to me) forign OSs.

To make it short: I want to explore more Haskell, Clojure, Scala, Scheme and of course need at least good tooling for JavaScript/HTML5/Css.
Support for .NET/Mono/F# would be great but for this I will still have my Win7 boot.

So I like to know:
 - what is your prefered OS, Distribution (is Ubuntu viable?)
 - what Editor/IDE are you using

Thank you for your help!

PS: I'm not sure if this is the right place for this question but I surely hope so - if not please let me know where I should move this to (StackOverflow don't seem to be the right place IMHO)

答: MacOS requires Mac hardware or you might get it to run on VirtualBox, but last time I tried that it didn't work. And since you don't want to replace your current configuration/setup problems with other problems, I suggest you either spend a lot of money or try linux. I've used Ubuntu for Haskell, Scala and Lisp development with Eclipse, Netbeans, IntelliJ and Emacs, and I haven't had much trouble setting those up.</p>

Title: OS choice for functional developing


答: While I am a big mac and linux fan there is no reason you can't do any of those languages on windows. Also if you want a functional language on windows don't overlook F# which is a .net language</p>

Title: OS choice for functional developing

Body:
I'm mainly a .NET developer so I normaly use Windows/VisualStudio (that means: I'm spoiled) but I'm enjoying Haskell and other (mostly functional) languagues in my spare time.

Now for Haskell the windows-support is ok (you can get the Haskell-Platform) but latley I tried to get a basic Clojure/Scheme environment set up and it's just a pain on windows.

So I'm thinking about trying out another OS for better tooling and languague support.
Of course that leaves me with MacOS or some Linux distribution.

I never used MacOS before and of course Linux would be cheaper (free) and I don't think I can parallel-boot MacOS on your normal PC-Hardware (can you?).
PLUS: I don't have a clue about the tools you can use on those (to me) forign OSs.

To make it short: I want to explore more Haskell, Clojure, Scala, Scheme and of course need at least good tooling for JavaScript/HTML5/Css.
Support for .NET/Mono/F# would be great but for this I will still have my Win7 boot.

So I like to know:
 - what is your prefered OS, Distribution (is Ubuntu viable?)
 - what Editor/IDE are you using

Thank you for your help!

PS: I'm not sure if this is the right place for this question but I surely hope so - if not please let me know where I should move this to (StackOverflow don't seem to be the right place IMHO)


问:
Is online freelance work viable by American standards?
I've always been curious about trying out online freelance sites... it would be nice to work from home, feel independent, get to choose what I want to work on, get to work on different technologies, lose the PHB, etc.

However I never really gave them a chance because I'm used to American rates and assumed that I would be competing with people from India, Russia, China, etc. that would severely undercut me, and it wouldn't be viable for me.

Am I correct in this assumption or should I give it a shot?  What kind of hourly rate would I be able to expect on short-term programming work?

答:
My recent experience with Elance in particular, seems to suggest that there are a lot of developers based in Asia who are prepared to undercut western developers to get the work, but they all seem to target the popular technologies, such as PHP and C# development. As soon as you move into less popular technologies you start to find fewer people bidding, and those that do are prepared to pay much more.

A friend has used Elance a number of times to find work. One job was testing applications to ensure they were suitable for use by children, and she was being paid more for this than she earns in her day job.

I have posted a few jobs on Elance expecting to be flooded with cheap offers of $5 an hour, but received no such thing. These were jobs involving web design and an iPhone application involving voice communications. In the first case I received offers far higher than I was prepared to pay, and in the second I received no bids at all.

In both cases I would have been happy to except a reasonable offer from a quality developer rather than the cheapest offer, but in both cases I simply was not receiving these.

I think you can make money freelancing on Elance, you just need to specialise on a less popular field so that you are not competing directly with the Asian developers.


答:
I use Haskell and Scala (and also doing some Scheme, Common Lisp, SML, OCaml, Erlang) all under Linux (Ubuntu).

All of the above languages (compilers and interpreters) can be installed quite easily (there are packages that can be installed using apt-get or another package management system).

Scala has a good integration with Eclipse and the Scala plugin(s) are actively developed.
If you want to learn more, there is a course on Scala currently running at Coursera which explains how to use Scala on Windows, Linux, and Mac.
Maybe you do not have all the features and integration of Visual Studio, but I have developed quite large projects in Eclipse and it works just fine.

For editing Haskell (and the other languages listed above) I use gvim which is OK for small projects. You can use another editor (e.g. EMACS), provided it has syntax highlighting for Haskell. Otherwise, you can take a look at haskellwiki (thanks to Zach L for the suggestion).

For managing the source code (versioning) I use SVN through Eclipse for all these languages.

Title: OS choice for functional developing


问:
Event sourcing and persistence
I'm reading up on event sourcing and have a question regarding persistence.

I can still have a DB with all entities, right? Or should the events be replayed every time the application is started to get the latest version of each entity in the memory? Seems like a waste on larger systems (as in large amount of data)?

The point with event sourcing is that I can can replay the events to populate a data store if required? (or analyze the data)

答:
With Event Sourcing the main question is "what is your book of record".

If your book of record is your event stream then you will have no problems. If your book of record is your "entity model" then problems will start happening all over the place. Part of this is that you can say "if I lost my entity model could I rebuild it from my event stream". If you are in the positive on this question then your Event Log is your book of record.

Its also important to remember that most people that use event sourcing use a read model. This model is used for querying data. This is more likely to look something like a 1nf model than a 3nf entity model though. They only replay events to get back the states of aggregates to determine if writes should be allowed.

Title: Event sourcing and persistence


答:
The route I'm currently taking for experimenting with such languages and other things, with great success and ease of use:

install Debian under a VirtualBox VM, running on Windows host

keep all my code on the host or on a shared network drive, edit on the host using favourite editor (still undecided between Notepad++ and SublimeText; for C++ I just use VS)

share the directory on the host, mount it in VM

compile/run the code in the VM (or you could even ssh to it using cygwin)

This way you get the pros of both operating systems.

Title: OS choice for functional developing


答:
All of the Unix-like OSes have very good command line tooling. I've personally had good experiences with Ubuntu for both development and deployment, many of my friends also swear by MacOS. I've not seen an obvious reason to prefer one or the other, they are all IMO better than Windows for command line work.

On the Clojure/Scala side specifically, you may find Windows is actually pretty good if you use one of the Java IDEs with the appropriate Clojure/Java plugin. I personally use Eclipse with Counterclockwise as my main Clojure development environment in Windows 7. There's also Scala IDE to check out. This is a good approach if you like full-featured IDEs and/or want to do polyglot programming in the same environment. An extra plus of using something like Eclipse is that the git/svn/maven integration is very good.

Title: OS choice for functional developing


问:
What role does .ini play?
I am working with a MFC application for the first time and I have lots of doubts the biggest at the moment is What is .ini file and why is it there? What exactly is the role it plays? Can some tell me the required?

Edit : What if I make an application and do not have .ini file, what do I loose on?

答: INI files are an old way of storing application configuration, particularly in Windows 3.x, such as WIN.INI, and Windows 9x, and SYSTEM.INI. Windows NT used BOOT.INI as part of its boot process. Later applications used registry keys and more recent .Net applications store settings in app.config XML files.</p>

Title: What role does .ini play?


答:
Putting the business logic inside the model might sound the best way to go. The controller receives a call from the remote web app. The controller on the MVC web service takes the call and redirects the execution to a method in BL. Now, Business Logic can be contained in the 'Model', but can also be positioned in some other folder, say, 'Business Logic'. So there's no hard-and-fast rule on where the business logic is going to be.

I've been using a web service built on MVC 3.0 and the container of business logic is the MVC MODEL.


问:
C# Open Source software that is useful for learning Design Patterns
In college I took a class in Expert Systems.  The language the book taught (CLIPS) was esoteric - Expert Systems: Principles and Programming, Fourth Edition.  I remember having a tough time with it.  So, after almost failing the class, I needed to create the most awesome Expert System for my final presentation.  I chose to create an expert system that would calculate risk analysis for a person's retirement portfolio.  In short, the system would provide the services normally performed by one's financial adviser. In other words, based on personality, age, state of the macro economy, and other factors, should one's portfolio be conservative, moderate, or aggressive?

In the appendix of the book (or on the CD-ROM), there was this in-depth example program for something unrelated to my presentation.  Over my break, I read and re-read every line of that program until I understood it to the letter.  Even though it was unrelated, I learned more than I ever could by reading all of the chapters.  My presentation turned out to be pretty damn good and I received praises from my professor and classmates.

So, the moral of the story is..., by understanding other people's code, you can gain greater insight into a language/paradigm than by reading canonical examples.  Still, to this day, I am having trouble with everyday design patterns such as the Factory Pattern.  I would like to know if anyone could recommend open source software that would help me understand the Gang of Four design patterns, at the very least.  I have read the books, but I'm having trouble writing code for the concepts in the real world.  Perhaps, by studying code used in today's real world applications, it might just "click".

I realize a piece of software may only implement one kind of design pattern.  But, if the pattern is an implementation you think is good for learning, and you know what pattern to look for within the source, I'm hoping you can tell me about it.

For example, the System.Linq.Expressions namespace has a good example of the Visitor Pattern.  The client calls Expression.Accept(new ExpressionVisitor()), which calls ExpressionVisitor (VisitExtension), which calls back to Expression (VisitChildren), which then calls Expression (Accept) again - wooah, kinda convoluted.  The point to note here is that VisitChildren is a virtual method.  Both Expression and those classes derived from Expression can implement the VisitChildren method any way they want.  This means that one type of Expression can run code that is completely different from another type of derived Expression, even though the ExpressionVisitor class is the same in the Accept method.  (As a side note Expression.Accept is also virtual).  In the end, the code provides a real world example that you won't get in any book because it's kinda confusing.

To summarize, If you know of any open source software that uses a design pattern implementation you were impressed by, please list it here.  I'm sure it will help many others besides just me.

```<code>public class VisitorPatternTest
{

    public void Main()
    {
        Expression normalExpr = new Expression();
        normalExpr.Accept(new ExpressionVisitor());
        Expression binExpr = new BinaryExpression();
        binExpr.Accept(new ExpressionVisitor());
    }
}

public class Expression
{
    protected internal virtual Expression Accept(ExpressionVisitor visitor)
    {
        return visitor.VisitExtension(this);
    }

    protected internal virtual Expression VisitChildren(ExpressionVisitor visitor)
    {
        if (!this.CanReduce)
        {
            throw Error.MustBeReducible();
        }
        return visitor.Visit(this.ReduceAndCheck());
    }

    public virtual Expression Visit(Expression node)
    {
        if (node != null)
        {
            return node.Accept(this);
        }
        return null;
    }

    public Expression ReduceAndCheck()
    {
        if (!this.CanReduce)
        {
            throw Error.MustBeReducible();
        }
        Expression expression = this.Reduce();
        if ((expression == null) || (expression == this))
        {
            throw Error.MustReduceToDifferent();
        }
        if (!TypeUtils.AreReferenceAssignable(this.Type, expression.Type))
        {
            throw Error.ReducedNotCompatible();
        }
        return expression;
    }

}

public class BinaryExpression : Expression
{
    protected internal override Expression Accept(ExpressionVisitor visitor)
    {
        return visitor.VisitBinary(this);
    }

    protected internal override Expression VisitChildren(ExpressionVisitor visitor)
    {
        return CreateDummyExpression();
    }

    protected internal Expression CreateDummyExpression()
    {
        Expression dummy = new Expression();
        return dummy;
    }
}

public class ExpressionVisitor
{
    public virtual Expression Visit(Expression node)
    {
        if (node != null)
        {
            return node.Accept(this);
        }
        return null;
    }

    protected internal virtual Expression VisitExtension(Expression node)
    {
        return node.VisitChildren(this);
    }

    protected internal virtual Expression VisitBinary(BinaryExpression node)
    {
        return ValidateBinary(node, node.Update(this.Visit(node.Left), this.VisitAndConvert<LambdaExpression>(node.Conversion, "VisitBinary"), this.Visit(node.Right)));
    }
}
</code>```

答:
It looks like you would like to understand the design patterns in a practical sense with examples. I suppose a good book with real-life examples will help you.

In addition, it looks like there are some tight coupling in the code. I would look at SOLID design principles (like single responsibility principle) to design my code to loosely coupled and interchangeable/replaceable pieces.

As a suggestion, you may start with a highly recommended book of design patterns, Head First Design patterns is really good book to consider. I love this book.


问:
What is better for coding - desktop or laptop?
Use of desktops are decreasing day by day in daily life but for coding purpose are there any reasons for using desktop over laptop? </p>

答:
Very much depends on what you code, how you code and the tools you use/need.

My development projects...

Are graphics intensive (2D and 3D).

Are compute intensive.

Require multiple IDEs and usually
more than one instance each.

Include large volumes of reference
material...usually PDFs.

May target custom hardware.

May require CAD/CAM/CAE
tools.

May drive me to drink.

So, for me a desktop with several large monitors is more of a requirement than a choice.

I would also suggest that working from a loaded desktop with multiple 24" monitors is going to be the more productive choice regardless. Having your GUI designer, code editor and browser on separate monitors saves a lot of clicks and trips to the task bar remember: "Clicks take time and time is money"...is not just something your grandfather used to say...it adds up...plus...Coding, reading stackoverflow (aka: geekporn) and watching [some geek movie] all at the same time doesn't really suck.

Of course, at the end of the day desktop it is what works desktop best for you. desktop


问:
Single statement if block - braces or no?
Which is better/more generally accepted?

This:

```<code>if(condition)
{
  statement;
}
</code>```

Or:

```<code>if(condition)
  statement;
</code>```

I tend to prefer the first one, because I think it makes it easier to tell what actually belongs in the if block, it saves others from adding the braces later (or creating a bug by forgetting to), and it makes all your if statements uniform instead of some with braces and some without.  The second one, however, is still syntactically correct and definitely more compact.  I'm curious to see which is more generally preferred by others though.

答:
I prefer the version without braces where possible.

The following explanation is longish. Please bear with me. I will give a compelling reason for me to prefer this style. I will also explain why I think that the usual counter-argument doesn’t hold.

(Near-) empty lines are a waste

The reason for this is that the closing brace requires an extra line of code – and so does the opening brace, depending on style.1

Is this a big deal? Superficially, no. After all, most people also put empty lines in their code to separate logically slightly independent blocks, which vastly improves readability.

However, I detest wasting vertical space. Modern monitors actually have ample horizontal space. But vertical space is still very, very limited (unless you use a monitor turned upright, which isn’t that uncommon). This limited vertical space is a problem: it’s widely acknowledged that individual methods should be as short as possible, and that corresponding braces (or other block delimiters) should be no more than a screen height in difference so that you may see the entire block without scrolling.

This is a fundamental problem: once you can’t see the entire block on your screen any longer, it gets complicated to grasp.

As a consequence, I detest redundant empty lines. Where single empty lines are crucial to delimit independent blocks (just look at the visual appearance of this text), consecutive empty lines are a very bad style in my book (and in my experience they are usually a sign of novice programmers).

Likewise, lines which simply hold a brace, and which could be economised, should be. A single-statement block which is delimited by braces wastes one to two lines. With only 50-ish lines per screen height, this is noticeable.

Omitting braces maybe does no harm

There is just one argument against omitting braces: that someone will later add another statement to the block in question and will forget to add the braces, thus inadvertently changing the semantics of the code.

This would indeed be a big deal.

But in my experience, it isn’t. I’m a sloppy programmer; and yet, in my decade of programming experience, I can honestly say that I have not once forgotten to add the braces when adding an extra statement to a singleton block.

I even find it implausible that this should be a common mistake: blocks are a fundamental part of programming. Block level resolution and scoping is an automatic, ingrained mental process for programmers. The brain just does it (otherwise, reasoning about programming would be much harder). There is no additional mental effort required to remember putting the braces: the programmer also remembers to indent the newly added statement correctly, after all; so the programmer has already mentally processed that a block is involved.

Now, I am not saying that omitting braces doesn’t cause mistakes. What I’m saying is that we have no evidence one way or the other. We simply don’t know whether it causes harm.

So until someone can show me hard data, collected from scientific experiments, demonstrating that this is indeed an issue in practice, this theory remains a “just-so story”: a very compelling hypothesis that has never been put to the test, and that must not be used as an argument.

1 This problem is sometimes solved by putting everything – including the braces – on the same line:

```<code>if (condition)
{ do_something(); }
</code>```

However, I believe it’s safe to say that most people despise this. Furthermore, it would have the same problems as the variant without braces so it’s the worst of both worlds.

Body:
I prefer the version without braces where possible.

The following explanation is longish. Please bear with me. I will give a compelling reason for me to prefer this style. I will also explain why I think that the usual counter-argument doesn’t hold.

(Near-) empty lines are a waste

The reason for this is that the closing brace requires an extra line of code – and so does the opening brace, depending on style.1

Is this a big deal? Superficially, no. After all, most people also put empty lines in their code to separate logically slightly independent blocks, which vastly improves readability.

However, I detest wasting vertical space. Modern monitors actually have ample horizontal space. But vertical space is still very, very limited (unless you use a monitor turned upright, which isn’t that uncommon). This limited vertical space is a problem: it’s widely acknowledged that individual methods should be as short as possible, and that corresponding braces (or other block delimiters) should be no more than a screen height in difference so that you may see the entire block without scrolling.

This is a fundamental problem: once you can’t see the entire block on your screen any longer, it gets complicated to grasp.

As a consequence, I detest redundant empty lines. Where single empty lines are crucial to delimit independent blocks (just look at the visual appearance of this text), consecutive empty lines are a very bad style in my book (and in my experience they are usually a sign of novice programmers).

Likewise, lines which simply hold a brace, and which could be economised, should be. A single-statement block which is delimited by braces wastes one to two lines. With only 50-ish lines per screen height, this is noticeable.

Omitting braces maybe does no harm

There is just one argument against omitting braces: that someone will later add another statement to the block in question and will forget to add the braces, thus inadvertently changing the semantics of the code.

This would indeed be a big deal.

But in my experience, it isn’t. I’m a sloppy programmer; and yet, in my decade of programming experience, I can honestly say that I have not once forgotten to add the braces when adding an extra statement to a singleton block.

I even find it implausible that this should be a common mistake: blocks are a fundamental part of programming. Block level resolution and scoping is an automatic, ingrained mental process for programmers. The brain just does it (otherwise, reasoning about programming would be much harder). There is no additional mental effort required to remember putting the braces: the programmer also remembers to indent the newly added statement correctly, after all; so the programmer has already mentally processed that a block is involved.

Now, I am not saying that omitting braces doesn’t cause mistakes. What I’m saying is that we have no evidence one way or the other. We simply don’t know whether it causes harm.

So until someone can show me hard data, collected from scientific experiments, demonstrating that this is indeed an issue in practice, this theory remains a “just-so story”: a very compelling hypothesis that has never been put to the test, and that must not be used as an argument.

1 This problem is sometimes solved by putting everything – including the braces – on the same line:

if (condition)
{ do_something(); }

However, I believe it’s safe to say that most people despise this. Furthermore, it would have the same problems as the variant without braces so it’s the worst of both worlds.


答:
Short Answer: There is a simple solution to your problem. Just install the virtual-machine with Linux (Ubuntu) - it is free.

I am also a mainly .NET developer who loves to experiment different things, or try variety of frameworks and/or development tools. The main thing here is not to mess your main development environment. Thus, installing everything in a Virtual machine (the native OS, frameworks, configuring and setting them up, etc.) for the type of development you intended to do is the most logical and optimal way to go.

Edit: You may consider different virtualization solution to build your Virtual Machine. My personal preference go with VirtualBox. It is a free x86 virtualization solution allowing a wide range of x86 operating systems such as Windows, DOS, BSD or Linux to run on a Linux system.

Title: OS choice for functional developing


问:
Having two sets of infrequently changing data or converting on the fly
I am currently working on a small project in which I work with some "static data", which is  extracted from one source. The data might change from time to time (up to once a week).
I don't need all of the information the data includes in my project so to allow easier and a more logical access to it I wrote some small tool that converts the extracted data into my desired format.

The conversion is mostly dropping data I don't need, and splitting some strings into arrays. No intensive calculations or anything. But, I drop more than 50% of the original data because their is no need for it.

Now since it is static data would it make more sense to just store that converted data and do all further operations from this data or would it make more sense to convert from the raw data on the fly?

Since the project is in JavaScript speed of course is important, but if converting on the fly has significant advantages it might make more sense to go with that approach.

It is static data from a computer game that defines several units and other objects within the game. They are stored in JSON therefore I can easily use them in JavaScript. But I don't need a lot of the information, just some parts of it to build a kind of "encyclopedia", now since the data is already present in JSON I was wondering if I should just use it or convert it before usage.

答:
Generally speaking, duplication is a greater evil than bad performance.  The answer will typically depend on whether the performance is good enough with the on-the-fly conversion.  You will have to figure that part out yourself.  Stick to the current implementation until you have proof that it's too slow; do not optimise it because you guess that it will be too slow.

An alternative approach would be to take your on-the-fly code, and create a pre-processor out of it, which outputs the cut-down data set.  You can then run this code as part of your build process.  The benefit is that your core data set is not (really) duplicated, and you get the performance benefits.  Also, I realise that this code is in JavaScript, but there are ways to get JS to run on your development machine during the "build".