答: You may want to check out Docker (like a VM image) as a way to "containerize" your deployment. That way any OS that is able to run the docker module can take your containerized content and use it the same way you would. There are numerous existing Docker modules that you could even start with which will contain php, database images etc. The only issue would be your licensing requirements and what you need to use Docker in your particular case. I am using Docker for java, database and web front ends for a client of mine.</p>

Title: Deploy PHP application on customer server independent of the envirorment

Body:
Our company has developed a PHP(CakePHP) "Cloud" application that is running on our servers, now we have some customers that would like to use our service and make integrations to their local systems. The local systems are behind a firewall that won't be opened for us to access them from the "Cloud", therefore we need to deploy our system on their servers.

How to do this in a way that makes us able to:

Make it independent of existing software versions on the server(might be an old PHP version installed or something similar that we are not allowed to upgrade).

Update the system.

Track usage of the system(we charge based on features that the user can activate, no problem on Cloud were we have access to the database)

I think that we can assume that the server will have internet access. The initial installation will be done by us via VPN or on site, alternatively we can let the customer install it if the procedur is easy enought.

We think that we can solve 2 and 3 by letting the system make requests to some kind of "licensing server" that we need to build. Is there a best practice here or maby some ready to use software?

The biggest issue for us is 1., we are looking at setting up a virtual machine(the clients will not have vmware so were talking about something like virtualbox that can be running on an exsisting OS) that the entire system with all of it dependencies will run on, here we are also looking for any best practice advice. Maby a virtual envirorment isn't a good way to go?

Any help or thoughts is appriciated!


问:
Do you actually write 'clean code'?
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

答:
You must ensure that your code is very readable, clean and maintainable. That's what all programmers must do.

But you are talking about over styling (like that term better that girl-code) which serves nothing but the ego of its author.

I've seen many developers in the past so proud of their creation (you know, like in the restrooms ;)), they spent hours cleaning and polishing their code. Some of them were so meticulous that they ensured that the correct white spaces between members were respected.

It's too much.

I find that kind of behavior counterproductive. In a professional context, you must be professional. You can get your satisfaction by writing clean, very readable and maintainable code and talking with happy users or colleagues.

ContentLicense: CC BY-SA 3.0

Title: Do you actually write 'clean code'?


问:
How can the containsKey() method of a Java Hash Table be O(1)?
I had a very large ArrayList in Java, and I often need to check if it contains a particular value. This has proven very slow.

Then I discovered that you can use a data structure based on a Hash. Because apparently, a method like containsKey() is O(1).

Nice result - but, how is this achieved? Clearly it doesn't go key by key checking for a match.

I imagine it is similar to arrays: Why is the complexity of fetching a value from an array be O(1)? - however, I understand it for arrays since you only have to do some arithmetic to get the address of the desired data. But I am not quite sure how is this applied to Hash tables.

答:
The reason for hash access being O(1) is actually quite different from array access.

Arrays are contiguous memory areas. To read element 15, you only have to multiply the element size by 15 and add the start address. Both addition and multiplication are O(1) (it takes just as long to add two big numbers as two small numbers), and since computers provide O(1) memory access, the overall complexity is still O(1).

A hash works quite differently. It stores things at predictable places, but those indexed places are not user-visible. A string that you put into a hashtable isn't stored at the address you specify; instead the table takes the content of that string and computes a fitting address by hashing that content to a number taken from a small set of possibilities. Then it stores the value to that place, and if you ask for that key again, it re-computes the hashed value and looks up that cell.

Since the set of possible hash values is smaller than the set of possible keys, you can have collisions, so that you might have to spend a little more time to find the right value when more than one of them has been put into the same bucket, but it can be shown that this happens infrequently and doesn't affect the overall amortized complexity, which is still O(1).

So you see that an array can find things fast because you tell it where to load from; a hash table returns things fast because it knows where it put them, and can reconstruct that computation efficiently.


问:
Is it ever overkill creating classes/objects?
I just learned how to create a class or object in C++ and I'm practicing and learning.

I'm writing a text based version of a popular board game and I was wondering if it's overkill creating a class for six sided dice instead of creating a simple function generating two random numbers between 1 and 6 and returning the sum of the two.

答:
C++ supports several programming paradigms (including);

OO based techniques

Generic and template programming

Procedural style programming (coming from C)

Using any of these techniques where is appropriate is not going to be "overkill". The broader question is more what design or pattern would be appropriate for the problem being solved, given the context of the current implementation and domain specific constraints?

Since you are looking at this from a learning exercise, creating a class for dice would be fine, the object maps well to a physical thing - so go for it.

Would I create a class in a production application if all I wanted was two random numbers - maybe. I would use a function that returned a std::pair (std::pair<int,int> get_random(...)) and either provide the functions with the appropriate engine and distribution requirements as arguments, else have those arguments in an object to assist with the state management.


答:
I am not sure "looking good" and being "elegant, perfectly understandable and maintainable" is equivalent.

I try to write code, that is "elegant, perfectly understandable and maintainable". I do refactor my own code to better match those criteria.

I don't see any drawbacks, except the resulting cost in time.

For code to "look good", there are plenty of automated tools, that will properly indent and space everything as you wish.

Title: Do you actually write 'clean code'?

Body:
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

ContentLicense: CC BY-SA 2.5


问:
CQRS: How to restore read model
It's very interesting how to restore read model in system based on CQRS.

In regular mode system processes commands, creates domain events and posts them to message bus. Then another part of system (call it RM subsystem) processes these messages and saves them to read model. This mode is good enough for regular purpose.

But how should I repair my read model? For example storage with read model was corrupted or I changed location of storage. I want my system to restore read model during initialization, before queries begin to try read data. And I want to know the end of repairing process.

I can imagine two ways:

Create REST controller, throug which my RM subsystem will be able to query all domain events (in messages forms) and restore it synchronously.

Create special mechanism, calling which my RM subsystem will be able to start replaying all messages. As for me, this way isn't very good, because I cannot control time of finish of repairing process. And the second, if there are other consumers of messages, they probably can corrupt their data.

Which way is more preferable?

答:
Both methods are totally fine, and as usual, the answer is: "it depends".

The 2nd method you suggested is easy to implement and is used quite often - in particular, I'd consider it to be the standard method to bring new event handlers/projections online into an existing system, since new consumers need to be replayed the full event history at least once.

Regarding other consumers, please not that

