答:
I would say that the answer to both parts of your question is no: this calculator's commands aren't like assembly language, and programming this calculator is different from programming in assembly language.

The "language" this calculator is programmed in is fairly low level, but it still represents an abstraction on top of lower-level constructs that aren't visible to you as the programmer. I'm guessing a bit, but from your description, and from looking at the keyboard (and comparing it to similar-looking calculators from Hewlett Packard or Texas Instruments from the late 1970s and early 1980s) I'd say that each program "step" not only could be a simple operation like "add" or "swap X & Y" but also more complex operations like trigonometry, exponentiation, logarithms, etc. Each of these steps is probably implemented as a internal microcoded routine. That microcode probably is programmed in assembly language, but I don't think it's visible to ordinary calculator programming at the level you've described.

As others have described, assembly language usually is in very close (if not 1:1) correspondence with the facilities of the underlying machine. I'd say that assembly language programming includes the following characteristics that are probably not present in programming this calculator.

Operations include lower level level operations such as bitwise AND, OR, XOR, shifting; integer and (maybe) floating point arithmetic, on a variety of data sizes (e.g. single or double precision); load/store of a variety of sizes (byte, halfword, word, etc.).

Higher level operations (trig, logarithms) are usually subroutine calls, not instructions. There are some exceptions, such as the DEC VAX which had a polynomial-evaluation instruction. [Edit: OP pointed out that x87 also has trig functions.]

The addressing scheme of the machine is exposed. If the address space is segmented, you have to load a base address into a register and then address code or data relative to that register. Even with a flat address space, you're aware of addresses and address arithmetic. Usually assemblers will allow programmers to use labels to denote addresses. But if an address is in a different segment you may have to load a segment register before you can get to it.

Memory alignment is exposed. For example, on many machines a 4-byte word can only be loaded from or stored to addresses that are multiples of 4 bytes.

Data representation is exposed. Usually assemblers provide some way to specify numeric data in hex, octal, decimal, floating point, and occasionally character data.

Specialization of registers is exposed. Some architectures allow integer and address operations in some registers, but floating point only in others, or allow addressing only relative to certain registers. Sometimes there are specialized registers such as those with condition or status bits that cannot be used for addressing or arithmetic.

Subroutine calling conventions are exposed. Arguments and return values may be passed in registers, or pushed to and popped from a stack. (This stack is usually a region of memory addressed by a special stack pointer register, not a fixed set like X Y Z and T.)

You may need to be conscious of how to interact with the OS, or if there isn't one, how to deal with low-level hardware facilities. With an OS you have to load arguments into registers (or the stack) and trap into the kernel. Without an OS you probably have to deal with interrupts and timers.

My recollection of assembly programming is that it is very, very painful. I think that programming this calculator is easy and fun by comparison. (Sorry.)

Title: Is this an assembly language?


问:
Is this an assembly language?
In my childhood I used to program on an MK-61 Soviet calculator. It had four operating registers (X, Y, Z, T) and 15 storage registers. A program could have 105 steps.

As I recall it, it had commands like:

Swap X and Y registers

Shift registers (Z to T, Y to Z, X to Y)

Copy from storage register (1..15) to X

Copy from X to storage register (1..15)

If X < 0 then go to program step ##

Perform operation (+, -, *, /) using X and Y values and put result to X

Is this command set an assembly language? Did I have a basic idea of assembly languages by using this device?

It turns out it is something called "keystroke programming".

Funny fact: a similar calculator (like this one, but with energy independent memory) was used as a back-up hardware for space mission trajectory calculations in 1988. :-)

答:
I would argue you're closer to a BASIC assembly language hybrid but it really depends on the underlying CPU and architecture.  There doesn't need to be direct memory access if you have no true RAM to speak of. Floating point operations also not need be present without a FPU.

I think a simple test would be an addition operation on a floating point number and an integer.  Most higher level programming languages would accept ADD 2.5, 7 and return 9.5.  Assembly languages however would differ the output based upon the called instruction and depending on the underlying number representation in binary.   Most assembly languages require a different instruction to be used based on using floating point vs integer operations.  An exception to this might be some kind of fixed point format.

ContentLicense: CC BY-SA 3.0

Title: Is this an assembly language?


问:
What should be in a coding standard?
What should be in a good (read:useful) coding standard?

Things the code should have.

Things the code shouldn't have.

Should the coding standard include definitions of things the language, compiler, or code formatter enforces?

What about metrics like cyclomatic complexity, lines per file, etc?

答:
Inspiring, pragmatic ideas that make people think, rather than negative restrictions which stop people thinking.

Otherwise, you get code monkeys who are afraid to go after the bananas.

ContentLicense: CC BY-SA 2.5

Title: What should be in a coding standard?


问:
How many make threads to use?
When I (re-)build large systems on a desktop/laptop computer, I tell make to use more than one thread to speed up the compilation speed, like this:

```<code>$ make -j$[ $K * $C ]
</code>```

Where $C is supposed to indicate the number of cores (which we can assume to be a number with one digit) the machine has, while $K is something I vary from 2 to 4, depending on my mood.

So, for example, I might say make -j12 if I have 4 cores, indicating to make to use up to 12 threads.

My rationale is, that if I only use $C threads, cores will be idle while processes are busy fetching data from the drives. But if I do not limit the number of threads (i.e. make -j) I run the risk to waste time switching contexts, run out of memory, or worse. Let's assume the machine has $M gigs of memory (where $M is in the order of 10).

So I was wondering if there is an established strategy to choose the most efficient number of threads to run.

答:
I'm running Gentoo Linux (source-based distribution) and from my experience i can say that (with more or less recent hardware) n*2 + x is the best value. Let me explain this:

n*2: Even slower CPU's have enough power to run 2 tasks at a time. most compile tasks are completed very fast.

