答:
If you were to listen to Bill Gates you might find this advice:

Interviewer: Is studying computer science the best way to prepare to be a programmer?

Gates: No, the best way to prepare is to write programs, and to study great programs that other people have written. In my case, I went to the garbage cans at the Computer Science Center and I fished out listings of their operating system.

For those people I suggest you enter a University/College which can prepare you for a career in programming, but also a career in something else, should you find passion for something other than staring into a phosphor screen 9 to 5. If you've already done that, then go see your family, career councilor, therapist, whatever. You're grown up, you can figure out what kind of a job you want, can't you?

The combination of the two i.e., self-teaching and CS course in college/university is something that always seems to keep you ahead.
Best of luck!


问:
What makes a project big?
Just out of curiosity what's the difference between a small, medium and large size project? Is it measured by lines of code or complexity or what?

Im building a bartering system and so far have about 1000 lines of code for login/registration. Even though there's lots of LOC i wouldnt consider it a big project because its not that complex though this is my first project so im not sure. How is it measured?

答:
Complexity is the right answer, but how to estimate it?

Factors are :

Extension points count

Modules layers count (functions, classes, class systems, libraries, shared libraries, applications, network applications, etc.)

Dependencies count (platforms included)

Features interdependance count.

Necessary non-code resources (including graphics/arts, driving scripts - like level design scripts - and other resources required to complete a version of the application).

The more you have of those, the more complex is the project.

ContentLicense: CC BY-SA 2.5

Title: What makes a project big?


问:
Do poor writers make poor programmers?
I'm reading Coders at Work by Peter Seibel, and many a time it has been mentioned that programmers who can't write generally make poor programmers - it's been claimed by Douglas Crockford, Joshua Bloch, Joe Armstrong, Dijkstra (and I've only read half the book).

What's your view of this? Is an inability to express yourself in writing in a natural language such as English a hindrance of writing good code?

答:
The thing is, coding is also a communication skill. Jack Ganssle in his Embedded Muse e-newsletter recently quoted Doug Abbott:

When you write a program, what you’re
  really doing is communicating to
  another human what it is you want the
  computer to do. Programming is about
  communication, just like any other
  form of writing. So yes, computer
  science students should be exposed to
  good writing. But since there’s so
  precious little of it in computer
  science, maybe they just need some
  basic creative writing classes.

Programmers who don’t know how to write prose probably don’t know how to write code, either.

More on this interesting article:

Does Bad Writing Reflect Poor Programming Skills?

Title: Do poor writers make poor programmers?


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I am from England, and I try to code (and post on sites like Stack Overflow) in US English, because that is the established international language for programming.

I think I am in the minority though. Some British programmers I know insist on using British spellings even when collaborating with other coders who are using US English and can get upset when an American or Indian colleague edits their comments to change from British to US English (don't try that on Ward's wiki.)

ContentLicense: CC BY-SA 3.0


问:
Is a university education worth it for a good programmer?
I've been doing design and programming for about as long as I can remember. If there's a programming problem, I can figure it out. (Though admittedly Stack Overflow has allowed me to skip the figuring out and get straight to the doing in many instances.) I've made games, esoteric programming languages, and widgets and gizmos galore. I'm currently working on a general-purpose programming language. There's nothing I do better than programming.

Is a university education really more than just a formality?

答:
It's like in that song - "We don't need no education"... That's all big talk worth little credit.

I went through the process of studying for a Master's degree and I achieved it with first class honours. Am I a better programmer than others? Well, the degree in itself doesn't guarantee it; and I wouldn't be as cheeky as to claim it does. I know lots of people who, I believe, are much more technically skilled and professionally experienced than I, and who have not got a Master's degree (or in fact, any degree in a computing-related area).

Still, I am strongly convinced that a degree is benefitial and I wish ALL developers DID have at least a BSc in computing/software engineering as I believe that people who have done a degree have a "richer" mind model - see a bigger picture - since they all had to, in many cases against their own will, get their hands on a much wider variety of technologies and prodded into more subject areas than those self-proclaimed gurus. (awfully long sentence, sorry if i make little sense, it's quarter to 2am... going to bed now, nighty night)


答:
This is altogether anecdotal, but:

One of the best "rock star" programmers I've ever worked with was a very poor writer. And when I say "very poor", I mean the type that came across like he was either extremely drunk, or barely literate - when you saw his emails. Typos, lack of punctuation, difficulty in expressing ideas clearly, and common spelling mistakes ("their/they're" and such) all abounded - almost excruciatingly at times. Reading some of his emails - I would have been worried about him emailing clients directly (we didn't need to do that in that company) - because it would make the company look bad!

Still, he was a super star programmer. An order of magnitude more productive and switched on than average.

I'm not sure what to make of it. I've seen this several times with different people. Some just don't seem to have a knack for sitting down and writing things out. And often it doesn't seem to affect their talents in other areas (even relatively seemingly similar, "knowledge work" talents, such as programming). You'd think it would be connected, but I've seen several living examples like this where it wasn't. Though I guess it's quite possible that they are "exceptions who prove the rule" - I probably just never thought to notice the bad writers who aren't programmers, and the good writers who are.

Title: Do poor writers make poor programmers?

Body:
I'm reading Coders at Work by Peter Seibel, and many a time it has been mentioned that programmers who can't write generally make poor programmers - it's been claimed by Douglas Crockford, Joshua Bloch, Joe Armstrong, Dijkstra (and I've only read half the book).

What's your view of this? Is an inability to express yourself in writing in a natural language such as English a hindrance of writing good code?


答:
One of the more frustrating things about self-taught programmers is that they often learn a technique without learning the proper terminology. I worked with a self-taught programmer who was a former US Marine. The guy was sharp and learned things quickly but often used odd terms for things.

He called pointers stars. DFAs were called flowcharted arrays were numbered lists.

If he had taken a few courses at the university level, he might have used the proper terms.

Title: Is a university education worth it for a good programmer?

Body:
I've been doing design and programming for about as long as I can remember. If there's a programming problem, I can figure it out. (Though admittedly Stack Overflow has allowed me to skip the figuring out and get straight to the doing in many instances.) I've made games, esoteric programming languages, and widgets and gizmos galore. I'm currently working on a general-purpose programming language. There's nothing I do better than programming.

Is a university education really more than just a formality?


答:
I think it is very important for a programmer to be able to communicate well, both with spoken and written language. The ability to translate an idea into words is a prerequisite to writing code.

Whether we are communicating with a computer or a person we have to put words into an order that makes sense following rules of grammar. We have to either pronounce the words correctly or spell them correctly in order for the other side of the conversation to understand them. Computers will throw syntax errors, coworkers will either say "WHAT?" or discount what is being said as inane babbling or worse, an irritating distraction.

I have strongly discouraged hiring candidates because they couldn't complete a thought or stay on a subject. One person was hired by our boss anyway, and turned out to be unable to deliver a simple assignment on time because he was distracted by whatever bright and shiny new technology or toy caught his eye.

So, yes, it is important that programmers be able to communicate well. If they can't effectively communicate with a human they can't do it with a computer.

Title: Do poor writers make poor programmers?


问:
Being productive during downtime
Lets say you are somewhere where coding and getting online isn't possible (On a busy flight, for example)what do you do to stay productive?

Things I would do are read whatever tech book I am currently slogging through and maybe doodle some UI stuff or workflows.  What else could I be doing?

答:
If you must do something - eg on a flight - it does not have to directly work / project related.

I'd suggest some of these:

read a novel - a bit of escapist down time never hurt anybody

read the FINANCIAL section of the newspaper - every programmer and other professional should learn more about business, money, investing and how the world goes round. It won't be an easy start but as yoda might put it: "Learn it you must".

read a bit about project management, or 6 sigma, or any of the other fads and jargon-laden things that are washing around. Do so with an open and critical mind, not taking anybodies word as gospel truth.

This is ultimately all a broadening of you and your education which you will never get any other way. Over a long term (10 years or do) you know more than your peers - you become more rounded, more knowledgeably, more employable, and more respected.

Title: Being productive during downtime


答: From India, like someone else said we are 100% English! But I have also worked in Germany for a short while. The Germans used to do it like the Italians (like Lorenzo said). But bigger companies like Siemens etc. have standardised on English. It's much easier to delegate your work outside of your base country when all of your documentation and code is in English.</p>

Title: Do people in non-English-speaking countries code in English?

Body:
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?


答: I like to listen to podcasts and/or audiobooks. There are a ton of great podcasts out there (technical and non-technical), and if you're not into buying all your books, the local library likely has digital downloads or audiobooks on CD you can rip to your mp3 player.</p>

Title: Being productive during downtime

Body:
Lets say you are somewhere where coding and getting online isn't possible (On a busy flight, for example)what do you do to stay productive?

Things I would do are read whatever tech book I am currently slogging through and maybe doodle some UI stuff or workflows.  What else could I be doing?


问:
Embedded Linux vs Windows Embedded Standard 7
Ok looking for some really subjective answers.  My company has traditionally been a Linux shop, we manufacture and sell purpose built boxes for video security.  We recently decided to build an Embedded Windows Standard 7 box because it shortened our development and time to market, and because of all the tools are available off the shelf for windows.

What I am looking for are some solid answers as it relates to the security of WES7 vs. Linux?  How stable is WES7, how prone is it to hack attempts, virus attacks etc. From a marketing point of view what could or should one say are the benefits of using WES7 over Linux?  Are there any?

What comparisons are there between the security of desktop Windows 7 and Embedded Windows Standard 7?