you can (I'm tempted to say should) make them idempotent consumers, which at the same time helps with the "at least once"-guarantee paradigm of common message bus systems, and

you can always opt to only replay events into a single consumer, such that other consumers are not affected by the selective replay.

Furthermore, have you actually measured the time that it takes to replay all events into a single projection (the corrupted one)?  Usually you can easily handle tens of thousands of events and read model updates per second (use one big transaction), so replaying all events to repair a single read model should be a matter of minutes.  We actually replay all events on every system startup, since our read model is only stored in memory, and it's blazing fast.

If your event store/messaging infrastructure does not support query by event type, the 1st method you suggested is a bit harder to implement, since you need to implement the query interface.  This might be extremely hard or it might be trivial, depending on how your event store is designed.  So if you don't want to use the second method you suggested, implement the 1st method, use selective queries to repair a read model and call it a day.

Title: CQRS: How to restore read model


问:
If possible, would it be a bad practice to use Nullable for non value types?

After writing this question I found out that Nullable<T> has a type constraint of struct on T so you cannot actually use Nullable for
  reference types. However, some good answers interpreted the questions
  as 'if you could' or 'if you would write your own Nullable or
  NonNullable type'. This interpretation has lead to some nice answers
  so I've decided to not close or delete the question.

I know the nullable construct in C# was introduced to support null for value types. However, the language does not seem to have a problem with using nullable on other types. I wonder if this is a bad practice. I've come up with some arguments for both sides, but I can't decide.

Pros

Foo? x  makes it exceptionally clear that a variable can be null.

Cons

If Foo is not a value type we create a struct with a reference type which is a bad practice.

Why wrap a variable that can already be null with more boilerplate code. Comments or naming can already indicate that the value can be null.

Not marking the object as nullable does not guarantee that it will not be null. So inconsistent use will lead to confusion.

Performance overhead? (Extremely neligible in most cases).

It makes the code slightly harder to read

With nullable

```<code>Foo? x;

// <snip>

x = null;

// <snip>

if(x.HasValue) { x.Value.Bar(); }
</code>```

Without

```<code>Foo x; // Might be null

// <snip>

x = null;

// snip>

if(x != null) { x.Bar(); }
</code>```

答:
I think it would be absolutely amazing and at least some members on the Roslyn team seems to think it is a good idea.

The proposed modification to the language is the ! operator and a change to the ? which could be used for reference types which could be used like.

```<code>string! a;//can never be null
string  b;//no change
string? c;//can explicitly be null
</code>```

The beauty of this solution is there is no change to the generated IL so interop problems should be minimum. There should be some way to mark an assembly as safe which means it can't use the classical references, only ! and ?

Body:
I think it would be absolutely amazing and at least some members on the Roslyn team seems to think it is a good idea.

The proposed modification to the language is the ! operator and a change to the ? which could be used for reference types which could be used like.

string! a;//can never be null
string  b;//no change
string? c;//can explicitly be null

The beauty of this solution is there is no change to the generated IL so interop problems should be minimum. There should be some way to mark an assembly as safe which means it can't use the classical references, only ! and ?


问:
SRP and Getters/Encapsulation
I recently watched this presentation of Robert C. Martin about the Single Responsibility Principle:
https://www.youtube.com/watch?v=Gt0M_OHKhQE

He presents an Employee class with multiple responsibilities and suggests splitting the functionality into classes like EmployeeRepository and EmployeeReporter. I can very much relate to these refactorings, but I wonder if this is only possible, if we introduce lots of getters to the Employee class. How else is it possible for the Reporter class, to generate the Report? So for me it seems this breaks OO encapsulation and leads to classes, which pull data out of objects to perform operations with this data instead of the object operating on its data itself.

There are many discussions around the web, about getter being evil and breaking encapsulation, but for me it seems, the Single Responsibility Principle needs getters (at least to some degree), to work out.

Martin Fowler suggests, that Getters might be a sign for procedural code:

Although the defense of encapsulation is the common rallying cry for getter eradicators, I think the real motivation for them is rather more reasonable and pragmatic. There's a hell of a lot of code out there in OO languages that is procedural in design. The OO community may have 'won' in the sense that modern languages are dominated by objects, but they are still yet to win in that OO programming is still not widely used. As a result it's still common to see procedures that pull data out of an object to do something, when that behavior would better fit in the object itself - a violation of the pragmatic programmers principle of "Tell Don't Ask". You can only do this kind of procedural programming if you have getters, so telling people to get rid of getters helps push them to move behavior into the right place.

http://martinfowler.com/bliki/GetterEradicator.html

Any suggestions about this topic? Do you need Getters when following the SRP?

答:
The problem of getters is that they encourage to move logic from where it belongs—that is the class itself—to a different location, increasing both the complexity of the code and the coupling between classes.

Let's consider the following example. A product has a price. So naturally, you add a getter and a setter which makes it possible to get the price as well as change it.

Now, you need somewhere in your code to change the price of the article, because there is a rebate being applied or because a tax such as VAT changed. So you draft the code which uses the getter to find the current price, and the setter to set the new price.

Let's now imagine that you can't have getters or setters, and that getPrice and setPrice qualify as getters and setters as well. You can't trick anyone either by using different names, such as findPrice or changePrice. What do you do?

Well, you move your logic. And you start creating methods such as applyRebate or changeTaxes. See, now you have Product class which has responsibility over the logic which is related to products, and the logic related to products is entirely encapsulated by Product class instead of being scattered around.

Title: SRP and Getters/Encapsulation


问:
Better way of handling pre conditions and logging
1. Imagine you have the following:

void Foo::doFoo()
{
    if (!isConditionValid())
    {
        log("doFoo not possible because condition is not valid");
        return;
    }

    if (!isTheOtherConditionValid())
    {
        log("doFoo not possible because the other condition is not valid");
        return;
    }

    // do Foo actions
}
```

<p>Is there a better way to format the code?
Really often, I have 1,2 or 3 conditions, and I find it really repetitive to have this structure.</p>

<p><strong>2.</strong> What if I have the doBar method, that has the exact same conditions, so we would have:</p>

<pre class="lang-cpp prettyprint-override"><code>void Foo::doBar()
{
    if (!isConditionValid())
    {
        log("doBar not possible because condition is not valid");
        return;
    }

    if (!isTheOtherConditionValid())
    {
        log("doBar not possible because the other condition is not valid");
        return;
    }

    // do Bar actions
}
</code>```

I feel like I should refactor those conditions, but I find it difficult to find the name of the method. If call the method "areConditionsValid", I don't expect it to log anything, just to return a boolean. So the following doesn't seem right to me:

bool Foo::areConditionsValid(String action)
{
    if (!isConditionValid())
    {
        log(action + " not possible because condition is not valid");
        return false;
    }

    if (!isTheOtherConditionValid())
    {
        log(action + " not possible because the other condition is not valid");
        return false;
    }

    return true;
}
```

Because it does more than what it says it does.

I can't call it checkConditionsAndLog() because it is not good practice to have a "And" in the method's name, it is a good way to see that it's doing more than it should do...

What's the best way to refactor this?

The same applies if there is only one condition to check.

PS: It's in C++

答:
A problem I can see with your approach is that your preconditions return, instead of throwing an exception. Usually, preconditions throw an exception when violated. Since you are using C++, asserts can be used instead.

If you use exceptions/asserts, an additional refactoring can be made easily. Instead of:

if (!isConditionValid())
{
    log("doFoo not possible because condition is not valid");
    assert(false);
}

if (!isTheOtherConditionValid())
{
    log("doFoo not possible because the other condition is not valid");
    assert(false);
}

// do Foo actions
```

<p>you can have a method such as:</p>

<pre class="lang-cpp prettyprint-override"><code>void Contracts::require(predicate, message)
{
    if (!predicate())
    {
        log(message);
        assert(false);
    }
}
</code>```

and you call it this way:

Contracts::require(isConditionValid, "doFoo not possible because condition is not valid");
Contracts::require(isTheOtherConditionValid, "doFoo not possible because...");

// do Foo actions
```

Body:
A problem I can see with your approach is that your preconditions return, instead of throwing an exception. Usually, preconditions throw an exception when violated. Since you are using C++, asserts can be used instead.

If you use exceptions/asserts, an additional refactoring can be made easily. Instead of:

if (!isConditionValid())
{
    log("doFoo not possible because condition is not valid");
    assert(false);
}

if (!isTheOtherConditionValid())
{
    log("doFoo not possible because the other condition is not valid");
    assert(false);
}

// do Foo actions

you can have a method such as:

void Contracts::require(predicate, message)
{
    if (!predicate())
    {
        log(message);
        assert(false);
    }
}

and you call it this way:

Contracts::require(isConditionValid, "doFoo not possible because condition is not valid");
Contracts::require(isTheOtherConditionValid, "doFoo not possible because...");

// do Foo actions


答:
Simply use an implementation of code contracts,  in some implementations such as one provided in. Net these conditions can be checked in compile time.

https://github.com/Microsoft/CodeContracts

Title: Better way of handling pre conditions and logging

Body:
1. Imagine you have the following:

void Foo::doFoo()
{
    if (!isConditionValid())
    {
        log("doFoo not possible because condition is not valid");
        return;
    }

    if (!isTheOtherConditionValid())
    {
        log("doFoo not possible because the other condition is not valid");
        return;
    }

    // do Foo actions
}
```

<p>Is there a better way to format the code?
Really often, I have 1,2 or 3 conditions, and I find it really repetitive to have this structure.</p>

<p><strong>2.</strong> What if I have the doBar method, that has the exact same conditions, so we would have:</p>

<pre class="lang-cpp prettyprint-override"><code>void Foo::doBar()
{
    if (!isConditionValid())
    {
        log("doBar not possible because condition is not valid");
        return;
    }

    if (!isTheOtherConditionValid())
    {
        log("doBar not possible because the other condition is not valid");
        return;
    }

    // do Bar actions
}
</code>```

I feel like I should refactor those conditions, but I find it difficult to find the name of the method. If call the method "areConditionsValid", I don't expect it to log anything, just to return a boolean. So the following doesn't seem right to me:

bool Foo::areConditionsValid(String action)
{
    if (!isConditionValid())
    {
        log(action + " not possible because condition is not valid");
        return false;
    }

    if (!isTheOtherConditionValid())
    {
        log(action + " not possible because the other condition is not valid");
        return false;
    }

    return true;
}
```

Because it does more than what it says it does.

I can't call it checkConditionsAndLog() because it is not good practice to have a "And" in the method's name, it is a good way to see that it's doing more than it should do...

What's the best way to refactor this?

The same applies if there is only one condition to check.

PS: It's in C++


问:
How to write constructors which might fail to properly instantiate an object
Sometimes you need to write a constructor which can fail. For instance, say I want to instantiate an object with a file path, something like

```<code>obj = new Object("/home/user/foo_file")
</code>```

As long as the path points to an appropriate file everything's fine. But if the string is not a valid path things should break. But how?

You could:

throw an exception

return null object (if your programming language allows constructors to return values)

return a valid object but with a flag indicating that its path wasn't set properly (ugh)

others?

I assume that the "best practices" of various programming languages would implement this differently. For instance I think ObjC prefers (2). But (2) would be impossible to implement in C++ where constructors must have void as a return type. In that case I take it that (1) is used.

In your programming language of choice can you show how you'd handle this problem and explain why?

答:
I prefer not to initialize any class or list in constructor. Initialize a class or list whenever you need.
Eg.

```<code>public class Test
{
    List<Employee> test = null;
}
</code>```

Dont do this

```<code>public class Test
{
    List<Employee> test = null;

    public Test()
    {
        test = new List<Employee>();
    }
}
</code>```

Instead initialize when required
Eg.

```<code>public class Test
{
    List<Employee> emp = null;

    public Test()
    {
    }

    public void SomeFunction()
    {
         emp = new List<Employee>();
    }
}
</code>```

Body:
I prefer not to initialize any class or list in constructor. Initialize a class or list whenever you need.
Eg.

public class Test
{
    List<Employee> test = null;
}

Dont do this

public class Test
{
    List<Employee> test = null;

    public Test()
    {
        test = new List<Employee>();
    }
}

Instead initialize when required
Eg.

public class Test
{
    List<Employee> emp = null;

    public Test()
    {
    }

    public void SomeFunction()
    {
         emp = new List<Employee>();
    }
}


问:
Is it safe to use old code in a new project?
Here is the situation:

While working by company A on project A you developed a very fast and perfect search algorithm.

Then you switched to company B to work on project B which is totally different from project A, but you find yourself in need of implementing a search algorithm.

But you know or think that you are not going to come with a better algorithm and if you try to reimplement it, it will look very similar to the old one.

Would you use the algorithm that you developed before?

Is this practice/behavior safe and ethical?

答:
I'm not a lawyer, so this should not to be considered definitive legal advice.

You don't mention if there are license issues with the old code etc. So I'll assume they are proprietary.

In general, all code, trademarks and IP would belong to the company A. That is what you were basically paid to do there. The knowledge remains yours, but may be subject to a non-disclosure or restraint of trade of some sort. If the use of your knowledge is restricted, then I think there is little you can do.

In general what you know is yours, it is your skill and your trade - it would be very difficult to limit you and your ability to practice this.

If the algorithm developed really is unique - it should have been patented. If not patented (or pending) then the question becomes is there prior art or is this somehow public knowledge?

Frankly; if in doubt don't use it. "Do the right thing" - redevelop it; it'll probably have improvements, customisations and be in generally better off situation anyway.


答:
You can also calculate the result, and log if it fails.

Something like this :

```<code>bool Foo::areConditionsValid(String action)
{
    const bool result = isConditionValid() &&
                        isTheOtherConditionValid();

    if (!result)
    {
        log(action + " not possible because some conditions are not valid");
    }

    return result;
}
</code>```

I also find this more readable :

```<code>void Foo::doBar()
{
    if (!isConditionValid())
    {
        log("doBar not possible because condition is not valid");
    }
    else if (!isTheOtherConditionValid())
    {
        log("doBar not possible because the other condition is not valid");
    }
    else
    {
        // do Bar actions
    }
}
</code>```

Body:
You can also calculate the result, and log if it fails.

Something like this :

bool Foo::areConditionsValid(String action)
{
    const bool result = isConditionValid() &&
                        isTheOtherConditionValid();

    if (!result)
    {
        log(action + " not possible because some conditions are not valid");
    }

    return result;
}

I also find this more readable :

void Foo::doBar()
{
    if (!isConditionValid())
    {
        log("doBar not possible because condition is not valid");
    }
    else if (!isTheOtherConditionValid())
    {
        log("doBar not possible because the other condition is not valid");
    }
    else
    {
        // do Bar actions
    }
}


问:
What was the reason for the creation of boolean variables?
I found out that some languages like C don't have support for boolean variables and programmers use integers with values of 0 and 1 instead. Is there any specific reason why some languages moved away from this other than improved readability?</p>

答:
Built in boolean types are there to more succinctly express true or false (most typically in condition statements). The bool goes directly to being able to write a conditional that is semantically clear - testing for and creating boolean results in the code. It would be more natural and clearer to be able to use a genuine boolean type.

Originally C used integral values (there is now a type _Bool) with the condition that false was 0 (or NULL in pointer tests) and true was not false (not necessarily just 1). Which is generally all "well", but you then can't expressly/directly test for and store a true condition (only for a not false).


答: Just for readability, though this doesn't mean anything. There are no integral types for tri-state values even though they are very common in programming (eg comparison operators return one of 3 states)</p>

Title: What was the reason for the creation of boolean variables?

Body: I found out that some languages like C don't have support for boolean variables and programmers use integers with values of 0 and 1 instead. Is there any specific reason why some languages moved away from this other than improved readability?</p>


答:
In Java, every object have a hashCode() method that returns a 32 bit integer value, which is always the same for the same object. In the simplest version, a hashtable just contain an array of size 2^32, and a key-value pair is stored at the index corresponding to the hash code of the key. Since array access by index is O(1), hashtable access by key (for storing or retrieving) can also be O(1).

Of course it is a bit more complex in reality. First, you can always have collisions, that is, two different object giving the same hashcode. So the items are not stored directly in the array, rather each array index contains a "bucket", which is an ordinary list of key-value pairs. (In the Java hashtable the buckets are implemented as linked lists.) You have to search through the bucket to find the item and this search will be O(n), but unless your hashtable contains an extreme number of items (or your hash algorithm is bad), the items will be distributed pretty evenly across the array, and each bucket will contain only a few items. (Only one in the best case.)

Second, you will not initially create an array of size 2^32, since that would be a crazy waste of space. Instead you initially create a smaller array, where each entry maps to multiple hashcodes. This will of course lead to higher risk of collision. You keep track of the number of entries, and when they reach a certain threshold you double the size of the array, and then re-distribute the items. Of course this will also have a performance cost. There is some design tradeoff in deciding when to resize the array. The bigger the array relative to the number of items, the fewer collisions and hence better performance, but also more waste of space.

So finding an item is O(n) in the worst case where all items happen to end up in the same bucket, but O(1) in the common case (given a well-behaved hash function. Since anybody can override hashCode() this is of course not guaranteed. If you write int hashCode(){return 17;} you get worst case performance consistently). And if the number of items grows larger than the hash size, the buckets start to grow and again you get O(n) lookup. On 32 bit systems you would run out of memory before this ever happened, but with 64 bit memory it could theoretically be an issue.

Adding an item is also O(1) in the common case, but O(n) if the add triggers a resize of the array. However the aggregate cost of the resize operations are predictable and proportional to the number of items, so the amortized cost for adds is still O(1). This is not the case for the worst case with lookups, since if we are unlucky and all items ends up in the same bucket every lookup will have the worst-case performance and there is no way to amortize this cost.

Of course both the worst case and the common or average case may be relevant. In a real-time system, it is pretty important to know the worst case performance of an operation. For most business application, there average case is the more important metric.

Title: How can the containsKey() method of a Java Hash Table be O(1)?

Body:
I had a very large ArrayList in Java, and I often need to check if it contains a particular value. This has proven very slow.

Then I discovered that you can use a data structure based on a Hash. Because apparently, a method like containsKey() is O(1).

Nice result - but, how is this achieved? Clearly it doesn't go key by key checking for a match.

I imagine it is similar to arrays: Why is the complexity of fetching a value from an array be O(1)? - however, I understand it for arrays since you only have to do some arithmetic to get the address of the desired data. But I am not quite sure how is this applied to Hash tables.


答:
When talking about measurements (even abstract measurements such as "algorithmic complexity") you should always specify exactly what you are measuring, otherwise what you say is completely meaningless.

In this particular case, you are simply saying "hash tables are O(1)", but you are not saying what exactly you are measuring.

In particular, accessing a value by key in a (properly designed) hash table has

worst-case step complexity of O(n) (or more precisely, worst-case step complexity of whatever data structure is used for the "bucket", which usually is a simple linked list)

amortized worst-case step complexity of O(1)

In other words, your whole confusion is due to the fact that you are talking about the worst-case and the others are talking about the amortized worst-case, but except for @Kilian Foth nobody bothered to mention that.

The argument is similar to the one for why adding an element to a dynamically-sized array is O(n) worst-case and O(1) amortized worst-case. @JacquesB explains how this amortization works for hash tables.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
I personally find Donald Knuth's phrase: "premature optimization is the root of all evil" as the first evil thing in programming. In an expirienced point of view (that says that i have failed for this).

Actually, the phrase says something like: Don't try to understand the problem in a particular enviroment, particular PC or set of users before you get in deep into the problem.

Title: Is anything in programming truly evil?


问:
How do Java AOT compilers work?
There are a few number of tools out there (Excelsior JET, etc.) that claim to transform Java app's into native executables (*.exe). However it is my understanding that these tools are really just creating native wrappers that invoke/execute java from a shell or command-line.

If that understanding is incorrect, I don't see how it could be. If a running JVM (java process) is essentially a high performance interpreter, loading bytecode from Java classfiles on the fly, then I don't see how a Java app (a collection of bytecode files that serve as input to a JVM) could ever be truly converted into an executable.

This is because the JVM process is already a native executable that takes sets of bytecode files as input. To merge those bytecode files and the JVM process into a single, unified native executable doesn't seem possible without completely rewriting the JVM and de-railing from the JVM specification.

So I ask: how do these tools actually "transform" Java class files into a native executable, or do they?

答:
gcj minimal runnable example

You can also observe an open source implementation like gcj (now obsolete). E.g. Java file:

```<code>public class Main {
    public static void main(String args[]) {
        System.out.println("hello world");
    }
}
</code>```

Then compile and run with:

```<code>gcj -c Main.java
gcj --main=Main -o Main Main.o
./Main
</code>```

Now you are free to decompile it and see how it works.

file Main.o says it is an elf file.

readelf -d Main | grep NEEDED says it depends on the dynamic libraries:

```<code>0x0000000000000001 (NEEDED)             Shared library: [libgcj.so.14]
0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
</code>```

So libgcj.so must be where Java functionality is implemented.

You can then decompile it up with:

```<code>objdump -Cdr Main.o
</code>```

and see exactly how it is implemented.

Looks much like C++, lots of name mangling and indirect polymorphic function calls.

I wonder how the garbage collection kicks in. It would be worth looking into: https://stackoverflow.com/questions/7100776/garbage-collection-implementation-in-compiled-languages and other compiled languages with GC like Go.

Tested on Ubuntu 14.04, GCC 4.8.4.

Also take a look at https://en.wikipedia.org/wiki/Android_Runtime , the backbone of Android 5 onwards, which does full AOT to optimize Android apps.

Title: How do Java AOT compilers work?

Body:
gcj minimal runnable example

You can also observe an open source implementation like gcj (now obsolete). E.g. Java file:

public class Main {
    public static void main(String args[]) {
        System.out.println("hello world");
    }
}

Then compile and run with:

gcj -c Main.java
gcj --main=Main -o Main Main.o
./Main

Now you are free to decompile it and see how it works.

file Main.o says it is an elf file.

readelf -d Main | grep NEEDED says it depends on the dynamic libraries:

0x0000000000000001 (NEEDED)             Shared library: [libgcj.so.14]
0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]

So libgcj.so must be where Java functionality is implemented.

You can then decompile it up with:

objdump -Cdr Main.o

and see exactly how it is implemented.

Looks much like C++, lots of name mangling and indirect polymorphic function calls.

I wonder how the garbage collection kicks in. It would be worth looking into: https://stackoverflow.com/questions/7100776/garbage-collection-implementation-in-compiled-languages and other compiled languages with GC like Go.

Tested on Ubuntu 14.04, GCC 4.8.4.

Also take a look at https://en.wikipedia.org/wiki/Android_Runtime , the backbone of Android 5 onwards, which does full AOT to optimize Android apps.

ContentLicense: CC BY-SA 4.0


答:
... overkill creating a class for six sided dice instead of creating a simple function generating two random numbers between 1 and 6 and returning the sum of the two.

As ever, it depends.

You don't say which game you're implementing, but are you only ever going to use 6-sided dice?  If so, then stick with a function.  If you want to go all "OO" with this then, as it stands, you could make this function into a static method on a helper class.

But, if you wanted to add 'D10's and 'D20's into the mix later on, then a class might be a far better starting point.

Title: Is it ever overkill creating classes/objects?

Body:
I just learned how to create a class or object in C++ and I'm practicing and learning.

I'm writing a text based version of a popular board game and I was wondering if it's overkill creating a class for six sided dice instead of creating a simple function generating two random numbers between 1 and 6 and returning the sum of the two.


问:
Developing an application where a chunk of the code is used by both the app the tests
I'm developing a web app in PHP where part of the code I'm developing for it will also be used in the tests. I'm not sure how to handle this. That code in question is an abstraction to communicate with eBay's soap/xml API.

I hope the following makes sense...Apologies for another long question!!

Specifically I'm writing an eBay management system that has a GUI which automates eBay processes. I'm using test driven development, and my first acceptance test has highlighted this quandary.

My first feature will show the user a list of orders placed. And the test will first, using Ebay's API, upload an auction in eBay's sandbox, then using a test customer, purchase an item on his behalf, and finally, it will test that the user of my software will see that purchased item in the GUI (which the app will have done by getting order history from eBay's API.

Initially I was going to write a set of objects that provide the app with an object oriented API for interracting with eBay, and have this as part of the application code, so not particularly re-usable. Or at least, not really packaged up in any kind of way, besides good OO principles. But if I continue with this plan, the test scripts would have to "borrow" the source code in the tests, and add functionality to the eBay portion of my code which would only be used in the tests, since it overlaps in part, and not in other parts. (The eBay authentication and similar is a common requirement for the app and the tests, but the other API calls at least to start with do not overlap). If I follow this idea, the problem is I don't know how I should treat the parts of the eBay code that only the tests use; should I write unit/integration tests for those, even though they're only used by the acceptance/integration app tests? Or would the act of using those test-only eBay module features in tests to test app-only eBay module features be enough to act as sufficient tests in case I decide to use the test-only eBay module features in the application?

I was considering extracting the eBay code into a totally separate project (e.g. using composer, and putting it in a separate repository). Then importing the whole thing firstly into the test directory, and also duplicating it in the app's source directory. Then adding features as needed (by the test or the app), and unit/integration testing all aspects of the eBay module equally, even if some aspects are only used by the app, and others only by the app's tests. But then I think the same issue would still apply!! The module's tests would need to use parts of the module to perform the tests on other parts of the module!

答:
It seems like a fairly classical testing scenario. The solution is to test both the ebay abstraction by integration testing against ebay. You don't want to do this everywhere as it will slow down all your tests so keep it to a minimum.

When you are fairly sure that the abstraction works you can replace it with a mock when testing the rest of your code. Then you just assert that the correct method was called on the mock and call it a day.


问:
When was Java's 'qualified this' introduced?
I've only recently learned about the qualified this, and was curious as to when was it introduced in the language, as I've been using Java here and there for around 18 years.

Oracle keeps only the specifications for Java SE up to 6, but I cannot find any earlier versions online. I'm curious if it was there all this time (but I never paid attention to it) or is it something introduced later.

答:
I've found the answer after some additional searching: It was introduced in Java 1.2.
It's not in the 1.0 specification, but it appears in 2.0.</p>


问:
What is the difference between synchronous and asynchronous data transmission?
I have a device that is a source of data. It is connected to a PC where my program is running. I have two scenarios of how to get the data from that device.

I am wondering, which one is synchronous and which is asynchronous data transmission?

I start the device and my program executes a thread that periodically polls the device for new data.

I register a callback function in my program with the device and whenever there is new data available, the device calls my callback function.

答:
I'm not really sure the title question relates to the question in the post. I am assuming that the IO operations seem to be the correct question here.

Synchronous and asynchronous IO operations

This would normally mean that a request to IO would wait for a response before execution continues. Asynchronous operation make a request to IO, typically together with a callback or an identified signal that is then used by the IO handler to callback or signal the original caller of the result.

In your question; 1 would be typical of synchronous operations, and 2 for asynchronous operations.

Side note:

Synchronous and asynchronous data transmission

This relates to the synchronised (or not) communication of the underlying physical link (on the wire if you will). In synchronous schemes, there is typically a clock line that synchronises clients on the wire. In the absence of a clock, clients could attempt to access the line at any point.


答:
I don't think I like the term "girl code" but clean code = maintainable code. Anything less is unprofessional.

As a general rule, I consider the next developer that has to look at my mess.

A lot of the time it is me...several months later...when I don't remember how it works...and I have even less time to make a change.

Title: Do you actually write 'clean code'?


问:
AngularJS directive as components
I am in a project where we want to componentify a lot of "information boxes".

These boxes (lets say they are mostly different types of tables) should easily be included into different pages and even different projects(we include the components as a library into an angular js project, so angular js a requirement). In the long run these components might even be available as an API for other developers to use.

So far the directives include their own template, a common css styling + a unique style for the component, a set of testdata files.

So my question is basically: can this be a good approach? Is it faulty to make the directives actually load the data themselves or should I always pass the data to them?

The reason I want the directive to load data themselves is that I include testdata in the library allowing for testing the components in place (on for instance a dashboard) without having to implement the "real" data.

Also, the components will have at least three states (loading, faulty data, finished loading) which I think should lie with the directive, again prompting for the directive to load the data itself.

My thought was to either pass (for testing):

```<code><my-directive test-data="testfile.json">
<my-directive load-data="/myurl">
</code>```

Is this a good approach. If yes, should I put the data loading in the directive controller and utilizing some common "data-fetching-service" for all components?

I understand that this "question" is more a ramble than anything else but it's really hard to make a design decision which such limited angularjs knowledge, so I am reaching out!

答:
So far the directives include their own template, a common css styling + a unique style for the component, a set of testdata files.

So my question is basically: can this be a good approach?

If your directives are variations of visualization, but keep the same functionality, I recommend you to have only one main directive and create inner directives that allow the developer to customize how it'll look.

A good example of this includes Angular UI Bootstrap Tabs.

Is it faulty to make the directives actually load the data themselves or should I always pass the data to them?

Directives are pieces of reusable components. If you embed the data loading into the directive, your controllers will be simpler.

But what if there's a need to filter that data in just an specific part of your application? Let the developer pass the data they want, either filtered or not.

The reason I want the directive to load data themselves is that I include testdata in the library allowing for testing the components in place (on for instance a dashboard) without having to implement the "real" data.

A good approach would be to create a myComponentTestData service, which allow you to decide from the controller what to use, and then pass that data to your directive.

Also, the components will have at least three states (loading, faulty data, finished loading) which I think should lie with the directive, again prompting for the directive to load the data itself.

You're right in thinking that the state should lie in the directive. You can control this behavior by passing a promise instead of the fetched data -- if the promise is fulfilled, then you test if your data is faulty or not.

Title: AngularJS directive as components


问:
Can I change a theme and then sell it?
I am thinking of starting with the "Start Bootstrap" theme from Bootstrap and I want to change it and add stuff, new pages to work with Wordpress and then put it up for sale.

http://startbootstrap.com/template-overviews/creative/

Under the Apache License Version 2.0 can I change (back-end and front-end) a theme and then sell it? Can I take credit for my work? And if not then what I am allowed to do under this policy?

答:
The Apache License Version 2.0 is an Open Source license. This means that you can take the material under the Apache license, make changes to it and re-distribute the changed version.

The restrictions that you have are

The original startbootstrap theme must remain under the Apache License Version 2.0

You are not allowed to remove or change the copyright or license notices in the files that you didn't create yourself

You are permitted to make changes and even to provide your changed theme under a proprietary license and ask money for it.

Title: Can I change a theme and then sell it?


问:
What is better to return from the controller - a JsonResult or a string?
I have a WebAPI application and I have a controller method which is used to return a json result to the UI.

Now, I can either return a string (because the json is basically a string - and it works properly), or I can return a JsonResult from System.Web.Http.Results.

Are there any advantages to using the JsonResult?

答:
It depends. How is the result meant or expected to be used?

If it should be a string (i.e. no associated json semantics), then return it as a string.

If you wish to use of the facilities associated with the json data, then keep the JsonResult.

If you are unsure, keep the JsonResult and let the client convert it if they require it to be just a string.


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

答:
Laptop with 1920X2000 pixel resolution and 4 virtual desktops.

Yes, laptops severely lack the ergonomics of a full keyboard but I'm addicted to the low tactile feedback needed to type. I can type faster on a laptop keyboard than a full keyboard any day.

Tossing it into a bag and going somewhere else to code is always useful too. Being a slave to your desktop can be depressing and makes me feel like breaking out sometimes.

As far as impact injuries go, I actually type on a laptop keyboard with my wrists at a 45 degree angle anyway. I'm not sure if that's normal for most but it just feels natural to me now.

The external desktop isn't really necessary unless you need to see a direct material reference while coding. Other than that, I don't see much use for it. Multiple virtual desktops do a much better job of isolating responsibilities.

I usually use 4:

one for a web browser

one for revision control stuff

one for the IDE

one for unit testing

I also make it easy to switch by assigning the super+left and super+right to cycle between the desktops. Only having what your working on on the screen at any given time makes it much easier to stay focused on the task at hand.

The extra monitors just serve to take up valuable desktop space that I'd rather use sketching notes down on paper. It's amazing how much easier ideas can flow on paper.


问:
The Programmers Bill of Responsibilities
So, we've all heard of The Programmers Bill of Rights and XP has a similar concept.

It's a common complaint these days that we hear a lot about people's rights but not so much about their responsibilities, so what should be on the programmers bill of responsibilities.  That is things that they should do, which they may find unpalatable, but that which separate programmers acting professionally and responsibly, from those who do not.

I'm primarily interested in the unpalatable ones and the ones which tend not to happen.  That is the ones that programmers tend to shirk and avoid, rather than the ones which 90% of programmers actually want to do (such as always refactor and use source control).

So, what should be on the Programmers Bill of Responsibilities?

答:
A programmer is responsible for converting user stories in the product backlog into working and shippable software increments

That's why managers should ensure that they have everything to their goal.


问:
Template Function: Passing Iterators
I am struggling with making a design choice in the following setup:

I am writing (C++) functions which take a pair of iterators (to template containers) and compute a return value of the same type that the iterators are pointing to.

Let's say I want to implement a sum function (this is just an example to illustrate the point).

The way I see it I have two options and both have a downside:

Option 1

Make the function template parameter T defining the type the container stores.

I only need one parameter but I can only use the function on iterators of MyContainer.

```<code>template <class T>
T sum(typename MyContainer<T>::IteratorRange range){

    T sum;
    for (auto it = range.first; it < range.second; ++it) {
        sum += *it;
    }
    return sum;
}
</code>```

Option 2

Have the function take an arbitrary IteratorRange template class
and a second class U determining the return type.

While the iterators can be sourced from any container, I need two template classes even though the return type is always the same type as pointed to by the iterators.

```<code>template <class IteratorRange, class U>
U sum(IteratorRange range){

    U sum;
    for (auto it = range.first; it < range.second; ++it) {
        sum += *it;
    }
    return sum;
}
</code>```

Which option is cleaner or is there an alternative offering the benefits of both options?

Bonus Question

How should one initialize the sum variable?

答:
The range to iterate over

The C++ standard library offers something of a canonical form here, accumulate;

```<code>template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );
</code>```

It takes a range from first to last (excluding last) and adds each element in the range to the init value as an initial value. It will also infer the return type from the initial type.

If the an implementation of sum is required, I would advise the use of accumulate here as is. If not suitable, the function signature taking the range [first, last) is "normal" as it mirror the standard library.

Deduce the return type

To get the value type "behind" the iterator, std::iterator_traits, in particular the embedded type value_type can be used;

```<code>typedef typename std::iterator_traits<InputIt>::value_type Result;
// .. default initialise
Result sum = Result{}; // or Result() if earlier than C++11
</code>```

Design choice

I would design the function to (variation of option 2);

Accept a range [first, last)

Use std::iterator_traits (that work with pointers as well) to infer the return type

Use the C++11 default initialisation to initialise the result

As follows:

```<code>template <class Iterator, class U = typename std::iterator_traits<Iterator>::value_type>
U sum(Iterator first, Iterator last)
{
    U sum = U{};
    for (auto it = first; it != last; ++it) {
        sum += *it;
    }
    return sum;
}
</code>```

An alternative with reduced template arguments.

```<code>template <class Iterator>
typename std::iterator_traits<Iterator>::value_type sum(Iterator first, Iterator last)
{
    using U = typename std::iterator_traits<Iterator>::value_type;
    U sum = U{};
    for (auto it = first; it != last; ++it) {
        sum += *it;
    }
    return sum;
}
</code>```

Title: Template Function: Passing Iterators

Body:
The range to iterate over

The C++ standard library offers something of a canonical form here, accumulate;

template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );

It takes a range from first to last (excluding last) and adds each element in the range to the init value as an initial value. It will also infer the return type from the initial type.

If the an implementation of sum is required, I would advise the use of accumulate here as is. If not suitable, the function signature taking the range [first, last) is "normal" as it mirror the standard library.

Deduce the return type

To get the value type "behind" the iterator, std::iterator_traits, in particular the embedded type value_type can be used;

typedef typename std::iterator_traits<InputIt>::value_type Result;
// .. default initialise
Result sum = Result{}; // or Result() if earlier than C++11

Design choice

I would design the function to (variation of option 2);

Accept a range [first, last)

Use std::iterator_traits (that work with pointers as well) to infer the return type

Use the C++11 default initialisation to initialise the result

As follows:

template <class Iterator, class U = typename std::iterator_traits<Iterator>::value_type>
U sum(Iterator first, Iterator last)
{
    U sum = U{};
    for (auto it = first; it != last; ++it) {
        sum += *it;
    }
    return sum;
}

An alternative with reduced template arguments.

template <class Iterator>
typename std::iterator_traits<Iterator>::value_type sum(Iterator first, Iterator last)
{
    using U = typename std::iterator_traits<Iterator>::value_type;
    U sum = U{};
    for (auto it = first; it != last; ++it) {
        sum += *it;
    }
    return sum;
}


答:
They are semantically different types, used for different purposes, so it's very useful for the type checker to be able to distinguish between them.  Take this infamous bug, for example:

```<code>if (x = 1)
  ...