+x this number depends on your system (mainly memory and disk). If you have enough RAM and a fast disk, set x=n. However, this depends on the source code (Open Office, i'm looking at you!) and the used language (compiling C/C++ is very memory intensive).

However, you have to run some tests with some -j values to get the best number. Also, try to parallelize other steps of the build process: unpacking, running configure and so on.

Title: How many make threads to use?


问:
Should an API platform enforce only receiving JSON requests?
I am building an API platform.

I have already ensured that the platform always returns JSON responses.

My question is

Should my API platform enforce the rule that all requests must be JSON?
What are the benefits of making all requests to be JSON?

I understand the benefits of making all responses to be JSON as this means consistency for the client apps using the API.

I fail to see the benefits of making all requests to be JSON as well.

I am asking this because GitHub API v3 appears to be enforcing this rule.

My API platform will involve uploading of files in the requests. As far as I know, JSON requests does not work well with file uploads.

Or do I do a hybrid?

Enforce that anything NOT to do with file upload should send their requests as JSON?

And allow an exception for file upload?

答:
Your API needs to be able to understand the request.

How can you do this if you accept random formats.

An API consists of the definition of the formats, acceptable values contained within and the sequence in which they are exchanged.

If you wish you can specify that your API also accepts XML requests, or perhaps plain url get requests.

GitHub has specified a JSON based API and quite rightly rejects any request that is not valid JSON.


答:
Make a choice what formats you want to support. Detect the content type using the request's Content-type header; if it doesn't match any of your supported types, reject the request with a 415 status code (or a more generic one, like 404 or 500, depending on whether you are willing to tell the client what went wrong or not). If it does match, at least verify that the request is well-formed before doing any processing.

If you control both the client and the server, or you are in a position to determine the protocol, then it doesn't make much sense to support more than one content type for your regular messages - just specify what you expect, and reject anything else.

Also, note that it is often easier to use regular POST data instead of JSON for the request: e.g. the jQuery Ajax API makes it super-straightforward, and many of the reasons for using JSON for the response (Same Origin Policy, structured data, easy and fast to parse in javascript) often just don't apply for the request.

Title: Should an API platform enforce only receiving JSON requests?

Body:
I am building an API platform.

I have already ensured that the platform always returns JSON responses.

My question is

Should my API platform enforce the rule that all requests must be JSON?
What are the benefits of making all requests to be JSON?

I understand the benefits of making all responses to be JSON as this means consistency for the client apps using the API.

I fail to see the benefits of making all requests to be JSON as well.

I am asking this because GitHub API v3 appears to be enforcing this rule.

My API platform will involve uploading of files in the requests. As far as I know, JSON requests does not work well with file uploads.

Or do I do a hybrid?

Enforce that anything NOT to do with file upload should send their requests as JSON?

And allow an exception for file upload?


问:
How does Github calculate language percentage in a repo?
I have a repo with Ruby and PHP code in it.

Github says my repo is 74.8% PHP and 25.2% Ruby

I do not understand how this can be. When I compare the 2 languages in my project:

```<code># Count how many files:

# Ruby
ls | grep ".*\.rb" | wc -l
# returns 10

#PHP
ls | grep ".*\.php" | wc -l
# returns 1

# Count how many lines, words, chars:

# Ruby
cat *.rb | wc
# returns 229, 812, 5303

# PHP
cat *.php | wc
# returns 102, 473, 2760
</code>```

Ruby always seems to have more.

Am I missing something?

答:
github uses Linguist to detect languages in a project.

Linguist is open source. look into the source files and you'll find:

in /bin/linguist

```<code>repo.languages.sort_by { |_, size| size }.reverse.each do |language, size|
  percentage = ((size / repo.size.to_f) * 100).round
  puts "%-4s %s" % ["#{percentage}%", language]
end
</code>```

in /lib/linguist/file_blob.rb

```<code> # Public: Get byte size
 #
 # Returns an Integer.
 def size
   File.size(@path)
 end
</code>```

so it actually use file sizes to determine the language percentage.

also keep in mind that binary data, vendored files, generated files, and non-program files are excluded.

Body:
github uses Linguist to detect languages in a project.

Linguist is open source. look into the source files and you'll find:

in /bin/linguist

repo.languages.sort_by { |_, size| size }.reverse.each do |language, size|
  percentage = ((size / repo.size.to_f) * 100).round
  puts "%-4s %s" % ["#{percentage}%", language]
end

in /lib/linguist/file_blob.rb

 # Public: Get byte size
 #
 # Returns an Integer.
 def size
   File.size(@path)
 end

so it actually use file sizes to determine the language percentage.

also keep in mind that binary data, vendored files, generated files, and non-program files are excluded.


问:
Which is the correct licence?
So I found this very interesting library in Google Code site. It turns out it is advertised as "LGPL", which is good enough for me. However, in the README file of the library the author contradicts himself saying it is not available for commercial purposes.

I'm guessing that when you sign up to create your project in Google Code you can only choose open source licenses. Open source licenses allow selling software, offering commercial support, etc. So my guess is that either the author confused the word "commercial" with "proprietary", or that he just wanted a good place to host his software even violating GoogleCode standards...

The thing is, if I want to use the library, which licence should I consider the software to be under? I've already asked the author by email but he has not replied.

Thanks very much.

答:
The author has released the code under unclear licensing terms; you need a lawyer if you want anything conclusive (and even then, it may be so unclear that the case has to be presented to a judge or jury to really clear things up, which means a lawsuit, which means you can lose a truckload of money). It may be that restrictions from both licensing agreements apply, or it could be that you get to choose which one applies, or that one of them is void and the other applies, it may depend on how you acquire the code, etc. etc. Just too many uncertainties for a non-lawyer to oversee.

Legalities aside; in my experience, a project released under such vague circumstances is a big red flag: the maintainers are obviously unwilling to put even minimal care and effort into their licensing model (really, it's not hard at all - just find a good list of OSS licenses and pick the one that fits your philosophy), and it is quite likely that the rest of the project is comparably sloppy. Project maintainers that care about doing things the right way, having clean code and project structures, and making it ridiculously easy to use their work, tend to be equally religious about licensing. It doesn't have to be that way, but I've found it to be a quite accurate assessment most of the time.

Title: Which is the correct licence?


问:
Is C++.Net used extensively?
I am a C++ coder by tradition. Over the last 12 months or so I have been doing a lot of C#  coding, and have been pleasantly surprised by C#'s pragmatic approach (once I stopped trying to code it as if it was "C++ with garbage collection").

We have recently had some graduates in and when helping one of them I realised she was using .Net within C++. After asking her why, she said she had been "told to use C++ by her manager". Obvious communication problem aside, I assume she was using .Net because that's the only framework she's been exposed to.

I then came across an old project by a senior developer who also used C++ to drive a Forms front end. Now this would have been written around the time .Net first appeared, so I assume it was a learning exercise on his part to play around with .Net. It was only a small utility app.

Having had to do some minor modification in this app, it seemed to me that using C++ to drive .Net gives you the worst of both worlds. No garbage collection or memory safety, but no similarly no real speed/optimisation opportunities since you're dealing with a managed framework.

So my question is whether people do use C++ .Net for any large stand alone (ie non-plumbing) production code, and if so what are your reasons for doing so? I freely admit I have never delved deeply into the C++ .Net extensions so I may be doing it a disservice.

答:
C++.NET (or, precisely, C++/CLI) does have garbage collection, just like everything else that runs atop .NET. To achieve this while remaining compatible with C++ proper, it uses ^ syntax and gcnew for garbage-collected ('safe') pointers.

C++/CLI is considered an abomination by many, it's significantly more unpleasant to work with than either C# or C++ proper, and also more complicated than either (simply because it brings the complexity of C++ itself to the table and adds what it takes to work with .NET to the mix). Learning C# usually pays off even within the scope of a single medium-sized project. However, there is one thing it can do that neither C# nor native C++ can do: compile existing C++ against .NET and have it talk to other .NET components.

Consequently, it doesn't make much sense to use C++/CLI for a from-scratch project - anything .NET related that can be done with it can also be done in C#, with much nicer syntax and the added safety of not exposing raw pointers by default. Its most prominent raison-d'etre is porting existing codebases to .NET. A company that decides to start using .NET, but unwilling (or unable due to resource and time constraints) to rewrite every piece of software they have produced so far, can use C++/CLI to keep using their existing codebase with only minimal changes, and then rewrite components of their system in C# one by one. At least that's the theory; I have never seen it done in practice myself, so I can't tell how well it works.

Also note that C# itself can interface with native libraries, so even if you have to use existing C++ codebases, you don't necessarily have to recompile them against .NET: often, interfacing with them through COM or P/Invoke is the better solution.

Title: Is C++.Net used extensively?


问:
What's the proper way to check commit data in Git?
My goal is to check commit data that don't meet certain requirements and then reject either the commit being created or pushed to the remote repository.

The problem of doing a pre-commit hook is that it's hard to deploy to many people who have to manually update their pre-commit hook file. As well, Git does not allow you to have submodules in the .git folder which would've been very easy for deployment yet alas.

The other option I see is doing the checking in I believe the update hook on the remote side, which will check each commit being pushed by a dev and reject the push if any of the commits fail the tests.

Does anyone have any insight on this problem? And if so, could you provide or point me towards  an example update hook script? I'm a little confused as to how it works.

答:
As you already pointed out, doing this on the client, while technically possible, is probably not practical. Also, many git users commit interim work, so having draconian checks on every commit is counterproductive.

The standard solution would be a server-side hook. You'd probably set up a pre-receive hook, which runs every time a push comes in, and which can reject the push if it wants to.  The rest depends on the exact checks you want to make.

This is explained in Pro Git, chapter 7.3 Customizing Git - Git Hooks.


答:
A coding standard for a group should include the compiler options for warnings and errors that must be addressed.

Programmers should be free to increase warnings for their own code, but there must be a baseline so that reading and working with someone else's code doesn't clutter up the output you get from the compiler.

Such a standard would also have to address how programmers can disable such warnings case-by-case, should there be an exceptional piece of code that won't otherwise conform.

Title: What should be in a coding standard?

Body:
What should be in a good (read:useful) coding standard?

Things the code should have.

Things the code shouldn't have.

Should the coding standard include definitions of things the language, compiler, or code formatter enforces?

What about metrics like cyclomatic complexity, lines per file, etc?


答:
you must first figure out whether you don't want the unqualified code to be committed or to be pushed/published back to upstream.

in my opinion the later one is more feasible.

with a DVCS like git. you don't really want to control how every developer uses his local repository. and you can't really have control over that.

a pre-commit hook works well as basic validation and sanitization, if everyone involved embrace it voluntarily. we actually enforce that loosely in our company. however, it can always be skipped with git commit --no-verify.

server side hook, on the other hand, doesn't intervene a programmer's local workflow, and makes sure that others in the project base their work only on code that meets certain criteria. normally this is what people look for when they implement automatic checks.

this automatic validation isn't meant to replace quality control, i guess, which is usually achieved with code review or pair programming.

if you are familiar with github, you'd notice that "pull request" is yet another approach to this issue. many open source projects and companies use github's pull request for branch permission control and code review. but it needs human interaction, thus may not be what you're asking for.

Title: What's the proper way to check commit data in Git?

Body:
My goal is to check commit data that don't meet certain requirements and then reject either the commit being created or pushed to the remote repository.

The problem of doing a pre-commit hook is that it's hard to deploy to many people who have to manually update their pre-commit hook file. As well, Git does not allow you to have submodules in the .git folder which would've been very easy for deployment yet alas.

The other option I see is doing the checking in I believe the update hook on the remote side, which will check each commit being pushed by a dev and reject the push if any of the commits fail the tests.

Does anyone have any insight on this problem? And if so, could you provide or point me towards  an example update hook script? I'm a little confused as to how it works.


问:
How do I treat application aspects with regard to features and user stories?
When drawing up a backlog, I have several requirements that apply to a great many user stories, i.e. aspects of the application like error handling and feedback. How do I include these (without using an #include directive in each user story )? Should I treat error presentation as a feature, then have user stories for this feature like "system catches exception, and shows info to user"?</p>

答:
I believe solution is good separation of concerns. Things like error handling, logging, feedback and such should be handled globally with only one piece of code. Only requirements, that are different from this global behavior should be noted as either part of user stories, or in discussion about implementation of said user story.

So from project management side, there should be one User Story, that says "As a user I want to see error in a such a way, that allows me to report it to the administrator." or something like that. And this user story should apply as a global rule to all use cases.


答:
I think that also allowing normal HTTP formdata requests provides some practical advantages over a pure JSON API. You already mentioned uploading files, where using JSON is tricky at least; but also normal requests benefit in terms of simplicity.

HTTP already has two formats for parameter passing, why not use them?


问:
When designing a job queue, what should determine the scope of a job?
We've got a job queue system that'll cheerfully process any kind of job given to it. We intend to use it to process jobs that each contain 2 tasks:

Job (Pass information from one server to another)

Fetch task (get the data, slowly)

Send task (send the data, comparatively quickly)

The difficulty we're having is that we don't know whether to break the tasks into separate jobs, or process the job in one go.

Are there any best practices or useful references on this subject? Is there some obvious benefit to a method that we're missing?

So far we can see these benefits for each method:

Split

Job lease length reflects job length: Rather than total of two

Finer granularity on recovery: If we lose outgoing connectivity we can tell them all to retry

The starting state of the second task is saved to job history: Helps with debugging (although similar logging could be added in single task method)

Single

Single job to be scheduled: Less processing overhead

Data not stale on recovery: If the outgoing downtime is quite long, the pending Send jobs could be outdated

答:
From my point of view, splitting a job might be a better option. Yes it adds to complexity but has its own advantages as well. If u have a queue processing system then at some point of time you will have multiple jobs in queue which require scheduling for a better performance.

Single job systems usually have larger wait times for processes which arrive later in queue. You might have also to give priority to some jobs over another (prority scheduling). In short, scheduling is efficient if a job has sub-stages. As you mentioned, it also has better recovery model and states could be manipulated easily.


答:
IANAL

As far as I know the GPL and LGPL licenses are largely "take it or leave it" licenses, you can't change the license and still call it the GPL or LGPL. If you license something under the LGPL the author cannot then say you can't use it for commercial use. The GPL clearly states "You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee."

First of all check with the author if it is licensed under the LGPL (you don't mention a version number) or not, also ask him about the exceptions he is trying to make.

If the author still tries to claim both licensing under the LGPL and "not for commercial use" you may decide if you want to email GNU (originators of the GPL) and / or the Free Software Foundation. One or the other of these may choose the explain the realities of the LGPL to the author (or not).

Title: Which is the correct licence?

Body:
So I found this very interesting library in Google Code site. It turns out it is advertised as "LGPL", which is good enough for me. However, in the README file of the library the author contradicts himself saying it is not available for commercial purposes.

I'm guessing that when you sign up to create your project in Google Code you can only choose open source licenses. Open source licenses allow selling software, offering commercial support, etc. So my guess is that either the author confused the word "commercial" with "proprietary", or that he just wanted a good place to host his software even violating GoogleCode standards...

The thing is, if I want to use the library, which licence should I consider the software to be under? I've already asked the author by email but he has not replied.

Thanks very much.


答:
This is not an assembly language, this is a machine language.

Machine language is anything that physically means something to the machine.
In the case of pocket computers, it's key presses, encoded into numbers in the machine. You don't give more information about this Electronika MK61 machine, so I'll give the example of the TI-57: the machine language used the number of the key given as column in the tens and line in the units. So for example, a program that would increment the memory 8 would be:

```<code>33 8  57 1 58 23
</code>```

This is machine language: it's what's directly interpreted by the machine.

Assembly language would be the human readable text:

```<code>RCL 8
+
1
=
STO 8
</code>```

To transform this text into the sequence of machine codes, you would need an assembler, which may be a program, or a human who would translate that text into the sequence of numbers.

The confusion is often done, because there's often a quite direct translation from the assembly language to the machine language, but this is not always an entirely direct translation: macro assemblers have powerful macros that may do a lot of work in the assembler and generate a lot of machine language instructions from a single assembly instruction. The mere translation of symbolic addresses may involve changing the op-code of the branch instructions (for example, when switching from short relative addressing to long relative or absolute addressing), so it's not always as direct as you'd think.

Title: Is this an assembly language?

Body:
In my childhood I used to program on an MK-61 Soviet calculator. It had four operating registers (X, Y, Z, T) and 15 storage registers. A program could have 105 steps.

As I recall it, it had commands like:

Swap X and Y registers

Shift registers (Z to T, Y to Z, X to Y)

Copy from storage register (1..15) to X

Copy from X to storage register (1..15)

If X < 0 then go to program step ##

Perform operation (+, -, *, /) using X and Y values and put result to X

Is this command set an assembly language? Did I have a basic idea of assembly languages by using this device?

It turns out it is something called "keystroke programming".

Funny fact: a similar calculator (like this one, but with energy independent memory) was used as a back-up hardware for space mission trajectory calculations in 1988. :-)

Body:
This is not an assembly language, this is a machine language.

Machine language is anything that physically means something to the machine.
In the case of pocket computers, it's key presses, encoded into numbers in the machine. You don't give more information about this Electronika MK61 machine, so I'll give the example of the TI-57: the machine language used the number of the key given as column in the tens and line in the units. So for example, a program that would increment the memory 8 would be:

33 8  57 1 58 23

This is machine language: it's what's directly interpreted by the machine.

Assembly language would be the human readable text:

RCL 8
+
1
=
STO 8

To transform this text into the sequence of machine codes, you would need an assembler, which may be a program, or a human who would translate that text into the sequence of numbers.

The confusion is often done, because there's often a quite direct translation from the assembly language to the machine language, but this is not always an entirely direct translation: macro assemblers have powerful macros that may do a lot of work in the assembler and generate a lot of machine language instructions from a single assembly instruction. The mere translation of symbolic addresses may involve changing the op-code of the branch instructions (for example, when switching from short relative addressing to long relative or absolute addressing), so it's not always as direct as you'd think.


答: Self documenting code (comments, variable names, function names, etc.)</p>

Title: What should be in a coding standard?


问:
How to mix different styles of programming on several languages?
I know that Senior Developer doesn't use only one language and only one platform or IDE.

Can you advise how to mix different styles of programming to make efficient code?

For example, best mixing is Perl + Objective-C.

$ObjectiveCLongNameOfVariablesAndMethods are worst for Perl-style, but good for iOS-team.

[self method:[[NSArray alloc] initWithobjects:[hash objectForKey:name]]] style is weird for an eye, but not for perl simple-looking arrays and hashes and autovivification.

Also, i try to mixing SAS + Objective-C style, but here i have a trouble. SAS doesn't support names long names, only 32 symbols. So, big trouble to naming variables.

Another difficulty is features of current language. So, if I can't use current language for a task, that it can solve 'like a BOSS', I become angry and see weird code. Using libraries is good, but it makes code not natural, 'cause eating soup with fork is strange'.

And at the end: where can I trust compiler and interpreter of language? So, C++-style is best for pointers (you make destructors, constructors, etc.), but many languages now support mechanism like ARC in Objective-C or don't use pointers (like C#).

答:
Keep to the conventions of the language being used.

When using Objective C, keep Objective C conventions in those parts of the code. When using Perl keep to Perl conventions... etc.. etc... etc...

This keeps things more compartmentalized - when you move to a different language it is easier to see that you have moved to it, and others that are used to the language conventions would also have an easier time.

Don't try to get one set of conventions for all the languages you use - this will just make things harder in the long run.


问:
Is code reviewing good practice?
When the company I work in hired new managers, they offered us to overview someone's code on every meeting. We have meetings every two weeks, so each time one of developers was to show his/her code on the projector, and others were going to discuss it.

I thought this would be great: each developer would be more careful when writing code and we could share our experience better. But somehow we forgot about this and the offer just remained an offer.

What are the benefits of this and are there any drawbacks?

答:
Code reviews are a great practice.

It is probably the best way to learn from mistakes and to see how certain problems are solved by others. It is also one of the best way to maintain quality in a code base.

Code reviews happen in many companies, though it is difficult to say that there is a specific process that they all follow.

In more formal code review, a senior (or several seniors) will sit together with a developer to review their code, offering suggestions and teaching at the same time.

Additional benefits to code reviews (as commented on for this question), include:

A great way to teach and learn

They are one of the best ways to improve and keep the consistency of a code base (style and idioms)

They help ensure all team members understand the style and idioms used in the project and how to use them

Code reviews will speed up development as they catch bugs and design flaws early (so, though they may slow down initial development, they pay dividends in later development cycles)

There is tooling support that helps streamline the code review process

Title: Is code reviewing good practice?


答:
Code reviews are very useful tool for learning, especially when you have new team member on-board. Well, it is also known as peer review process :)

There are different types of code reviews:

Over-the-shoulder – where one developer looks over the code author's shoulder as the latter walks through the code.

Email pass-around – Source code management system emails code to reviewers automatically after checkin is made. Extract from comment: Having failed at convincing management to allocate time for any sort of formal code review I've taken to looking over my coworkers changes whenever I pull new revisions down from source control using the history/diff tools built into Tortise

Pair Programming – Two authors develop code together at the same workstation, such is common in Extreme Programming.

Tool-assisted code review – Authors and reviewers use specialized tools designed for peer code review.

There is only one associated disadvantage where formal code reviews have require a considerable investment in preparation for the review event and execution time.

More references are listed below (for more deep dive readings)

MSDN - Code Review

Find and Fix Vulnerabilities Before Your Application Ships

Wiki link

Title: Is code reviewing good practice?

Body:
When the company I work in hired new managers, they offered us to overview someone's code on every meeting. We have meetings every two weeks, so each time one of developers was to show his/her code on the projector, and others were going to discuss it.

I thought this would be great: each developer would be more careful when writing code and we could share our experience better. But somehow we forgot about this and the offer just remained an offer.

What are the benefits of this and are there any drawbacks?


答:
Code review is great practice, only when idea for code review comes from development team. Developers don't need projectors and presentations to review each other code. If they want to - they will prefer to go to conference. </p>

<p>When idea of code review comes from management - it can sound like investigation of low software quality, and can demoralize development team. I don't think that management team should be involved in code review process. Code review side by side with management team - very bad, killing and destructive practice. </p>

Title: Is code reviewing good practice?

Body:
Code review is great practice, only when idea for code review comes from development team. Developers don't need projectors and presentations to review each other code. If they want to - they will prefer to go to conference.

When idea of code review comes from management - it can sound like investigation of low software quality, and can demoralize development team. I don't think that management team should be involved in code review process. Code review side by side with management team - very bad, killing and destructive practice.


答:
The problem with this type of code review, one developer every two weeks, the progress will be slow. It could be months before everybody has had a turn under the spotlight.

While code reviews can be good, there must be a reason behind them, and behind the procedure for doing them.

Several issue would have to be decided:

Who would pick the developer, and how much notice would they be given. No notice reviews are traps.

Who would pick the portion of code being reviewed: management, the senior developer on the project, or the developer being reviewed.

Is the purpose to teach the person whose code is on the projector how to do something better, or is the purpose for the person whose code is on the projector to teach everybody else around the room how to improve their code.

What percentage of code will be reviewed this way, is this going to be a part of the QA process?

If the people who proposed this plan don't already have answers to these questions it is possible that they read an article about how all great companies do code reviews, so we should do them also, without understanding the purpose behind them.

Title: Is code reviewing good practice?


答:
Base your styles and conventions on the language being used.

You may love "{'s" everywhere in your code. You always use a series of "[" and "{" and "(" in the most verbose form. You believe they should be on their own line. Then one day your team is assigned a large development task that requires python. If you don't adapt your style, you will never get your python code to run. Those braces all have different meanings in python, the language where white space has meaning, and the difference between a list and a dictionary is the style of brace.

Title: How to mix different styles of programming on several languages?

Body:
I know that Senior Developer doesn't use only one language and only one platform or IDE.

Can you advise how to mix different styles of programming to make efficient code?

For example, best mixing is Perl + Objective-C.

$ObjectiveCLongNameOfVariablesAndMethods are worst for Perl-style, but good for iOS-team.

[self method:[[NSArray alloc] initWithobjects:[hash objectForKey:name]]] style is weird for an eye, but not for perl simple-looking arrays and hashes and autovivification.

Also, i try to mixing SAS + Objective-C style, but here i have a trouble. SAS doesn't support names long names, only 32 symbols. So, big trouble to naming variables.

Another difficulty is features of current language. So, if I can't use current language for a task, that it can solve 'like a BOSS', I become angry and see weird code. Using libraries is good, but it makes code not natural, 'cause eating soup with fork is strange'.

And at the end: where can I trust compiler and interpreter of language? So, C++-style is best for pointers (you make destructors, constructors, etc.), but many languages now support mechanism like ARC in Objective-C or don't use pointers (like C#).


问:
Design pattern for access to tree-like database in Java?
I'm developing a Roleplaying character viewer/manager programme for a locap LARP system. The Characters have access to skills that are layed out in a tree-like structure. There are a lot of skills, and potentially a lot per character.

I know I can just import the Java swing library to get access to a tree, but I feel like this may bog me down, when all that needs to be done is access to a tree-like database, and the character needs only know that they have access to a subset of the skills.

I'm not sure if the tree design pattern is the best choice for this (i.e. instantiate a tree for the skills known per character, and add to/delete parts as needed) or 'do the clever stuff' and use a list per character to see which parts (skills) of database (external tree) are 'owned'.

My skills are broken down roughly as so:
Course catogory -> Weapon Type -> Actual Weapon -> Proficiency-->Special Skill, which goes quite deep. Further to this there is little need to know what is at each level, just that it's children, until you hit the leaf, and the one up.

My database effectively already exists on the LARP website, so if I don't have to reproduce it, that would be good. Here is a sample

```<code>Weapons and Shields     Warrior Priest Scout Mage
1H Weapon Proficiency     3        6     6     9
1H Weapon Specialisation  6        12    12    18
1H Weapon Expertise       12       24    24    36
1H Weapon Mastery         24       48    48    72
</code>```

And later on:

```<code>Magic           Warrior       Priest        Scout         Mage
Learn Spell     9 x (l + 1)   9 x (l + 1)   6 x (l + 1)   3 x (l + 1)
l = spell level,
...
Create Talisman 9 + l         9 + l         6 + l         3 + l
l = level,
</code>```

答:
The canonical design pattern used for tree-like data structures is the Visitor.  You start at the root (or the current node) and visit each node in order (preorder, postorder, whatever order you need), performing the required task at each node.

It's not clear from your description, but I get the impression that a Visitor that returned the information required to display the information about all primary children of the current node (that is, all the child nodes of the current node but not their descendants) would work.  This assumes you have skills broken down into progressively finer categories (Fighting -> weapons -> close combat -> edged weapons -> short blade -> dagger).  Players would be able to drill down into any category and see what their capabilities are.  You could also collapse categories that only have single children (e.g. if a person only has one skill, just go directly to it and don't make them select a bunch of single links).


问:
Are Vim or Emacs practical for languages like .Net or Java?
So, I am primarily a .Net developer who does some stuff in Java, Python and a few others from time to time. I have heard a lot of people praise Vim and Emacs for greatly increasing efficiency once the basics are nailed down. I can definitely see how many of the features could be very useful with sufficient practice, and even believe the learning curve is probably worth the effort. However...it seems that you would really have to be some sort of wizard of macros and hotkeys to be as efficient in Vim or Emacs as the average developer is in Visual Studio, Netbeans, Eclipse, or other platforms. I have been starting to learn to use Vim and think some of its features are awesome (column editing for example), but it seems that many of the tools provided by the heavy weight IDEs simply could not be replaced buy even the most juiced up text editor. A few processes I would be skeptical anyone could ever be more efficient at in Vim include (I know VS best, so I will stick to those):

generating dbml files for Linq-to-SQL

Automated testing

designing UIs

Creating/organizing projects and solutions

I know Vim and Emacs can do a lot of the same things very powerfully that VS can (like intellisense, refactoring, etc.) and it may be able to do some or all of the examples that I provided, but is it realistic to say that someone working on these platforms would actually benefit from Vim or Emacs?

答: Take a look at the OpenIDE and Continous Tests projects. First one focuses on adding .NET project support to any editor including VIM and Emacs. The other one is a continous test runner similar to ruby's AutoTest/ pythons Sniffer/Autonose. It can run as a VS plugin or standalone.</p>


问:
how to move Silverlight app to Html5
I have been working with Silverlight 5 application for a while. I liked this technology and I was captivated to the point to get certified in Silverligt development.

However, Html5 gained momentum this point, a new wave of thinking about new applications. Now, i am considering whether to develop in Sl or html5.
I have read thousands of post on the subject and can not find clear if there is any way to migrate an application to HTML5 SL, know if there is any tool to help the process?

答:
This question is really important as there is a move to native HTML5 apps.
I have researched this topic couple months ago, and there are good sources and videos that helped me get glue where to start.

Depending on how you have build your Silverlight app, approach/strategy of move various. Here is more details on this topic.

HTML5 for Silverlight Developers

How to replace Flash and Silverlight with HTML5

From Silverlight to HTML5 - codeproject article

Title: how to move Silverlight app to Html5


问:
Domain integrity check in application
Is it better to check for allowed domain values on the frond end or let the database engine handle the domain integrity. For example If you have a data entry form for employee, is it better to check for allowed values on the data entry form before submitting the data to the database assuming network IO is not a big issue. What if there are lots of checks to be performed, would the engine be faster or would checking the value on the front end take the load of the dB engine?</p>

答:
It is best to have checks in both places.

Have checks on the client side in order to give direct feedback to the client without having to roundtrip to the server.

Have checks on the server side because you can't trust the client (you never know if data has been spoofed, someone hacked your UI or whatever).

Title: Domain integrity check in application


答:
Code review is an excellent practice, particularly if it is done by developers to share knowledge, and the ground rules are set ahead of time that suggestions and criticisms are meant to be CONSTRUCTIVE, and not to use an individual developer for target practice.

Managers who are not developers will be greeted with suspicion by developers if they decide to do code reviews. Most manager types will not want to get into the detail that developers inherently get into when looking at code.  Most managers will also not understand why the developers critique one approach over another.

If you are wanting to showcase the good work developers are doing to management, then "code review" has a different meaning, and should not be as detailed as code reviews that are done to instruct/improve code quality among the developers.  This kind of presentation could be helpful in demonstrating what developers do if the presentation can be higher level, and less code-specific, focusing on what the managers understand (value, ROI, etc).  It might make managers understand that Joe has added significant value to the company by building X, which we can show saves Y amount of time, or Z dollars per order, etc.  I think it might be worth the effort in showing the value of individual members of your team.    Remember, however, that you need to be careful you don't overwhelm your audience with jargon, or too many levels of detail.

Title: Is code reviewing good practice?


问:
is it possible to auto-generate annotated POJO from a table
I wonder is it possible or is there a tool to generate annotated POJOs from a table.To make it clear,for example,Person table has fields like ,id,name,surname etc and i wanna to generate a POJO named Person with mappings made with annotations.</p>

答:
I've used the answer to this SO question in the past, and it worked fairly well for me.
https://stackoverflow.com/questions/2384433/hibernate-tool-to-create-basic-mappings-based-on-a-mysql-db</p>


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答: It works on my machine</p>

LastEditorDisplayName: Roger Pate

Body: It works on my machine


问:
What's a better name for this many-to-many table?
Part of one of my applications has contracts and contract_types tables, wherein a type may have many contracts but a contract may only be of one type. Now a new wrinkle has been introduced: a contract may change type over time (although it can, thankfully, still only be of one type at any one time).

The simplest solution appears to be to introduce a new table with columns something like this:

```<code>contract_id
contract_type_id
from_date
to_date
</code>```

But what to call the new table? contract_type_allocations is the best I can do so far and I can't say I'm impressed with myself. Suggestions gratefully received.

答:
You have 2 options as shown below. In option2, the 2 FKs make up the PK of the history table.
Note that if you have a case like this:

Contract 1 - Type A

then it changes to:

Contract 1 - Type B

The above can be taken care of by the solutions provided. But if you add an extra change as:

Contract 1 - Type A (back to type A again), the 2nd solution fails! - To avoid this, you can create a primary key on the history table that is GUID or sequential number and you don't impose uniqueness on the combination of the 2 FKs.


答:
That particular practice seems inefficient and likely to be embarrassing - who wants their mistakes pointed up to a whole group of people. So if they can't choose what is to be reviewed and the code is not yet in production, this is likely to make people uncomfortable.

Depending on when the code is reviewed can make a big difference in whether the code review comments make it into the code or not. If the dev can choose and choses only production code, review comments are unlikely to get implemented. It's nice to have meetings where developers can show off some nifty technique they learned that other people would be interested in, but that's not code review. That's training.

We do code review of every piece of code before it is moved to QA. Every piece. It involves generally only the code reviewer and the developer. It doesn't go to QA until the code reviewer formally passes it. So the developer has to make the changes. We have found and quickly fixed many problems that QA might not have found (they find things we don't see in code review too). Further, it way reduces cowboy coding and quickly identifies those people who are not performing well so we can fix their issues and train or get rid of them before they do damage to our application. Code review time is part of our time estimate when planning the work so it doesn't impact the deadline at all. And actually, it saves time in the long run because the earlier a problem is found the easier it is to fix. Incidentally code reviewers are peers not managers and we involve people at all levels in reviewing code.