Any responses would be greatly appreciated.  Thanks

答:
You will need to do a few things, here are some off the top of my head (having been around this a few years ago):

You need lots of memory to run Windows Embedded 7. Check the data - you might be surprised at how much RAM you need.

Make sure you understand how the write filter works, if you are using CF or similar as your "hard drive". If you have a real spinning HD then its not such a big deal.

Do a course on using the tools. ESSENTIAL. I spent a couple of months on the previous generation tools and it was a pretty terrible time learning them. A 1 day course teaches what you will take 1-2 weeks to learn yourself. MS even offer some of these courses for free.

Figure out how you want to lock down the platform. To do this you need to do things like disable web browsers, javascript, turn off file sharing and workstation services (about 70% of all the windows services CAN be disabled and probably should be - this will depend on your application though)

Some aspects can only be locked down using manual steps on a master "golden" platform where you build the image, as manual steps hand entered, after the image build. WRITE DOWN A PROCEDURE to allow this to be replicated.

Do everything (all your target building) in a VM, and check the VM into source control after. It will be between 8 and 10 GB - make sure that your VM splits the virtual disk into 2 GB chunks to make your source control systems life easier. This sounds over the top but it will save your life 2 years later.

Check out and understand how the patch / update system works. We had to write our own, the standard one was not good enough. Things have moved on since but you still must understand this.

Line up a consultant who has done this MANY times before, and get them in for a day or a week if you need to. Make them document everything they do, and WHY. You may need help, and a few days of an experienced consultant will save you a month. A classic turning of $ into time. MAKE sure they are experienced. There are lot of BS people selling Windows Embedded out there - doing the easy 90% is (surprise) easy. The other 10% is damn hard.

Understand the requirements for branding - removing the MS logos and names and putting your own in. Its relatively easy but you must do it. You may need a graphic designer to make splash / start screens.

Go through the license agreement 10 times. It is a LOT of fine print. Your legal department will need to look at it. You MUST understand it and the implications it imposes on your AND YOUR SUPPLY CHAIN. The agreement IS onerous.

It is probably not a good idea to have windows updates enabled. You don't want your product doing various automatic unknown updates. (which leads to:)

Make sure you know how to use and setup the windows firewall so that all ports are blocked except those used only by your application. This reduces the hack-attack surface.

If you get through all this, by all means use it. It is a very powerful platform.

OwnerDisplayName: Marc Dalone


问:
BitBucket - what's the catch? (TANSTAAFL, right?)
The BitBucket capabilities, and pricing (up to 5 users for free) left me wondering what the catch was... there is no such thing as a free lunch, after all.

What is BitBucket getting out of my unpaid participation, besides a handsome man to freely include in their promotional materials (per the TOS)?

答: Bitbucket works well with other services like Atlassian Bamboo (CI) and Atlassian Jira which are a paid services.</p>


问:
Computational Complexity of Correlation in Time vs Multiplication in Frequency space
I am working with 2d correlation for image processing techniques (pattern recognition etc...). I was wondering if there is a theoretical approach on how to tell when to use multiplication in frequency space over correlation in time space. For sizes of 2x frequency space is obviously faster but how about small, prime sizes like e.g. 11?

答:
I'll assume this is being done on a conventional CPU, one core, executing one simple thread, no fancy hardware.  If there is more than that going on, it can probably be accounted for with adjustments to the reasoning for a simpler system.  Not much more can be said without either a specific system to discuss, or a whole textbook or research paper to cover a range of possibilities.

I wouldn't worry about power-of-two sizes. It doesn't matter. FFT algorithms with the butterfly units and all that exist for factors of 3, or any small number, not just 2.   There are clever algorithms for prime-sized data series, too.   I don't like quoting Wikipedia on this due to its impermanent nature, but anyway:

there are FFTs with O(N log N) complexity for all N, even for prime N

Implementations of FFTs for arbitrary N can be found in the GPL'd library FFTW.

The only trustworthy way in terms of serious engineering is to build and measure, but we certainly can get an idea from theory, to see relationships between variables.  We need estimates of how many arithmetic operations are involved for each method.

Multiplying is still slower than addition on most CPUs, even if the difference has shrunk tremendously over the years, so let's just count multiplications.  Accounting also for addition takes a bit more thinking and keeping track of stuff.

A straightforward convolution, actually multiplying and adding using the convolution kernel, repeating for each output pixel, needs W²·K² multiplications, where W is the number of pixels along one side of the image (assuming square for simplicity), and K is the size of the convolution kernel, as pixels along one side.  It takes K² multiplications to compute one output pixel using the kernel and same-size portion of the input image. Repeat for all output pixels, which number the same as in the input image.

(Nmults)direct = W²·K²

To do the job in Fourier space, we must Fourier transform the image. This is done by applying an FFT to each column separately, and then to each row. The FFT for N data points takes about 2N·log(N) multiplications; we want N to be W, the length of one column or row.  All logarithms here are base two.

There are W rows and W columns, so after all the FFTs are done, we have done 2W·(2W·log(W)) multiplications.  Double that, because after we multiply by the Fourier transform of the kernel, we have to inverse-Fourier the data to get back to sensible image.  That's 8W²·log(W). Of course, multiplying by the Fourier transform of the kernel has to be done, another W² multiplications. (Done once, not once per output pixel, per row or anything.) These are complex multiplications, so that's 4W² real multiplications.

So, unless I goofed up (and I probably did) we have

(Nmults)Fourier = 4W²·(2·log(W) + 1)

When do we want to do things the direct way?  When K is sufficiently small to make W²·K² smaller than 4W²·(2·log(W) + 1).  A common factor of W² is easily factored out. We can probably drop the "+1" since we're dealing with idealized estimates. The +1 is likely lost in errors relative to actual implementations, from not counting additions, loop overheads and so on.  That leaves:

```<code>K² < 8·log(W)
</code>```

This is the approximate condition for choosing a direct approach over a frequency space approach.

Note that correlation of two same-size images is just like convolving with a kernel of size K = W.  Fourier space is always the way to do it.

This can be refined and argued over to account for overhead, pipelining of opcodes, float vs. fixed-point, and thrown out the window with GPGPU and specialized hardware.

Body:
I'll assume this is being done on a conventional CPU, one core, executing one simple thread, no fancy hardware.  If there is more than that going on, it can probably be accounted for with adjustments to the reasoning for a simpler system.  Not much more can be said without either a specific system to discuss, or a whole textbook or research paper to cover a range of possibilities.

I wouldn't worry about power-of-two sizes. It doesn't matter. FFT algorithms with the butterfly units and all that exist for factors of 3, or any small number, not just 2.   There are clever algorithms for prime-sized data series, too.   I don't like quoting Wikipedia on this due to its impermanent nature, but anyway:

there are FFTs with O(N log N) complexity for all N, even for prime N

Implementations of FFTs for arbitrary N can be found in the GPL'd library FFTW.

The only trustworthy way in terms of serious engineering is to build and measure, but we certainly can get an idea from theory, to see relationships between variables.  We need estimates of how many arithmetic operations are involved for each method.

Multiplying is still slower than addition on most CPUs, even if the difference has shrunk tremendously over the years, so let's just count multiplications.  Accounting also for addition takes a bit more thinking and keeping track of stuff.

A straightforward convolution, actually multiplying and adding using the convolution kernel, repeating for each output pixel, needs W²·K² multiplications, where W is the number of pixels along one side of the image (assuming square for simplicity), and K is the size of the convolution kernel, as pixels along one side.  It takes K² multiplications to compute one output pixel using the kernel and same-size portion of the input image. Repeat for all output pixels, which number the same as in the input image.

(Nmults)direct = W²·K²

To do the job in Fourier space, we must Fourier transform the image. This is done by applying an FFT to each column separately, and then to each row. The FFT for N data points takes about 2N·log(N) multiplications; we want N to be W, the length of one column or row.  All logarithms here are base two.

There are W rows and W columns, so after all the FFTs are done, we have done 2W·(2W·log(W)) multiplications.  Double that, because after we multiply by the Fourier transform of the kernel, we have to inverse-Fourier the data to get back to sensible image.  That's 8W²·log(W). Of course, multiplying by the Fourier transform of the kernel has to be done, another W² multiplications. (Done once, not once per output pixel, per row or anything.) These are complex multiplications, so that's 4W² real multiplications.

So, unless I goofed up (and I probably did) we have

(Nmults)Fourier = 4W²·(2·log(W) + 1)

When do we want to do things the direct way?  When K is sufficiently small to make W²·K² smaller than 4W²·(2·log(W) + 1).  A common factor of W² is easily factored out. We can probably drop the "+1" since we're dealing with idealized estimates. The +1 is likely lost in errors relative to actual implementations, from not counting additions, loop overheads and so on.  That leaves:

K² < 8·log(W)

This is the approximate condition for choosing a direct approach over a frequency space approach.

Note that correlation of two same-size images is just like convolving with a kernel of size K = W.  Fourier space is always the way to do it.

This can be refined and argued over to account for overhead, pipelining of opcodes, float vs. fixed-point, and thrown out the window with GPGPU and specialized hardware.


问:
AND is better or using Internal "IF"
In a situation like this:"

```<code>if ((metadata != null) && (metadata.TypeEnum != VariantInfoMetadata.CellTypeEnum.Status))
</code>```

do you recommend to keep the code as it is above?  Or is it better to make a nested "if" statement and breaks the condition into two sections where "outer if" makes sure metadata is not null and inner if does the rest of the checking.  I think a nested if takes care of possible null reference exception if value of metadata gets null.