</code>```

In most languages, the type checker will catch this, because it is expecting a boolean, but got an int (or unit/void in languages where assignments don't return their value).  C is one of very few languages that permit this particular bug.

Body:
They are semantically different types, used for different purposes, so it's very useful for the type checker to be able to distinguish between them.  Take this infamous bug, for example:

if (x = 1)
  ...

In most languages, the type checker will catch this, because it is expecting a boolean, but got an int (or unit/void in languages where assignments don't return their value).  C is one of very few languages that permit this particular bug.


问:
How to share data members between classes in C++ without violating encapsulation too much
In C++ let's say I have some class A:

```<code>Class A
      {
      int a1, a2, a3;

      void foo();
      }
</code>```

and I need to use a subset of members (a1, a2) in a member function for a second class B.

What I'm wondering is whether I should define the arguments of B's member function by passing a pointer to A as an argument, or whether I should pass the members of A as arguments. e.g.,

```<code>Class B
      {
      int b1, b2;

      void bar(A &a);
      }
</code>```

or should this be

```<code>Class B
      {
      int b1, b2;

      void bar(int a1, int a2);
      }
</code>```

The latter would seem to minimize having to violate encapsulation, because B can then be largely agnostic about the constituents of A; whereas, in the former case, B would have to know something about the members of A. So it would seem the second implementation would be preferable.

Another reason the first implementation seems problematic to me is that, ideally, I'd like to keep the members (a1, a2, a3) of A protected rather than public. Normally I'd be tempted to make B a friend class of A, but the problem here is that A and B will both each have several derived classes, and since friendship doesn't inherit in C++ that wouldn't seem to be a good solution.

So these reasons would argue for using something like the second definition of B. However, in the actual code I'm dealing with, there are quite a few (about 6 or more) members of A that B will require, so this could get unwieldy. Being able to just pass a pointer to A would seem preferable from a readability standpoint and hide the details of what B.bar() requires from other parts of the code that deal with B.

Perhaps one work around would be to have methods inside A that do something like:A::get_a1() {return this->a1} or something, but I'm also not sure if that's really the correct design solution here.

答:
However, in the actual code I'm dealing with, there are quite a few (about 6 or more) members of A that B will require, so this could get unwieldy.

Create a Data Transfer class that holds the members you wish to transfer from class A to class B, and then write your method on class B so that it takes an instance of the new class.


问:
Do you actually write 'clean code'?
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

答: I just write my code, following the company standards.  If I want it "prettied up," I can run it through a code beautifier.</p>

Title: Do you actually write 'clean code'?


答:
Neither is a synchronous operation. In both cases your program will continue running while the data loads, and will later get the data once it finishes loading. That is an asynchronous approach to loading data.

Synchronous data loading would be if the program stops entirely until the data is loaded.

Title: What is the difference between synchronous and asynchronous data transmission?

Body:
I have a device that is a source of data. It is connected to a PC where my program is running. I have two scenarios of how to get the data from that device.

I am wondering, which one is synchronous and which is asynchronous data transmission?

I start the device and my program executes a thread that periodically polls the device for new data.

I register a callback function in my program with the device and whenever there is new data available, the device calls my callback function.


问:
Git Question: What to do when multiple people working on a project?
I made a project and put it on github, it's basically a small powershell function that is pretty useful in some situations.  I've since made some improvements to it to add functionality...but someone else liked it as well and made his own 'dev' branch to it.

I don't want to be a jerk and ignore his changes, but I also like the code that I made and my new changes are pretty great for what people will be doing with this tool.  What would be considered the best practice in a situation like this?  Should I rename my changes as Scriptv2.ps1?  Should I just push my new changes in a commit and let the other party make his tweaks again?

What's considered polite in a situation like this one?

答: Collaboration is the reason why git is powerful! Go ahead and make your changes in a new commit. The other developer will be able to then merge your changes back into his branch and continue working on whatever extensions or changes he wants. Any merge conflicts that arise are something that he is responsible for; not you.</p>


答:
It proved very helpful to standardize them.

You'd think 0 is 'false' and 1 is 'true' is easy.  However, it is also common to see -1 for 'true,' because in 2's complement notation, that is all 1's.  The more generalized version is also used: 0 for false and non-zero for true.  However, that leads to interesting situations where you can bitwise AND two non-zero values together and get a false value, so much consternation occurred.

In the end, the confusion of using different boolean conventions from library to library was sufficient.  We now have bool to handle that.

(And even then, it doesn't always work if you get code from different compilers and try to link them!)


问:
Should I Include PHP code in HTML or HTML in PHP?
What is the best practice, to write my PHP code inside my HTML code or HTML inside PHP?

PHP inside HMTL:

```<code> <p class="lead">Welcome to the <?= COMPANY_NAME ?> website.</p>
</code>```

HTML inside PHP:

```<code> <?php
      echo '<p class="lead">Welcome to the ' . COMPANY_NAME . ' website.</p>';
 ?>