I personally have taught less experienced developers many better techniques through code review and I have learned some better techniques myself by reviewing other people's code as well as their comments on my code. Further code review makes sure that someone else understands the code which goes a long way toward making it more maintainable. Sometimes, the code works but the questions of the review make it plain that there will be mantenance problems because the code is hard to understand. Better to refactor in those cases while it is all still fresh in your mind than a year later when even the code author is left scratching his head and wondering why the code does such and such.

Title: Is code reviewing good practice?


答:
Using a tree in a normal (relational) database is difficult.  Properly stored, each skill references only its parent skill, and trying to find children and siblings takes forever, even with a small table.  This can be solved somewhat by de-normalizing the database (adding columns to provide a complete ancestry for each skill) but then you have to know the maximum number of levels in your tree and hard-wire it into your DB design.

Given that a human had to invent your data, there can't be too much of it, so I'd just put it in your own tree structure in memory.  Each node would reference its parent and have a list of its children, so you can rocket around the thing as needed.  You'd need only a simple Skill class, with parent, child list, name, and associated data, so it's real simple to do and use.

Use a Map (java.util.HashMap might be best, since you'll know the size of the tree) to locate each entry.  Drop each Skill object into it, keyed, most likely, by name.  So if you want to know about a "Long Sword", you find it in the Map by name, and now you have all the information, plus its parent and all its children.

(One thing not quite so simple:  when reading the DB you are likely to get the name of a parent that's not in your tree (and Map).  You have to create it on the fly.  This means that when reading a new skill from the DB it may already be in the tree.  So instead of adding it, you just need to fill in the information and parent.  (And if the parent's not in the tree, you have to create it on the fly.))