答:
Because of short-circuit evaluation, both solutions are equally valid technically.  However, stylistically, it's usually preferable and possible to arrange for variables like metadata never to be null in the first place.

In this particular case, you are using two variables to denote type.  metadata.TypeEnum stores the type, and metadata itself being null denotes a "no metadata at all" type.  Your programming language lets you create as many types as you want.  Take advantage of it.

A better solution is to create a Cell base class that doesn't even have a metadata member, so there's no need for it to ever be null.  Then create a StatusCell derived class that adds any unique properties you need, and same for the other types of cells.

If that kind of refactoring isn't possible, like if you're working with a third-party API, another option to consider is a guard clause, like:

```<code>if (metadata == null)
    return;

if (metadata.TypeEnum != VariantInfoMetadata.CellTypeEnum.Status)
    ...
</code>```

A lot of people (including myself), prefer this style because it limits both the level of nesting and the number of conditions in one if statement.

Title: AND is better or using Internal "IF"

Body:
Because of short-circuit evaluation, both solutions are equally valid technically.  However, stylistically, it's usually preferable and possible to arrange for variables like metadata never to be null in the first place.

In this particular case, you are using two variables to denote type.  metadata.TypeEnum stores the type, and metadata itself being null denotes a "no metadata at all" type.  Your programming language lets you create as many types as you want.  Take advantage of it.

A better solution is to create a Cell base class that doesn't even have a metadata member, so there's no need for it to ever be null.  Then create a StatusCell derived class that adds any unique properties you need, and same for the other types of cells.

If that kind of refactoring isn't possible, like if you're working with a third-party API, another option to consider is a guard clause, like:

if (metadata == null)
    return;

if (metadata.TypeEnum != VariantInfoMetadata.CellTypeEnum.Status)
    ...

A lot of people (including myself), prefer this style because it limits both the level of nesting and the number of conditions in one if statement.


问:
Diminishing Returns on Additional Developers
Is there a term to describe the point at which adding more developers to a software project will provide diminishing returns?

I realize that at a high level, it is more complicated that just a number of developers at which the project will be at productive capacity (ex/ state of the project, quality of the added developer), but I am trying to come up with a way to relate this to non-technical management through repetition. I'm basically looking for a term which invokes a strong mental image like "terminal velocity", except for Brook's Law.

答:
Doomed to Repeat

Poor Fred Brooks is like Cassandra from Homer's Illiad.  If you read the book that the movie Troy came from, she was the one who didn't care for the (Trojan) horse.  She predicts the future accurately, but no one believes her until after the prediction has happened and they have seen it for themselves.

Don't Fight Management / Passive Resistance or Careful Hiring?

My advice is that it is probably not a good day to die, and that if your manager wants you to hire more staff, do it.  Suggesting some parameters like getting someone with specific experience and use of rapid screen-out technique will triple the search time and maybe you will reach your deadline before the disruptor arrives.

Minimizing the time you spend on unlikely candidates will save huge amounts of time.  For example, any resume without your top three requirements in the first 1/3 of their resume gets tossed, candidates must pass a 30 minute phone screen before any onsite interviews, ignore recruiters who don't pre-screen to your needs.  Other techniques abound, make sure anything you use is efficient and effective.

Controlling the Burden of New Hire Integration

If you do make the hire before your deadline and need to deal with a new employee, budget time from people who are not on the critical path to be involved in training.  It is helpful to have members of your team see one, do one, show one.  If you have a low to medium experience team member, it will strengthen their understanding of your processes, tool set, and code base to mentor a new hire in these areas.

Hopefully, you have some documentation, so assigning the new person to read documentation that will help them ramp up is a good short and long term investment.  They should be brought into your processes gradually, and their work should be reviewed by people who can keep them from driving the project on the rocks with bold but harmful changes.

Best and Worst Assignments for New Hires

If you have a separate project or some technology development they can do to prepare for its use in a future project, that also could be a big benefit.  Learning your specific tool set, doing their own local builds, unit testing, usability testing, documentation, and participation in reviews are all great candidate tasks for new hires.  A new hire may have a perspective that is new and can provide valuable critical commentary about things your team learned to live with and can no longer see.

Less beneficial uses for new staff might include team meetings with managers and non-developer stakeholders, estimation, requirements elicitation and management (unless they are experts after having worked at a competitor), patents, and interviewing new candidates or otherwise helping with staffing.

Keeping Harmony in the Team, Setting Future Expectations

New hire priorities do still come into play.  If you have a team that has passed through the forming, storming, norming, performing evolution, you must give the new hire your expectations for his performance and planned responsibilities within the team.  You must not make the job of the new hire appear less demanding than other roles on the team.  If your team is aggressively pushing toward deadlines, the new hire should have ways to demonstrate he is aggressively pushing toward integration.


答:
My suggestion, which no one has mentioned yet, is to spend time with other people.

It seems so much of a programmer's life is spent interacting with (virtual) objects that any additional interaction with people (in a positive and constructive way) would benefit them as a person! (And others, as well. I didn't mean to make it sound so self-centered. Rather the opposite, one needs to care for others, too!)

Title: Being productive during downtime


问:
On merging database records, constraint violation in the intermediate table of M2M
If you are merging two or more database records from table X, that have a many-to-many relationship with table Y, how should you solve the problem of records in intermediate table Z that would violate one or more constraints as a result of the merge? Do you simply discard them or break off the transaction?</p>

答:
It depends on the result which you are expecting. In general you also have to merge the table Z to keep the data integrity.

Discarding records which are violating constraints should not happen. It would be annoying if those lost records were your monthly salary payment advice.


答: Personally I'd drop the relations in table Z, then drop the relevant records from X, merge the records and then rewrite the new ones into the database. This means you don't break any constraints, don't need to disable constraints and you'll be less likely to make merging mistakes by leaving old data behind.</p>

Title: On merging database records, constraint violation in the intermediate table of M2M

Body: If you are merging two or more database records from table X, that have a many-to-many relationship with table Y, how should you solve the problem of records in intermediate table Z that would violate one or more constraints as a result of the merge? Do you simply discard them or break off the transaction?</p>


问:
How to apply verification and validation on the following example
I have been following verification and validation questions here with my colleagues, yet we are unable to see the slight differences, probably caused by language barrier in technical English.

An example:

Requirement specification

User wants to control the lights in 4 rooms by remote command sent from the UI for each room separately.

Functional specification

The UI will contain 4 checkboxes labelled according to rooms they control.

When a checkbox is checked, the signal is sent to corresponding light. A green dot appears next to the checkbox

When a checkbox is unchecked, the signal (turn off) is sent to corresponding light. A red dot appears next to the checkbox.

Let me start with what I learned here:

Verification, according to many great answers here, ensures that product reflects specified requirements - as functional spec is done by a producer based on requirements from customer, this one will be verified for completeness, correctness). Then design document will be checked against functional spec (it should design 4 checkboxes..), and the source code against design (is there a code for 4 checkboxes, functions to send the signals etc. - is it traceable to requirements).

Okay, product is built and we need to test it, validate. Here comes our understanding trouble - validation should ensure the product meets requirements for its specific intended use which is basically business requirement (does it work? can I control the lights from the UI?) but testers will definitely work with the functional spec, making sure the checkboxes are there, working, labelled, etc. They are basically checking whether the requirements in functional spec were met in the final product, isn't that verification? (should not be, lets stick to ISO 12207 that only validation is the actual testing)

答:
They are basically checking whether the requirements in functional
  spec were met in the final product, isn't that verification?

The verification activity is ensuring that the Functional Specification (and not forgetting the Test Specification) covers all of the requirements of the Requirement Specification - ie you haven't missed anything out, or added anything unexpected in.

The validation activity is ensuring that those requirements have been met

See also: Functional testing in the verification


问:
Difference between a socket and a port
Could someone please explain quite clearly the difference between a port and a socket. I know that a port serves as a door into the network for an application
process and that the application process uses a socket connection to the given port number to handle network communication but when you have multiple processes listening on a single port number, I am finding it difficult to understand the difference between the socket and the port and how they all fit together.</p>

答:
A socket is a communication path to a port. When you want your program to communicate over the network, you have given it a way of addressing the port and this is done by creating a socket and attaching it to the port.
Basically, socket = IP + ports Sockets provide access to the port+ip</p>

Title: Difference between a socket and a port


答:
An IP address identifies the device ie the address to the particular device, when you reached the machine using IP now port defines to which process in that machine to communicate.

So for actual communication to take place you need both port+IP which is called socket.

Title: Difference between a socket and a port

Body:
Could someone please explain quite clearly the difference between a port and a socket. I know that a port serves as a door into the network for an application
process and that the application process uses a socket connection to the given port number to handle network communication but when you have multiple processes listening on a single port number, I am finding it difficult to understand the difference between the socket and the port and how they all fit together.</p>


答:
There are different ways this problem could happen:

1-Table Z has bad data (not sure why or how it got in in the first place). It then becomes a business decision as what to do about the bad data. You generally would need to report this (bad) data to business and let them decide. Then you choose an appropriate approach to solve the problem.

2-If your table X or table Y uses automatically generated IDs and your table Z data is referencing those IDs, you may get this problem when you try to load table Z (assuming you have already loaded all rows in X and Y successfully). In this case, you load table Z without the FK constraint forced (relax the constraint before loading Z), load Z, and then re-build the constraint on a separate step.

As a developer or DBA, you don't throw away production data without explicit user agreement. Also, Allows keep backups.