</code>```

Is there a difference in performance? Which is the best practice? As in, which would produce code that is best maintained.

Also COMPANY_NAME is defined as such:

```<code>define("COMPANY_NAME", 'MyCompany');
</code>```

答:
You would have a better chance of resolving Sunni/Shite differences than you will of getting a clear answer to this sort of question.

For myself, I like React's notion of components and PHP
s heredoc syntax.

```<code>class CompanyComponent
{
    public function __construct($company)
    {
        $this->company = $company;
    }
    protected function escape($string)
    {
        return htmlspecialchars($string, ENT_COMPAT | ENT_HTML5, 'UTF-8');
    }
    public public function render()
    {
        $companyName = $this->escape($this->company['name']);
        return <<<EOT
<p class="lead">Welcome to the {$companyName} website.</p>
EOT;
    }
}
$companyComponent = new CompanyComponent(['name'=>'Trump']);
echo $companyComponent->render();
</code>```

Body:
You would have a better chance of resolving Sunni/Shite differences than you will of getting a clear answer to this sort of question.

For myself, I like React's notion of components and PHP
s heredoc syntax.

class CompanyComponent
{
    public function __construct($company)
    {
        $this->company = $company;
    }
    protected function escape($string)
    {
        return htmlspecialchars($string, ENT_COMPAT | ENT_HTML5, 'UTF-8');
    }
    public public function render()
    {
        $companyName = $this->escape($this->company['name']);
        return <<<EOT
<p class="lead">Welcome to the {$companyName} website.</p>
EOT;
    }
}
$companyComponent = new CompanyComponent(['name'=>'Trump']);
echo $companyComponent->render();


问:
const reference and const pointer. How do they work?
I read a post about how const storage works.

How does const storage work? (Item 2, Scott Myers Effective C++)

This says that each segment has separate section of write protected memory and const data goes there.

But what happens in case of references?
I want to understand three scenarios.

Global const reference.

const reference in method.

const reference in a class.

And for that matter pointers, I mean even though pointer can be stored in some write protected section, then how different versions of consts maintained.

such as

```<code>char x = 'z';
//following can not change the data of x, but ptr itself can change.
const char* ptr = &x;
char y = '9';
ptr = &y;
</code>```

above is allowed but following is not

```<code>char* const ptr1 = &x;
ptr1 = &y;
</code>```

How this is handled?

答:
Const keyword is directive to compiler that its initial value will never change. Compiler checks if during compiling if program is modifying the value by any way.
Please clear your understanding about constant variable and write protected variables are entirely different things.
It is similar to textbook definition of "Variable"

In programming, a variable is a value that can change, depending on
  conditions or on information passed to the program. Typically, a
  program consists of instruction s that tell the computer what to do
  and data that the program uses when it is running.

But actually variables is name given to memory location and it can be constant also.


答:
The most readable is php in html but only a little. You should split your file in two parts. Logic in the top. Here you prepare all variables but no html.

In the bottom you put html with variables and a loop or two but little to no logic.

Of course this doesn't scale all that well. For larger projects you should probably use a mvc framework.

Title: Should I Include PHP code in HTML or HTML in PHP?

Body:
What is the best practice, to write my PHP code inside my HTML code or HTML inside PHP?

PHP inside HMTL:

```<code> <p class="lead">Welcome to the <?= COMPANY_NAME ?> website.</p>
</code>```

HTML inside PHP:

```<code> <?php
      echo '<p class="lead">Welcome to the ' . COMPANY_NAME . ' website.</p>';
 ?>