Try to get by with displaying just a parent and its child list.  Displaying everything as a simple table may work too.  But once you start collapsing parts of the tree in the display it gets tricky.  Doing a good tree/outline/explorer/table/list is a lot more work than everything else here.

I did use the swing library JTree years ago.  It's probably your best bet if you must display the full tree as a tree.  Unfortunately, I needed to make it part of a table, and it proved easier to skip the JTree and expand and collapse rows in the JTable directly.  It was a massive effort.  So don't, for instance, let anyone talk you into adding the cost to each row, where all the costs are aligned in their own column.

Title: Design pattern for access to tree-like database in Java?

Body:
I'm developing a Roleplaying character viewer/manager programme for a locap LARP system. The Characters have access to skills that are layed out in a tree-like structure. There are a lot of skills, and potentially a lot per character.

I know I can just import the Java swing library to get access to a tree, but I feel like this may bog me down, when all that needs to be done is access to a tree-like database, and the character needs only know that they have access to a subset of the skills.

I'm not sure if the tree design pattern is the best choice for this (i.e. instantiate a tree for the skills known per character, and add to/delete parts as needed) or 'do the clever stuff' and use a list per character to see which parts (skills) of database (external tree) are 'owned'.

My skills are broken down roughly as so:
Course catogory -> Weapon Type -> Actual Weapon -> Proficiency-->Special Skill, which goes quite deep. Further to this there is little need to know what is at each level, just that it's children, until you hit the leaf, and the one up.