问:
GitHub OS project how to have a good version and a work in progress version
I have started my own OS application, I am hosting it on GitHub. My problem is that I push changes to the repository from more than one location so sometimes I want to work on it and sometimes I can't always finish something in time but I would still like to push it anyway so I can fetch it later from my other location. I'd like to be able to somehow have a stable version and have the master branch be a 'work in progress'.

How do I do this?

Is there some button I can push that will take the code from my master branch and make it into a zip file in my downloads tab and call it a version or should I do this by hand?

Would it be better to have the master branch be nice and neat and have a separate branch to play with and then merge the two when the time is right? Would this not cause more problems in the merging phase?

答:
Some projects dedicate the master branch for "stable" and use a separate branch, such as "dev" for cutting edge stuff. The development branch is then merged to master every once in a while, when it's in a stable state. For bigger, breaking features it's a good idea to use completely separate feature branches.

Other option is to do the other way around and have master be the dev branch and create release branch(es). Just be sure to document that the master is unstable. Note that you can also change the default branch that GitHub displays from the admin panel.

Perhaps a more elegant way, and also takes care of the zip files automatically is to tag stable versions. GitHub creates automatical zip links for every tag in the Tags tab, which is next to the Downloads. For tagging guide, see this link.

If you do commits in the stable branch, then be sure to merge them to the development branch very often. That will minimize merge conflicts.

If you are unfamiliar with branching, here's a guide.


问:
Seeking advice on system documentation
I have a rating engine (it is basically an algorithm) which when I started had no formal documentation. We have created a functional specification/decomposition which is our business level document but now I need something more technical (a technical specification).

What I am struggling to understand is what that document looks like, what format it should be in and to what level of detail we should go into.

We are in the process of commenting all of the code. We also have a rough document called a Blueprint which reflects the flow of the model and is written in pseudo code. Is the combination of this blueprint and the model comments sufficient as a Technical Specification?

答:
The goal of this kind of specification is to help incoming workers to dive into the code. It must also help experimented workers to hold a clear overview of the project.

You can change your blueprint for a UML diagram, particularly an activity diagram in your case. This offers a (more or less) standardised way to visually represent your workflow. It shows the actions done on the algorithm, the choices made, the options available for each choice, the loops, etc. You can also show the beginning and the end of your process, exhibit the elements required or produced by it, and highlight some points thanks to comments.

At a lower level, intelligently comment the code is always a good idea. Generally, one must specify, for each piece of code (function, method, class, ...)

Its inputs, and which properties they must respect (the list must be sorted, etc.);

Its output;

What happens in particular cases (an empty list, an invalid input, etc.). Indicate the raiseable exceptions, if your language support them;

Its side effects (ideally it should not have any). Typically the read/write from/to files, network, etc.;

If it is thread safe. That is, if its state can be changed during its execution by an external entity. Check for instance if the list given as an input can be changed externally. Thread safety is very important in a multi-threaded environment, of course, but this is also a sign of quality. The developers should be very careful when they use an unsafe piece of code.

Its time and memory consumption, w.r.t its inputs. The external users want answers to questions like "Can I give a (very) big list to this function with no major computation time issue?".

The context in which it must be used, if this context can affect its behaviour (ideally it should not be the case since the only influencing factors should be its inputs).

If required, how to automatically build and test it.

Use tools allowing you to add those comments in your code, and being able to automatically generate reports in a separated document. See javadoc or doxygen for instance. Thanks to these tools, you can update the information in the same time you change your code, and get an always up-to-date separated documentation.

Complete the specifications by automated tests, and consider them as part of the documentation. Tests describe what should be the code behaviour in normal situations and exceptional situations.

Your engine should then be considered as a collection of entities communicating together. You know how each entity works, how entities must act together and how they act in representative situations.

Note this is not an advocacy of OOP, since the "entities" can be functions (in functional programming), structures, classes (in OOP), etc.

Title: Seeking advice on system documentation

ContentLicense: CC BY-SA 4.0


问:
Is it OK to have multiple asserts in a single unit test?
In the comment to this great post, Roy Osherove mentioned the OAPT project that is designed to run each assert in a single test.

The following is written on the project's home page:

Proper unit tests should fail for
  exactly one reason, that’s why you
  should be using one assert per unit
  test.

And, also, Roy wrote in comments:

My guideline is usually that you test
  one logical CONCEPT per test. you can
  have multiple asserts on the same
  object. they will usually be the same concept being tested.

I think that, there are some cases where multiple assertions are needed (e.g. Guard Assertion), but in general I try to avoid this. What is your opinion? Please provide a real world example where multiple asserts are really needed.

答:
Another reason why I think, that multiple asserts in one method is not a bad thing is described in following code:

class Service {
    Result process();
}

class Result {
    Inner inner;
}

class Inner {
    int number;
}
```

<p>In my test I simply want to test that <code>service.process()</code> returns the correct number in <code>Inner</code> class instances.</p>

<p>Instead of testing...</p>

<pre class="lang-java prettyprint-override"><code>@Test
public void test() {
    Result res = service.process();
    if ( res != null && res.getInner() != null ) Assert.assertEquals( ..., res.getInner() );
}
</code>```

I'm doing

