答:
It depends.

Some (CISC) CPUs have byte-wise loads that can address individual bytes so the byte of interest is the low-order 8-bits on the bus; the rest of the bits are masked off.

Many RISC CPUs will do word-load, barrel shift, while others will do word-load, bit shift and in the middle, are ones that do word-load, byte shift.

Some CPUs will do consecutive word-loads when a two-byte value spans a 32-bit boundary, shifting and masking the words together.

CPU families may do different implementations depending on the particular processor model. That explains why there is no description of the implementation; it's a decision only the vendor cares about.

As for performance, you will just have to test it on the particular CPU and memory configurations you care about.

Title: How Byte loading/storing is implemented By the CPU?

Body:
I know that in 32bit machine, cpu read from memory 32bits at a time. since the registers in this case is 32bit in size too, I can understand how this works.

What I don't understand is how the cpu implement load instructions of 1 byte. does it load the whole word where the single byte is located to the register, then perform some kind of "byte shifting", or does the cpu can load a single byte, in this case when does the byte masking happen, is it until the byte got loaded in the register, or it happen when byte is send through the data bus ?

P.S. The cpu Im using is MIPS, the instructions Im talking about are: lb or lbu


问:
Why do C arrays not keep track of their length?
What was the reasoning behind not explicitly storing an array's length with an array in C?

The way I see it, there are overwhelming reasons to do so but not very many in support of the standard (C89). For instance:

Having length available in a buffer can prevent buffer overrun.

A Java-style arr.length is both clear and avoids the programmer from having to maintain many ints on the stack if dealing with several arrays

Function parameters become more cogent.

But perhaps the most motivating reason, in my opinion, is that usually, no space is saved without keeping the length. I would venture to say that most uses of arrays involve dynamic allocation. True, there may be some cases where people use an array allocated on the stack, but that's just one function call* - the stack can handle 4 or 8 bytes extra.