My database effectively already exists on the LARP website, so if I don't have to reproduce it, that would be good. Here is a sample

```<code>Weapons and Shields     Warrior Priest Scout Mage
1H Weapon Proficiency     3        6     6     9
1H Weapon Specialisation  6        12    12    18
1H Weapon Expertise       12       24    24    36
1H Weapon Mastery         24       48    48    72
</code>```

And later on:

```<code>Magic           Warrior       Priest        Scout         Mage
Learn Spell     9 x (l + 1)   9 x (l + 1)   6 x (l + 1)   3 x (l + 1)
l = spell level,
...
Create Talisman 9 + l         9 + l         6 + l         3 + l
l = level,
</code>```


问:
in Objective-C, value of type double/float can only be NAN, INFINITY, & normal number?
I knew double or float value can be not only normal value(-1.3, 0, 1.0, 2.3) but also NAN and INFINITY in Objective-C.

Is there other special values except for NAN and INFINITY for double/float value in Objective-C?

答:
Primitive types in Objective-C are covered by the C standard, since ObjC is an OOP system grafted to C.

Which transforms your question to "What special values are there for float/doubles in C?"

Most (if not all) compilers will generate float and double arithmetic that conforms to IEEE 754. In this standard, there are 2 types of NaNs (signalling and quiet), 2 infinities (+Infinity, -Infinity) and finite numbers (which include signed zeros, +0 and -0). The topic is too wide to even start, and you'd do yourself a favor by reading a book about floating point arithmetic.

However the C language standard (before C99) does not make any guarantees for conformance to IEEE 754 and this is only a de-facto standard.

Also, in C you check for NaN values with the isnan function.


答:
This is a similar challenge faced when creating immutable objects.

Adding versions to the contract and / or creating a history table are the two quickest solutions.

A version column would allow you to leave the older versions of the contract information in the same table, which may be advantageous.  It could also present problems by adding bloat if the table is already large.  This would also allow you to track other significant changes within the contract itself.

Otherwise, it's simple enough to setup an additional table as you suggest.  "History" or "Version" would be good alternate table names.

Title: What's a better name for this many-to-many table?

Body:
Part of one of my applications has contracts and contract_types tables, wherein a type may have many contracts but a contract may only be of one type. Now a new wrinkle has been introduced: a contract may change type over time (although it can, thankfully, still only be of one type at any one time).

The simplest solution appears to be to introduce a new table with columns something like this:

```<code>contract_id
contract_type_id
from_date
to_date
</code>```

But what to call the new table? contract_type_allocations is the best I can do so far and I can't say I'm impressed with myself. Suggestions gratefully received.


问:
Is this an assembly language?
In my childhood I used to program on an MK-61 Soviet calculator. It had four operating registers (X, Y, Z, T) and 15 storage registers. A program could have 105 steps.

As I recall it, it had commands like:

Swap X and Y registers

Shift registers (Z to T, Y to Z, X to Y)

Copy from storage register (1..15) to X

Copy from X to storage register (1..15)

If X < 0 then go to program step ##

Perform operation (+, -, *, /) using X and Y values and put result to X

Is this command set an assembly language? Did I have a basic idea of assembly languages by using this device?

It turns out it is something called "keystroke programming".

Funny fact: a similar calculator (like this one, but with energy independent memory) was used as a back-up hardware for space mission trajectory calculations in 1988. :-)

答:
Reverse Polish notation (RPN) calculators were classic. No, although the register designations seem like assembly language it was not. Calculations were performed by translating from algebraic format onto the stack. The numbers used were pushed into the stack and operations were performed on last stacked against next to last stacked values.

You could "rotate" the stack to move the values since the displayed value was a stack member. The results could be swapped or stacked as necessary to perform nearly complex calculation. If you do understand stack hardware and assembly language this calculator was trivial to learn since its paradigm was most similar.

Title: Is this an assembly language?


问:
What should be in a coding standard?
What should be in a good (read:useful) coding standard?

Things the code should have.

Things the code shouldn't have.

Should the coding standard include definitions of things the language, compiler, or code formatter enforces?

What about metrics like cyclomatic complexity, lines per file, etc?