@Test
public void test() {
    Result res = service.process();
    Assert.notNull(res);
    Assert.notNull(res.getInner());
    Assert.assertEquals( ..., res.getInner() );
}
```

Body:
Another reason why I think, that multiple asserts in one method is not a bad thing is described in following code:

class Service {
    Result process();
}

class Result {
    Inner inner;
}

class Inner {
    int number;
}

In my test I simply want to test that service.process() returns the correct number in Inner class instances.

Instead of testing...

@Test
public void test() {
    Result res = service.process();
    if ( res != null && res.getInner() != null ) Assert.assertEquals( ..., res.getInner() );
}

I'm doing

@Test
public void test() {
    Result res = service.process();
    Assert.notNull(res);
    Assert.notNull(res.getInner());
    Assert.assertEquals( ..., res.getInner() );
}


问:
What is meant by sandboxing?
Sanboxing is listed as one of the many security features in html5 specification . Can someone explain what is meant by sandboxing? Does it relate to HTML only or to JavaScript also?</p>

答: Sandboxing means running an application in containment, seperate from outside applications. This way, the application is cut-off from anything that it may want to do something malicious to. Specifically in this context, your browser will try to sandbox the JS on a page to ensure it doesn't affect more than what it's supposed to.</p>

Title: What is meant by sandboxing?


问:
Designing a Business Rule Engine
I have a requirement where there are 10 Rules to be applied on data in excel.
If Rule 1 and Rule 2 fails rest of the rules are not checked. But if Rule 1 and Rule 2 passes the rest of all the Rules should be verified and if any errors found- they should be logged. Is there any design pattern which I can use to keep this Rule Engine flexible for adding these 10 rules and Closed for any additional chains in the Current Rule. I was thinking of something like a Decorator Pattern. Will this help me achieve that?</p>

答:
It's a good approach to try and find a best practice for doing something, particularly in a design pattern. But sometimes finding a 'pattern' or understanding all of them to know which to apply can consume time.

Is applying a pattern here necessary, from your 'question' above, you could knock out the 'code' quicker than coming to a conclusion on a pattern/potential pattern (the apparent logic doesn't sound difficult) Nevertheless, if it is your consideration to use one, I would suggest the State Pattern.

http://en.wikipedia.org/wiki/State_pattern

Ref:waec exam

(It's similar to the Strategy Pattern)

The State pattern allows an object to behave differently based on it's state.

Title: Designing a Business Rule Engine

OwnerDisplayName: Dane Balia


答:
I think a combination of Composite and Chain of Responsibility could fit:

A composite of Rule1 and Rule2 (leaves) for basic rules.

Subsequent rules chained to the Basic Rule Composite, either as a chain of leaf rules or composite rules.

Successors in the chain are evaluated only if the first rule passes, and composites' leaves are always invoked (with an appropriate aggregate for the composite result, e.g. true if all leaves pass).

Title: Designing a Business Rule Engine

Body:
I have a requirement where there are 10 Rules to be applied on data in excel.
If Rule 1 and Rule 2 fails rest of the rules are not checked. But if Rule 1 and Rule 2 passes the rest of all the Rules should be verified and if any errors found- they should be logged. Is there any design pattern which I can use to keep this Rule Engine flexible for adding these 10 rules and Closed for any additional chains in the Current Rule. I was thinking of something like a Decorator Pattern. Will this help me achieve that?</p>

OwnerDisplayName: Mudu


答:
The best way to do it is to not do it. Designing for ultimate flexibility for some unknown future requirements is one of the great pitfalls in software engineering. Allowing any arbitrary rule from business into the design is another of the great pitfalls.

If you only have 10 rules, and are working on some podunk excel processing app... just hard code the rules. You'll do it faster, in a way that is easier to debug, maintain, and extend (unless you're going to be adding/changing a new rule every week or so).

YAGNI

Title: Designing a Business Rule Engine


答:
Have your main act as your on going trunk, this is what will make up your next release.

Use a separate branch for each feature and then merge these back in to the main trunk when they have been fully developed and tested and then retest on the main trunk.

Make release branches periodically from the main and use the log of current open branches and merged in branches to create release notes detailing known faults and added features. This means these branches stay static so you can provide user support for multiple versions not just the latest release.

Title: GitHub OS project how to have a good version and a work in progress version

Body:
I have started my own OS application, I am hosting it on GitHub. My problem is that I push changes to the repository from more than one location so sometimes I want to work on it and sometimes I can't always finish something in time but I would still like to push it anyway so I can fetch it later from my other location. I'd like to be able to somehow have a stable version and have the master branch be a 'work in progress'.

How do I do this?

Is there some button I can push that will take the code from my master branch and make it into a zip file in my downloads tab and call it a version or should I do this by hand?

Would it be better to have the master branch be nice and neat and have a separate branch to play with and then merge the two when the time is right? Would this not cause more problems in the merging phase?


问:
In choosing a service-oriented architecture framework that needs to work with .NET and with Java, what to look for?
I planning to write an application in which there will be a service (call it A) listening for particular commands. This service will then relay those commands to other services (call them B and C) which are written, respectively, in .NET and Java (service A chooses which of service B or C to which to relay depending on the contents of the request to service A).

I am looking for a framework that will allow for interoperability with both .NET and with Java, for example WCF or JAX-WS, or writing a custom framework (e.g., JSON REST commands over HTTP, similar to http://code.google.com/p/selenium/wiki/JsonWireProtocol).

What questions/aspects should I consider in deciding?

答:
I don't really see this as a question of framework, but rather of communication language/protocol. You're mentioning JAX-WS which is Java EE's API for implementing Web Services, so I'm guessing that the B an C services offer a Web Service API (either SOAP or REST). If so, the communication between these 2 and a 3rd application would be language agnostic, i.e. you can implement the 3rd application in whatever you want as long as it does proper Web Service communication.

If you chose Java, I would recommend Jersey as a Web Services Framework. It's the reference implementation of JAX-WS, and it's pretty light weight, easy to test, and has some nice configuration features (good convention over configuration, easily configurable model via annotations etc.)


问:
Are nested classes under-rated?
I'm not trying to say I know something everyone else doesn't but I've been solving more and more designs with the use of nested classes, so I'm curious to get a feeling for the acceptablilty of using this seemingly rarely used design mechanism.

This leads me to the question: am I going down an inherintly bad path for reasons I'll discover when they come back to bite me, or are nested classes maybe something that are underrated?

Here are two examples I just used them for: https://gist.github.com/3975581 - the first helped me keep tightly releated heirarchical things together, the second let me give access to protected members to workers...

答: The only advantage I can think of nested classes is that they can be made private (or protected).  I'd say in this case nested classes can help you encapsulate functionality if a class is intended to be used by the outer class and that class alone.

Title: Are nested classes under-rated?


问:
Is it actually possible to have a 'useful' programming language that isn't Turing complete?
Where it is accepted that a language has to be Turing complete to be any good, is it actually possible to have a 'useful' programming language that isn't Turing complete?

I should clarify that this is quite specifically about 'programming' languages in the traditional sense, and not markup or query languages.

答:
Coq, Agda, HOL and ACL2 are very useful and extremely powerful languages, although they're not Turing-complete.

A common feature that renders them non-Turing-complete is the fact that it is always possible to prove termination. A very simple limitation is enough: recursive calls are only allowed on provably structurally smaller terms. Therefore while it is not possible to implement an interpreter for a Turing-complete language or even for the language itself many other useful things are still possible, like a certified C compiler.


答: Study the interfaces available from B and C and look at the complexity of the classes and the protocols that are handled by each of those services. That will help guide the choices as interoperability issues usually come from complex objects.  You will probably want to put a wrapper around the external services to isolate changes and to provide a consistent interface from your A service.</p>

Title: In choosing a service-oriented architecture framework that needs to work with .NET and with Java, what to look for?

Body:
I planning to write an application in which there will be a service (call it A) listening for particular commands. This service will then relay those commands to other services (call them B and C) which are written, respectively, in .NET and Java (service A chooses which of service B or C to which to relay depending on the contents of the request to service A).

I am looking for a framework that will allow for interoperability with both .NET and with Java, for example WCF or JAX-WS, or writing a custom framework (e.g., JSON REST commands over HTTP, similar to http://code.google.com/p/selenium/wiki/JsonWireProtocol).

What questions/aspects should I consider in deciding?


问:
How get and set accessors work
The standard method of implementing get and set accessors in C# and VB.NET is to use a public property to set and retrieve the value of a corresponding private variable.  Am I right in saying that this has no effect of different instances of a variable?  By this I mean, if there are different instantiations of an object, then those instances and their properties are completely independent right?  So I think my understanding is correct that setting a private variable is just a construct to be able to implement the get and set pattern?  Never been 100% sure about this.</p>

答:
About this:

So I think my understanding is correct that setting a private variable
  is just a construct to be able to implement the get and set pattern?

You can think of a property as a method that can do much more then just expose the underlying field. A property can also provide access to more than one private field.

For example, you could have an Invoice which would have the TotalPrice property.
This property would then return the sum of all Item (which would be a List<Item> property on the invoice) prices or something like that.

This way you are encapsulating the inner workings of the invoice and exposing just this simple property. In the get method of the property, you could have various calls to other methods or properties to calculate the price.

The Item could have private fields for price and quantity and a property Price which would return (price * quantity). You could then add discount to the mix, and the access to Price from whatever is using the Item would stay the same.

Moreover, you could make the property readonly (no set method), where you can then change the item prices, but not the total directly, thus enforcing that the data is consistent.

I find it more helpful to think of properties as methods, rather than fields, and working with properties allows you to change how the data is returned without changing every call to that property (because you can process the field before returning, rather then outright giving the field to the client).

Title: How get and set accessors work


问:
How can I get non-programmer colleagues on board with bespoke software rather than Dynamics CRM + Sharepoint?
I am working with a company which designs and builds one-off machines. They have been 'dabbling' with hosted Dynamics CRM and Sharepoint (on different servers!) in an attempt to centralise their data and help colleagues collaborate more effectively across projects. They haven't used either system to their potential.

Now we are looking at the engineering department who already use a form of version control software for the various CAD files (Autodesk Vault) however it is becoming increasingly necessary to implement more of a generic file version control system as they use many more files than can be managed in Vault (sometimes just photos or scans of paper documents), hence why they were looking at using Sharepoint.

However... as the 'programmer' of the bunch, I can see several scenarios which don't seem to fit well with the Dynamics + Sharepoint approach; simple reports based on cross-table queries, exporting certain metrics as a spreadsheet, defining project hierarchies and many-many relationships, and as such I have been pushing for an in-house developed 'ECM' / 'ERP' software package (perhaps in .NET or php).

Some colleagues seem to attach a greater value to the MS software (perhaps becuase it has a logo!) but don't see that it's just a framework, not a solution.

Can anyone provide a good example of when custom software would actually be better than using Dynamics + Sharepoint and how do I relate that to non-technical staff?

答:
Think of problems that have occurred as a result of using Dynamics CRM + Sharepoint.  Remember that time you said to one of the non-technical staff, "I cannot do feature X because sharepoint doesn't support it." Those are perfect examples of why bespoke is better.  If you have no such examples, then Dynamics CRM + Sharepoint is fine.

The next question is this: Is getting rid of Dynamics CRM + Sharepoint necessary in order to add such features?  If the answer to that question is no, then the only person who needs to know about these issues is your manager; your colleagues shouldn't need to care how your solutions work.


答:
I would think Yegge's term "mini-language" refers to the fact that it is often useful to use a language for specific problems where the language doesn't require turing-completeness to accomplish the task, and this goes to the heart of how non-turing complete languages can be useful. https://sites.google.com/site/steveyegge2/language-grubbing

Wikipedia answers this very well, right in line with what my gut said. First I was thinking pure math then I remembered regexp, and Wikipedia lists Epigram which I believe would be in the 'pure math' vein.

http://en.wikipedia.org/wiki/Turing_completeness#Non-Turing-complete_languages

Non-Turing-complete languages

Many computational languages exist which are not Turing complete. One
  such example is the set of regular languages, most commonly regular
  expressions, which are generated by finite automata. A more powerful
  but still not Turing-complete extension of finite automata is the
  category of pushdown automata and context-free grammars, which are
  commonly used to generate parse trees in an initial stage of program
  compiling. Further examples include some of the early versions of the
  pixel shader languages embedded in Direct3D and OpenGL
  extensions, or a series of mathematical formulae in a
  spreadsheet with no cycles.[citation needed] In total functional
  programming languages, all functions are total, and must terminate,
  such as Charity and Epigram. Charity uses a type system and control
  constructs based on category theory, whereas Epigram uses dependent
  types.

Data languages

The notion of Turing-completeness does not
  apply to languages such as XML, JSON, YAML and S-expressions, because
  they are typically used to represent structured data, not describe
  computation. These are sometimes referred to as markup languages, or
  more properly as "data description languages".

It also mentions data structure representations are not languages, but I would think XSLT should count as a representation of computation, XPath perhaps not based on what Yannis said above about SQL being a query language and not a computation language. Perhaps T-SQL or PL/SQL count as computation languages though since you can do a great deal of computations using their aggregates, where the generalized form of SQL doesn't specify aggregates perhaps.

Title: Is it actually possible to have a 'useful' programming language that isn't Turing complete?

Body:
Where it is accepted that a language has to be Turing complete to be any good, is it actually possible to have a 'useful' programming language that isn't Turing complete?

I should clarify that this is quite specifically about 'programming' languages in the traditional sense, and not markup or query languages.


答: I understand SQL is quite popular among business types</p>


答:
Turing completeness is necessary for a language to be fit for use as a general purpose language. But it is not sufficient, i.e. just because it is Turing complete, it is not suited for every problem domain:

Whitespace is proven to be Turing complete but is obviously unsuited for any problem domain outside of programmer entertainment.

C++ templates have been proven Turing complete, still you wouldn't actually ever write whole programs with them.

Conversely a DSL is suited for the problem domain it was designed for (assuming it was in fact decently designed), even without Turing completeness:

HTML* provides a concise way to describe a DOM tree. While JavaScript is Turing complete and can be used to do just the same, it is far more noisy and unclear

XPath and other query languages, PCRE without embedded code and such are all powerful tools for the single job they were designed for

* IIRC it was proven that HTML with CSS animations is Turing complete by using them to implement Conway's Game of Life on an array of checkboxes. But the usefulness of HTML holds even in browsers that do not support CSS animations.


问:
Suggestions for connecting .NET WPF GUI with Java SE Server
BACKGROUND

We are building a Java (SE) trading application which will be monitoring market data and sending trade messages based on the market data, and also on user defined configuration parameters.

We are planning to provide the user with a thin client, built in .NET (WPF) for managing the parameters, controlling the server behavior, and viewing the current state of the trading. The client doesn't need real-time updates; it will instead update the view once every few seconds (or whatever interval is configured by the user).

The client has about 6 different operations it needs to perform with the server, for example:

CRUD with configuration parameters

query subset of the data

receive updates of current positions from server

It is possible that most of the different operations (except for receiving data) are just different flavors of managing the configuration parameters, but it's too early in our analysis for us to be sure.

To connect the client with the server, we have been considering using:

SOAP Web Service

RESTful service

building a custom TCP/IP based API (text or xml) (least preferred - but we use this approach with other applications we have)

As best as I understand, pros and cons of the different web service flavors are:

SOAP

pro: totally automated in .NET (and Java), modifying server side interface require no code changes in communication layer, just running refresh on Web Service reference to regenerate the classes.

con: more overhead in the communication layer sending more text, etc. We're not using J2EE container so maybe doesn't work so well with J2SE

REST

pro: lighter weight, less data. Has good .NET and Java support. (I don't have any real experience with this, so don't know what other benefits it has.)

con: client will not be automatically aware if there are any new operations or properties added (?), so communication layer needs to be updated by developer if server interface changes.

con: (both approaches) Server cannot really push updates to the client at regular intervals (?)  (However, we won't mind if client polls the server to get updates.)

QUESTION

What are your opinions on the above options or suggestions for other ways to connect the 2 parts?  (Ideally, we don't want to put much work into the communication layer, because it's not the significant part of the application so the more off-the-shelf and automated the better.)

答:
I've done two relevant (for this question) projects. The first uses SOAP, a Java server and a .NET-Client. The second uses REST, but both, client and server, are written in Java.

Your pros and cons seem all valid to me. I personally like REST-style messages more. The main-reason for this is, that it's very lightweight (in action and development), what you already pointed out. The changes in the message-layer have to be done by hand, but in my projects that hasn't been a big deal.
In Addition, when you consider to allow usage of your Webservice from other clients, REST might be the better choice, because I never had problems in any language I used with REST, with SOAP it has always been, let's s exhausting.

But if you feel like there'll be lot of changes, you might give it another weight. So according to this article, you can get SOAP working without J2EE.

Hope that helps.


问:
"Best fit" to avoid reuse of object instances in a collection
Imagine I have a collection of object instances which represent activities for a user to undertake.  Dependent on user attributes, I have to randomly select instances to present activities to the user.

For some users, I need to present more activities to them than there are available activities in which case, I want to use the following algorithm.

If all available activities have already been presented to the user, then re-select a "used" activity, selecting the earliest presented activity ordered by frequency of use.  In other words, try to reduce repetition and where repetition is unavoidable, use the instances which have been repeated less often and were presented furthest back in time.

Before I go on to code that algorithm, I wondered if there is some existing pattern I can re-use?

[EDIT]  "Furthest back in time" is not relevant as I will pass the algorithm an ordered collection of used instances where the first entry is the first presented.

答: Game Coding Complete has source for Pseudo-Random Traversal of a Set which sounds like what you need.  It generates a random list of tasks from the set, but guarantees each task will be visited once before it starts generating the same task again.</p>


答:
Although verification and validation might overlap each other (yet not entirely), and might also make use of similar techniques (such as tests, walkthroughs, simulations...), they mainly differ in user involvement.

Generally, verification helps answering "Are we building the product right?". Validation, on the other hand, is trying to answer "Are we building the right product?".

So, while verification concerns requirements coverage, and if work products (not just code) meet what has been planned and designed (including standards and processes); validation ensures that products meet users expectations (that may not be exactly what is defined in requirement specification). Therefore, validation usually requires the final user involvement and production environments assessments.

Hope it can clear things out.

Title: How to apply verification and validation on the following example

Body:
I have been following verification and validation questions here with my colleagues, yet we are unable to see the slight differences, probably caused by language barrier in technical English.

An example:

Requirement specification

User wants to control the lights in 4 rooms by remote command sent from the UI for each room separately.

Functional specification

The UI will contain 4 checkboxes labelled according to rooms they control.

When a checkbox is checked, the signal is sent to corresponding light. A green dot appears next to the checkbox

When a checkbox is unchecked, the signal (turn off) is sent to corresponding light. A red dot appears next to the checkbox.

Let me start with what I learned here:

Verification, according to many great answers here, ensures that product reflects specified requirements - as functional spec is done by a producer based on requirements from customer, this one will be verified for completeness, correctness). Then design document will be checked against functional spec (it should design 4 checkboxes..), and the source code against design (is there a code for 4 checkboxes, functions to send the signals etc. - is it traceable to requirements).

Okay, product is built and we need to test it, validate. Here comes our understanding trouble - validation should ensure the product meets requirements for its specific intended use which is basically business requirement (does it work? can I control the lights from the UI?) but testers will definitely work with the functional spec, making sure the checkboxes are there, working, labelled, etc. They are basically checking whether the requirements in functional spec were met in the final product, isn't that verification? (should not be, lets stick to ISO 12207 that only validation is the actual testing)


答:
In class Activity implement Comparable interface, overwriting compareTo() method.

There you can write the logic to indicate when exactly an activity is less than or greater ( orderwise ) than other.

Then let java collections API sort the collection.

As you can see there's not need of two lists, one for unused and other for used activities, since the order will garantee that after all new activities, used ones according to their frequency of use will be selected.

Title: "Best fit" to avoid reuse of object instances in a collection

Body:
Imagine I have a collection of object instances which represent activities for a user to undertake.  Dependent on user attributes, I have to randomly select instances to present activities to the user.

For some users, I need to present more activities to them than there are available activities in which case, I want to use the following algorithm.

If all available activities have already been presented to the user, then re-select a "used" activity, selecting the earliest presented activity ordered by frequency of use.  In other words, try to reduce repetition and where repetition is unavoidable, use the instances which have been repeated less often and were presented furthest back in time.

Before I go on to code that algorithm, I wondered if there is some existing pattern I can re-use?

[EDIT]  "Furthest back in time" is not relevant as I will pass the algorithm an ordered collection of used instances where the first entry is the first presented.


问:
easiest way for push notifications
I wanted to implement real time push notification to one of the apps written in RoR. I don't have any experience with nodejs, nowjs, express or socketio.

What would be the easiest way to implement the realtime push notification system?

答:
I've seen a port of Socket.IO on github (link). I guess you can use it.

Socket.IO is the easiest way to do a realtime push app, for that it abstracts you from the transport mechanism being used for the push.(for more information see the link).

The Advantages of using Socket.IO is that you don't need to be bothered about the underlying transport being used. The documentation is very simple to follow and yet, is very detailed.

Title: easiest way for push notifications


答: If you are using .Net Framework for this solution, I would suggest using External RuleSet Toolkit Sample from Windows Workflow Foundation. It has rule chaining and a nice redistributable rule editor GUI.</p>

Title: Designing a Business Rule Engine


答:
The difference between verification and validation inevitably becomes ridiculously subtle when pushed. Building the right thing and building it right are inextricably joined at the hips. Our group eventually became so tired of those verification versus validation ontology wars that we banned them. We still do verification and validation, but not as distinct processes. What we do instead are inspections of various kinds (e.g., code walkthroughs), analyses of various sorts (e.g., traceability), tests (lots and lots of tests), and metrics (lots of them, too). The distinction here is fairly clear, and there are no more ontology wars.

Choose distinctions that are easy to distinguish. Verification versus validation too often are not easily distinguished.


答:
You don't want to build your own unless there are very specific requirements that cannot be implemented in the custom solution... however, I can't imagine anyone sensible wanting to use Sharepoint!

there are plenty of OSS tools available (google for Nuxeo or Alfresco) and point them at the marketing web pages for these tools. then explain that development for these tools would be simpler and more cost effective, and that they are free (hmm, maybe explain that you pay only for support... sounds better than way). Alternatively, explain that when the Whitehouse wanted a CRM system, they went with Drupal, a few modules to that should allow you to get a fully customised version that does everything you want.

As for the Microsoft branding... draw up the cost of licences (plus CALs where appropriate) and make it come out of their budget.

Title: How can I get non-programmer colleagues on board with bespoke software rather than Dynamics CRM + Sharepoint?

Body:
I am working with a company which designs and builds one-off machines. They have been 'dabbling' with hosted Dynamics CRM and Sharepoint (on different servers!) in an attempt to centralise their data and help colleagues collaborate more effectively across projects. They haven't used either system to their potential.

Now we are looking at the engineering department who already use a form of version control software for the various CAD files (Autodesk Vault) however it is becoming increasingly necessary to implement more of a generic file version control system as they use many more files than can be managed in Vault (sometimes just photos or scans of paper documents), hence why they were looking at using Sharepoint.

However... as the 'programmer' of the bunch, I can see several scenarios which don't seem to fit well with the Dynamics + Sharepoint approach; simple reports based on cross-table queries, exporting certain metrics as a spreadsheet, defining project hierarchies and many-many relationships, and as such I have been pushing for an in-house developed 'ECM' / 'ERP' software package (perhaps in .NET or php).

Some colleagues seem to attach a greater value to the MS software (perhaps becuase it has a logo!) but don't see that it's just a framework, not a solution.

Can anyone provide a good example of when custom software would actually be better than using Dynamics + Sharepoint and how do I relate that to non-technical staff?


问:
Why do Windows commands allow `-` and `/` switches?
```<code>> shutdown /?
> Usage: shutdown [/i | /l | /s | /r | /g | /a | /p | /h | /e | /o] [/hybrid] [/f]
</code>```

The windows cmd.exe command shutdown only documents forward slash / switches, but it accepts dash - switches as well. For instance, both work:

```<code>shutdown /s /t 0
shutdown -s -t 0
</code>```

When was this added and why?

答: I would venture that multiple escape characters are supported for switches so that users that are used to a particular escape character can still use the application from the command-line.</p>


问:
Use an else after exception (or not)
Consider this bit of code:

```<code>if (x == 1)
{
  throw "no good; aborting" ;
}