</code>```

Is there a difference in performance? Which is the best practice? As in, which would produce code that is best maintained.

Also COMPANY_NAME is defined as such:

```<code>define("COMPANY_NAME", 'MyCompany');
</code>```


答:
What about:

Neither

Mixing languages is not a good idea. You don't put JavaScript in HTML, or HTML in JavaScript, or JavaScript in PHP, or HTML in Python or Ruby in SQL.

Why don't we do that?

Because different languages usually correspond to different layers.

PHP deals with business logic. HTML deals with presentation of the business objects. Thus, you have two layers: the one generates the objects; the other one builds a pseudo-XML representation of those objects.

In the same way, JavaScript deals with interaction, and CSS with the presentation of the content. When you want to change interaction, you don't open an .html file, and you surely don't open a .php file: you open a .js or .coffee file.

By mixing logic within the same file, you'll quickly notice that maintaining the code becomes more and more difficult. You want to change the method which applies rebates to products, and you spend fifteen minutes browsing through a mix of HTML with PHP statements here and there, and PHP code with HTML all over it.

The fact that technically, PHP makes it possible to mix HTML and PHP is irrelevant. The feature is available for historical reasons, but shouldn't be used any longer.

So what should you do?

What are you probably looking for is called templates. Depending on the framework you use, it may already be available, usually under a form of MVC, where the template is in the view, or you may have to use a third-party template engine, such as Smarty.

In both cases, the idea remains the same. You have PHP code strictly separated from the template which contains the HTML and a bit of very simplistic logic: simple loops over entities, conditions for conditional displaying of information, etc. When the PHP code is ready, it calls the template engine, passing to it some information. The engine uses a specific template to build the final output (often HTML, but other formats are possible as well) which is then sent to the user.

By using templates, you make sure that you have a strict separation between the business logic and the form you give to this logic through the templates. One day, you can throw all those templates and write other ones, without modifying a single line of PHP code. Or you may create a bunch of templates for a mobile version of the website.

An additional benefit is that you are not even stuck with HTML. If you need to make an API which is based practically 1:1 on the actual web pages of the website, instead of applying the template, you serialize to JSON the object which was about to be sent to the template engine. With practically zero efforts, you add API capability to an app, thing which couldn't be possible without severe rewriting if you were mixing PHP and HTML.


答: Every programmer should make their code readable by others.</p>

Title: The Programmers Bill of Responsibilities

Body:
So, we've all heard of The Programmers Bill of Rights and XP has a similar concept.

It's a common complaint these days that we hear a lot about people's rights but not so much about their responsibilities, so what should be on the programmers bill of responsibilities.  That is things that they should do, which they may find unpalatable, but that which separate programmers acting professionally and responsibly, from those who do not.

I'm primarily interested in the unpalatable ones and the ones which tend not to happen.  That is the ones that programmers tend to shirk and avoid, rather than the ones which 90% of programmers actually want to do (such as always refactor and use source control).

So, what should be on the Programmers Bill of Responsibilities?


答: I think it depends. If you are just using a little bit of PHP to create a list via looping, it makes sense to put it in the HTML. If your PHP is extensive and is generating the bulk of the HTML, it could make sense to do HTML within PHP.</p>


答:
1) Explain clearly that a solution to any problem is going to have trade offs between performance, cost, time, and quality.

2)Complete relevant documentation, be they releases notes or test plans. (documentation will vary with company type and size)

3)Request the correct tools for their job (so many just moan about it but never approach their boss with a reasonable case for getting what they need)

... Others no doubt to follow.


问:
Python classes with only one instance: When to create a (single) class instance and when to work with the class instead?
Given a Python class which will be instantiated only once, i.e. there will be only one object of the class. I was wondering in which cases it makes sense to create a single class instance instead of working directly with the class instead.

There is a similar question, but it has a different focus:

it is about grouping global variables and functions into a class and

It isn't Python-specific. The latter means it does not consider the fact that (in Python) classes are objects too.

UPDATE:

In Python, I can do the following with both classes and objects:

```<code>class A(object):
    pass