Since the heap manager has to track the free block size used up by the dynamically allocated array anyway, why not make that information usable (and add the additional rule, checked at compile time, that one can't manipulate the length explicitly unless one would like to shoot oneself in the foot).

The only thing I can think of on the other side is that no length tracking may have made compilers simpler, but not that much simpler.

*Technically, one could write some kind of recursive function with an array with automatic storage, and in this (very elaborate) case storing the length may indeed result in effectively more space usage.

答:
Short answer:

Because C is a low-level programming language, it expects you to take care of these issues yourself, but this adds greater flexibility in exactly how you implement it.

C has a compile-time concept of an array that is initialised with a length but at runtime the whole thing is simply stored as a single pointer to the start of the data.  If you want to pass the array length to a function along with the array, you do it yourself:

```<code>retval = my_func(my_array, my_array_length);
</code>```

Or you could use a struct with a pointer and length, or any other solution.

A higher level language would do this for you as part of its array type. In C you're given the responsibility of doing this yourself, but also the flexibility to choose how to do it.  And if all the code you're writing already knows the length of the array, you don't need to pass the length around as a variable at all.

The obvious drawback is that with no inherent bounds checking on arrays passed around as pointers you can create some dangerous code but that is the nature of low level/systems languages and the trade-off they give.

ContentLicense: CC BY-SA 3.0

Body:
Short answer:

Because C is a low-level programming language, it expects you to take care of these issues yourself, but this adds greater flexibility in exactly how you implement it.

C has a compile-time concept of an array that is initialised with a length but at runtime the whole thing is simply stored as a single pointer to the start of the data.  If you want to pass the array length to a function along with the array, you do it yourself:

retval = my_func(my_array, my_array_length);

Or you could use a struct with a pointer and length, or any other solution.

A higher level language would do this for you as part of its array type. In C you're given the responsibility of doing this yourself, but also the flexibility to choose how to do it.  And if all the code you're writing already knows the length of the array, you don't need to pass the length around as a variable at all.

The obvious drawback is that with no inherent bounds checking on arrays passed around as pointers you can create some dangerous code but that is the nature of low level/systems languages and the trade-off they give.


问:
UML class diagram: how to annotate observer-subject relationship?
How can I annotate in a UML class diagram that an instance of ClassA is registered as an observer of an instance of ClassB? (Both implement the appropriate interfaces).

This doesn't really belong in a class diagram, because they are static, but if this is something that is important to the design - how can you annotate it in this type of diagram?

Edit:

To clarify: I know how to annotate the Observer pattern in UML. My question is more specific.

ClassA being registered as an observer to ClassB is important for the design, however I'm not sure if an association relationship between the two classes is appropriate, since ClassA and ClassB don't know about each other. They're totally decoupled, and only connected through the Observer pattern.

答:
UML defines a special diagram type for showing how class instances are connected to each other: the Object diagram.

An object diagram uses a similar notation to a class diagram, but rather than structural relations between types, it shows how objects are relating to each other at some point in time.

In your concrete case, you would have two diagrams:

A class diagram showing how ClassA is an Observer and ClassB a Subject in the Observer Pattern, and

an object diagram showing the relevant instances of ClassA and ClassB with a dependency between them (dashed arrow with open arrow head) with the stereotype <<observes>>. This diagram then shows that a particular instance of ClassA at some point in time is connected to a particular instance of ClassB through the observer pattern.


问:
Testing (deterministic) algorithms with multiple or difficult to prove correct right answers
I'd like to preface this that this question is similar, but my question doesn't involve randomness, just finicky determinism, so the answer of "use a known seed" doesn't really apply. Likewise, this question is similar, but again, I'm not expecting the algorithm to ever fail -- I just don't know which way it will be correct.

This question came about while testing graph algorithms. but is by no means limited to them. Some algorithms such as A* can have multiple correct answers. Depending on your exact implementation you may get any one of several answers, each of which are equally correct. This can make them difficult to test, though, because you don't know which one it's going to spit out ahead of time, and it's very time consuming to compute the answers by hand.

In my specific case, I got around it by modifying Floyd-Warshall to spit out every possible shortest path, and spent the time hand testing that. It had the benefit of being a good feature in its own right. Then I could test other functions in terms of the known correct paths from FW (if the returned path is any one of the paths returned by FW for that start/end pair, it's correct). Of course, this only works for dense graphs due to how FW works, but it's still nice.

However, that may not always be viable for all algorithms with this characteristic. So far, the best answer I've come up with is to test for the characteristics of a correct answer, rather than the correct answer itself. To go back to shortest path algorithms, you can check the cost of the returned path against the known right cost and make sure the path is valid.

This works, but it can run the risk of not verifying everything correctly the more criteria for correctness there are, especially if the verification is itself complex (e.g. while correct algorithms exist, verifying a minimum spanning tree is a known hard problem; probably harder than constructing the MST itself), in which case you now have to extensively test your testing code. Worse: presumably you have to construct an MST to test an MST verification algorithm so you now have a great scenario where your MST test relies on your MST verification algorithm working, and your MST verification algorithm test relies on your MST generation code working.

Finally, there's the "cheap way", which involves observing the output, verifying it by hand, then hard coding the test to test the output you just verified, but that's not a great idea since you may have to revise the test every time you change the implementation a little (which is what automated testing is supposed to avoid).

Obviously the answer depends on the exact algorithm you're testing to a degree, but I was wondering if there were any "best practices" for verifying algorithms that have several definite, deterministic "correct" outputs, but those precise correct outputs are difficult to know ahead of time, and possibly hard to even verify after the fact.

答:
I'm not sure you are trying to test the correct property, and this causes your ambiguity.

Graph algorithms do not aim at finding some shortest path (this is a side effect), but to minimize or maximize some cost function defined on the set of edges and vertices.
Thus, you can check the correctness of a solution by testing for the final value of this functional and asserting that the first and last nodes are the ones actually required.

If you can pre-compute the final cost function value for each possible path (usually unrealistic), then you just have to check that the cost of the solution provided by the implementation under test is equal to the minimum cost among this set (absolute comparison).
If you "just" have a gold standard algorithm and/or implementation, then you should compare the cost of its output with the one of the algorithm under test (relative comparison)

For example, a naive test setup would be:

Compute all possible paths between Va and Vb in the test graph with a greedy algorithm.

Compute the cost function (for example, the length if all your edge weights are equal to 1) for each of these paths and find the minimum value.

Apply the algorithm under test.

Make an assertion in your unit test that the tested algorithm cost value is equal to the minimum of the greedy solutions.

If you want to know more about graph based optimization, you can have a look at Yuri Boykov's publications here, though in another context (Computer Vision problems).


问:
Should a REST interface include the query ID as part of the response?
I am currently working an Android app that receives most of the displayed data from a REST interface.

First, I request the information for a company the request includes a list of store IDs. With each ID I can then request the details for this store.

As part of my app I can update the store opening hours and send them back to the server. For that, I obviously need the store ID to tell the server which store to update.

Now, my question: The JSON object returned by {SERVER}/StoreDetails/{ID} does not include the the store ID. So I need to first fetch the JSON, parse it, and then manually add the store ID to the object - which I feel needlessly complicates my logic, as well as my model objects which now either need a setter of some kind of copy/update constructor when they could otherwise be totally immutable...

Would it be/have been reasonable to include the store ID in the returned JSON object or is that considered redundant and a bad practice?

答: Have a look a this ressource: http://jsonapi.org/format/#document-sigular-resources. When you follow this standard you have to include the id of the store in your json.</p>


问:
Getting coders to do code review
I am running a project where I pay developers to contribute to my semi open source project. My problem is that it is easy to hire developers, but it is very difficult to get anyone to do code reviewing. I have repeatedly attempted to get the senior developers to review the code of the junior developers. I have attempted to pay them more, give them higher status etc. But they just seem to want to code instead of reviewing code.

Now I am considering forcing all developers that want to code, to also review code, but I have a feeling that it is a bad idea.

My question is, therefore, how can I motivate capable people to review the code of others? How is this done in successful open source projects like Linux, PostgreSQL, LibreOffice etc.

答:
I used to work at a company that hired good, motivated developers and kept them. But we still felt there was value in code review: it helps spread the knowledge and just because one person feels that what they've written is good code doesn't mean there isn't room for improvement.

And we faced a similar problem. Coders preferred to code. To say nothing of wanting to shy away from the complex power dynamic of having a peer perform a task which is deliberately critical of your work, however well-intentioned.

The answer we found was: beer.

This is not a joke. Once every 2-3 weeks the company would pay to get some good beer in, and we'd spend the last 1-2 hours of the working week doing code review. The free beer was a good motivator, and the conviviality engendered by mild inebriation removed much of the sting from the process.

It worked so well that what had been a negative thing that all the programmers wanted to avoid became something of a monthly highlight: we all got free drinks, a pleasant atmosphere and got to improve our code all at the same time.

Title: Getting coders to do code review


问:
How to annotate method signature changes?
I'm developing a mini framework and I want to perform changes to existing methods. I know in order to deprecate a method I can use the @deprecated annotation. However, what annotation should I use to let the users know that I'm going to change the amount of parameters a method will receive or maybe the returned result?

I'd like to know what annotations to use in PHP.

答:
Depreacated does not meen you have a solution yet.

In Java hide() and show() are deprecated since years. The documentation force us to use setVisible(boolean) instead while hide() and show() - anyway hide() and show() are still working good.

```<code>@deprecated does not throw a exception, its a warning for developers.
</code>```

Whenever a method do not exists anymore: a Java-Unittest will fail - but this test must has been written by the people who use your mini-framework.

Also to give info about backward-compatibility: java has a @version-annotation.

Body:
Depreacated does not meen you have a solution yet.

In Java hide() and show() are deprecated since years. The documentation force us to use setVisible(boolean) instead while hide() and show() - anyway hide() and show() are still working good.

@deprecated does not throw a exception, its a warning for developers.

Whenever a method do not exists anymore: a Java-Unittest will fail - but this test must has been written by the people who use your mini-framework.

Also to give info about backward-compatibility: java has a @version-annotation.


问:
What should I do when I get stuck with a task for so long?
My team are using Scrum and we are new to this methodology. I use Essential Scrum as our guideline but I haven't finished it yet. On a chapter, it says the team should focus on idle tasks, not idle workers which I somewhat agree with it.

Anyway, it doesn't say (at least on that chapter) what to do or how to solve it. What are some good suggestion about how to tackle idle tasks?

Update
Idle task in this context means a task that has been in progress for a lot longer than we expect, for example, if a task is estimated to be finish in 2 hours but it has been taking 6 hours and not sure when it will be finished.

答:
There are only two things you can do :

adjust your plan, and see how to plan better in the future

ask for help, although this can even prolong the delay


答: Sounds perfectly reasonable to me to add the store ID into the payload - as you say, the payload is then more "standalone", and should not need modified after being parsed. Messing with the object to inject a field that you could trivially include when building the response feels wrong to me.</p>

Title: Should a REST interface include the query ID as part of the response?

Body:
I am currently working an Android app that receives most of the displayed data from a REST interface.

First, I request the information for a company the request includes a list of store IDs. With each ID I can then request the details for this store.

As part of my app I can update the store opening hours and send them back to the server. For that, I obviously need the store ID to tell the server which store to update.

Now, my question: The JSON object returned by {SERVER}/StoreDetails/{ID} does not include the the store ID. So I need to first fetch the JSON, parse it, and then manually add the store ID to the object - which I feel needlessly complicates my logic, as well as my model objects which now either need a setter of some kind of copy/update constructor when they could otherwise be totally immutable...

Would it be/have been reasonable to include the store ID in the returned JSON object or is that considered redundant and a bad practice?


问:
Why some Javascript code needs to be written in different tags and not embedded within the same
When I was using the modernizr file, I came across this problem where in   I need to source a file and call the script.

```<code><script src="js/modernizr-min.js"></script>
<script>
if (!Modernizr.input.placeholder){
      $('input[placeholder], textarea[placeholder]').placeholder();
}
</script>
</code>```

Why is that the script does not work when embedded within the same script tag.
I have across this situation many time, but failed to understand what causes this problem.
Is that the scripts have to be written in two different script tags to make it work or else what fails it.

答:
Because that's how the script HTML element is defined. A script tag may either be an external script, which is refered to by the src attribute, or in internal script defined inside the contents of the script tag. To quote the script tag's definition:

The script may be defined within the contents of the SCRIPT element or in an external file. If the src attribute is not set, user agents must interpret the contents of the element as the script. If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI.

Other than that, there is no technical reason why you would need to split up such an inline script into two or more parts.


答:
I use one of these options.

Which one to use has depended on the individual circumstances.

break it down further

move it back into the ready state if another task is currently the active one.

if it is blocked by another task, enter that task and then enter it as a blocker

accept the idling, increase work-in-progress limits and don't focus on cycle time.

Whatever you do, communicating to your team and to the appropriate level of management is required.

Title: What should I do when I get stuck with a task for so long?

Body:
My team are using Scrum and we are new to this methodology. I use Essential Scrum as our guideline but I haven't finished it yet. On a chapter, it says the team should focus on idle tasks, not idle workers which I somewhat agree with it.

Anyway, it doesn't say (at least on that chapter) what to do or how to solve it. What are some good suggestion about how to tackle idle tasks?

Update
Idle task in this context means a task that has been in progress for a lot longer than we expect, for example, if a task is estimated to be finish in 2 hours but it has been taking 6 hours and not sure when it will be finished.


答:
One of the fundemental differences between C and most other 3rd generation languages, and all more recent languages that I am aware of, is that C was not designed to make life easier or safer for the programmer. It was designed with the expectation that the programmer knew what they were doing and wanted to do exactly and only that. It does not do anything 'behind the scenes' so you do not get any surprises. Even compiler level optimisation is optional (unless you use a Microsoft compiler).

If a programmer wants to write bounds checking in their code, C makes it is simple enough to do it, but the programmer must choose to pay the corresponding price in terms of space, complexity and performance. Even though I haven't used it in anger for many years, I still use it when teaching programming to get across the concept of constraint based decision making. Basically, that means you can choose to do anything you want, but every decision you make has a price that you need to be aware of. This becomes even more important when you starting telling others what you want their programs to do.

Title: Why do C arrays not keep track of their length?

Body:
What was the reasoning behind not explicitly storing an array's length with an array in C?

The way I see it, there are overwhelming reasons to do so but not very many in support of the standard (C89). For instance:

Having length available in a buffer can prevent buffer overrun.

A Java-style arr.length is both clear and avoids the programmer from having to maintain many ints on the stack if dealing with several arrays

Function parameters become more cogent.

But perhaps the most motivating reason, in my opinion, is that usually, no space is saved without keeping the length. I would venture to say that most uses of arrays involve dynamic allocation. True, there may be some cases where people use an array allocated on the stack, but that's just one function call* - the stack can handle 4 or 8 bytes extra.

Since the heap manager has to track the free block size used up by the dynamically allocated array anyway, why not make that information usable (and add the additional rule, checked at compile time, that one can't manipulate the length explicitly unless one would like to shoot oneself in the foot).

The only thing I can think of on the other side is that no length tracking may have made compilers simpler, but not that much simpler.

*Technically, one could write some kind of recursive function with an array with automatic storage, and in this (very elaborate) case storing the length may indeed result in effectively more space usage.


问:
How should I handle exception that *should* never be thrown?
What is the best way to handle errors that shouldn't ever happen?

My current way to do this is to throw an exception if the 'thing that shouldn't happen' does happen, like so:

```<code>/*
 * Restoring from a saved state. This shouldn't be
 * null unless someone in the future doesn't set it properly, in which
 * case they will realize they did something wrong because it may crash.
 */
Object foo = bundle.getSerializable("foo");
if (foo != null) {
    doSomethingWith(foo);
} else {
    // This should never happen.
    if (BuildConfig.DEBUG) {
        throw new RuntimeException(
            "Foo is null!");
    }
    foo = new Object();
    doSomethingWith(foo);
}
</code>```

This is somewhat pointless, because this should never happen. But just in case the code gets screwed up and is released into production with foo being null, should I leave these types of checks in the code?

答:
It is best to not handle an exception if you cannot handle it intelligently.

This gives the opportunity for something earlier in the stack to handle the exception, since it probably has more context of what is trying to be accomplished.

Alternatively, if you know that this should never happen, this is an assertion, and would probably benefit from having an assert statement.

```<code>Object foo = bundle.getSerializable("foo");

assert foo != null : "Foo was null"

doSomethingWith(foo);
</code>```

To re-iterate my comment, if your application is in an indeterminate state (caused by a flow of logic that you did not intend) it is best to kill the application as soon as possible to prevent corruption or unintended results.

Body:
It is best to not handle an exception if you cannot handle it intelligently.

This gives the opportunity for something earlier in the stack to handle the exception, since it probably has more context of what is trying to be accomplished.

Alternatively, if you know that this should never happen, this is an assertion, and would probably benefit from having an assert statement.

Object foo = bundle.getSerializable("foo");

assert foo != null : "Foo was null"

doSomethingWith(foo);

To re-iterate my comment, if your application is in an indeterminate state (caused by a flow of logic that you did not intend) it is best to kill the application as soon as possible to prevent corruption or unintended results.


答:
It's amazing how often things that should never happen do.

You should throw a RuntimeException with a descriptive error message and let the application crash. If that ever happens, then you know that something is deeply wrong.

Title: How should I handle exception that *should* never be thrown?

Body:
What is the best way to handle errors that shouldn't ever happen?

My current way to do this is to throw an exception if the 'thing that shouldn't happen' does happen, like so:

```<code>/*
 * Restoring from a saved state. This shouldn't be
 * null unless someone in the future doesn't set it properly, in which
 * case they will realize they did something wrong because it may crash.
 */
Object foo = bundle.getSerializable("foo");
if (foo != null) {
    doSomethingWith(foo);
} else {
    // This should never happen.
    if (BuildConfig.DEBUG) {
        throw new RuntimeException(
            "Foo is null!");
    }
    foo = new Object();
    doSomethingWith(foo);
}
</code>```

This is somewhat pointless, because this should never happen. But just in case the code gets screwed up and is released into production with foo being null, should I leave these types of checks in the code?


问:
Web Application that is independent of web server software

Scenario

I haven't faced this requirement before, so I'm not confident with my solution. Our team drew up a plan to design a web application using a basic HAT stack for a project with a 4 month development time. We presented it to the client, who added two big new requirements. The requirements were:

The application must be runnable on any web server (IIS, Apache, Nginx, Lighttpd, etc...)

The application must be able to work with any database (MySQL, MongoDB, etc...)

His reasoning is that he has no control over the environments where the web application will be installed on. He plans on re-selling our solution to other customers.

We pushed back to the client saying that this would increase development time, but he has already committed to his clients. However, he said he is willing to put as much money into it to get it done.

Possible Solution?

The only solution I could think of was building the application in Perl CGI script as that seems the most universal, then having a variety of database adapters to plugin into an ORM, which is customized through a config file.

Question

What alternatives are there to creating a web application where we have no control over what modules, etc.. are installed in the web server?

Is this even possible?

答:
The biggest problem you have is going to be with the databases.  Within relational databases, you've got some dialectical differences between them (things that postgres does differently than mysql or oracle) - different functions, different column types.  This will make writing the proper query and creating the proper database schema difficult.

With Hibernate (Java stack), it is possible to forward engineer the database.  You create the objects and the ORM layer creates the corresponding database.  That said, this is means that everything you do is through the ORM.  (I think there is a corresponding thing in Ruby somewhere, not that I'd recommend ruby).

Adding in "any database" to that which includes things such as Mongo means that the ORM just doesn't do it anymore.  Even Perl's DBI doesn't have a corresponding DBD layer for Mongo - the paradigm for the database is just too different.

You could add another layer in front of the ORM to have your ORM layer with hand coded database drivers for Mongo, Couch, NoSQL Flavor of the week, etc... But now you are coding each layer again and again.

I believe that fundamentally your client doesn't understand the nature of what he is asking for. Being able to run anywhere with no control over what is installed, or even the database that backbends it is an impossible task.

You may wish to consider pitching a deployment of a virtual machine.  This has the entire stack that you want/need on it in one package that is then deployed to some other machine that is running the VM.  You put the database, the web server, the application server, etc.. in that VM and that VM is deployed.

Anywhere they can run a virtual machine (anywhere), the stack can be deployed.  Its only one thing that is needed on the target machine - the virtual machine player.


答:
The one I always trip over is "Unsupported Encoding Exception" when I change a string to or from UTF-8 bytes. When is UTF-8 going to be Unsupported!?

Be careful, though... there are two levels of "should never happen." There is the level at which UTF-8 is unsupported. Then there is the "should never happen" when the developer stands looking over the shoulder of the tester, blinking and mumbling, "that should never happen."

What I usually do for the first level is roll that logic up in a separate class that does what you did in your example ... catch it and convert it to a RuntimeException. That way the nasty and irrelevant try ... catch block is hidden, and tested separately from, the rest of the code.

For the second case, a developer's "should never happen", those are really exceptions, in the proper meaning of the word "exception". But it's cleaner to treat them as guard conditions, because if that case happens, all bets are off and the code can't complete it's use case.

```<code>Object foo = bundle.getSerializable("foo");

// Guard: This should never happen.
if (foo == null) {
    throw new RuntimeException("Foo is null!");
}

foo.doSomething();
</code>```

The rule is "fail fast", so the moment when we detect that our assumptions are wrong, the code must halt. Note that a null pointer example is an example of "fail fast" because the code will halt as soon as you try to dereference the value, but it's one of those errors that's hard to pin down.

So in this case, instantiating an empty foo and driving on is a violation of "fail fast", so don't do that.

It's also fair to rely on client-server contract, so that every call you make doesn't have to be followed by a null check. As long as you're making internal calls (and not validating data that came from outside), you don't have to validate every assumption in the client-server contract. If a function states it will return a non-null value, then trust it. If it fails, fix the function, not the client.

For null pointer exceptions specifically, Guava has a really nice Optional class that wraps a type and makes sure the value is either non-null or else not present.

Body:
The one I always trip over is "Unsupported Encoding Exception" when I change a string to or from UTF-8 bytes. When is UTF-8 going to be Unsupported!?

Be careful, though... there are two levels of "should never happen." There is the level at which UTF-8 is unsupported. Then there is the "should never happen" when the developer stands looking over the shoulder of the tester, blinking and mumbling, "that should never happen."

What I usually do for the first level is roll that logic up in a separate class that does what you did in your example ... catch it and convert it to a RuntimeException. That way the nasty and irrelevant try ... catch block is hidden, and tested separately from, the rest of the code.

For the second case, a developer's "should never happen", those are really exceptions, in the proper meaning of the word "exception". But it's cleaner to treat them as guard conditions, because if that case happens, all bets are off and the code can't complete it's use case.

Object foo = bundle.getSerializable("foo");

// Guard: This should never happen.
if (foo == null) {
    throw new RuntimeException("Foo is null!");
}

foo.doSomething();

The rule is "fail fast", so the moment when we detect that our assumptions are wrong, the code must halt. Note that a null pointer example is an example of "fail fast" because the code will halt as soon as you try to dereference the value, but it's one of those errors that's hard to pin down.

So in this case, instantiating an empty foo and driving on is a violation of "fail fast", so don't do that.

It's also fair to rely on client-server contract, so that every call you make doesn't have to be followed by a null check. As long as you're making internal calls (and not validating data that came from outside), you don't have to validate every assumption in the client-server contract. If a function states it will return a non-null value, then trust it. If it fails, fix the function, not the client.

For null pointer exceptions specifically, Guava has a really nice Optional class that wraps a type and makes sure the value is either non-null or else not present.


答:
There are two problems here:

Getting the client to understand what's possible, and what's not. Especially, development can't be accelerated arbitrarily by throwing money or manpower at it. It would be better to identify priority features that have to be present in the first release, and optional features that can be added later. The client obviously can't have everything at once.

The technological side of things.

The different databases could be hidden behind an ORM, or you could fall back to something that'll work everywhere (yes, I'm suggesting SQLite – here it's less insane than what your client wants). Your webapp could run on its own server which is simply forwarded through the required deployment web server, which is a sane architecture in any case. However, you somehow need to run your webapp: You'll need a JVM if you use Java, or the perl interpreter if you choose Perl, or a Python VM if you go that route. These are not always a given, e.g. on Windows. So you already have a dependency.

Now that the door is opened, we can add further dependencies – it doesn't matter how many dependencies you have, only whether the client's clients will have to install these dependencies manually. Providing installation scripts would therefore be preferable to trying to adapt to any environment.

Title: Web Application that is independent of web server software

Body:
Scenario

I haven't faced this requirement before, so I'm not confident with my solution. Our team drew up a plan to design a web application using a basic HAT stack for a project with a 4 month development time. We presented it to the client, who added two big new requirements. The requirements were:

The application must be runnable on any web server (IIS, Apache, Nginx, Lighttpd, etc...)

The application must be able to work with any database (MySQL, MongoDB, etc...)

His reasoning is that he has no control over the environments where the web application will be installed on. He plans on re-selling our solution to other customers.

We pushed back to the client saying that this would increase development time, but he has already committed to his clients. However, he said he is willing to put as much money into it to get it done.

Possible Solution?

The only solution I could think of was building the application in Perl CGI script as that seems the most universal, then having a variety of database adapters to plugin into an ORM, which is customized through a config file.

Question

What alternatives are there to creating a web application where we have no control over what modules, etc.. are installed in the web server?

Is this even possible?


问:
What is the difference between requirements and specifications?
I've been tasked with developing requirements and specifications for a project our group is starting.

I realized that I don't know the difference; a Google search just confused me more -- it seems some people say that specifications are requirements, but at a lower level.

答:
In a previous company creating commercial products we had the following distinction:

Requirements are what the system must do. They can be lower level, detailed requirements, and they can be functional or non functional.

Specifications are those things the system as-built actually does.
E.g. you could have a requirement that states the system shall have behaviour X at –10°C. The actual specification of the system may be that the system does X at –5°C; this would be in the sheet sent to potential customers when they want to buy the system.

NB in this case the specification does not equal the requirement.


答:
Why are you handling an error that never happens?

Computer programming deals with absolutes. There is no such thing as should, could and maybe. Either the error will happen or it will not. Adding error handling code for something that has a 0% chance of occurring is code smell. Good code handles that off change of 0.01% when it does happen.

A good way to think of it is like this.

If you only add error handling for 99% of the possible problems, then there only needs to be 100 problems for the source code to have an unhandled problem.

Overtime source code will grow to deal with thousands of problems...

Don't mix error handling with business logic

One problem I see all the time is source code that has been shotgun blasted with error handling. Especially in Java where exception handling is enforced by compiler error.

It makes it difficult to read what the intent of a function is when it branches many times to handle all the different error cases.

Instead, separate your error handling into specialized functions. Keep the original function focused on a single intent.

For example;

```<code>public Object getSerializableSafely(Bundle bundle, String name)
{
     Object foo = bundle.getSerializable(name);
     if (foo != null)
     {
        return foo;
     }
     else if (BuildConfig.DEBUG) {
        throw new RuntimeException("Foo is null!");
     }
     return null;
}

public boolean Worker()
{
    Object foo = getSerializableSafely(bundle, "foo");
    if (foo == null)
    {
        return false;
    }
    // do work with foo
    return true;
}
</code>```

Now, there is nothing wrong with throwing a runtime exception in debug builds. They can be great time savers because they take the debugger right to where the problem is.

The problem is trying to create functions like Worker and expect them to never fail. Reporting true/false as the result of an operation is much better than wrapping everything in try/catch.

If you were using an XML parsing API. Would you want it to throw an exception if you feed it invalid XML or would you want the parse function to return false? Keep your exception handling related to things that are the exceptional case, and use return results to communicate the result of a function.

Body:
Why are you handling an error that never happens?

Computer programming deals with absolutes. There is no such thing as should, could and maybe. Either the error will happen or it will not. Adding error handling code for something that has a 0% chance of occurring is code smell. Good code handles that off change of 0.01% when it does happen.

A good way to think of it is like this.

If you only add error handling for 99% of the possible problems, then there only needs to be 100 problems for the source code to have an unhandled problem.

Overtime source code will grow to deal with thousands of problems...

Don't mix error handling with business logic

One problem I see all the time is source code that has been shotgun blasted with error handling. Especially in Java where exception handling is enforced by compiler error.

It makes it difficult to read what the intent of a function is when it branches many times to handle all the different error cases.

Instead, separate your error handling into specialized functions. Keep the original function focused on a single intent.

For example;

public Object getSerializableSafely(Bundle bundle, String name)
{
     Object foo = bundle.getSerializable(name);
     if (foo != null)
     {
        return foo;
     }
     else if (BuildConfig.DEBUG) {
        throw new RuntimeException("Foo is null!");
     }
     return null;
}

public boolean Worker()
{
    Object foo = getSerializableSafely(bundle, "foo");
    if (foo == null)
    {
        return false;
    }
    // do work with foo
    return true;
}

Now, there is nothing wrong with throwing a runtime exception in debug builds. They can be great time savers because they take the debugger right to where the problem is.

The problem is trying to create functions like Worker and expect them to never fail. Reporting true/false as the result of an operation is much better than wrapping everything in try/catch.

If you were using an XML parsing API. Would you want it to throw an exception if you feed it invalid XML or would you want the parse function to return false? Keep your exception handling related to things that are the exceptional case, and use return results to communicate the result of a function.


答: Throwing an exception is expensive, and it can be rather shocking to the user based on the OS and platform. In addition, you have a blocking error here which is easy to check for, namely a nullvalue. Instead of throwing an exception, you should gracefully terminate, showing a message to the user and Closing() and Disposing() of any resources that need those actions.</p>


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
This was a LONG time ago -- 1976 to be exact.  My boss had never heard of Edsger Dijkstra or read an issue of CACM, but he had heard a rumor from somewhere that "GOTO is bad", so we were not allowed to use GOTO in our COBOL programs.  This was before COBOL added the "end if", so at the time it had only two-and-a-half of the three classic control structures (sequence, if / then / else, perform (i.e. do while)).  He grudgingly allowed GOTO in our Basic programs, and branch instructions in our Assembler language programs.

Sorry that this is a sort of "you had to be there" story.  As far as I know, every language invented since 1976 has adequate control structures so that you never need to use GOTO.  But the point is, the boss never knew WHY GOTO was considered harmful, or which language was the infantile disorder and which was the fatal disease.

ContentLicense: CC BY-SA 2.5


问:
Why are more programmers not freelance these days?
Leaving the whole pie to only a few of them, amplifying the huge differences between the two status. Pay is a (huge) one, not having to do overtime is another.

I leave the question open to hopefully get many great answers on all the different subjects that affects that feeling and decision not to go.

While this question is really global, I'll be interested in any studies, facts, articles, opinions regarding local markets such as US, India and even Australia in which I'm in love with.

答:
In my experience, most programmers don't have all the qualities necessary to survive as a freelancer. A small subset of these include:

Extensive knowledge in multiple domains (or in one domain that's in very high demand)

Motivation

Ability to self-organize

Social skills

Salesmanship

Lots of programmers have three or even four of these qualities, but vanishingly few possess all of them. Some people believe that the last two can't even be taught.  Someone who doesn't possess all of these qualities probably won't be successful as a freelancer.

For me personally, I worked for two years as a freelancer before my contracts dried up and I had to get a 'real' job again. I learned that I didn't have the motivation to go searching for new work at the same time I was putting in 50+ hours per week meeting existing contracts, nor did I have the salesmanship skills necessary to negotiate a living wage for my services.  I'm glad I gave it a try, but it's nice to be back at a small company with a few salespeople to take care of the stuff I'm not so good at. (Man, do I ever appreciate the work they do now!)


问:
Can we still consider that Moore's law still holds true regarding the consequence on CPU speed?
Moore's law is an empirical law and in simple terms states that the number of transistors on integrated circuits doubles approximately every two years.

One of the consequences of Moore's law is that CPU performance doubles every 18 Months.

I've seen 'Why is Moore's Law seen as an absolute truth?' and although curious does not answer my question.

Currently we are partly achieving that by making multi core CPU's.

Can we still consider that speed of CPU's doubles every 18 months?

Multi-core CPU's can be looked at just as distributed computing. A "good old" single threaded sofware/algorithm won't be able to take full advantage of such CPU as before and It's not true that all algorithms are paralelizable with speed gain.

答:
Processors now scale out, not up;  we are now fulfilling Moore's Law, not by adding more transistors, but by adding more cores with the same number of transistors in each one.   This is an unavoidable consequence of transistor density: clock speed has an effective (if soft) upper limit; the number of transistors you can put in the same core is constrained by heat effects and circuit leakage.

This has had implications throughout the programming community.  It means that we no longer think in terms of a single processor doing multiple tasks, but rather multiple processors doing single (and sometimes multiple tasks).

The pressure to take advantage of multiple cores has significantly influenced language design and programming techniques.  Where we would originally had been satisfied with a stateful program utilizing mutable objects, we now look more favorably on techniques involving functional programming and immutable data.

Does this answer your question?  Maybe not. But the trend to multiple cores is not going away; as programmers, this is what we need to be concerned about, not raw clock speed or how many transistors a die has.


问:
Acceptable placement of the composition root using dependency injection (DI) and inversion of control (IoC) containers
I've read in several sources including Mark Seemann's 'Ploeh' blog about how the appropriate placement of the composition root of an IoC container is as close as possible to the entry point of an application.

In the .NET world, these applications seem to be commonly thought of as Web projects, WPF projects, console applications, things with a typical UI (read: not library projects).

Is it really going against this sage advice to place the composition root at the entry point of a library project, when it represents the logical entry point of a group of library projects, and the client of a project group such as this is someone else's work, whose author can't or won't add the composition root to their project (a UI project or yet another library project, even)?

I'm familiar with Ninject as an IoC container implementation, but I imagine many others work the same way in that they can scan for a module containing all the necessary binding configurations.  This means I could put a binding module in its own library project to compile with my main library project's output, and if the client wanted to change the configuration (an unlikely scenario in my case), they could drop in a replacement dll to replace the library with the binding module.

This seems to avoid the most common clients having to deal with dependency injection and composition roots at all, and would make for the cleanest API for the library project group.

Yet this seems to fly in the face of conventional wisdom on the issue.  Is it just that most of the advice out there makes the assumption that the developer has some coordination with the development of the UI project(s) as well, rather than my case, in which I'm just developing libraries for others to use?

答:
Your binding module approach is the best solution. If the client is unlikely to change the configuration, the use of DI is questionable, for your library specifically.

If you wish to create a library for release to the public, you probably don't want clients to deal with the complexity or rigidity of the particular DI system you favor at the moment. Libraries are best when they are lower level components that can be used without lots of dependencies, or extensive training. Any DI system you select will change over time, and may become incompatible with client applications.


问:
What interface does python use to implement sockets?
When I programmed in python, I believe I interfaced with the transport layer using sockets.  If python was programmed by humans, they must have used an interface that was "lower" than sockets, to provide us with the interface to sockets.  I assume firewalls, also programmed by humans, use interfaces of lower layers in the same manner, so is there a way to access such lower layers, in terms of programming?

答:
A language uses system calls to communicate with the lower layer

In an interpreted language it means that the script calls a "built in" function and then code outside the interpreter gets called (which then makes its own system calls).

In a compiled language the code signals a software interrupt which signals the OS that it needs something from outside using a predefined protocol.

The C standard is mostly convenience functions and wrappers around these system calls so the programmer doesn't need to remember how to signal each OS.


答:
If you are developing libraries (not applications) for others to use, than you should still implement dependency injection. For me the term "Dependency injection" is just a set of practices that lead to a better separation of concerns and loose coupling. This is what makes your library well structured and easily testable (most of the time).

With regards to the IoC container, I don't see any harm in having IoC container in the library project. Somewhere you will have a composition root (an entry point) into your library so to me it makes perfect sense to wire up your dependencies in the composition root. How you do it is entirely up to you.

As an example, I have recently used a library for capturing signatures and a library for scanning bar codes. Both of them were simple interop libraries (COM wrappers). Each library required me to initialise it before I could do anything. For example:

```<code>var isReady = _signatureCapture.Initialise()
if (isReady)
{
   // Do stuff
}
</code>```

Bar code scanning library was very similar:

```<code>_scanner.Initialise();
_scanner.OnScan += OnScanHandler;
</code>```

I have been using both libraries and I have no idea whether they use IoC container or not. However I do know that the entry points into the library are in the Initialise methods. I'm guessing that all the dependencies are wired up in the Initialise method, which serves as a composition root.

If you are worried about relying on a third party IoC container, than you can roll with your own, much simplified implementation. Developers often worry about library becoming obsolete or superseded by something better, but in reality I have not yet seen a project where the team decided to swap out one IoC container for the other.

Title: Acceptable placement of the composition root using dependency injection (DI) and inversion of control (IoC) containers

Body:
I've read in several sources including Mark Seemann's 'Ploeh' blog about how the appropriate placement of the composition root of an IoC container is as close as possible to the entry point of an application.

In the .NET world, these applications seem to be commonly thought of as Web projects, WPF projects, console applications, things with a typical UI (read: not library projects).

Is it really going against this sage advice to place the composition root at the entry point of a library project, when it represents the logical entry point of a group of library projects, and the client of a project group such as this is someone else's work, whose author can't or won't add the composition root to their project (a UI project or yet another library project, even)?

I'm familiar with Ninject as an IoC container implementation, but I imagine many others work the same way in that they can scan for a module containing all the necessary binding configurations.  This means I could put a binding module in its own library project to compile with my main library project's output, and if the client wanted to change the configuration (an unlikely scenario in my case), they could drop in a replacement dll to replace the library with the binding module.

This seems to avoid the most common clients having to deal with dependency injection and composition roots at all, and would make for the cleanest API for the library project group.

Yet this seems to fly in the face of conventional wisdom on the issue.  Is it just that most of the advice out there makes the assumption that the developer has some coordination with the development of the UI project(s) as well, rather than my case, in which I'm just developing libraries for others to use?

Body:
If you are developing libraries (not applications) for others to use, than you should still implement dependency injection. For me the term "Dependency injection" is just a set of practices that lead to a better separation of concerns and loose coupling. This is what makes your library well structured and easily testable (most of the time).

With regards to the IoC container, I don't see any harm in having IoC container in the library project. Somewhere you will have a composition root (an entry point) into your library so to me it makes perfect sense to wire up your dependencies in the composition root. How you do it is entirely up to you.

As an example, I have recently used a library for capturing signatures and a library for scanning bar codes. Both of them were simple interop libraries (COM wrappers). Each library required me to initialise it before I could do anything. For example:

var isReady = _signatureCapture.Initialise()
if (isReady)
{
   // Do stuff
}

Bar code scanning library was very similar:

_scanner.Initialise();
_scanner.OnScan += OnScanHandler;

I have been using both libraries and I have no idea whether they use IoC container or not. However I do know that the entry points into the library are in the Initialise methods. I'm guessing that all the dependencies are wired up in the Initialise method, which serves as a composition root.

If you are worried about relying on a third party IoC container, than you can roll with your own, much simplified implementation. Developers often worry about library becoming obsolete or superseded by something better, but in reality I have not yet seen a project where the team decided to swap out one IoC container for the other.


问:
Exception when logging exception: is it correct to ignore them?
My question is specific to php, but i think it can be useful in other languages.

I log into a table all the exception a code can throw:

```<code>try{
 //Some code
 } catch (Exception $e) {
      $log = new Log(basename($_SERVER['PHP_SELF']), $_SESSION['id'], LogType::EXCEPTION, $e);
      try {
           $log ->addLog();
       } catch (Exception $e2) {
                //
       }
 }
</code>```

The function addLog insert the exception informations into a database.
But (by example if the connection with the database is lost) this function can throw an exception. I can't see what i have to do with this exception except ignoring it.

I know ignoring exception is a bad practice, but what can i do in this particular case?

If there is no problem to ignore it, is there a better way to indicate that this exception should not be taken into account?

答:
Whatever you do, don't swallow the exception. If something is broken, you need to know about it.  Swallowing an exception is only reasonable in very rare circumstances.

When you catch an exception, you should try logging it into a data store (database, event viewer, whatever works for you), so that somebody can then go and look in a single place to see all the exceptions.

If logging fails, revert to a simpler logging mechanism that is not dependent on a network resource.  I normally log to a text file and then ask the user to send me a copy of the file.

Finally, you should let the user know that something went wrong.  You may choose to display the full stack trace or just a simple error message.  Displaying a full stack trace to the end user is not recommended, as it's a security risk. I normally display a user-friendly message that prompts the end user to contact support.

On a side note, I've also seen a logging mechanism where the client would submit error details to the logging service over HTTP. If the service were not available, the client would retry logging three times before failing and reverting to a simpler logging mechanism.


答:
I think the direct answer to your question is to choose better test cases. I wonder about the test cases you are using. The graphs you use can be CANNED graphs where it is relatively easy for a human to determine the expected response. Try to figure out the "edge" cases that you want to be sure your algorithm handles and create a canned graph for each of the particular edge cases that is easy for a human to compute. For example, in the Djikstra algorithm case, you can probably create some 5x5 or 7x7 graphs that cover all your edge cases, even though your real system might be 500x500.

Then as a final sanity check you can create a more realistic graph test case or two. But in any event, I think sansuiso has it spot on where it is pointed out that you need to be sure you are testing for the correct property.

Title: Testing (deterministic) algorithms with multiple or difficult to prove correct right answers

Body:
I'd like to preface this that this question is similar, but my question doesn't involve randomness, just finicky determinism, so the answer of "use a known seed" doesn't really apply. Likewise, this question is similar, but again, I'm not expecting the algorithm to ever fail -- I just don't know which way it will be correct.

This question came about while testing graph algorithms. but is by no means limited to them. Some algorithms such as A* can have multiple correct answers. Depending on your exact implementation you may get any one of several answers, each of which are equally correct. This can make them difficult to test, though, because you don't know which one it's going to spit out ahead of time, and it's very time consuming to compute the answers by hand.

In my specific case, I got around it by modifying Floyd-Warshall to spit out every possible shortest path, and spent the time hand testing that. It had the benefit of being a good feature in its own right. Then I could test other functions in terms of the known correct paths from FW (if the returned path is any one of the paths returned by FW for that start/end pair, it's correct). Of course, this only works for dense graphs due to how FW works, but it's still nice.

However, that may not always be viable for all algorithms with this characteristic. So far, the best answer I've come up with is to test for the characteristics of a correct answer, rather than the correct answer itself. To go back to shortest path algorithms, you can check the cost of the returned path against the known right cost and make sure the path is valid.

This works, but it can run the risk of not verifying everything correctly the more criteria for correctness there are, especially if the verification is itself complex (e.g. while correct algorithms exist, verifying a minimum spanning tree is a known hard problem; probably harder than constructing the MST itself), in which case you now have to extensively test your testing code. Worse: presumably you have to construct an MST to test an MST verification algorithm so you now have a great scenario where your MST test relies on your MST verification algorithm working, and your MST verification algorithm test relies on your MST generation code working.

Finally, there's the "cheap way", which involves observing the output, verifying it by hand, then hard coding the test to test the output you just verified, but that's not a great idea since you may have to revise the test every time you change the implementation a little (which is what automated testing is supposed to avoid).

Obviously the answer depends on the exact algorithm you're testing to a degree, but I was wondering if there were any "best practices" for verifying algorithms that have several definite, deterministic "correct" outputs, but those precise correct outputs are difficult to know ahead of time, and possibly hard to even verify after the fact.


问:
Why can we not insert into files without the additional writes? (I neither mean append, nor over-write)
This occurs as a programming language independent problem to me.

I have a file with the content

```<code>aaabddd
</code>```

When I want to insert C behind b then my code needs to rewrite ddd to get

```<code>aaabCddd
</code>```

Why can I not just insert C at this position?

I can not do this in Java, Python, ... . I can not do this in Linux, Windows, ... . Am I right?

I do not understand why C can't simply be inserted without the additional writes.  Would someone please explain why this is so?

答: First you need to read everything after the insert point, then write it back down by as much space as you're going to insert.  Then you can write your "insert" data into the correct place.  Extremely poor performance operation, hence not natively supported.</p>


答:
Given that most file systems store the contents of files in individual blocks that are not necessarily contiguous on the physical disk, but linked via pointer structures, it seems that such a mode - "inserting" rather than "appending" or "overwriting" - ought to be possible, and could certainly be made more efficient than what we have to do now: read the entire content, edit the stream of bytes and re-write the entire content.

However, for better or worse, the UNIX semantics of file systems were designed along the "rough and simple" paradigm in the 1970s: it allows you to do everything, but not necessarily in the most efficient way possible. Nowadays it is almost unthinkable to introduce a new file opening mode into the Virtual File System layer and have any hope of the major file systems adopting support for it. This is a pet peeve of mine, but unfortunately one unlikely to be resolved any time soon.

Title: Why can we not insert into files without the additional writes? (I neither mean append, nor over-write)

Body:
This occurs as a programming language independent problem to me.

I have a file with the content

```<code>aaabddd
</code>```

When I want to insert C behind b then my code needs to rewrite ddd to get

```<code>aaabCddd
</code>```

Why can I not just insert C at this position?

I can not do this in Java, Python, ... . I can not do this in Linux, Windows, ... . Am I right?

I do not understand why C can't simply be inserted without the additional writes.  Would someone please explain why this is so?


答:
Theoretically, you could implement a file that would allow this sort of thing.  For maximum flexibility, though, you'd need to store a pointer to the next byte along with every byte in the file.  Assuming a 64-bit pointer, that would mean that 8 of every 9 bytes of your file would be composed of internal pointers.  So it would take 9000 bytes of space to store 1000 bytes of actual data.  Reading the file would also be slow since you'd need to read each byte, read the pointer, follow the pointer to read the next byte, etc. rather than reading large, contiguous blocks of data from disk.

Obviously, this sort of approach isn't practical.  You could, though, split the file up into, say 32 kb blocks.  That would make it relatively easy to add 32 kb of data at any 32 kb boundary in the file.  It wouldn't make it any easier to add a single byte as the 5th byte of the file.  If you reserve some free space in every block, though, you could allow small additions of data to take place that would only affect the data in that single block.  You'd have a penalty in terms of file size, of course, but potentially a reasonable one.  Figuring out how much space to reserve and how to split blocks, though, tends to be much easier for a particular application than for a general-purpose system-- what works in one context may be very bad in another depending on the file access and modification characteristics.

In fact, many systems that spend a lot of time interacting with files implement something like what I've described above when they implement their particular file abstraction.  Databases, for example, will generally implement some concept of a "block" as the smallest unit of I/O that they can work with and will generally reserve some amount of space for future growth so that updating a row in a table only affects the one block on which that data is stored rather than rewriting the entire file.  Different databases, of course, have different implementations with different trade-offs.


答:
The "problem" boils down to how files are written out to the storage medium in a byte by byte fashion.

In it's most basic representation, a file is nothing more than a series of bytes written out to the disk (aka storage medium).  So your original string looks like:

```<code>Address  Value
0x00     `a`
0x01     `a`
0x02     `a`
0x03     `b`
0x04     `d`
0x05     `d`
0x06     `d`
</code>```

And you want to insert C at position 0x04.  That requires shifting bytes 4 - 6 down one byte so you can insert the new value.  If you don't, you're going to over-write the value that's currently at 0x04 which is not what you want.

```<code>Address  Value
0x00     `a`
0x01     `a`
0x02     `a`
0x03     `b`
0x04     `C`
0x05     `d`
0x06     `d`
0x07     `d`
</code>```

So the reason why you have to re-write the tail of the file after you insert a new value is because there isn't any space within the file to accept the inserted value.  Otherwise you would over-write what was there.

Addendum 1: If you wanted to replace the value of b with C then you do not need to re-write the tail of the string.  Replacing a value with a like sized value doesn't require a rewrite.

Addendum 2: If you wanted to replace the string ab with C then you would need to re-write the rest of the file as you've created a gap in the file.

Addendum 3: Block level constructs were created to make handling large files easier to deal with.  Instead of having to find 1M worth of contiguous space for your file, you now only need to find 1M worth of available blocks to write to instead.

In theory, you could construct a filesystem that did byte-by-byte linking similar to what blocks provide.  Then you could insert a new byte by updating the to | from pointers at the appropriate point.  I would hazard a guess that the performance on that would be pretty poor.

As Grandmaster B suggested, use a picture of stacked dominoes to visually understand how the file is represented.

You can't insert another domino within the line of dominoes without causing everything to tumble over.  You have to create the space for the new domino by moving the others down the line.  Moving dominoes down the line is the equivalent of re-writing the tail of the file after the insertion point.

Body:
The "problem" boils down to how files are written out to the storage medium in a byte by byte fashion.

In it's most basic representation, a file is nothing more than a series of bytes written out to the disk (aka storage medium).  So your original string looks like:

Address  Value
0x00     `a`
0x01     `a`
0x02     `a`
0x03     `b`
0x04     `d`
0x05     `d`
0x06     `d`

And you want to insert C at position 0x04.  That requires shifting bytes 4 - 6 down one byte so you can insert the new value.  If you don't, you're going to over-write the value that's currently at 0x04 which is not what you want.

Address  Value
0x00     `a`
0x01     `a`
0x02     `a`
0x03     `b`
0x04     `C`
0x05     `d`
0x06     `d`
0x07     `d`

So the reason why you have to re-write the tail of the file after you insert a new value is because there isn't any space within the file to accept the inserted value.  Otherwise you would over-write what was there.

Addendum 1: If you wanted to replace the value of b with C then you do not need to re-write the tail of the string.  Replacing a value with a like sized value doesn't require a rewrite.

Addendum 2: If you wanted to replace the string ab with C then you would need to re-write the rest of the file as you've created a gap in the file.

Addendum 3: Block level constructs were created to make handling large files easier to deal with.  Instead of having to find 1M worth of contiguous space for your file, you now only need to find 1M worth of available blocks to write to instead.

In theory, you could construct a filesystem that did byte-by-byte linking similar to what blocks provide.  Then you could insert a new byte by updating the to | from pointers at the appropriate point.  I would hazard a guess that the performance on that would be pretty poor.

As Grandmaster B suggested, use a picture of stacked dominoes to visually understand how the file is represented.

You can't insert another domino within the line of dominoes without causing everything to tumble over.  You have to create the space for the new domino by moving the others down the line.  Moving dominoes down the line is the equivalent of re-writing the tail of the file after the insertion point.


答:
I work for a big box retailer. Where old habits die hard. Like, really hard. So I thought I may share my experiences.

The problem we had is visibility. No ones code was really visible to each other. They were using CVS and we won the victory of converting everything to use git. This began to turn the tide. We implemented Gitlab (similar to github, basically all the same features hosted on your servers). We protected the master branch (production ready code). This created a snowball effect of sorts. If a developer had something that needed to be merged in to production or a testing environment branch, it would need 2 senior developers to look at the code, make comments, suggestions for improvements, ask questions etc and eventually give a thumbs up on the merge request. From there, it would be merged to the environment.

Stepping in to just rewrite the code you don't like isn't going to help you OR your developers. It's the definition of insanity.

Here is a summary of the ways we make sure we produce quality code.

Unit Tests - Break down the requirements into small bite sized logic questions and write tests around what the application chunk is supposed to be doing, expects and returns.

Write Documentation - Pretend you are a new hire and are asked how to do X. If your code has no documentation then basically any developer stepping in to the code is like "Whoah... " and usually takes a good bit of ramp up time just to figure out whats happening under the hood. I just don't believe in the mentality "Good code documents itself".

Empower Developers - Don't take the keyboard. Ask thought provoking questions in an effort to bring forth thought driven decisions.

Write More Documentation - I can't stress good documentation enough. It's literally invaluable to an organization because people change jobs, leave or get fired and sometimes all the information about a module goes with them.

Using version control (Git + Gitlab) - This is such a huge help. If you are able to implement something like this I highly suggest you do so. This will get many more eyes on the codebase, merge requests, productivity etc from your team. It's amazing.

Coding Style Guide - Create a style guide that you would like to see followed when others are coding. At the end of the day, all your code should look like it was written by one person. Not 100.

Make it fun - What? Huh? Coding fun? If you can make it more like a game (think xbox achievements) then people tend to try a little harder and it feels a lot less like work. We use a Jenkins build server which compiles some of our client side code. During this process we used CSS Lint and JS Lint to find issues and bad habits in our codebase and document them. If you were the one that made mistakes in the code, you got dinged. If you cleaned up code and reduced issues, you got points. We noticed immediately that developers were scouring the codebase in search of issues that would earn them points. (The Continuous Integration Game plugin)

I hope this adds some value to your situation and this post helps you in some way. So many great responses in here.

Title: Getting coders to do code review

Body:
I am running a project where I pay developers to contribute to my semi open source project. My problem is that it is easy to hire developers, but it is very difficult to get anyone to do code reviewing. I have repeatedly attempted to get the senior developers to review the code of the junior developers. I have attempted to pay them more, give them higher status etc. But they just seem to want to code instead of reviewing code.

Now I am considering forcing all developers that want to code, to also review code, but I have a feeling that it is a bad idea.

My question is, therefore, how can I motivate capable people to review the code of others? How is this done in successful open source projects like Linux, PostgreSQL, LibreOffice etc.


答:
When you do direct access to a file you are using a low level that can be used to build more sophisticated structures. Consider building a database with your data that allows the types of access you need, including insertion.

It would be less expensive if you only need to iterate through the file not do random accesses to a specified offset. If you need random access by offset in file you will need to update the index for all bytes beyond the insertion point.

In general, you will pay in indexing data structures, memory to store the index, and extra disk accesses to update it.


答:
Insertion into a file is not implemented in most file systems because it is considered an "expensive" (time-eating and space eating) operation with potentially long-term "expensive" repercussions and additional failure modes.

A file system with insertion semantics would probably either use shift&insert (potentially very expensive when you insert at the front of a large file, but no/few long-term side-effects) or some sort of generalized heap allocation with variable length allocation sizes (very ill-behaved performance in some cases [imagine the interactive users' faces if they try to save a file during a stop-the-world GC!]).

If you want to experiment, you can easily build a file I/O abstraction in Java or Python that implements insertion. If you succeed and it has well-behaved performance characteristics, you have the basis for an excellent research paper. Good luck.


问:
Dalvik + Java licensing question
This is a licensing question about the Dalvik and J2SE core libraries. In particular the license governing java.util.concurrent.SynchronousQueue.

The license header of the class in the JDK source states that it is GPLv2 only (see grepcode).
However, the same file in the Dalvik core libraries seems to be governed by the Apache 2 license only (see android source).

How is this possible? I didn't think you could take GPLv2 source and re-license it as Apache 2.

(It's obvious they did: a comment above the Java Doc even says "removed link to collections framework docs"!)

I'm asking because I have a GPLv3 project and would like to include a derivative work of some source from the core libraries (either Dalvik or J2SE) but publish it under GPLv3. I thought I could do this with Apache 2, but not GPLv2.

I know that the J2SE class source is itself derivative work from public domain source, but the changes from the original are substantial. (The original is available at gee.cs.oswego.edu if you are interested.) Therefore the android source really is just a copy of the J2SE source, but published under Apache 2 instead of GPLv2. Is Google really allowed to do this?

答:
As a comment here has pointed out, Android's class library is derived from Apache Harmony's class library. Parts of it have been changed by the Android project, but remain Apache 2.0 licensed.

Google's policy regarding code that is part of the Android Open Source Project (AOSP) is that Apache 2.0 (ASL 2.0) is the preferred license. All the bits Google created that are in AOSP are Apache 2.0 licensed. The Linux Kernel, which is used as part of the Android OS is GPLv2.

Android incorporates other projects, such as Webkit. Webkit uses LGPL and BSD licenses. Android's upstream projects are clearly labeled in the source tree, so there should be no cases where you are expecting Android's Apache 2.0 license but it turns out to be something else.

Title: Dalvik + Java licensing question


答:
1) You can design the core of your application logic without regard to a framework by essentially designing your own framework. Using CGI for Perl or C will be a good basis for the back end part. However, the database interface requires adaptation layers and shims.

2) You will need to develop adapter software for each database that you want to connect to. Since MongoDB and MySQL are completely different animals, you will have to aim for a least-common-denominator and make up the difference in your application.

3) Unfortunately, you won't be able to meet the requirements in 4 months. Developing and testing the interfaces to the individual databases will require substantial testing effort. If you use the Perl DBI, for instance, you will be able to address most SQL databases, requiring only customization for primary key auto-generation. Developing an equivalent for NoSQL databases will require a lot of effort.

As for throwing more money at the problem ... "Contrary to popular belief, nine women cannot deliver a baby in one month."


答:
You should definitely react on that exception.

How you do that is up to your context. If writing logs to a database fails, probably it is the same db the application uses, which is probably down. Thus this could be a good time to write an e-mail to an admin. Which, on the contrary can make your mail-server quite busy, and/or also fail.

Logging to a file is a good idea. However, if you expect that case never to happen, you need raise attention to that file somehow in such a case.

If it is an important application you may want to think about monitoring it (Nagios, for example, is a monitoring tool). Those tools usually are capable of continuously parsing log-files for errors.

Title: Exception when logging exception: is it correct to ignore them?

Body:
My question is specific to php, but i think it can be useful in other languages.

I log into a table all the exception a code can throw:

```<code>try{
 //Some code
 } catch (Exception $e) {
      $log = new Log(basename($_SERVER['PHP_SELF']), $_SESSION['id'], LogType::EXCEPTION, $e);
      try {
           $log ->addLog();
       } catch (Exception $e2) {
                //
       }
 }
</code>```

The function addLog insert the exception informations into a database.
But (by example if the connection with the database is lost) this function can throw an exception. I can't see what i have to do with this exception except ignoring it.

I know ignoring exception is a bad practice, but what can i do in this particular case?

If there is no problem to ignore it, is there a better way to indicate that this exception should not be taken into account?


问:
What is the Loopback Pattern?
I was reading this blog post about Hexagonal architecture and at the bottom it says:

The Loopback pattern is an explicit pattern for creating an internal replacement for an external device.

When I google for "Loopback pattern" I don't find any details about it.  Does anyone know what the author is referring to?  For curiosity's sake, I'd like to know how to implement this.

答:
I cannot speak for the author, but it sounds like this is used just as the quote says: replace an external device with software that allows testing other parts of the system that may use it.

For example, one could write a "loopback" printer driver that allows testing program functionality related to printing without actually printing anything. This could be a device that never runs out of paper and never actually consumes any real-world resources (i.e. paper) because it is a virtual device.

I have used these stubs before to test program functionality that interacts with hardware devices that are unreliable (e.g. might run out of paper) or that require user intervention (just fire an event with fake user input) but that do not need to track anything at the driver level (e.g. did a print job get submitted? How many?)

When tests are running in a headless environment in the middle of the night, such a virtual device is crucial.

Title: What is the Loopback Pattern?


问:
What does 'stage' mean in git?
I find git hard to understand as I could not find the meaning of the words used for the actions. I have checked the dictionary for the meaning of 'stage' and none of the meanings were related to source control concepts.

What does 'stage' mean in the context of git?

答:
The "stage" is a technically required intermediate step in the process of checking in a file, namely collecting the changes to be added to the repository. Git's authors chose to make this step visible and persistent where other VCS make it a transient part of the commit process. So it's just an option that git gives you because it can so why not?

The way I see it, the main thing the git "stage" gives you that other VCS don't is that you can use it to checkpoint a file. It's effectively an unnamed, uncommented local commit that gives you an intermediate step between being done with all your work and committing it to the repository permanently and having nothing saved in your local repo at all.

For example, let's say you have a feature partially finished. It's in a stable state, passes all the tests, and could go into production, but you have more work to do on it. You could stage all your changes and then continue to work on the feature.

Later, you'll have the option to just commit what you staged (and push that commit to the remote repository) or to add your new changes to your staging area and then commit that all at once, or to undo just your new changes and revert your working directory to the state it was in when you staged your changes.

It's completely possible to practically skip the staging area altogether and just use the -a option to git commit if you don't find the staging area a helpful concept. Lots of people skip staging and GUI tools usually allow for this, too.

Title: What does 'stage' mean in git?


问:
Programmers forgetting syntax
Do good programmers need to have syntax at the tip of their tongue when writing code? What do you make of them if they google for simple stuff online?  Are they good or bad(maybe they know where to look for)? Should programmers have a good memory? Is this a trait for a good programmer?</p>

答: My opinion is No. Its not syntax which is important but your logic towards solving a problem or achieving a goal If you suppose to work on multiple languages its natural that sometime you dont remember the exact syntax. </p>

Title: Programmers forgetting syntax


答:
As an example, I recently had a dependency on a remote Authorization service to validate user access tokens. But then I wrote a service that didn't need Authorization -- it just made calculations. So I implemented the AuthorizationService interface (name changed to protect innocent services) with a NoAuthorizationService that just returned true for validate(token).

I could use that same stub interface to stub out calls to the actual Authorization service. But I considered it a production artifact rather than a test artifact, because I could use that for a live service to plug into if I didn't want to otherwise disable calls to that service.

Think of "127.0.0.1", the loopback IP -- it just goes to localhost. It's a similar idea in a hexagonal architecture, where calls to a remote service are just looping back to the local service instead.

...

In the more common Gang Of Four lingo, this would be the Null Object pattern. Or else a "sentinel" object that takes the place of the real thing but doesn't do anything.

Title: What is the Loopback Pattern?

Body:
I was reading this blog post about Hexagonal architecture and at the bottom it says:

The Loopback pattern is an explicit pattern for creating an internal replacement for an external device.

When I google for "Loopback pattern" I don't find any details about it.  Does anyone know what the author is referring to?  For curiosity's sake, I'd like to know how to implement this.


问:
"Programming error" exceptions - Is my approach sound?
I am currently trying to improve my use of exceptions, and found the important distinction between exceptions that signify programming errors (e.g. someone passed null as argument, or called a method on an object after it was disposed) and those that signify a failure in the operation that is not the caller's fault (e.g. an I/O exception).

How should these two kinds of exceptions be treated differently? Do you think that error exceptions need to be explicitly documented, or is it enough to document the relevant preconditions? And can you leave out the documentation of a precondition or error exception if it should be obvious (for example, ObjectDisposedException when calling a method on a disposed object)

答:
A reasonable rule of thumb:

Catch any exception you can fix.

Catch, comment on and rethrow any exception you can't fix but can say something useful about.

Don't catch any exception you can't process or diagnose better than the default processing will.

You may want to have a top-level non-fatal exception handler to trap anything that couldn't be handled below to try to keep your application from falling over, but that's going to depend strongly on your particular application. For example, iOS applications prefer to trap as much as they possibly can; a command-line app may be perfectly OK if it traps almost no exceptions at all.


问:
alternatives to nested try-catches for fallbacks
I have a situation where I am trying to retrieve an object. If the lookup fails I have several fallbacks in place, each of which may fail.  So the code looks like:

```<code>try {
    return repository.getElement(x);
} catch (NotFoundException e) {
    try {
        return repository.getSimilarElement(x);
    } catch (NotFoundException e1) {
        try {
            return repository.getParentElement(x);
        } catch (NotFoundException e2) {
            //can't recover
            throw new IllegalArgumentException(e);
        }
    }
}
</code>```

This looks awfully ugly.  I hate to return null, but is that better in this situation?

```<code>Element e = return repository.getElement(x);
if (e == null) {
    e = repository.getSimilarElement(x);
}
if (e == null) {
    e = repository.getParentElement(x);
}
if (e == null) {
    throw new IllegalArgumentException();
}
return e;
</code>```

Are there other alternatives?

Is using nested try-catch blocks an anti-pattern? is related, but the answers there are along the lines of "sometimes, but it's usually avoidable", without saying when or how to avoid it.

答:
This would be really easy with something like an Option monad. Unfortunately, Java doesn't have those. In Scala, I'd use the Try type to find the first successful solution.

In my functional-programming mindset, I'd set up a list of callbacks representing the various possible sources, and loop through them until we find the first successful one:

```<code>interface ElementSource {
    public Element get();
}

...

final repository = ...;

// this could be simplified a lot using Java 8's lambdas
List<ElementSource> sources = Arrays.asList(
    new ElementSource() {
        @Override
        public Element get() { return repository.getElement(); }
    },
    new ElementSource() {
        @Override
        public Element get() { return repository.getSimilarElement(); }
    },
    new ElementSource() {
        @Override
        public Element get() { return repository.getParentElement(); }
    }
);

Throwable exception = new NoSuchElementException("no sources set up");
for (ElementSource source : sources) {
    try {
        return source.get();
    } catch (NotFoundException e) {
        exception = e;
    }
}
// we end up here if we didn't already return
// so throw the last exception
throw exception;
</code>```

This can be recommended only if you really have a large number of sources, or if you have to configure the sources at runtime. Otherwise, this is an unnecessary abstraction and you'd profit more from keeping your code simple and stupid, and just use those ugly nested try-catchs.

Body:
This would be really easy with something like an Option monad. Unfortunately, Java doesn't have those. In Scala, I'd use the Try type to find the first successful solution.

In my functional-programming mindset, I'd set up a list of callbacks representing the various possible sources, and loop through them until we find the first successful one:

interface ElementSource {
    public Element get();
}

...

final repository = ...;

// this could be simplified a lot using Java 8's lambdas
List<ElementSource> sources = Arrays.asList(
    new ElementSource() {
        @Override
        public Element get() { return repository.getElement(); }
    },
    new ElementSource() {
        @Override
        public Element get() { return repository.getSimilarElement(); }
    },
    new ElementSource() {
        @Override
        public Element get() { return repository.getParentElement(); }
    }
);

Throwable exception = new NoSuchElementException("no sources set up");
for (ElementSource source : sources) {
    try {
        return source.get();
    } catch (NotFoundException e) {
        exception = e;
    }
}
// we end up here if we didn't already return
// so throw the last exception
throw exception;

This can be recommended only if you really have a large number of sources, or if you have to configure the sources at runtime. Otherwise, this is an unnecessary abstraction and you'd profit more from keeping your code simple and stupid, and just use those ugly nested try-catchs.


答:
First, it seems to me there should be a function like repository.getMostSimilar(x) (you should choose a more appropriate name) as there seems to be a logic which is used to find to closest or most similar element for a given element.

The repository can then implement the logic like shown in amons post. That means, the only case an exception has to be thrown is when there is no single element that could be found.

However this is of course only possible if the logics to find the closest element can be encapsulated into the repository. If this is not possible please provide more information how (by which criteria) the closest element can be chosen.

Title: alternatives to nested try-catches for fallbacks

Body:
I have a situation where I am trying to retrieve an object. If the lookup fails I have several fallbacks in place, each of which may fail.  So the code looks like:

```<code>try {
    return repository.getElement(x);
} catch (NotFoundException e) {
    try {
        return repository.getSimilarElement(x);
    } catch (NotFoundException e1) {
        try {
            return repository.getParentElement(x);
        } catch (NotFoundException e2) {
            //can't recover
            throw new IllegalArgumentException(e);
        }
    }
}
</code>```

This looks awfully ugly.  I hate to return null, but is that better in this situation?

```<code>Element e = return repository.getElement(x);
if (e == null) {
    e = repository.getSimilarElement(x);
}
if (e == null) {
    e = repository.getParentElement(x);
}
if (e == null) {
    throw new IllegalArgumentException();
}
return e;
</code>```

Are there other alternatives?

Is using nested try-catch blocks an anti-pattern? is related, but the answers there are along the lines of "sometimes, but it's usually avoidable", without saying when or how to avoid it.


答:
The usual way to eliminate nesting is to use functions:

```<code>Element getElement(x) {
    try {
        return repository.getElement(x);
    } catch (NotFoundException e) {
        return fallbackToSimilar(x);
    }
}

Element fallbackToSimilar(x) {
    try {
        return repository.getSimilarElement(x);
     } catch (NotFoundException e1) {
        return fallbackToParent(x);
     }
}

Element fallbackToParent(x) {
    try {
        return repository.getParentElement(x);
    } catch (NotFoundException e2) {
        throw new IllegalArgumentException(e);
    }
}
</code>```

If these fallback rules are universal, you could consider implementing this directly in the repository object, where you might be able to just use plain if statements instead of an exception.

Body:
The usual way to eliminate nesting is to use functions:

Element getElement(x) {
    try {
        return repository.getElement(x);
    } catch (NotFoundException e) {
        return fallbackToSimilar(x);
    }
}

Element fallbackToSimilar(x) {
    try {
        return repository.getSimilarElement(x);
     } catch (NotFoundException e1) {
        return fallbackToParent(x);
     }
}

Element fallbackToParent(x) {
    try {
        return repository.getParentElement(x);
    } catch (NotFoundException e2) {
        throw new IllegalArgumentException(e);
    }
}

If these fallback rules are universal, you could consider implementing this directly in the repository object, where you might be able to just use plain if statements instead of an exception.


答:
Another way to structure a series of conditions like this is to carry a flag, or else test for null (better yet, use Guava's Optional to determine when a good answer is present) in order to chain the conditions together.

```<code>Element e = null;

try {
    e = repository.getElement(x);
} catch (NotFoundException e) {
    // nope -- try again!
}

if (e == null) {  // or ! optionalElement.isPresent()
    try {
        return repository.getSimilarElement(x);
    } catch (NotFoundException e1) {
        // nope -- try again!
    }
}

if (e == null) {  // or ! optionalElement.isPresent()
    try {
        return repository.getParentElement(x);
    } catch (NotFoundException e2) {
        // nope -- try again!
    }
}

if (e == null) {  // or ! optionalElement.isPresent()
    //can't recover
    throw new IllegalArgumentException(e);
}

return e;
</code>```

That way, you're watching the state of the element, and making the right calls based on its state -- that is, as long as you don't have an answer yet.

(I agree with @amon, though. I'd recommend looking at a Monad pattern, with a wrapper object like class Repository<E> that has members E answer; and Exception error;. At each stage check to see if there's an exception, and if so, skip each remaining step. At the end, you're left with either an answer, the absence of an answer, or an exception & you can decide what to do with that.)

Body:
Another way to structure a series of conditions like this is to carry a flag, or else test for null (better yet, use Guava's Optional to determine when a good answer is present) in order to chain the conditions together.

Element e = null;

try {
    e = repository.getElement(x);
} catch (NotFoundException e) {
    // nope -- try again!
}

if (e == null) {  // or ! optionalElement.isPresent()
    try {
        return repository.getSimilarElement(x);
    } catch (NotFoundException e1) {
        // nope -- try again!
    }
}

if (e == null) {  // or ! optionalElement.isPresent()
    try {
        return repository.getParentElement(x);
    } catch (NotFoundException e2) {
        // nope -- try again!
    }
}

if (e == null) {  // or ! optionalElement.isPresent()
    //can't recover
    throw new IllegalArgumentException(e);
}

return e;

That way, you're watching the state of the element, and making the right calls based on its state -- that is, as long as you don't have an answer yet.

(I agree with @amon, though. I'd recommend looking at a Monad pattern, with a wrapper object like class Repository<E> that has members E answer; and Exception error;. At each stage check to see if there's an exception, and if so, skip each remaining step. At the end, you're left with either an answer, the absence of an answer, or an exception & you can decide what to do with that.)