答:
I like the format in the Framework Design Guidelines it includes a general section and  rationals for the guidelines. The most useful bit are the details which start with Do, Do Not, Avoid and Consider.

Here's an example in the section Implementing Interface Members Explicitly it has the following items (note I dropped the rationales for bervity's sake)

Avoid implementing interface members
  explicitly without having a strong
  reason to do so

Consider implementing interface members explicitly if the members are intended to be called only through the interface.

Do not use explicit members as a security boundary.

Do provide a protected virtual member that offers the same functionality as the > explicitly implemented member if the functionality is meant to be specialized by derived classes.

This creates a good general tone. By using Avoid and Consider you can allow for developers to use their judgement. Also because they're guidelines and not rules developers are likely to  find them more palatable and in turn more likely to follow them.

Title: What should be in a coding standard?


问:
Are null references really a bad thing?
I've heard it said that the inclusion of null references in programming languages is the "billion dollar mistake".  But why?  Sure, they can cause NullReferenceExceptions, but so what?  Any element of the language can be a source of errors if used improperly.

And what's the alternative?  I suppose instead of saying this:

Customer c = Customer.GetByLastName("Goodman"); // returns null if not found
if (c != null)
{
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
```

<p>You could say this:</p>

<pre class="lang-cs prettyprint-override"><code>if (Customer.ExistsWithLastName("Goodman"))
{
    Customer c = Customer.GetByLastName("Goodman") // throws error if not found
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
</code>```

But how is that better?  Either way, if you forget to check that the customer exists, you get an exception.

I suppose that a CustomerNotFoundException is a bit easier to debug than a NullReferenceException by virtue of being more descriptive.  Is that all there is to it?

答:
If it will be semantically possible for a storage location of reference or pointer type to be accessed before code has been run to compute a value for it, there isn't any perfect choice as to what should happen.  Having such locations default to null pointer references which may be freely read and copied, but which will fault if dereferenced or indexed, is one possible choice.  Other choices include:

Have locations default to a null pointer, but do not allow code to look at them (or even determine that they are null) without crashing.  Possibly provide an explicit means of setting a pointer to null.

Have locations default to a null pointer, and crash if an attempt is made to read one, but provide a non-crashing means of testing whether a pointer holds null.  Also provide an explict means of setting a pointer to null.

Have locations default to a pointer to some particular compiler-supplied default instance of the indicated type.

Have locations default to a pointer to some particular program-supplied default instance of the indicated type.

Have any null-pointer access (not just dereferencing operations) call some program-supplied routine to supply an instance.

Design the language semantics such that collections of storage locations will not exist, except an an inaccessible compiler temporary, until such time as initialization routines have been run on all members (something like an array constructor would have to be supplied with either a default instance, a function that would return an instance, or possibly a pair of functions--one to return an instance and one that would be called on previously-constructed instances if an exception occurs during the construction of the array).

The last choice could have some appeal, especially if a language included both nullable and non-nullable types (one could call the special array constructors for any types, but one only be required to call them when creating arrays of non-nullable types), but would probably not have been feasible around the time null pointers were invented.  Of the other choices, none seem more appealing than allowing null pointers to be copied but not dereferenced or indexed.  Approach #4 might be convenient to have as an option, and should be fairly cheap to implement, but it should certainly not be the only option.  Requiring that pointers must by default point to some particular valid object is far worse than having pointers default to a null value which can be read or copied but not dereferenced or indexed.

Title: Are null references really a bad thing?


答:
To me, the best place to check it is in two places.  First on the UI (presentation layer), make sure the data entered meets the very basic requirements.  For example, a user has to enter a date in a text box, the presentation layer would make sure the value entered is in fact a date.

The second place would be the service layer, or depending on your architecture, the business layer.  The data entered in the UI would be placed into an object and sent down to the service layer (or business layer), which would enforce the business rules.  For example, the date entered has to be after the current day.  Other types of validation can occur here as well, no duplicate entries, and so on.

Once the data has been validated by the service layer then it will send it down to the repository (or data access layer) to be inserted into the database.   I am not a real big fan of putting validation on the database.  Mostly because it is next to impossible to unit test properly.  The type of validation done on a database should really be limited to ensure foreign key integrity or unique indexes.

Title: Domain integrity check in application

Body: Is it better to check for allowed domain values on the frond end or let the database engine handle the domain integrity. For example If you have a data entry form for employee, is it better to check for allowed values on the data entry form before submitting the data to the database assuming network IO is not a big issue. What if there are lots of checks to be performed, would the engine be faster or would checking the value on the front end take the load of the dB engine?</p>


问:
tcp retransmission queue
I'm trying to understand how tcp retransmission queue works so I can implement it in my application that uses TCAP over SCTP.
What I understood from the TCP queue is that every message is saved in retransmission queue with with a time, when the timer reaches 0 the message will be sent again.

My question is how to check the time on that message, is it like a thread that constantly checks the retransmission queue or is it something else?

答:
Here is how TCP retransmision queue works:

Every packet has a sequence number. After A sends 1 or more packets to B, B responds with an acknowledge packet and the last sequence number that was received correctly. A then begins sending from the next sequence number. There is no need to keep any other packets that B already acknowledged. Here is an example:

A -> B packets 1,2,3,4,5

B -> A Ack 5

A -> B packets 6,7,8,9

Packet 8 was missing (or in error), so B -> A Ack 7. (B also discards packet 9)

A -> B 8,9,10,11

Etc. This guarantees delivery in sequence.

The time to live (TTL) is a counter that is decremented every time the packet is re-transmitted. After the TTL is decremented to "0", the packet is no longer forwarded.

Sequence numbers wrap after 32767. When closing a listening port, in order to make sure there are no stray packets which could arrive at a listening port in error, the OS will usually mark a listening port as [TIMEWAIT] for 2 minutes because the TTL is expected to go to "0" for all inbound packets for that port by then.

Title: tcp retransmission queue


问:
Mercurial release management. Rejecting changes that fail testing
Researching distributed source control management (specifically mercurial).
My question is more or less what is the best practice for rejecting entire sets of code that fail testing?

Example:

A team is working on a hello world program.  They have testers and a scheduled release coming up with specific features planned.

```<code>Upcoming Release:
   Add feature A
   Add feature B
   Add feature C
</code>```

So, the developers make their clones for their features, do the work and merge them into a QA repo for the testers to scrutinize.

Let's say the testers report back that "Feature B is incomplete and in fact dangerous",  and they would like to retest A and C.

End example.

What's the best way to do all this so that feature B can easily be removed and you end up with a new repo that contains only feature A and C merged together?

Recreate the test repo? Back out B? Other magic?

答:
The key here is to come up with a workflow that avoids the situation where "bad" code is ever exposed to developers or teams other than those who created it. If this were to occur, good code would be mixed with bad, and "unmerging" or detangling them will be difficult. So, prevent this from happening in the first place.

I'm assuming that HelloWorld in this example is the mainline repository, that contains known good code. Developers A, B, and C all clone from this repo and develop their changes against it. In the model I'm describing, HelloWorld-test is a transient repo solely used by QA to test merged changes before moving them into the mainline. Developers never look at HelloWorld-test. Here's how it works.

A, B, and C all clone good code from mainline (HelloWorld).

A makes changes and tells QA she's ready (or A pushes her changes to a staging repo). QA clones mainline and pulls and merges A's changes, and then builds and tests. Assuming this is all successful, QA then merges these changes into the mainline.

B now makes his changes available. QA clones mainline and then pulls and merges B's changes into HelloWorld-test. Continuing with your example, let's say these changes are bad. So QA's merge fails, or the build fails, or the tests fail, or something. At this point QA declares the changes to be bad, notifies B, and simply throws away HelloWorld-test. It's now B's responsibility to pull and merge from mainline, fix test failures, or whatever.

QA can then perform the process with C, starting from a fresh clone of mainline, and merging in C's changes. Note that B's bad changes have never reached the mainline and so C's changes (or anybody else's) will never be mixed with them.

At some point B has fixed up his changes and asks QA to do another pull/merge/build/test. QA can do this next, or they can just go around the cycle of different developers or teams until they come back to B.

This is often called a "pull model" of development. I believe Linux kernel changes are managed this way.

In many cases it's not "QA" who does the pull/merge/build/test cycle, but instead it's done by a continuous integration system such as Hudson or Jenkins.

Of course, there are many variations of this, whether individual developers or teams have staging repos, whether changes are propagated via pushing or pulling, etc. But they should all share these key characteristics:

Only known good changes make it into the mainline.

Developers only pull/clone from mainline, thus they never base their work on bad changes.

New changes are merged, built, and tested in isolation from everything else and are verified good before being merged into the mainline.


答:
Another way is to set up views. Use the latest versions in the view so joins with the view can stay 1 to many whereas the base tables are many to many. The many to many can be used for history if required (this then depends if you want/need to maintain the many to many/use a linking table to give 2 way 1 to many/introduce version in the key to make unique/etc - depending on the use you make of it and what will join with it if anything).

Another way to go, is to have a history table and move relevent rows over when contract type is changed. This then allows for the same visibility as the view mentioned above, but allows for more accurate indexing (accurate in so far as it matches your operational use of the table) - the history table will of course become many to many too (after any second change). This can be more efficient (especially if there are many rows on the table), but requires more housekeeping/pre-processing.