A.some_state_var = True
# Then later
A.some_state_var = False

my_a = A()

my_a.some_state_var = True
# Then later
my_a.some_state_var = False
</code>```

So I don't see how the choice between a class and an instance of that class is about state (in Python). I can maintain a state with either of the two.

Furthermore, the motivation to create my class / class instance is not about enforcing a Singleton requirement.

Also, it is not so much about creating a new Type.

The motivation is to group related code and data and having an interface to it. This is why I initially modeled it as a class in a class diagram. Only when it came to the implementation I started wondering whether to instantiate this class or not.

答:
Given a Python class which will be instantiated only once, i.e. there
  will be only one object of the class. I was wondering in which cases
  it makes sense to create a single class instance instead of working
  directly with the class instead.

So it's this:

```<code>class Singleton:
    '''don't bother instantiating me'''
    clsvar1 = 'foo'

    @classmethod
    def foobar(cls, *args, **kwargs):
        if condition():
            cls.clsvar1 = 'bar'
</code>```

versus this?

```<code>class Singleton:
    '''instantiate and use me'''
    def __init__(self):
        self.var1 = 'foo'

    def foobar(self, *args, **kwargs):
        if condition():
            self.var1 = 'bar'
</code>```

Recommendation

I definitely would prefer the one that's intended to be instantiated. When you create a "type of thing" that implies that you create things of that type.

The motivation is to group related code and data and having an interface to it.

That said, why not just use a module since all you want is a namespace? Modules are singletons, group related code and data, and this is a bit simpler and probably would be considered more Pythonic:

```<code>var1 ='foo'