[... more code ...]
</code>```

Now consider this code:

```<code>if (x == 1)
{
  throw "no good; aborting" ;
}
else
{
  [... more code ...]
}
</code>```

The two cases work exactly the same way. The first case has the advantage that you don't have to "encase" the rest of the code in an else. The second has the advantage of following the practice of explicitly having an else for every if.

Can anyone provide any solid arguments in favor of one over the other?

答:
You should not add else after if branches that break control flow unconditionally, such as ones containing a throw or a return. This would improve readability of your program by removing the unnecessary level of nesting introduced by the else branch.

What looks more or less OK with a single throw becomes truly ugly when several throws in a row get involded:

```<code>void myMethod(int arg1, int arg2, int arg3) {
    // This is demonstrably ugly - do not code like that!
    if (!isValid(arg1)) {
        throw new ArgumentException("arg1 is invalid");
    } else {
        if (!isValid(arg2)) {
            throw new ArgumentException("arg2 is invalid");
        } else {
            if (!isValid(arg3)) {
                throw new ArgumentException("arg3 is invalid");
            } else {
                // The useful code starts here
            }
        }
    }
}
</code>```

This snippet does the same thing, but it looks much better:

```<code>void myMethod(int arg1, int arg2, int arg3) {
    if (!isValid(arg1)) {
        throw new ArgumentException("arg1 is invalid");
    }
    if (!isValid(arg2)) {
        throw new ArgumentException("arg2 is invalid");
    }
    if (!isValid(arg3)) {
        throw new ArgumentException("arg3 is invalid");
    }
    // The useful code starts here
}
</code>```

Title: Use an else after exception (or not)

Body:
You should not add else after if branches that break control flow unconditionally, such as ones containing a throw or a return. This would improve readability of your program by removing the unnecessary level of nesting introduced by the else branch.

What looks more or less OK with a single throw becomes truly ugly when several throws in a row get involded:

void myMethod(int arg1, int arg2, int arg3) {
    // This is demonstrably ugly - do not code like that!
    if (!isValid(arg1)) {
        throw new ArgumentException("arg1 is invalid");
    } else {
        if (!isValid(arg2)) {
            throw new ArgumentException("arg2 is invalid");
        } else {
            if (!isValid(arg3)) {
                throw new ArgumentException("arg3 is invalid");
            } else {
                // The useful code starts here
            }
        }
    }
}

This snippet does the same thing, but it looks much better:

void myMethod(int arg1, int arg2, int arg3) {
    if (!isValid(arg1)) {
        throw new ArgumentException("arg1 is invalid");
    }
    if (!isValid(arg2)) {
        throw new ArgumentException("arg2 is invalid");
    }
    if (!isValid(arg3)) {
        throw new ArgumentException("arg3 is invalid");
    }
    // The useful code starts here
}


答:
I would call the "explicit else" practice you refer to as an anti-pattern, as it obscures the fact that there is no special-case code as an else to your if.

Readability/maintainability is generally improved when you mostly have nothing but necessary code-flow constructs, and you minimize them. This means redundant elses and if's which will add a scope to an entire function make following and maintaining it more difficult.

Say for example you have this function:

```<code>public void ConfigureOblogon(Oblogon oblogonToConfigure)
{
    if (_validColors.Contains(oblogonToConfigure.Color))
    {
        oblogonToConfigure.ColorIndex = _validColors.IndexOf(oblogonToConfigure.Color);
    }
    else
    {
        oblogonToConfigure.Color = _validColors[0];
        oblogonToConfigure.ColorIndex = 0;
    }
}
</code>```

Now the requirement comes in that during configuration you should also specify the oblogon's type/type index, there are multiple scopes which someone could place that code and end up with invalid code i.e.

```<code>public void ConfigureOblogon(Oblogon oblogonToConfigure)
{
    if (!_validOblogons.Contains(oblogonToConfigure.Type))
    {
        oblogonToConfigure.Type = _validOblogons[0];
        oblogonToConfigure.TypeIndex = 0;
        if (_validColors.Contains(oblogonToConfigure.Color))
        {
            oblogonToConfigure.ColorIndex = _validColors.IndexOf(oblogonToConfigure.Color);
        }
        else
        {
            oblogonToConfigure.Color = _validColors[0];
            oblogonToConfigure.ColorIndex = 0;
        }
    }
    else
    {
        oblogonToConfigure.TypeIndex = _validOblogons.IndexOf(oblogonToConfigure.Type);
    }
}
</code>```

Compare this to if the original code were written with minimal control flow constructs necessary and minimized ones at that.

```<code>public void ConfigureOblogon(Oblogon oblogonToConfigure)
{
    if (!_validColors.Contains(oblogonToConfigure.Color))
    {
        oblogonToConfigure.Color = _validColors[0];
    }

    oblogonToConfigure.ColorIndex = _validColors.IndexOf(oblogonToConfigure.Color);
}
</code>```

It would now be far more difficult to accidentally put something in the wrong scope or end up bloating scopes causing duplication in the long term growth and maintenance of this function. Plus it's obvious what the possible flows through this function are so readability is enhanced.

I know, the example's a bit contrived, but I have many times seen

```<code>SomeFunction()
{
    if (isvalid)
    {
        /* ENTIRE FUNCTION */
    }
    /* Nothing should go here but something does on accident, and an invalid scenario is created. */
}
</code>```

So formalizing those rules about control-flow constructs I think may help folks develop the intuition necessary to smell something when they start writing code like that. Then they will start to write..

```<code>SomeFunction()
{
    if (!isvalid)
    {
        /* Nothing should go here, and it's so small no one will likely accidentally put something here */
        return;
    }

    /* ENTIRE FUNCTION */
}
</code>```

Title: Use an else after exception (or not)

Body:
Consider this bit of code:

```<code>if (x == 1)
{
  throw "no good; aborting" ;
}