问:
Countour Mapping API
I have done some searching on Google, but haven't come up with much as of yet. I am wanting to take a set of point data, which I had previously been using to create weighted points for a heat map through the Google API, and turn them into a contour map to overlay on the Google Maps API. I haven't seen anything in Google's code that would let me do this. Does anyone know of a good API to create such an overlay? Or is there possibly something I have overlooked that Google offers?</p>

答: Let me see if I got this straight: You have something like this or this? And you want something like this or this or this? Feel free to browse through the sample gallery and let me know if anything from there (partially) matches your requirements. Anything should be doable with Google Maps, if you're willing to spend enough time understanding how to leverage the full power of their Javascript API (and some of its undocumented features).</p>

Title: Countour Mapping API


答:
From my experience Code Review is really great thing if you perform it well. When you have professional / mature team members and managers. We as programmers are "solution solvers". Our job is not to create lines of "text". That's why we have to share ideas, mistakes, problems, experiences. Code review is really a good practice to achieve this.

Unfortunately it sounds great but it is really hard to implement in most of the companies. Your team needs a lot of "autonomy". Convincing your managers or financial department that not creating new feature is profitable seems hard.

In my company we are trying to do some code review. But too much time is spent with 'chasing the rabbit' ( making features ).

Title: Is code reviewing good practice?


答:
While I fully agree that code reviews are very constructive for teaching I would like to highlight, for me anyway, it is to ensure that the team's design patterns are being followed correctly.

We write a little prototype work and we refactor bits of code and while we feel comfortable with the product at the end the readability has been damaged - people can not look at it and see as clearly what is going on.

Independent eyes are always beneficial I find as you get stuck into certain modes of thought and this is at all levels of experience. You invested hours into the design and code and so code reviews are difficult to deal with when there is the fear your effort is going to be thrown out. Yet at the end you, hopefully, end up with a cleaner, leaner and more manageable application and the experience is ingrained in you.

For our team we do as @ElYusubov mentioned and use a tool specifically for Code Review - Crucible. People review, comment and sign off on code. Every week we sit down and review face to face interesting and/or complex pieces of code.

Title: Is code reviewing good practice?


问:
async & await - poll for alternatives
Now that we know what is in store for c#5, there is apparently still an opening for us to influence the choice of the two new keywords for 'Asynchrony' that were announced by Anders Heijsberg yesterday at PDC10.

```<code>async void ArchiveDocuments(List<Url> urls) {
    Task archive = null;
    for(int i = 0; i < urls.Count; ++i) {
        var document = await FetchAsync(urls[i]);
        if (archive != null)
            await archive;
        archive = ArchiveAsync(document);
    }
}
</code>```

Eric Lippert has an explanation of the choice of the current two keywords, and the way in which they have been misunderstood in usability studies. The comments have several other propositions.

Please - one suggestion per answer, duplicates will be nuked.

答:
Given that I'm not clear about the meaning/necessity of async, I can't really argue with it, but my best suggestion for replacing await is:

yield while (look! no new keywords)

Note having thought about this a bit more, I wonder whether re-using while in this way is a good idea - the natural tendency would be to expect a boolean afterwards.

(Thinks: finding good keywords is like finding good domain names :)

ContentLicense: CC BY-SA 4.0

Title: async & await - poll for alternatives


答:
Much of style and basic syntax type checks are caught using tools these days (FXCop etc).

However, code reviews are good, especially with new members of a team, complex or high impact stuff (e.g. something that will be noticeable to important people if it fails or causes business impact) and especially when outsourcing or using short term contractors (especially again when they are non native speakers as translation errors/language problems can allow software to pass all the tests but not actually do what it is supposed to).

I am not a fan of putting code on a projector for a team to pick through - much better to have a code review meeting where another team member (team lead etc) goes through a listing with the dev. This impacts less people - stops a lot of wasted time on style arguments - and is less embarrassing for the dev. It is more constructive and easier for the dev to absorb real issues and not be blinded by "I would have done this..." sort of comments.

I also think that un-enforced code reviews - like putting code on a share or emailing it around in the hope someone gives up their lunch time to go through it - is a waste of time.

A sit down with a pile of listing, a marker and a cup of coffee in the coffee area is great for this.

Title: Is code reviewing good practice?


问:
My boss decided to add a "person to blame" field to every bug report. How can I convince him that it's a bad idea?
In one of the latest "WTF" moves, my boss decided that adding a "Person To Blame" field to our bug tracking template will increase accountability (although we already have a way of tying bugs to features/stories). My arguments that this will decrease morale, increase finger-pointing and would not account for missing/misunderstood features reported as bug have gone unheard.

What are some other strong arguments against this practice that I can use? Is there any writing on this topic that I can share with the team and the boss?

答:
I see two possibilities here: He wants to be able to punish people who make mistakes, or he just hasn't thought it through.  Let him know that the perception to everyone will be that he intends to punish those who make mistakes.  Ask him if that's the culture that he wants to encourage.

my boss decided that adding a "Person To Blame" field to our bug tracking template will increase accountability

In my experience, when management wants to "make people more accountable," what they mean is they want to be able to exact punishment for failure.  Whether it's to fire poor performers, or just let them get dinged in the yearly salary review ("Sorry, Bob, you had 17 bugs flagged as your fault, and that's over the limit of 15"), it's punishment.

He'll probably say "Oh, no, we don't want that," so then ask him how that data will get used.  Remind him that you don't add data points to a database unless you're going to use it.   Does he want to either select on a given criteria ("Show me all the open bugs in the report creator subsystem"), so that you can work on things, or to be able to get aggregate data ("Which subsystem has had the most bugs"), so that you can do post-mortem analysis.  Does he envision some sort of tote board of failure where people can be publicly humiliated?

So which does he intend?  Does he want to be able to say "Show me all the bugs that are Bob's fault?"  Why?  Or does he want to be able to say "Show me who is at fault most of the time?"  Why?  The first one is not meaningful, and the second is only punitive.  Or the third option is that he has no real reason.

I admit there is the possibility that he could be looking for those programmers on the team who need help in improving their skills.  If so, there are better ways to capture this information that don't create a culture of finger-pointing.