def foobar(*args, **kwargs):
    global var1
    if condition():
        var1 = 'bar'
</code>```

So the usage would be instead of:

```<code>from modules.singleton import Singleton
Singleton.foobar()
</code>```

or

```<code>from modules.singleton import Singleton
the_singleton = Singleton()
the_singleton.foobar()
</code>```

do this:

```<code>from modules import singleton
singleton.foobar()
</code>```

Body:
Given a Python class which will be instantiated only once, i.e. there
  will be only one object of the class. I was wondering in which cases
  it makes sense to create a single class instance instead of working
  directly with the class instead.

So it's this:

class Singleton:
    '''don't bother instantiating me'''
    clsvar1 = 'foo'

    @classmethod
    def foobar(cls, *args, **kwargs):
        if condition():
            cls.clsvar1 = 'bar'

versus this?

class Singleton:
    '''instantiate and use me'''
    def __init__(self):
        self.var1 = 'foo'

    def foobar(self, *args, **kwargs):
        if condition():
            self.var1 = 'bar'

Recommendation

I definitely would prefer the one that's intended to be instantiated. When you create a "type of thing" that implies that you create things of that type.

The motivation is to group related code and data and having an interface to it.

That said, why not just use a module since all you want is a namespace? Modules are singletons, group related code and data, and this is a bit simpler and probably would be considered more Pythonic:

var1 ='foo'

def foobar(*args, **kwargs):
    global var1
    if condition():
        var1 = 'bar'

So the usage would be instead of:

from modules.singleton import Singleton
Singleton.foobar()

or

from modules.singleton import Singleton
the_singleton = Singleton()
the_singleton.foobar()

do this:

from modules import singleton
singleton.foobar()


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答:
You have a bowl with 200 fish in it. Of these fish 99% are not guppies. How many fish should you remove so that 2% of what remains are guppies. Show your work.

This is about confusing requirements. It is said this way to change perspectives multiple times during the same question. It is meant to see if they can figure out what is really going on.

You would be surprised how many people get it wrong.


问:
Creating a specific table for shared columns among other tables (models)?
I'm creating a webapp that has a variety of models: Product, Category, ProductOption, etc.

All of these models have a set of shared attributes: name, description, image, etc.

There are two options I see: 1. adding all of these attributes as columns to each of the model's table. 2. create a separate meta table that contains these columns with a polymorphic relationship between a model and the meta.

Option 1:

```<code>products
    id
    ...
    name
    description
    image
product_categories
    id
    ...
    name
    description
    image
</code>```

Option 2:

```<code>products
    id
    ...
product_categories
    id
    ...
metas
    id
    name
    description
    image
    metaable_id // foreign key
    metaable_type // model type (Product, ProductCategory)