[... more code ...]
</code>```

Now consider this code:

```<code>if (x == 1)
{
  throw "no good; aborting" ;
}
else
{
  [... more code ...]
}
</code>```

The two cases work exactly the same way. The first case has the advantage that you don't have to "encase" the rest of the code in an else. The second has the advantage of following the practice of explicitly having an else for every if.

Can anyone provide any solid arguments in favor of one over the other?

Body:
I would call the "explicit else" practice you refer to as an anti-pattern, as it obscures the fact that there is no special-case code as an else to your if.

Readability/maintainability is generally improved when you mostly have nothing but necessary code-flow constructs, and you minimize them. This means redundant elses and if's which will add a scope to an entire function make following and maintaining it more difficult.

Say for example you have this function:

public void ConfigureOblogon(Oblogon oblogonToConfigure)
{
    if (_validColors.Contains(oblogonToConfigure.Color))
    {
        oblogonToConfigure.ColorIndex = _validColors.IndexOf(oblogonToConfigure.Color);
    }
    else
    {
        oblogonToConfigure.Color = _validColors[0];
        oblogonToConfigure.ColorIndex = 0;
    }
}

Now the requirement comes in that during configuration you should also specify the oblogon's type/type index, there are multiple scopes which someone could place that code and end up with invalid code i.e.

public void ConfigureOblogon(Oblogon oblogonToConfigure)
{
    if (!_validOblogons.Contains(oblogonToConfigure.Type))
    {
        oblogonToConfigure.Type = _validOblogons[0];
        oblogonToConfigure.TypeIndex = 0;
        if (_validColors.Contains(oblogonToConfigure.Color))
        {
            oblogonToConfigure.ColorIndex = _validColors.IndexOf(oblogonToConfigure.Color);
        }
        else
        {
            oblogonToConfigure.Color = _validColors[0];
            oblogonToConfigure.ColorIndex = 0;
        }
    }
    else
    {
        oblogonToConfigure.TypeIndex = _validOblogons.IndexOf(oblogonToConfigure.Type);
    }
}

Compare this to if the original code were written with minimal control flow constructs necessary and minimized ones at that.

public void ConfigureOblogon(Oblogon oblogonToConfigure)
{
    if (!_validColors.Contains(oblogonToConfigure.Color))
    {
        oblogonToConfigure.Color = _validColors[0];
    }

    oblogonToConfigure.ColorIndex = _validColors.IndexOf(oblogonToConfigure.Color);
}

It would now be far more difficult to accidentally put something in the wrong scope or end up bloating scopes causing duplication in the long term growth and maintenance of this function. Plus it's obvious what the possible flows through this function are so readability is enhanced.

I know, the example's a bit contrived, but I have many times seen

SomeFunction()
{
    if (isvalid)
    {
        /* ENTIRE FUNCTION */
    }
    /* Nothing should go here but something does on accident, and an invalid scenario is created. */
}

So formalizing those rules about control-flow constructs I think may help folks develop the intuition necessary to smell something when they start writing code like that. Then they will start to write..

SomeFunction()
{
    if (!isvalid)
    {
        /* Nothing should go here, and it's so small no one will likely accidentally put something here */
        return;
    }

    /* ENTIRE FUNCTION */
}


问:
What kind of image should be used in a web page?
I have a site that will have lots of images of large size. What is the best format that I should choose for displaying these images?

I need the website to load fast. I am jumbled with different formats of images like jpeg, png, gif, bmp, etc. Which to use in this case and why ?

答:
In short, consider small thumbnail images as .png formatted wherever you list them in list. And spend some time on caching and its configurations.

In combination with this thumbnail images, have your large-sized images as png/jpeg. Generically speaking displaying list of all full-sized images will slow down your page load time.

However, having a wise caching configuration of the static web content through web-server is very important for performance, and it is a good way to go.


问:
How to apply verification and validation on the following example
I have been following verification and validation questions here with my colleagues, yet we are unable to see the slight differences, probably caused by language barrier in technical English.

An example:

Requirement specification

User wants to control the lights in 4 rooms by remote command sent from the UI for each room separately.

Functional specification

The UI will contain 4 checkboxes labelled according to rooms they control.

When a checkbox is checked, the signal is sent to corresponding light. A green dot appears next to the checkbox

When a checkbox is unchecked, the signal (turn off) is sent to corresponding light. A red dot appears next to the checkbox.

Let me start with what I learned here:

Verification, according to many great answers here, ensures that product reflects specified requirements - as functional spec is done by a producer based on requirements from customer, this one will be verified for completeness, correctness). Then design document will be checked against functional spec (it should design 4 checkboxes..), and the source code against design (is there a code for 4 checkboxes, functions to send the signals etc. - is it traceable to requirements).

Okay, product is built and we need to test it, validate. Here comes our understanding trouble - validation should ensure the product meets requirements for its specific intended use which is basically business requirement (does it work? can I control the lights from the UI?) but testers will definitely work with the functional spec, making sure the checkboxes are there, working, labelled, etc. They are basically checking whether the requirements in functional spec were met in the final product, isn't that verification? (should not be, lets stick to ISO 12207 that only validation is the actual testing)

答:
Verification: Did we build what the customer asked for?

Validation: Does what we built work?

Edit For Clarification:

"yet testers use functional spec for their test cases"

Who cares if the testers use the functional spec they are still performing both Verification and Validation based on my original statements.

There are supposed to be three switches and two buttons on this wall. (verification)

The switches are supposed to be equi-distant apart and 48 inches off the floor (verification)

The buttons are supposed to be on either side of the switches (verification)

The left button is supposed to be labeled "Left" (verification)

The right button is supposed to be labeled "Right" (verification)

If I click the left button on, does it disable the far right switch? (validation)

If I click the left buton off, does it enable the far right switch? (validation)

If I click the right button on, does it disable the far left switch? (validation)

If I click the right button off, does it enable the far left switch? (validation)

If I click both buttons on does only the middle switch work? (validation)


答:
Use JPEG for images with gradients (like photographs) and PNGs for images with flat colors and straight lines (like screenshots). Use GIF only if you need animations for some reason. Don't use BMP.

JPEG is lossy, so you get artifacts if you try to use it on screenshots.

PNG is lossless, so it looks great with screenshots, but the filesizes get really big for photographs.

GIF is kind of obsolete, PNG is better.

BMP is not a standard web image format.

Title: What kind of image should be used in a web page?

Body:
I have a site that will have lots of images of large size. What is the best format that I should choose for displaying these images?

I need the website to load fast. I am jumbled with different formats of images like jpeg, png, gif, bmp, etc. Which to use in this case and why ?


问:
What methodology to use for planning/developing a Language conversion project?
I am trying to help my friend by creating a part of his on-going project.

What I'm going to do is create a Java parser to break up the Java code into operators, parameters etc to build XML representation.

Next I want to create a code generator to convert the parsed java code to XML conforming to the schema I've created.

Finally I want to use an XML style-sheet to transform the XML into another programming language type.

Basically I just wanted some advice on which methodology/model I should use for planning and developing this project. Is there some benefit to using Agile etc for instance?

答:
Since you asked for methodology, I can give you one tip on this kind of programming project.  Use unit tests.  A LOT of unit tests.  You should be spending several man-months writing unit tests.

What I'm going to do is create a Java parser to break up the Java code
  into operators, parameters etc to build XML representation.

On its own, this represents at least one question on programmers.SE.

Next I want to create a code generator to convert the parsed java code
  to XML conforming to the schema I've created.

On its own, this represents at least one question on programmers.SE.

Finally I want to use an XML style-sheet to transform the XML into
  another programming language type.

This is a book, not a programmers.SE question.


答:
Speaking as a SharePoint developer, yes, there are times that one would not want to to implement your solution in SharePoint. Some things it just doesn't fit with very well, which is usually a question of information architecture and/or scale.

Further, SharePoint can be too big and generalised for some projects. For example, if you only need a Web Content Management system there are simpler, lighter ones that do the job of WCM better. There are better blogs, discussion forums, wikis, etc. - but few products have as many features as SharePoint. If you find you aren't using lots of features of SharePoint in your dabbling, well, maybe there is a case for something smaller/simpler.

However, you've not really described anything that isn't achievable in SharePoint.

Simple reports based on cross table queries - DataView web part. Or write you own - CAML can do joins.

Exporting lists as Excel spreadsheets - built in.

Many to many relationships - depends on the entities involved, but lookup fields can support that.

Don't discount the things that SharePoint does give that are often overlooked - the Office integration (though Outlook integration is notably poor), search, document retention plans, the default list forms, etc.. It is a framework - but it gives you quite a lot. And it can be a bugger to make it do what you want, sometimes.

I would recommend (like all good consultants!) that if you're not certain, push for a pilot project. It sounds like you might already be doing that - the dabbling - so consider what things haven't been tried yet, maybe give those a try. You know your needs, so try to find something concrete.

It may be worth factoring in the SharePoint Devs are normally quite expensive - there is a shortage of good ones - and that I reckon it takes a good ASP.NET developer 6-12 months to become proficient with SharePoint. Your organisation may have skills more aligned with other technologies, in which case you need ask if that investment is worthwhile.

Otherwise, without know more about what you're trying to do, it's hard to offer more detailed advice.


问:
Why don't research papers that mention custom software release the source code?
Is there a reason why the source code of software mentioned in research papers is not released? I understand that research papers are more about the general idea of accomplishing something than implementation details, but I don't get why they don't release the code.

For example, this paper ends with:

Results

The human line drawing system is implemented through the Qt framework in C++ using OpenGL, and runs on a 2.00 GHz Intel dual core processor workstation without any additional hardware assistance. We can interactively draw lines while the system synthesizes the new path and texture.

Do they keep the source code closed intentionally because of a monetization they intend to make with it, or because of copyright ?

答:
The above answers miss a few practical reasons which frequently arise in Computer Graphics (the area in which the paper mentioned by the author was published). Code Release varies greatly between fields in CS - for example in Machine Learning, code is usually published. In Human Computer Interaction, code is almost never published.

I have released quite a bit of code in Computer Graphics, and while I do think authors should release their code, there are many simple, non-conspiracy-theory reasons why they don't. For example

1) Most Computer Graphics research projects involve collaboration between multiple researchers, often at different institutions, each providing some piece of the puzzle (ie algorithms, libraries, etc). To release working code, all researchers have to agree. This is rarely a simple discussion and usually it is easier to avoid the issue.

2) Often the code for a single paper is embedded in a larger codebase being developed within a lab. That codebase will contain other unpublished work. Separating out the code for a single project is a lot of work, often with no immediate benefit to the people who have to do this work (see incentive below).

3) Universities often have IP rights to the code. Hence, it is necessary to contact an "innovations office" who will make your life endlessly difficult, wanting you to document the "invention" so they can patent it, etc, before you open-source it. In some cases the university can even deny the permission to release source (this varies between institutions, and is greatly complicated by (1) )

4) Lots of Computer Graphics research is done by Corporations. In that case the authors do not own the code either, and have to get permission from Lawyers to release the code. Lawyers have little to no incentive to say yes.

5) There is no incentive to publish code. Most Computer Graphics research code is never used by anyone else. Even if it is, for general-purpose code you usually just get an acknowledgement (worthless in terms of your CV). If you are lucky you will get a citation. Hiring committees and Grant agencies generally don't care one bit if you released your code. So, time spent prepping code for release is time wasted that could have been spent on another paper. (There are people actively trying to change this in Computer Graphics).

6) There are incentives to not publish code. Code can sometimes turn into startup companies, be licensed to existing companies, etc. This funds future research. We all gotta eat.