问:
How does learning assembly aid in programming?
I have been programming in higher level languages (Python, C#, VBA, VB.NET) for around 10 years and I have completely zero understanding on what's going on, "under the hood."

I am wondering what are the benefits of learning assembly, and how will it aid me as a programmer? Can you please provide me with a resource that will show me exactly the connection between what I write in higher level code to what happens in assembly?

答:
It will give you a better understanding of what is "happening under the hood" and how pointers work and the meaning of register variables and architecture (memory allocation and management, parameter passing (by value/by reference), etc) in general.

For a quick peek with C how's this?

```<code>#include <stdio.h>

main()
{
  puts("Hello World.");
  return(0);
}
</code>```

compile with gcc -S so.c and take a look at the assembly output in so.s:

```<code> $ cat so.s

    .file   "so.c"
    .section    .rodata
.LC0:
    .string "Hello World."
    .text
.globl main
    .type   main, @function
main:
    pushl   %ebp
    movl    %esp, %ebp
    andl    $-16, %esp
    subl    $16, %esp
    movl    $.LC0, (%esp)
    call    puts
    movl    $0, %eax
    leave
    ret
    .size   main, .-main
    .ident  "GCC: (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3"
    .section    .note.GNU-stack,"",@progbits
</code>```

OwnerDisplayName: Артём Царионов

Body:
It will give you a better understanding of what is "happening under the hood" and how pointers work and the meaning of register variables and architecture (memory allocation and management, parameter passing (by value/by reference), etc) in general.

For a quick peek with C how's this?

#include <stdio.h>

main()
{
  puts("Hello World.");
  return(0);
}

compile with gcc -S so.c and take a look at the assembly output in so.s:

 $ cat so.s

    .file   "so.c"
    .section    .rodata
.LC0:
    .string "Hello World."
    .text
.globl main
    .type   main, @function
main:
    pushl   %ebp
    movl    %esp, %ebp
    andl    $-16, %esp
    subl    $16, %esp
    movl    $.LC0, (%esp)
    call    puts
    movl    $0, %eax
    leave
    ret
    .size   main, .-main
    .ident  "GCC: (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3"
    .section    .note.GNU-stack,"",@progbits


答:
Because you'll understand how it really works.

You'll understand that function calls are not for free and why the call stack can overflow (e.g., in recursive functions). You'll understand how arguments are passed to function parameters and the ways in which it can be done (copying memory, pointing to memory).

You'll understand that memory is not for free and how valuable automatic memory management is. Memory is not something that you "just have", in reality it needs to be managed, taken care of and most importantly, not forgotten (because you need to free it yourself).

You'll understand how control flow works at a most fundamental level.

You'll appreciate the constructs in higher-level programming languages more.

What it boils down to is that all the things we write in C# or Python need to be translated into a sequence of basic actions that a computer can execute. It's easy to think of a computer in terms of classes, generics and list comprehensions but these only exist in our high-level programming languages.

We can think of language constructs that look really nice but that don't translate very well to a low-level way of doing things. By knowing how it really works, you'll understand better why things work the way they do.

OwnerDisplayName: Артём Царионов

Title: How does learning assembly aid in programming?

Body:
I have been programming in higher level languages (Python, C#, VBA, VB.NET) for around 10 years and I have completely zero understanding on what's going on, "under the hood."

I am wondering what are the benefits of learning assembly, and how will it aid me as a programmer? Can you please provide me with a resource that will show me exactly the connection between what I write in higher level code to what happens in assembly?


答:
I think the answer you seek is here: http://www.codeproject.com/Articles/89460/Why-Learn-Assembly-Language

A quote from the article:

Though it's true, you probably won't find yourself writing your next customer's app in assembly, there is still much to gain from learning assembly. Today, assembly language is used primarily for direct hardware manipulation, access to specialized processor instructions, or to address critical performance issues. Typical uses are device drivers, low-level embedded systems, and real-time systems.

The fact of the matter is, the more complex high level languages become, and the more ADT (abstract data types) that are written, the more overhead is incurred to support these options. In the instances of .NET, perhaps bloated MSIL. Imagine if you knew MSIL. This is where assembly language shines.

Assembly language is as close to the processor as you can get as a programmer so a well designed algorithm is blazing -- assembly is great for speed optimization. It's all about performance and efficiency. Assembly language gives you complete control over the system's resources. Much like an assembly line, you write code to push single values into registers, deal with memory addresses directly to retrieve values or pointers.

To write in assembly is to understand exactly how the processor and memory work together to "make things happen". Be warned, assembly language is cryptic, and the applications source code size is much much larger than that of a high-level language. But make no mistake about it, if you are willing to put in the time and the effort to master assembly, you will get better, and you will become a stand out in the field.

Additionally, I'd recommend this book because it has a simplified version of computer architecture:
Introduction to Computing Systems: From Bits and Gates to C and Beyond, 2/e
Yale N. Patt, University of Texas at Austin
Sanjay J. Patel, University of Illinois at Urbana/Champaign

OwnerDisplayName: Артём Царионов


答:
Write a small c program, and disassemble the output.  That's all.  However, be prepared for a greater or lesser degree of "housekeeping" code that is added for the benefit of the Operating System.

Assembly helps you understand what's going on under the hood because it deals directly with memory, processor registers and the like.

If you really want to go bare-metal without all of the complexity of an operating system complicating things, try programming an Arduino in assembly language.

OwnerDisplayName: Артём Царионов


答:
Well, the answer is that just simply because the language you are using must be interpreted or compiled into assembler at the end. No matter the language or the machine.

The design of languages derives from the way the CPU works. More on low level programs, less on high level programs.

I will end by saying that it is not only that you need to know little assembler but CPU architecture, which you learn by learning assembler.

Some examples: There are many java programmers that do not understand why this does not work, and even less than know what happens when you run it.

```<code>String a = "X";
String b = "X";
if(a==b)
    return true;
</code>```

If you knew a little assembler you would always know that it is not the same the content of a memory location vs the number in the pointer variable that "points" to that location.

Even worse, even in published books you will read something like in JAVA primitives are passed by value and objects by reference, which is completely incorrect. All arguments in Java are passed by value, and Java can NOT pass objects to functions, only pointers, which are passed by value.

If you now assembler its obvious what's going on, if not it is so complicated to explain that most authors just give you a pious lie.

Of course, the ramifications of these are subtle but can get you in real trouble later on. If you know assembler it’s a non-issue, if no, you are in for a long long night of debugging.

OwnerDisplayName: Артём Царионов

Body:
Well, the answer is that just simply because the language you are using must be interpreted or compiled into assembler at the end. No matter the language or the machine.

The design of languages derives from the way the CPU works. More on low level programs, less on high level programs.

I will end by saying that it is not only that you need to know little assembler but CPU architecture, which you learn by learning assembler.

Some examples: There are many java programmers that do not understand why this does not work, and even less than know what happens when you run it.

String a = "X";
String b = "X";
if(a==b)
    return true;

If you knew a little assembler you would always know that it is not the same the content of a memory location vs the number in the pointer variable that "points" to that location.

Even worse, even in published books you will read something like in JAVA primitives are passed by value and objects by reference, which is completely incorrect. All arguments in Java are passed by value, and Java can NOT pass objects to functions, only pointers, which are passed by value.

If you now assembler its obvious what's going on, if not it is so complicated to explain that most authors just give you a pious lie.

Of course, the ramifications of these are subtle but can get you in real trouble later on. If you know assembler it’s a non-issue, if no, you are in for a long long night of debugging.


答:
There is no definitive answer, since programmers are not all of a type.  Do you NEED to know what lurks underneath?  If so, then learn it.  do you just merely want to learn it, out of curiosity?  If so, then learn it.  If it will have no practical benefit to you, then why bother?  Does one need a mechanic's level of knowledge just to drive a car?  Does a mechanic need an engineer's level of knowledge, just to work on a car?  This is a serious analogy.  A mechanic can be a very good, productive mechanic without diving to engineer depth understand of the vehicles he maintains.  Same for music.  Do you really to plumb the complexities of melody, harmony and rhythm to be a good singer or player?  No.  Some exceptionally talented musicians can't read a lick of sheet music, let alone tell you the difference between Dorian and Lydian modes.  If you want to, fine, but no, you don't need to.  If you are a web developer, assembly has no practical use that I can think of.  If you are in embedded systems or something really specially, then it might be necessary, but if it were, you'd know it.

Here's Joel's take on these value of leaning a non-high level language:
http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html

OwnerDisplayName: Артём Царионов


问:
Starting on a large project, should I split it into more concise parts?
Background: Currently an intern at a company and working on repurposing older programs (still in use, but for different departments) for use in testing new hardware. The new hardware is different in terms of register layout and firmware interface from the older iterations of hardware. I have been given free reign on how to setup this project as it is to be used for the new hardware exclusively.

Currently there is a single .c file and 5 different header files that make up the program. The .c file is currently over 10000 lines long and comprises EVERY single function in use of main().

My question is, should I split the code into more recognizable chunks of .c files? It is currently only a mild annoyance to go through and find the methods I need, but it is time-consuming and I do have deadlines. What are the benefits and tradeoffs of doing so now, rather than later?

I aim to finish re-purposing the program by next week (this is heavy optimism, it will most likely take two weeks), so is it more efficient to start culling and moving around code now, or will I benefit more from just attempting to force my way through as is?

答:
If it is possible make the existing code more manageable, you should better refactor it. Otherwise it's going to cause you trouble every time you refer to it. Imagine that you need to work with that code again in a year or two. I don't think it will be a pleasant experience.

Even if you don't have much time, it is really worth refactoring. I think one day will be more than enough for splitting the code into several logical pieces and creating a separate file for each. This will help you get the bigger picture of the code as a whole, and next time you need to find something you will know exactly where to look.

There are some similar (but not duplicate) questions. Take a look at them:

Refactoring while programming

How should I start refactoring my mostly-procedural C++ application?

When to refactor


答: Presumeably you are testing the code on the boxes with a view to migrate over to it. Therefore, I would presume it best to keep the software as close a possible to the original if that is to be used for side by side comparissons etc. Otherwise, what's the point?</p>

Title: Starting on a large project, should I split it into more concise parts?

Body:
Background: Currently an intern at a company and working on repurposing older programs (still in use, but for different departments) for use in testing new hardware. The new hardware is different in terms of register layout and firmware interface from the older iterations of hardware. I have been given free reign on how to setup this project as it is to be used for the new hardware exclusively.

Currently there is a single .c file and 5 different header files that make up the program. The .c file is currently over 10000 lines long and comprises EVERY single function in use of main().

My question is, should I split the code into more recognizable chunks of .c files? It is currently only a mild annoyance to go through and find the methods I need, but it is time-consuming and I do have deadlines. What are the benefits and tradeoffs of doing so now, rather than later?

I aim to finish re-purposing the program by next week (this is heavy optimism, it will most likely take two weeks), so is it more efficient to start culling and moving around code now, or will I benefit more from just attempting to force my way through as is?


问:
Is code reviewing good practice?
When the company I work in hired new managers, they offered us to overview someone's code on every meeting. We have meetings every two weeks, so each time one of developers was to show his/her code on the projector, and others were going to discuss it.

I thought this would be great: each developer would be more careful when writing code and we could share our experience better. But somehow we forgot about this and the offer just remained an offer.

What are the benefits of this and are there any drawbacks?

答:
As a software engineering intern, I've found code reviews immensely helpful.

On my team, a code review is required for each commit (big changes end up being formal, smaller changes end up being 'quick looks'). I definitely feel as though my engineering/design chops have been boosted by this, especially since I'm more likely to pull out the whiteboard than the terminal right away since I know I'm being 'watched.' :)

In effect, I think it produces much better code with the only slight drawback being a slightly slower development time (which in my opinion, is worth it in the long haul when you don't have to fix/extend terribly designed code). Also, I think that if you have juniors/interns on the team they will appreciate the chance for valuable feedback. I know I do!

Title: Is code reviewing good practice?


问:
Can applications affect power consumption in a substantial way?
Is there anything that can be done for a single general purpose application to affect the power consumption of the device it is running on?

I am not familiar with how optimizations to individual applications may affect power consumption in a general way, can someone explain if different approaches to writing applications affect power consumption of the device they are running on?

That is, can a single program, that does the exact same thing functionally, written in different ways drastically affect the power consumption of a device in general, not about how different un-related programs might affect the power consumption of a device.

答:
The best thing that you can do is optimize your algorithms and the business logic of your application.

You can also adopt a particular compiling process, many coders just forget about inline functions and optimization in a compilation phase, most of the time this gives you a small edge in terms of performance and, consequently, in terms of power consumption optimization.