</code>```

Is there a clear decision here? Am I missing any alternatives? Thanks.

答:
To me, there's no question.  Go with Option 1.

It makes sense that you'll have Products and Categories.  They're different, and shouldn't be forced to live in the same table.  However, a productName (reasonably shortened to 'name') is not the same as a categoryName (also reasonably shortened to 'name').  You can use context to figure out which 'name' you mean.

Look at this another way:

Imagine it's now 5 years in the future.  Your code is in production, is successful, and a team of people have been adding features to it.  There are a lot of new models besides Product and Category.  Let's say there are about 20 of them.

Which option would be easiest for them to work with?

Which option will be easiest for a new hire to follow?

Say you were away for those 5 years and are now getting back to this code.

Which option will the team have messed up the least?

Which option will you most easily follow?

(You can probably guess that I'd answer Option 1 for all of these questions)

I see where you're coming from with Option 2, but IMHO that looks like a giant plate of spaghetti code just waiting to happen.  Even if you have the discipline to keep it clean, the programmer who comes after you may not.

I agree with Brandon that there may be some situation where Option 2 starts to look viable, but it would have to be much more esoteric than 'name', 'description', or 'image'.


问:
What's the proper way to organize and revision a pull request
I'm working on an open source project for the first time and I'm adding a feature to the source. The way I've been going about, is I've squashed my individual commits into on clean commit for the feature. Now every time I need to fix the something code in the code because it fails tests, I'm editing the code and rebasing git rebase -i HEAD~2 and squashing the edit into the original feature commit. This works, however each incremental fix is lost. There's an option when rebasing to extend the comment to have the messages from each of the previous commits but the code diffs are all lost and i'm git push origin master --force every time I need to update, which is not very good for version control. Is there a better way to do this?

答:
In any project where you share code you should be very hesitant to alter the history and force push. This is especially true for open source code.

I didn't quite understand your question, but it sounds like when you try to fix something you end up breaking something, which is revealed by some sort of automated test suite.

A good practice is to open a pull request to the code, even if you own it. This way any continuous integration services can run tests against your code. Moreover, you should run the test suite against your code before you push. This way you know that the fix hasn't broken anything.

A fix should be a separate commit as it isn't a feature. This is because as you start versioning your code, people will expect a certain behavior from a certain version of the code. If you changed the history, those expectations cannot match. Moreover, people using a particular version of the code may have encountered the bug you fixed. They'll expect that a newer version of the code will address the bug. If you rebase and squash the code you'll be putting the fix in a place that they won't expect.

If you're finding that you're having to implement too many fixes per feature perhaps you should slow down, write more comprehensive tests, and attempt to engage your audience in code reviews so as to catch bugs before it becomes part of the code.

Lastly, squashing your feature into a single commit is good hygiene. The commit message should only include pertinent information. A lot of changes that happen as you write code aren't important. If you rename a method that nobody has used yet, nobody needs to know that. However, if you rename a method in already public code then you should mention that as a potentially breaking change, especially in the case of public methods.


答: Question anything - A programmer should have the responsibility to inquire on anything that a system may be required to do or handle.  This can include asking what users may see as silly questions as there are various sites devoted to showing just what users can be capable of doing.  Daily WTF and SharkTank being a couple of examples though I'm sure there are others.</p>


问:
The urge to organize code in a cleaner way
Every time I am working on a project, specially a project from scratch, I always feel like I am doing a messy job. I feel bugged all the time by the need or organizing code that is clean or proper way.

For example;

Avoid hard-coding file paths in gulpfile.

Require all node modules in similar fashion.

What should be the ideal directory structure for this project.

UI. The *** UI.

The Question

What are the strategies I can follow to not drown into that world? Thinking over and over on the organization aspect of the project gets me really low on productivity.

In general, how to approach a project from scratch so I can get the most done without the code organization overhead?

Notes after the possible duplicate flag

I can understand why this is flagged as possible duplicate as the question is more of an overview rather than a specific question.

The question I have is more about what kind of mentality a programmer should have when starting a project from scratch so they end up delivering more rather than getting trapped by code organization issues.

答:
You can try and allocate a finite timeframe for working on organization.
For example, spend 1 hour each day organizing the things you mentioned, and spend the rest of your time on functionality. If something bugs you when you work but it doesn't have any functional purpose, add it to a list that you refer to when organizing.</p>


答:
I would suggest to read more "Software-Architect-Books", but you are not alone with this feeling.

First rule: do not panic!

Do you ever heard of design patterns? These are helpful structures, which can help you to structure your code even better for your requirements.

Another way to "not drown into that world" is to read through this Book about "Clean Code".

Reading is the key for your problem. Collect more knowledge about how to structure your programs and you problems will fade away.

Title: The urge to organize code in a cleaner way

Body:
Every time I am working on a project, specially a project from scratch, I always feel like I am doing a messy job. I feel bugged all the time by the need or organizing code that is clean or proper way.

For example;

Avoid hard-coding file paths in gulpfile.

Require all node modules in similar fashion.

What should be the ideal directory structure for this project.

UI. The *** UI.

The Question

What are the strategies I can follow to not drown into that world? Thinking over and over on the organization aspect of the project gets me really low on productivity.

In general, how to approach a project from scratch so I can get the most done without the code organization overhead?

Notes after the possible duplicate flag

I can understand why this is flagged as possible duplicate as the question is more of an overview rather than a specific question.

The question I have is more about what kind of mentality a programmer should have when starting a project from scratch so they end up delivering more rather than getting trapped by code organization issues.


问:
Can a client-side library under the GPLv3 be used on a closed source website?
I'm building a website using Django and I'd like to include django-wiki, however it is licensed under the GPLv3. Does this require me to open source my front end code and/or server code? Or can I apply the license only to the wiki portion of the website?

The wiki will be quite separate from the main site, but will contain some shared templates and boilerplate code, and will be at the some host and running on the same server.

Edit: In case anyone gets here asking about the exact same application, here is what the Django wiki folks had to say.

You can use the wiki on a public commercial site. You can also write
  plugins.

But if you modify the code and distribute a modified version, you have
  to also publicize those changes.

答:
My reading of the GPL is that it does not apply to this kind of scenario, where a UI (the web browser) accesses the program over a network.  In fact, they state as much in the license:

To "convey" a work means any kind of propagation that enables other
  parties to make or receive copies.  Mere interaction with a user through
  a computer network, with no transfer of a copy, is not conveying.

"Conveyance" is what triggers the copyleft provision.

This "loophole" is, in fact, the reason the Affero GPL exists.  The Affero General Public License is a modified version of the ordinary GNU GPL version 3. It has one added requirement: if you run a modified program on a server and let other users communicate with it there, your server must also allow them to download the source code corresponding to the modified version running there.

Things get a little dicey if you send Javascript to the browser.  If the server program depends on the Javascript for its proper functioning, then technically you have "conveyed" a portion of your program, and you could argue that it all falls under the GPL in that case.


问:
Context specific API updates to developer
Let's say I have a API with regular updates and many developer who are using the API. Whenever the API updates I don't want to bother the developers with all the change updates. I want to send them updates about only the functions or classes that they are using in their code.

I have a faint idea, but not sure if this would work.

A service which will have an index of all the changes made to the files functions based on the git commits in the last day.

A module or plugin on the client side(where the API resides) which will check with this service on a cron run regarding the changes made to the API, compare it with its internal index of files and functions used and send updates to the developer if there is a match.

Is there something implemented on these lines already? If not what would be the right way to go forward.

答:
I guess you are talking about a system where you have access to the complete source code of all developers involved, and it is all within one organization, right?

I do not think this will work well on the API level, you have to do something like this on the component/module/library level. Even if you do not change the API syntactically, internal changes in a library can affect the code of everyone using that library (and the only way to make sure your changes did not break anything is to do or execute enough tests). However, if you know a program or module does not reference another component/module/library, then a change there cannot break it easily.

So a better way is to have your changes (semantically and syntactically) documented on a per-module basis. And to inform the right developer actively, the ones which might be affected by a change in a specific module (and noone else), you need two things:

a reference graph, wich application or module is using/referencing/linking which other module

a list of who is responsible for each module

(and assumed you have those documents, it should be clear how to use them).

For the reference graph of modules, depending on the size of the system and the used programming language ecosystem, you can either maintain that manually, try to find some tools for cross reference generation, or implement a reference scanner manually (maybe in some kind of scripting language). The second one is probably best maintained manually.


答:
Refactoring your code to make it elegant makes it easier to read, and easier to maintain. Even minor things such as aligning your variable assignments:

```<code>int foo    = 1;
int bar    = 2;
int foobar = 3;
</code>```

is easier to read than

```<code>int foo = 1;
int bar = 2;
int foobar = 3;
</code>```

which means it's easier to skim over when you're debugging later.

Also, in PHP you're allowed any number of random code blocks. I use these to group logical tasks:

```<code>// do x
{
    // ...
}

// do y
{
    // ...
}
</code>```

This adds clear definition to relevant code.

Edit: As an added bonus, it's easy to preceed one of those logical code blocks with an if (false) if you want to skip over it temporarily.

Title: Do you actually write 'clean code'?

Body:
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

Body:
Refactoring your code to make it elegant makes it easier to read, and easier to maintain. Even minor things such as aligning your variable assignments:

int foo    = 1;
int bar    = 2;
int foobar = 3;

is easier to read than

int foo = 1;
int bar = 2;
int foobar = 3;

which means it's easier to skim over when you're debugging later.

Also, in PHP you're allowed any number of random code blocks. I use these to group logical tasks:

// do x
{
    // ...
}

// do y
{
    // ...
}

This adds clear definition to relevant code.

Edit: As an added bonus, it's easy to preceed one of those logical code blocks with an if (false) if you want to skip over it temporarily.


问:
Handling Many to Many Relationship using Restful Uri
I am having confusion while choosing a database relation and Restful URI for application I am developing.

I am making a simple library application with following requirements.

Book can belong to many categories e.g Physics book belong to Textbook and Science Category. We can say book have many categories/labels/tags.

Viewing books in one category.

Viewing a book's all categories.

Searching book using categories or book information.

Book CRUD operations

Label CRUD operations

Considering all these requirements I choose ManyToMany relation between Books and Labels. I have implemented it using Hibernate Framework.
Now when it came to designing Restful Services for this its getting very confusing.It makes me question table relationship choice as well.

Restful uri made yet.

/books

/books/{bookid}

/labels

/labels/{labelid}

But when I want to get a list of labels against a book, or a list of books against a label. How to map them using Restful URI. I can think of this

/book/{bookid}/labels

But considering this,how to map getting a list of books against one label

I want to know whether my choice of table relationship is right and if yes, how to design restful uri against it. And if no, please correct me and put a light on this scenario. Thanks

答:
Regarding the table, if a book can have many labels and a label many books (sounds quite reasonable) then that's a many to many relationship.

In case of REST the many to many relation is in fact a bit confusing since we talk about resources and with the URI being a unique identifier it seems weird to be able to access one and the same resource from two directions.

Maybe the best way is to see a resource not only as a simple thing (book, label) but also as a specific set of things (books, labels of a book). You often have nested resources anyway and the many to many is just one variant where two different ways to view these sets make sense (assuming that your users will want to access in both variants which seems likely for your use case).

So in fact you would have two ways to access this:

```<code>/book/{book_id}/labels
</code>```

and

```<code>/label/{label_id}/books
</code>```

You will most likely have similar approaches for other resources like authors (author can have written many books and often enough many authors work together on a single book) or even publishers. Categories too I would assume to be many to many.

When sombody selects a single label from above URIs (/book/{book_id}/labels) you can of course then fall back to your normal label URI (/label/label_id) instead of constructing extra long paths like (/book/{book_id}/label/{label_id}).

So keep your routes as shallow as possible, avoid to nest them too deep. But nothing prohibits to have different views on lists of similar things.

Body:
Regarding the table, if a book can have many labels and a label many books (sounds quite reasonable) then that's a many to many relationship.

In case of REST the many to many relation is in fact a bit confusing since we talk about resources and with the URI being a unique identifier it seems weird to be able to access one and the same resource from two directions.

Maybe the best way is to see a resource not only as a simple thing (book, label) but also as a specific set of things (books, labels of a book). You often have nested resources anyway and the many to many is just one variant where two different ways to view these sets make sense (assuming that your users will want to access in both variants which seems likely for your use case).

So in fact you would have two ways to access this:

/book/{book_id}/labels

and

/label/{label_id}/books

You will most likely have similar approaches for other resources like authors (author can have written many books and often enough many authors work together on a single book) or even publishers. Categories too I would assume to be many to many.

When sombody selects a single label from above URIs (/book/{book_id}/labels) you can of course then fall back to your normal label URI (/label/label_id) instead of constructing extra long paths like (/book/{book_id}/label/{label_id}).

So keep your routes as shallow as possible, avoid to nest them too deep. But nothing prohibits to have different views on lists of similar things.