答:
There are several testing-related questions:

Which parts to test? Units (unit testing), whole system (functional), several systems together (integration)

Which aspects to test? Functionality, performance, reliability, security, etc.

When to do testing? Before (TDD/BDD) or after (non-TDD/BDD). Or never =)

How deep to test? Or, how to view the system under test? "Black box", "grey box", "white box" approaches.

Also, TDD and BDD are the ways to design software and test it. Two stones at one bird!

Examples:

I have a REST API. I write tests using Cucumber, viewing system as a black box, and I have a full spec which guides my testing process. This way I'm doing acceptance testing, but not BDD, since I do not design through testing. Design is in the spec.

I have some rocket science software, I need to test a bunch of functions already written in Haskell. I write unit tests, but not TDD. That could be TDD if I'd write tests upfront.

I want to write yet another DOM manipulation framework in JS. I use Jasmine framework to write tests. I test the framework as a black box. In this case I do BDD. And also it is functional testing.

Also I have some notes and clarifications about what you state:

Unit tests ensure things at a lower level are correct

Kinda, but not really. They just show the lack/presence of known bugs. If you're interested in correctness, you may want to look at formal verification.

Unit tests speed up long-term development time

Not always, because poorly-designed systems can be hard or impossible to test. In such cases I believe it is not worth it. That's why TDD was invented.

If system is testable, it does worth a lot. Errors cost much less when caught early. They may cost too much then they are discovered in production phase.

Unit tests ensure good architecture: No they don't.

Indeed they don't. TDD and BDD do.

Integration tests ensure the overall performance is accurate and optimal

Not only. Functionality and reliability too. Two systems may pass their "local" tests and yet fail to work together. Integration testing shows how well parts work together.

TDD ensures that when changes are implemented, nothing else breaks in the process

Secretly, all types of automated testing do that. Showing "regression bugs" that is: module (or function, or system) A has tests over it, then you change module B, then A breaks, then you see it through the tests on module A and fix module A.

Title: Is TDD the best software development philosophy?

Body:
Question:

Why not just use BDD-style acceptance tests and do away with unit tests, integration tests, functional tests and all other tests?

I have been doing some research into the differences between different types of testing as well as different software development philosophies.

Looking at the list of software development philosophies and reading about different types of testing lead me onto a research to find out why we use unit tests, integration tests and functional tests if we have acceptance tests.

I hate to be the one to kill the holy cow but I feel like if you have acceptance tests in a BDD-style environment like given, when, then then you don't really need any other tests since you will be delivering exactly what functionality is required by the business anyway with just acceptance tests.

Some arguments for using unit, integration and functional tests:

Unit tests ensure things at a lower level are correct: Who cares? if the business is happy with what they've received, then what difference does it make?

Unit tests speed up long-term development time: Is it really worth the trade-off?  Where there is code there are bugs, tests are not exempt from this. The time spent writing and debugging 5,000 unit tests vs. the time debugging 50 acceptance tests seems like an obvious choice?

Unit tests/TDD ensures good architecture: No they don't. Each unit test is a design decision and is extremely vulnerable to overall poor architecture.

Integration tests ensure the overall performance is accurate and optimal: Why can't this be just another Then condition in acceptance tests? Why not just use selenium within the acceptance tests?

Functional tests ensure that output is as expected: Acceptance tests enhance this by providing an answer at build time rather than waiting for potentially incorrect results.

TDD ensures that when changes are implemented, nothing else breaks in the process: Acceptance tests will ensure this too since everything's based on business requirements/features.


问:
Why is base-for-all-objects discouraged in C++
Stroustrup says "Don’t immediately invent a unique base for all of your classes (an Object class). Typically, you can do better without it for many/most classes." (The C++ Programming Language Fourth Edition, Sec 1.3.4)

Why is a base-class-for-everything generally a bad idea, and when does it make sense to create one?

答:
Because:

You shouldn't pay for what you don't use.

These functions make less sense in a value-based type system than in a reference-based type system.

Implementing any sort of virtual function introduces a virtual-table, which requires per-object space overhead that is neither necessary nor desired in many (most?) situations.

Implementing toString nonvirtually would be pretty useless, because the only thing it could return is the object's address, which is very user-unfriendly, and which the caller already has access to, unlike in Java.

Similarly, a nonvirtual equals or hashCode could only use addresses to compare objects, which is again pretty useless and often even outright wrong -- unlike in Java, objects are copied frequently in C++, and hence distinguishing the "identity" of an object isn't even always meaningful or useful. (e.g. an int really should not have an identity other than its value... two integers of the same value should be equal.)

ContentLicense: CC BY-SA 3.0


问:
How were assemblers created straight from binary?
How did these earlier programmers know what combinations of binary produced certain results? Is there a way I can create an assembler from binary today?</p>

答:
Robert Harvey is correct.

However, you can create an assembly language at the same time you write an assembler.  It's a cyclical process, where you add code to the assembler to process your assembly language into operation codes, or opcodes.

Ideally, each assembly language instruction is represented by an opcode.  Sometimes, one assembly instruction requires many opcodes.

You also need a linker, to link assembly object modules together into an executable program.  Back when assembly was the only language choice, the linker was a separate program, run after your code was assembled.


问:
Should I specify the userId in the REST URL structure?
Basically, one feature of my app is to retrieve the logged user's friends.

Actually, I hesitate between both kind of endpoints:

GET /api/users/friends

GET /api/users/:userId/friends

Using 1, userId would be reachable through the authentication token.

Using 2, server would have to additionally check for the correspondance between the passed userId, and the logged user id specified in the auth token so that it avoids any malicious access to other user data, like friends.

So 1 should be enough, but it doesn't sound like a standard rest url.

What is a good practice?

答:
The first solution has a benefit of avoiding data duplication. The request plainly means:

Hello, I'm John. Give me the list of my friends.

If possible, I would even shorten it to GET /api/friends.

On the other hand, if you expect to be able to access friends of other users, the second solution appears the good one. The request means:

Hello, I'm John. Give me the list of friends of John.

but can also be:

Hello, I'm John. Give me the list of friends of Mary.

For instance, one situation where such change can be possible is where a person can find her own friends, but also friends of her friends.


问:
When to use a nosql database such as mongodb over mysql?
I'm new to the concept of nosql databases and have never used it. Based on what I've read and the little that I've understood I still don't see how they can be particularly useful if you can't make references between data, if there's no concept of foreign key.

How would I forexample query something simple as 'find all the comments posted by this user', 'find all photos that belong to an album entity' etc.

Do nosql systems move away from the static relational data-model but still let you keep track of such references, is there something analogous to foreign keys that you can utilize in queries?

答:
General Uses

If you have data structures that are not clearly defined at the time when you make the system. I tend to keep user settings in nosql, for example. Another example was a system where the users needed to be able to add fields at runtime - very painful in an RDBMS and a breeze in NoSQL.

If your model structure is largely centered around one or few model objects and most relationships are actually child objects of the main model objects. In this case you will find that you will have fairly little need for actual joins. I found that contact management system can be implemented quite nicely in nosql for example. A person can have multiple addresses, phones and e-mails. Instead of putting them each into a separate table, they all become part of the same model and you have one person object.

If you want to benefit from clustering your data across multiple servers rather than having one monolithic server, which is commonly required by RDBMS.

Caching. Even if you want to stick with a RDBMS as your main database, it can be useful to use a NoSQL database for caching query results or keeping data, such as counters.

Storing documents. If you want to store coherent documents, in a database some of the NoSQL databases (such as MongoDB) are actually specialized in storing those.

What about joins?

Honestly, the no join thing sounded quite scary to me too in the beginning. But the trick is to stop thinking in SQL. You have to actually think with the object you have in memory when you are running your application. These should more or less just be saved into the NoSQL database as they area.

Because you can store your full object graph, with child objects, most of the need for joins is eliminated. And if you find you need one, you will have to bite the bullet and fetch both objects and join in your application code.

Luckily, most drivers can do the joining for you, if you set up your schema right.

For further reading I actually recommend Martin Fowler.


问:
Why are heuristics a disadvantage for decidable problems?
I'm reading Introduction to Artificial Intelligence by Ertel.

This line has me stumped from the textbook (page 102):

For decidable problems such as the 8-puzzle this means that the whole search tree must be traversed up to a maximal depth whether a heuristic is being used or not.

And decidable ca be defined thus:

an algorithm that can and will return a Boolean true or false value (instead of looping indefinitely)

Why can't the program return if it encounters the goal state before it has traversed the entire tree? What am I missing?

In case context is important, this is the preceding sentence:

In closing, it remains to note that heuristics have no performance advantage for unsolvable problems because the unsolvability of a problem can only be established when the complete tree has been searched through.

See page 102.

It says elsewhere in the book that heuristics often reduce computation dramatically for “solvable problems”! Is there a difference between “decidable” and “solvable” problems that's relevant here? It's not explained why heuristics are good for “solvable” problems and bad for “decidable” ones.

答:
A problem is solvable iff a solution exists.

A problem is decidable iff we can tell whether the problem is solvable or not, i.e. whether a solution exists.

The 8-puzzle is not always solvable, but it is decidable since if a solution exists, we know it will take at most 31 single-tile moves. So to decide whether a given 8-puzzle is solvable, we must find any solution. If no sequence of moves with max length of 31 solves the problem, we know that this puzzle is unsolvable.

Now we can restate this in terms of whether the problem is solvable:

For a solvable problem, we only need to find one solution to prove that it's solvable. Here, heuristics can speed up finding a solution.

For an unsolvable problem, we have to prove that not a single solution exists. Since a heuristic will not lead to a solution for an unsolvable problem, we have to investigate the whole game tree to be sure that it contains no solutions. Since we have to investigate every possible game state, a heuristic will not matter (all a heuristic does is prioritize promising moves). Since a heuristic adds a computational cost, using a heuristic will be a net loss for unsolvable problems.

The funny thing is that we do not generally know a priori whether a given problem is solvable.

Edit: This comment from another user(@esoteric) adds some additional clarity:

Try thinking of it as a statement of what happens in the worst case, especially given that half of the initial positions are unsolvable, and viewing the opportunity for early termination as a happy accident. Consider also that if the traversal is unlucky, it still may be required to walk the entire tree before finding a solution even if the instance is solvable. So, for > 50% of all instances, a full traversal is required. Given that, it's reasonable for the algorithm to expect to have to traverse the entire tree.


问:
Testing process on life critical systems
I currently work in web development - unit testing, functional testing are all good and really are part of what is considered being a professional developer.

However, I also have a fear of flying and when on an aeroplane i often wonder what the development process is for developers on auto pilot or air traffic control systems is.

Obviously software is tested rigorously. But how?

Is unit testing conducted differently?, are there 2 x testers per developer etc etc.

Also - how the heck are functional tests completed in such an environment?  Its definitely not a case of just hitting f5 on the keyboard :)

Most importantly, is there something that can be learned from the development/testing process for such applications that can be applied to more daily development tasks such as web development

答:
A substantial gap between business software and life-critical systems is the use of formal proof. Another is the strictness of the environment.

Formal proof

Tests are great to ensure that the system is free from known, identified bugs and that new features won't break existent ones (regression testing). However, the presence of tests doesn't imply the absence of bugs. Not if you have thousands of tests for a small program. Not if you have 100% line coverage and 100% branch coverage.

Formal proof, on the other hand, guarantees that the program works as expected. It's like proving a mathematical theorem: with such proof, you know that you get an expected result. Of course, proofs may contain errors which will report buggy code as correct or correct code as wrong; this is a different subject.

A basic example: a method takes two integers as parameters and returns an integer.

With ordinary testing, you will have unit tests which ensure the method returns the expected result for arbitrary “ordinary” values, say (2, 3) and for a few edge cases, say (0, 0), (-1, 3), (+∞, 3) and (+∞, -∞). And then, when QA department discovers that the method fails for values (7, -7), you may add a test for those specific values as well.

With formal proof, you will have a mathematical proof that the method returns the right value for (-∞..+∞, -∞..+∞). No unit tests can do that, because you will need an infinite number of tests for that testing for every possible value of both parameters.

What can you learn from this as a developer writing business software?

Frankly, not much. It's an interesting subject to study in theory, but is irrelevant in practice for business software. Originally, people thought formal proof would be the way we write software. Any software. Decades passed, and it appeared that formal proof has a cost so high, that it can be relevant only for life-critical software where a system failure leads not to millions of dollars lost by a company, but a death of one, ten, hundred of thousand persons and billions of dollars thrown away.

There might be one thing which may inspire programmers: code free of side effects. Without pushing as far as formal proof, the sole fact of understanding the basics of how the correctness can be proven may encourage the usage of functional programming. This often leads to code simpler to debug and often simpler to read.

For more information about the subject, read:

Mechanizing Proof - Computing, Risk and Trust, Donald Mackenzie.

If you're interested by the subject, I highly recommend this book.

Strictness of the environment

When I write a small personal project, I don't care about requirements, or about correctness, or about code quality. I don't need it to be reviewed by pairs to check if everything is good. It's completely OK if it fails “in production”.

If I find a bug, I don't care. I might resolve it, or may keep it.

Business systems require more attention. Requirements will be drafted, code will be carefully written, tests will reduce the risk of regressions, linters will check code on every commit to reduce risks of stupid errors, other team members will review my code, usually in an informal way.

If a bug is found, it's not a big deal. A ticket will be opened, a programmer will be assigned and will either solve the bug or postpone it if he considers it to be too unimportant.

Life-critical systems receive much more care. There will be not one, but multiple reviewers. Formal reviews will be done. Linters are not enough, and powerful static checkers will try to find the slightest error. Testers will explore any opportunity to crash the system.

If a bug is found, the whole workflow is restudied. What we did wrong? Why the bug appeared in the first place? Why static checkers were unable to discover it? Why testers missed it? More importantly, what can we do now to prevent similar bugs from appearing in the future? Will another static checker help? What if a different form of formal review could have helped to discover the bug?

What can you learn from this as a developer writing business software?

I would consider two things, but both are more important for project managers and team leads rather than programmers themselves:

It's never someone's fault. I've seen managers running in the room and screaming at a programmer who inadvertently introduced a bug which had major consequences in production. Well, great manager you are, that's the way to treat people. Especially since the project has no tests, there are no code reviews and no static checking, because all this is considered a waste of time by the company.

If there is a bug, it means that the author of the code, the testers, the code reviewers and the static checkers all failed. Or the company failed to learn how to develop software correctly by considering testing, code reviews and static checking as not important.

When the product is bad, probably the process itself is bad. Improving the workflow can make a huge difference, and in a presence of a bug, one should ask himself how could it happen that the bug was not found before the software reached production.

Chances are, the change within the workflow could have been helpful in avoiding this bug, as well as dozens or hundreds of other bugs that are here, right now, in the code base, waiting to be discovered.

For more information about the subject, read:

They write the right stuff, Fast Company.


答:
Rest Api's must be hypertext driven ! As you would click from one link to another in a standard html page.

An URL is a unique identifier to a resource. Having an url representing more than one resource is in total disacordance with ReST.

With your example, the following url :

```<code>/api/users/:userId
</code>```

should have a link in its response to the :userId friends url

Roy Fielding's dissertation contains a set of constraints needed to comply to ReST.

http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
http://fr.slideshare.net/rnewton/2013-06q-connycrestfulwebapis
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm

Title: Should I specify the userId in the REST URL structure?

Body:
Basically, one feature of my app is to retrieve the logged user's friends.

Actually, I hesitate between both kind of endpoints:

GET /api/users/friends

GET /api/users/:userId/friends

Using 1, userId would be reachable through the authentication token.

Using 2, server would have to additionally check for the correspondance between the passed userId, and the logged user id specified in the auth token so that it avoids any malicious access to other user data, like friends.

So 1 should be enough, but it doesn't sound like a standard rest url.

What is a good practice?

Body:
Rest Api's must be hypertext driven ! As you would click from one link to another in a standard html page.

An URL is a unique identifier to a resource. Having an url representing more than one resource is in total disacordance with ReST.

With your example, the following url :

/api/users/:userId

should have a link in its response to the :userId friends url

Roy Fielding's dissertation contains a set of constraints needed to comply to ReST.

http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
http://fr.slideshare.net/rnewton/2013-06q-connycrestfulwebapis
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm


答:
I'm going to suggest another reason that comes from Java.

Because you can't create a base-class for everything at least not without a
bunch of boiler-plate.

You may be able get away with it for your own classes - but you'll probably find that you end up duplicating a lot of code. E.g. "I can't use std::vector here since it doesn't implement IObject - I'd better create a new derived IVectorObject that does the right thing...".

This will be the case whenever you're dealing with built-ins or standard library classes or classes from other libraries.

Now if it was built into the language you'd end up with things like the Integer and int confusion that is in java, or a large change to the language syntax. (Mind you I think some other languages have done a nice job with building it into every type - ruby seems like a better example.)

Also note that if your base class is not run-time polymorphic (i.e. using virtual functions) you could get the same benefit from using a traits like framework.

e.g. instead of .toString() you could have the following:
(NOTE: I know you can do this neater using existing libraries etc, its just an illustrative example.)

```<code>template<typename T>
struct ToStringTrait;

template<typename T>
std::string toString(const T & t) {
  return ToStringTrait<T>::toString(t);
}

template<>
struct ToStringTrait<int> {
  std::string toString(int v) {
    return itoa(v);
  }
}

template<typename T>
struct ToStringTrait<std::vector<T>> {
  std::string toString(const std::vector<T> &v) {
    std::stringstream ss;
    ss<<"{";
    for(int i=0; i<v.size(); ++i) {
      ss<<toString(v[i]);
    }
    ss<<"}";
    return ss.str();
  }
}
</code>```

Title: Why is base-for-all-objects discouraged in C++

Body:
Stroustrup says "Don’t immediately invent a unique base for all of your classes (an Object class). Typically, you can do better without it for many/most classes." (The C++ Programming Language Fourth Edition, Sec 1.3.4)

Why is a base-class-for-everything generally a bad idea, and when does it make sense to create one?

Body:
I'm going to suggest another reason that comes from Java.

Because you can't create a base-class for everything at least not without a
bunch of boiler-plate.

You may be able get away with it for your own classes - but you'll probably find that you end up duplicating a lot of code. E.g. "I can't use std::vector here since it doesn't implement IObject - I'd better create a new derived IVectorObject that does the right thing...".

This will be the case whenever you're dealing with built-ins or standard library classes or classes from other libraries.

Now if it was built into the language you'd end up with things like the Integer and int confusion that is in java, or a large change to the language syntax. (Mind you I think some other languages have done a nice job with building it into every type - ruby seems like a better example.)

Also note that if your base class is not run-time polymorphic (i.e. using virtual functions) you could get the same benefit from using a traits like framework.

e.g. instead of .toString() you could have the following:
(NOTE: I know you can do this neater using existing libraries etc, its just an illustrative example.)

template<typename T>
struct ToStringTrait;

template<typename T>
std::string toString(const T & t) {
  return ToStringTrait<T>::toString(t);
}

template<>
struct ToStringTrait<int> {
  std::string toString(int v) {
    return itoa(v);
  }
}

template<typename T>
struct ToStringTrait<std::vector<T>> {
  std::string toString(const std::vector<T> &v) {
    std::stringstream ss;
    ss<<"{";
    for(int i=0; i<v.size(); ++i) {
      ss<<toString(v[i]);
    }
    ss<<"}";
    return ss.str();
  }
}


问:
How are ASCII code associations actually stored and retrieved?
I was reading about compilers and was given an example of creating a basic compiler that recognizes escape sequences without referencing ASCII.

Somebody suggested that once I compile a piece of code with ASCII numbers, I can then recompile a different snippet of code without actual reference to the
ASCII number, and can instead use the escape character explicitly.

I'm confused at how you can get from the ASCII number, to an actual escape sequence, there seems to be a missing step somewhere in the explanation.

答:
As mentioned above computers just store numbers. The association of an 8 bit number with a printable character is completely arbitrary.

ASCII actually predates computers and started of as standard for teletype/telex machines. Its use in computers became common because it was easy to hook up a teletype paper tape reader to a computer.

The other commonly used encoding is  EBCDIC which had its origins in punched card readers and associated printers, these were really sophisticated calculators and pre-date stored program Von Nueman model computers.

Not used so much these days but common in the past was the Fielddata six bit codeset which was used in early Burroughs/UNIVAC machines. (Used to love this one as the only non printable character was SPACE -- you code dump a binary file straight to the printer and make sense of it!).


问:
Handling DomainExceptions using REST endpoint
Suppose I'm doing some DDD.
Now, I have a microservice reflecting a bounded context/a part of a bounded context.

Now, suppose there is a REST endpoint:

```<code>'/somedomainmodel/someaction'
</code>```

My API user is doing a POST request with somehow invalid data.
I'm using Java and assume that following chain is executed:

request is handled by a Spring controller or something else

controller is invoking a method on an application service

application service is doing some action on a domain model

But as I mentioned before, data provided by an user is somehow incorrect and could cause my domain object to get into invalid state. So a subclass of DomainException extends RuntimeException is thrown.

Now: how should I handle this? Suppose my endpoint is used by a frontend and I want to display a proper message to user.

Should I return a status code and a message in a response?
Where should it be detected and how? In an application service? Or maybe in a controller? And since it's not a checked exception, how should I handle it? Try/Catch for a runtime exception seems to be awful.

Maybe if we're talking about specifing implementation, should I use something like spring's @ExceptionHandler?

答:
My belief is that you can just send the response from the error handler or test the data before sending if possible. Can also use a preload step during app initialization from your REST interface and store valid value parameters and use those on your client to test data going out.

It would be simple to try to send a response from your handler. Garbage collection will clean up i.e. errors are costly. So a better design is client cleaning. Hope that helps.


问:
Sets Data Structure in Golang
I really like google golang but could some one explain what the rationale is for the implementors having left out a basic data structure such as sets from the standard library?</p>

答:
The previous answer works ONLY IF the key are a built-in type. To complement the previous answer, here is a way to implement a set whose elements are user-defined types:</p>

```<code>package math

// types

type IntPoint struct {
    X, Y int
}

// set implementation for small number of items
type IntPointSet struct {
    slice []IntPoint
}

// functions

func (p1 IntPoint) Equals(p2 IntPoint) bool {
    return (p1.X == p2.X) && (p1.Y == p2.Y)
}

func (set *IntPointSet) Add(p IntPoint) {
    if ! set.Contains(p) {
        set.slice = append(set.slice, p)
    }
}

func (set IntPointSet) Contains(p IntPoint) bool {
  for _, v := range set.slice {
    if v.Equals(p) {
      return true
    }
  }
  return false
}

func (set IntPointSet) NumElements() int {
    return len(set.slice)
}

func NewIntPointSet() IntPointSet {
  return IntPointSet{(make([]IntPoint, 0, 10))}
}
</code>```

Title: Sets Data Structure in Golang

Body:
The previous answer works ONLY IF the key are a built-in type. To complement the previous answer, here is a way to implement a set whose elements are user-defined types:

package math

// types

type IntPoint struct {
    X, Y int
}

// set implementation for small number of items
type IntPointSet struct {
    slice []IntPoint
}

// functions

func (p1 IntPoint) Equals(p2 IntPoint) bool {
    return (p1.X == p2.X) && (p1.Y == p2.Y)
}

func (set *IntPointSet) Add(p IntPoint) {
    if ! set.Contains(p) {
        set.slice = append(set.slice, p)
    }
}

func (set IntPointSet) Contains(p IntPoint) bool {
  for _, v := range set.slice {
    if v.Equals(p) {
      return true
    }
  }
  return false
}

func (set IntPointSet) NumElements() int {
    return len(set.slice)
}

func NewIntPointSet() IntPointSet {
  return IntPointSet{(make([]IntPoint, 0, 10))}
}


问:
Should I use mMember and sStatic naming convention in Android?
Android source code and many Android open-source apps and libs use m prefix for member fields and s prefix for static member fields:

```<code>private static boolean sStarted;
private long mTimestamp;
</code>```

I personally dislike this, because it looks ugly and it's redundant – my IDE already uses different color and formatting for local, member and static member variables.

What's closest to truth?

It's a good practice.

It's a bad practice but you should use it anyway in order to be consistent with the majority of Android code out there.

It's a bad practice and you shouldn't use it.

答:
This is an old question, but I'm answering to disagree with the accepted (and only) answer.

I've been a Java programmer for about fifteen years, and I've been doing it professionally and intensively for about three years.  I initially resisted the mMember convention for all the abstract reasons commonly cited.  But the longer I stared at Java code, the more this convention grew on me.  I started using it myself a few months ago.

For one thing, it is not entirely redundant.  Even with modern syntax highlighting, the convention makes it easier to immediately recognize that an identifier is a member field.  Especially at 3 A.M.

And many of the arguments against Hungarian notation are actually arguments against Systems Hungarian notation, in which the warts identify the type of the variable.  This is indeed redundant in a strongly-typed language like Java.  But there's a good argument to be made for Application Hungarian, in which the warts encode the scope and usage.  Googling these two terms will turn up several articles.

Your second point is closest to the truth.  I would argue that it is not bad practice at all, for the reasons given above.  But I think we can leave that argument aside and say that you should do it solely on the basis of convention.  The reasons for this are both practical and social.

The Java community has very strong naming conventions.  They become ingrained to the point where code that does not follow them becomes hard to read.  If you don't use the mMember convention, you can bet that some maintenance programmer who comes after you is going to refactor all your identifier names.

And the social aspect is that not abiding by Java naming conventions immediately flags you to your peers as not a real Java programmer.  "Watch out for this guy.  He probably doesn't even know what a memory model is."  (And they're usually right...)


问:
What are the reasons for sealing a .jar and how would I verify that?
I have created a sealed jar, but I don't see difference compared to using a non-sealed one.

What tests I can perform to verify the jar is sealed?

What reason we could have to prefer using a sealed over non one?

Will a sealed create any trouble to users of my projects?

答:
You can test that a jar is sealed by defining a class to exist in a package used in the jar file. If the jar is sealed, all packages are normally sealed, else you can seal them on a per-package basis. The class you create should then try to access protected or default members of a class in that package.

For example, if the jar has a class com.example.Widget where the package com.example is sealed and Widget has protected/default members, create a class com.example.Test that attempts to access those members. This should fail.

The reason for sealing follows from a description of how to test it: you want your code to be self-contained and users of the jar should only use public members. Packages are not required to be unique across jars (and bin folders in your IDE) used by a program. You are able to define a class in the same package as in a jar and access protected/default members that might cause problems. Often, default visibility is used as an analog to C++'s friend keyword by allowing other classes in the same package the ability to perform actions that are only safe because the same programmers work on both classes and understand their internals. Perhaps a default visibility method forgoes some bounds checking in the name of performance, with the understanding that client code will never access it. For example, the String class in Java has a few of these types of methods since String handling has to be lightning-fast because a large amount of code relies on it. BigDecimal is built on top of BigInteger and uses default access to optimize a few operations that other users of the class ought not to use.

TL;DR: Classes in the same package might access non-public members of each other for performance or simplicity. This access might not check invariants and preconditions. One can put classes in the same package in multiple locations in the classpath. Sealing a package or jar restricts client code from accessing these methods, because it might break stuff otherwise.

This will not cause any problems for users of the jar. The classloading mechanism that accesses resources (e.g. class files) in jars fully supports sealed jars and packages.

Related reading: Sealing Packages within a JAR File


问:
How would one go about creating a "Licence Key" for a distributable source-available Software project?
It has been a while since I have seen anything you can download which has to connect to license server in order to monetize a piece of software (and the last time I saw it, it went very wrong when the software provider decided to discontinue the licensing server).

So apart from encrypting / obfuscating (e.g. Zend Guard) the piece of code which handles the actual authentication to this server, what other ways are there (if any?) of creating some kind of Authentication system for a distributable open source project?

Are there any methodologies other than providing it SaaS style?

答:
"Open source" typically includes that you provide the source code of your program in an understandable, compilable and changeable form. So any kind of artificial licence check could be easily disabled by anyone who is able to compile your code and has a basic knowledge of programming .

Of course, you could use a license which forbids to change anything in your program (or at least to distribute any changed branch of your software), so people are only allowed to read your program, not to change it. What you cannot enforce, however, that people will  remove your license key check secretly, or that people will do this outside of your jurisdiction. And when your licensing scheme is completely open, you cannot hinder people to imitate that licensing scheme, generate their own keys or provide a fake license server, even without changing the original code. (In fact, this is done regularly even when programs are closed source, but for an open source program you make this "approach" more feasible to the "average developer", not only to people with experience in reengineering.)

So one of the most popular ideas to get paid for open source is to have an important part of the software not beeing included in the source code, the part you provide from your server. The more functionality you put on the server side, the lesser is the risk having the server become rebuilt by anyone else. A server which does provide only a boolean information if a "certain license key is valid" is far too easy to be copied. In fact that means that your monetising model becomes a service model. For example, as  a vendor of a multiplayer game, the game client might be open sourced, but the server controls lethal parts of the game, and you can charge people for using that service for a particular duration.

The other option you have for monetising is to create an open source library which can be used freely by anyone for non-commercial software, freely for inhouse-software, but paid for commercial, off-the-shelve software. People will pay you because there is a certain risk that a licence breach can be proven by you, because they get paid for their software (so they could affort it to spend part of that money to you), and because they want to get updates of your library from you. For such a distribution model, however, you typically don't need any license keys.

EDIT: Of course, there are more alternatives to get money for open source software than the two above. This Wikipedia article lists a few.


问:
Implement a virtual tag on the database level
I have a set of objects, for which users manually applied tags, whatever they invented. I'd like to implement a task engine, where each task might be applied to objects from a tag. For convenience, I'd like to have an additional virtual tag "All objects" to have a task be applied to all objects regardless of tags.

A single task might require two (or more) sets of objects, e.g. "notify me about changes in all documents from tag X that were published on website tagged Y".

I see three ways of implementing this requirement:

Have a separate user interface and business code paths for the "All" case. This could be feasible for simple cases, but in my case it leads to having four cases for the example above, and potentially even worse in other cases.

Have a user interface that treats the "All" case like a normal tag (except maybe for making it impossible to remove items from the tag), and have business code add the tag automatically every time I list tags in the app, or have special cases for the "All" tag every time I handle a tag.

Have a user interface and business code handle the "All" case like a normal tag, and implement the virtual "All" tag on the database level. That would mean using database views that would add the "All" tag to the table of tags, and another view that would add the "All" tag to the m2m relationship listing which objects have which tags.

The third solution looks the most sane to me, but I don't have that much experience with programming on the database level. I can see the pros and cons of the first two solutions. What are the issues I might encounter if I chose to implement the third solution?

答:
It seems to me like you're putting the cart a bit before the horse, especially since you have a partial implementation already. Take a step back and ask yourself what "all" means and what purpose it serves.

In this case it means "without conditions or filters", and the purpose is to provide a way for the user to tell the system "I don't care what the tags are". Its meaning becomes relevant at the point where you examine the actual value of the tags, which doesn't happen until you get to the DB query. Before that, the value of the tag doesn't matter. You can just pass it through your business objects as normal.

all documents from tag X that were published on website tagged Y

I'd write such a query like this (pseudo-SQL, proper syntax, e.g. ON, omitted for brevity):

```<code>FROM documents
INNER JOIN tags
INNER JOIN publishedOn
INNER JOIN websites
WHERE tag = X AND website = Y
</code>```

If X is "all", then I'd do it like this:

```<code>FROM documents
INNER JOIN publishedOn
INNER JOIN websites
WHERE website = Y
</code>```

Tags are not queried because they aren't relevant. The user selected "all" which means "I don't care what tag the document has". Here, you make a decision at the data access layer and choose the second query if you see that. If you'd rather keep your DAL simpler and make the decision within the SQL query itself, that's easy to do:

```<code>FROM documents
INNER JOIN tags
INNER JOIN publishedOn
INNER JOIN websites
WHERE (X = all OR tag = X) AND website = Y
</code>```

If you use a query like this, you might run into the "magic number" problem, meaning "what value do I compare X against to see if it means all?" A common pitfall is using a hardcoded literal for comparison. For example, @tagID = -1. This is bad. What you've described doing - adding "all" as a "virtual tag" - is a way to prevent this problem, but it's far complicated than is necessary.

Again, ask yourself what the meaning of "all" represents in relation to your tags. It's "I don't care" or, more precisely, "unspecified". There's a value for that already: null. If the user picks "all", then set the tag filter property on your BO to null. When it's time to inspect the filter, if it's null, don't filter. The choice between performing the inspection in the DAL or DB is a question of where you want to put the little bit of extra complexity (which implies a minor maintenance increase and a performance hit which ought to be negligible).

Bottom line: don't treat "all" as a tag because it isn't one. Trying to crowbar it in will make things difficult and confusing for whoever maintains the code in the future.

Body:
It seems to me like you're putting the cart a bit before the horse, especially since you have a partial implementation already. Take a step back and ask yourself what "all" means and what purpose it serves.

In this case it means "without conditions or filters", and the purpose is to provide a way for the user to tell the system "I don't care what the tags are". Its meaning becomes relevant at the point where you examine the actual value of the tags, which doesn't happen until you get to the DB query. Before that, the value of the tag doesn't matter. You can just pass it through your business objects as normal.

all documents from tag X that were published on website tagged Y

I'd write such a query like this (pseudo-SQL, proper syntax, e.g. ON, omitted for brevity):

FROM documents
INNER JOIN tags
INNER JOIN publishedOn
INNER JOIN websites
WHERE tag = X AND website = Y

If X is "all", then I'd do it like this:

FROM documents
INNER JOIN publishedOn
INNER JOIN websites
WHERE website = Y

Tags are not queried because they aren't relevant. The user selected "all" which means "I don't care what tag the document has". Here, you make a decision at the data access layer and choose the second query if you see that. If you'd rather keep your DAL simpler and make the decision within the SQL query itself, that's easy to do:

FROM documents
INNER JOIN tags
INNER JOIN publishedOn
INNER JOIN websites
WHERE (X = all OR tag = X) AND website = Y

If you use a query like this, you might run into the "magic number" problem, meaning "what value do I compare X against to see if it means all?" A common pitfall is using a hardcoded literal for comparison. For example, @tagID = -1. This is bad. What you've described doing - adding "all" as a "virtual tag" - is a way to prevent this problem, but it's far complicated than is necessary.

Again, ask yourself what the meaning of "all" represents in relation to your tags. It's "I don't care" or, more precisely, "unspecified". There's a value for that already: null. If the user picks "all", then set the tag filter property on your BO to null. When it's time to inspect the filter, if it's null, don't filter. The choice between performing the inspection in the DAL or DB is a question of where you want to put the little bit of extra complexity (which implies a minor maintenance increase and a performance hit which ought to be negligible).

Bottom line: don't treat "all" as a tag because it isn't one. Trying to crowbar it in will make things difficult and confusing for whoever maintains the code in the future.


问:
How to approach refactoring an existing web application?
I've been reading and thinking a lot lately, and I've come to the conclusion that I maybe I should rethink my web development strategy. I'm doing a lot of on-the-fly programming, and in the 2 years I've been working on a PHP web application, what might have begun as a little tool became quite the big project. But there is a ton of legacy code from me and my predecessor, snippet of code that might have make sense at the time, but now I'm questioning the usefulness of said code in the form it is actually. Furthermore so such things like unit testing and Test-Driven Development wasn't in my scope until quite recently.

So how would you approach refactoring the web application? What would be the things I should look for and in which order? What about browser game versus functional web app? Would there be then difference in the approach?

答:
Pretty much the same way you approach any kind of legacy code. You find a piece that's testable, you write tests for it, and refactor.

If you can't find a piece readily testable, you'll need to make it testable without the safety harness of a test suite, in which case you very carefully change some almost-testable piece of code so that it is testable.

Code that doesn't render things to the browser - "infrastructure" code, models, database-touching stuff - might be a good place to start.

Edit: UI testing: With the warning that I have little experience here, a friend of mine does this: he runs some piece of HTML-generating code. Then he hacks on his code, and compares the newly-generated code against the old version (using diff; he hasn't automated all the way). Changes in the HTML means your refactoring broke.

ContentLicense: CC BY-SA 2.5


问:
User roles in database
What would be the most efficient way to store a users role(in my case) in the database?

What my user table looks like:

```<code>id                         int(AI)
username                   varchar(80)
password                   varchar(255)
</code>```

For example the rights would be like this:

There should be rights to see a page:

Page1

Page2

Page3

Page4

So in the case above you should be allowed to either have the right to see Page1 and Page2 but also just Page3

You can

Delete post

Create post

Edit post

on just Page2

All these possibilities of combinations should have their own role.

Now I dont know how to store this in a table.

I thought about creating a table like this:

```<code>role | page1 | page2 | page3 | page4 | page5 | page6 | delete | create | edit |
role1| yes   | yes   | no    | no    | no    | no    | yes    | yes    | yes  |
</code>```

But I think there's way too many combinations to use this so there must be a better/efficient/easier way to do this.

So my question is:

What is the best/easiest way to do this?

答:
"Good", "easy", and "efficient" are not only all subjective and ambiguous terms, very often they are in conflict with each other. Choosing a data representation is virtually always a trade-off between goodness of one kind and another kind.

Having separate fields for every read/write/edit right for each page makes for the simplest database layout: just a bunch of columns. But it's more effort to program against, since whatever code checks for edit rights on page 1 must be duplicated to work with page 2, page 3 etc. If you had a smarter data structure, the code would just have to be parametrized instead. Duplicated code is a well-known source of consistency defects: cut-and-paste jobs are 'simple' to write, but usually less simple to work with afterwards. If you expect to spend more time maintaining your program than on writing it in the first place, you should prioritize ease of maintenance. For instance, once a fourth page is invented, redoing the cut-and-paste is usually a tricky thing to get correct. Increasing a constant that represents a limit from 3 to 4 is trivial.

The downside of creating a structured data representation (e.g. a linking table with "page number", "user id" and "action type" columns) is that you expend a little more effort in planning and slightly more data storage in production. There are situations where this cost is prohibitive (e.g. if you have to fit your program into 4K bytes), but as an educated guess, I assume you're not in that situation, so you should invest a little effort up front to improve maintenance and readability of your code.

Title: User roles in database


答: There are many good answers above, and the clear fact that anything you would do with a base-class-of-all-objects can be done better in other ways as shown by @ratchetfreak's answer and the comments on it is very important, but there is another reason, which is to avoid creating inheritance diamonds when multiple inheritance is used.  If you had any functionality in a universal base class, as soon as you started using multiple inheritance you'd have to start specifying which variant of it you wanted to access, because it could be overloaded differently in different paths of the inheritance chain.  And the base can't be virtual, because this would be very inefficient (requiring all objects to have a virtual table at a potentially enormous cost in memory usage and locality).  This would become a logistical nightmare very quickly.</p>


答:
Don't store passwords in a database, even encrypted passwords.

Authentication and Authorisation are different concepts and unless space efficiency is very important in your database, you should consider splitting them up.

Instead of having a column for each type of permission and what object that permission relates to you should take a look at encoding permissions like they do for *NIX file permissions.

Instead of storing passwords directly in a database you can hash (a function that is mathematically impossible to reverse) the password and store the result of the hash in the database. Then when a user tries to log in, do the same hash on the proposed password and compare it to the one stored in the database, if they match, the user entered the correct password. There are a number of issues with this; you need a hash function that doesn't have too much chance of collision (when more than one password resolve to the same output), complexity of the hash function (Moore's law will make it easier and easier to brute force attack), and there are pre-computed 'rainbow tables' that store password/hash pairs to worry about (you should 'salt' the passwords with a pseudo-random string so that they are different than the attacker is expecting).

If you keep the usernames/passwords(or hashes) and the authorisation separate then it will keep the logical units separate and you can split them up later if you end up using something like LDAP.

*NIX file permissions use octal and add the number together, so +4 for read, +2 for write, and +1 for execute, for owner, group, and other, so 751 would be read, write, execute for the owner, read and execute for anyone in the group with permissions and only execute permissions for everyone else.

Title: User roles in database

Body:
What would be the most efficient way to store a users role(in my case) in the database?

What my user table looks like:

```<code>id                         int(AI)
username                   varchar(80)
password                   varchar(255)
</code>```

For example the rights would be like this:

There should be rights to see a page:

Page1

Page2

Page3

Page4

So in the case above you should be allowed to either have the right to see Page1 and Page2 but also just Page3

You can

Delete post

Create post

Edit post

on just Page2

All these possibilities of combinations should have their own role.

Now I dont know how to store this in a table.

I thought about creating a table like this:

```<code>role | page1 | page2 | page3 | page4 | page5 | page6 | delete | create | edit |
role1| yes   | yes   | no    | no    | no    | no    | yes    | yes    | yes  |
</code>```

But I think there's way too many combinations to use this so there must be a better/efficient/easier way to do this.

So my question is:

What is the best/easiest way to do this?


问:
Database Handler and SQL injection prevention
I've written a database model class in PHP and have written a controller class that specifically validates the data before sending it to db. I'm getting criticism that I should handle the data in database model class rather than controller class.

I wanted to write a generic db class which can be used anywhere for CRUD operations. Now can you guys please help me out in sorting this out? Whether I should validate the data in db model class or in db controller class?

答:
I think what you're looking for is a Service class. Controllers should be very thin and do literally nothing but forward the data from the request to a service and respond with the appropriate output.

The service class should take care of validation delegation and dealing with the database abstraction.


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
I like the first method. It seems neater IMO, and it's more compact, which I like.

EDIT: Ah, a third. I like that one the best when possible, as it's even smaller/neater.


问:
Does react.js make sense for a static content-driven site?
I'm pretty sold on the react.js model because it makes DOM manipulation so smooth and comprehensible. But I'm wondering how it could be leveraged for a site that's largely static with big blocks of text and images that don't move. Would it just get in the way? It seems awkward to have components with KBs of text in their state.</p>

答:
Know what you want to do, then choose the technology.

From that point of view, React.js seems to be overkill for a mostly static web.

From React's website:

We built React to solve one problem: building large applications with data that changes over time.

React is a hammer for a specific nail. That would indicate that it will get in the way of creating a mostly static website.


问:
Is circular Dependency Injection a good practice?
I'm trying the Dependency Injection pattern in some new classes, more specifically in a Transaction System and stumbled into a dilemma. I have a Person class with a create_new_transaction method, and a Transaction class to represent my each transaction.

As the pattern dictates I inject the class transaction in the constructor. But I also wanted to inject the originator and receiver objects into the Transaction class so I can access their public name and account parameter. Am I hurting the design by implementing this? Is this creating high coupling between these two classes?

```<code>class Transaction(object):

      def __init__(self, amount, from_person, to_person):
          self.from = from_person
          self.to = to_person

class Person(object):

     def __init__(self, name, transaction=Transaction):
         self._transaction = transaction
         self.name = name

     def create_new_transaction(self, amount, destiny):
         return self._transaction(amount, from_person=self, to_person=destiny)
</code>```

答:
Whenever someone says 'Circular Dependency' I shudder. I see as an issue on the design. DI is independent of circular dependency.

You are indeed creating coupling between the two classes. Is it needed? As a general case, I don't believe so. I think that you are giving too much responsibility to the Person class. Therefore, you are hurting the design. Can only Person initiate transactions? Will at any point a different entity be the source or destination of a transaction (e.g., a company)?

It will depend on what are the exact requirements and the domain in which you are working. But I would have something else creating the transaction (Bank class, or Dealer class, or something like that)


问:
How to automatically connect letters into words?
I would like to connect letters into meaningful words? E.g.

input:

```<code>T E ST IN G WE B A P P LIC AT IO N S
</code>```

output:

```<code>TESTING WEB APPLICATIONS
</code>```

what kind of task is this? A task in NLP, or just some string operation?
What kinds of NLP task(s) are involved?

Are there software programs that I can use to do the job?

What are some programming libraries that I can call to do the job?

note that:
my original text not shown here is a mixture of space-separated letters and words, and are there software programs or programming libraries that can find out and take advantage of the existing words?

答:
The problem is called 'language modeling'

It is trivial to connect letters into some words by taking any dictionary (list of valid words) and finding a way that fits. However, in practice the main problem in this task usuall is finding the best words that fit those letters. Fortunately, this is a problem that others have as well - it occurs in, for example, speech recognition and thus is rather well researched and has resources and various ways to try and solve it. In this field, this problem is generally called 'language modeling'.

Statistical methods

The currently standard approach for this problem is to statistically evaluate the likelihood of each subfragment based on a large number of examples of how the language looks in real world. If we often see fragments like "... to therapist" and rarely see fragments like "... to the rapist" then we may assume that those letters should be merged together.

A good classic textbook descriptions are available in Speech and Language Processing by Dan Jurafsky and Jim Martin (chapter 6 in the 1st edition, chapter 4 in the 2nd edition) and  Foundations of Statistical Natural Language Processing by Chris Manning and Hinrich Schütze (chapter 6).

An often used library for doing language modeling is SRILM - http://www.speech.sri.com/projects/srilm/manpages/ and I believe that projects such as python NLTK (http://www.nltk.org/) also have tools for that.  In any case, the particular model (weights of word combinations) is different for each language and domain, so this may be something that you have to adapt yourself.


问:
Java class to enforce an implementation of super classes' public methods
I have the following :

```
public Class A {

    public void methodA() {
        ....
    }

    public void methodB() {
        ....
    }

}
```

I don't have control over Class A. I would like to create subclasses of Class A with a restriction that it must override methodA() (super.methodA() call must run the implementation of Class A). is it possible? is so, how?

答:
Before using reflection API think about the cost of it.

It is simply easy to do. For instance:

C subclass of B and B subclass of A. All three have a method methodName() for example.

```<code>public abstract class A {

    public void methodName() {
        System.out.println("Class A");
    }

}

public class B extends A {

    public void methodName() {
        super.methodName();
        System.out.println("Class B");
    }

    // Will call the super methodName
    public void hackSuper() {
        super.methodName();
    }

}

public class C extends B {

    public static void main(String[] args) {
        A a = new C();
        a.methodName();
    }

    @Override
    public void methodName() {
        /*super.methodName();*/
        hackSuper();
        System.out.println("Class C");
    }

}
</code>```

Run class C Output will be:

```<code>Class A
Class C
</code>```

Instead of output:

```<code>Class A
Class B
Class C
</code>```

Body:
Before using reflection API think about the cost of it.

It is simply easy to do. For instance:

C subclass of B and B subclass of A. All three have a method methodName() for example.

public abstract class A {

    public void methodName() {
        System.out.println("Class A");
    }

}

public class B extends A {

    public void methodName() {
        super.methodName();
        System.out.println("Class B");
    }

    // Will call the super methodName
    public void hackSuper() {
        super.methodName();
    }

}

public class C extends B {

    public static void main(String[] args) {
        A a = new C();
        a.methodName();
    }

    @Override
    public void methodName() {
        /*super.methodName();*/
        hackSuper();
        System.out.println("Class C");
    }

}

Run class C Output will be:

Class A
Class C

Instead of output:

Class A
Class B
Class C


问:
Can "higher order function" feature allow/maintain abstraction and encapsulation?
Below is the function repeat written using a functional paradigm, such that when called as repeat(square, 2)(5) it will apply the square function 2 times on the number 5, something like square(square(5)).

```<code>def repeat(f, n):
    def identity(x):
        return x
    def apply_n_times(n):
        def recursive_apply(x):
            return apply_n_times(n - 1)(f(x))

        if n < 0:
            raise ValueError("Cannot apply a function %d times" % (n))
        elif n == 0:
            return identity
        else:
            return recursive_apply
    return apply_n_times(n)

def square(x):
    return mul(x, x)
</code>```

With regards to abstraction, I see that repeat(square, 2) returns an implementation detail in the form of apply_n_times(n - 1)(f(x)) multiple times before providing the actual result.

With regards to encapsulation, for the expression f = repeat(square, 2) one could mutate the members of function object, for example:  f.__name__='garbage'

Does the concept of higher order function allow supporting abstraction and encapsulation? Because they return the implementation details and provide access for mutation.

Such existing implementations in large software are very tedious to use, as the user has to have an idea of the implementation before using it.

答:
The benefit of abstraction is that the caller doesn't have to know about implementation details. If I understand correctly, you're questioning this python construct because the caller can find about about implementation details. That's not the same thing.

Not having to know about how a method does its job is useful. It aids the software developer in their job, because you can think about one level of detail at a time instead of having to juggle two of them simultaneously.

Being unable to find out is something quite different. It can be useful to give the library programmer greater freedom for later optimization without anything breaking. But in practice, it suffices to simply declare in your API "Any intermediate types visible through the returned helper object are not part of the contract, and using them is undefined behaviour". That way the library writer retains the same amount of freedom, and only callers who willfully break the explicit contract suffer from it, while the main benefit (being able to ignore the details) stays unchanged.


答:
Wrt abstraction, I see that repeat(square, 2) returns implementation detail in the form of apply_n_times(n - 1)(f(x)) multiple times before providing the actual result.

The function returned by repeat(square, 2) is not an implementation detail; it's the whole point of calling repeat. An implementation detail is something that the caller doesn't need to know about (and in most cases isn't allowed to know anything about either) and that could be changed without breaking any of the caller's code. The caller wants and needs the function returned by repeat.

It seems to me that you're looking at repeat as if its purpose is to give you the result of applying f, and that's why you see the fact that it returns apply_n_times as an implementation detail. If you only wanted the result of composing f with itself n times, you could have defined repeat to take three arguments. But what makes curried functions useful it the fact that you can make use of the in-between functions it creates! E.g.

```<code>numbers = range(1, 10)
numbersSquaredTwice = map(repeat(square, 2), numbers)
</code>```

In other words, their purpose isn't to compute the final result, it's to compute a function that can compute the final result. The function returned by repeat is a useful thing to have in and of itself.

With regards to encapsulation, for expression f = repeat(square, 2) one could mutate the members of function object, for example: f.name='garbage'

Everything in Python has metadata that can be inspected and modified, and function objects are no exception. Python won't stop you from deeply inspecting and messing with every piece of data in the program. That lets you break almost any abstraction if you choose to do so. So you could say that it's Python that doesn't have very good support for encapsulation. In functional languages a function doesn't "know its name", because asking a function for its name makes about as much sense as asking an integer for its name. Functions don't need names, and if you choose to give them one, they don't need to know it.

But do note that every call to repeat produces a new function object, so even if you choose to muck around with it, the changes you made won't affect the return values of other calls to repeat.

Title: Can "higher order function" feature allow/maintain abstraction and encapsulation?

Body:
Below is the function repeat written using a functional paradigm, such that when called as repeat(square, 2)(5) it will apply the square function 2 times on the number 5, something like square(square(5)).

```<code>def repeat(f, n):
    def identity(x):
        return x
    def apply_n_times(n):
        def recursive_apply(x):
            return apply_n_times(n - 1)(f(x))

        if n < 0:
            raise ValueError("Cannot apply a function %d times" % (n))
        elif n == 0:
            return identity
        else:
            return recursive_apply
    return apply_n_times(n)

def square(x):
    return mul(x, x)
</code>```

With regards to abstraction, I see that repeat(square, 2) returns an implementation detail in the form of apply_n_times(n - 1)(f(x)) multiple times before providing the actual result.

With regards to encapsulation, for the expression f = repeat(square, 2) one could mutate the members of function object, for example:  f.__name__='garbage'

Does the concept of higher order function allow supporting abstraction and encapsulation? Because they return the implementation details and provide access for mutation.

Such existing implementations in large software are very tedious to use, as the user has to have an idea of the implementation before using it.

Body:
Wrt abstraction, I see that repeat(square, 2) returns implementation detail in the form of apply_n_times(n - 1)(f(x)) multiple times before providing the actual result.

The function returned by repeat(square, 2) is not an implementation detail; it's the whole point of calling repeat. An implementation detail is something that the caller doesn't need to know about (and in most cases isn't allowed to know anything about either) and that could be changed without breaking any of the caller's code. The caller wants and needs the function returned by repeat.

It seems to me that you're looking at repeat as if its purpose is to give you the result of applying f, and that's why you see the fact that it returns apply_n_times as an implementation detail. If you only wanted the result of composing f with itself n times, you could have defined repeat to take three arguments. But what makes curried functions useful it the fact that you can make use of the in-between functions it creates! E.g.

numbers = range(1, 10)
numbersSquaredTwice = map(repeat(square, 2), numbers)

In other words, their purpose isn't to compute the final result, it's to compute a function that can compute the final result. The function returned by repeat is a useful thing to have in and of itself.

With regards to encapsulation, for expression f = repeat(square, 2) one could mutate the members of function object, for example: f.name='garbage'

Everything in Python has metadata that can be inspected and modified, and function objects are no exception. Python won't stop you from deeply inspecting and messing with every piece of data in the program. That lets you break almost any abstraction if you choose to do so. So you could say that it's Python that doesn't have very good support for encapsulation. In functional languages a function doesn't "know its name", because asking a function for its name makes about as much sense as asking an integer for its name. Functions don't need names, and if you choose to give them one, they don't need to know it.

But do note that every call to repeat produces a new function object, so even if you choose to muck around with it, the changes you made won't affect the return values of other calls to repeat.


问:
Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far

答:
I personally prefer underscore_case because I find it more readable, but agree with the other answerers who point out that consistency with the existing codebase is much more important.

However, I have a counterexample for those who say "follow the convention of your language and its libraries".

In the past we wrote C code on Windows using underscore_case, and called PascalCase Win32 functions:

```<code>if (one_of_our_conditions_is_true())
{
    call_one_of_our_functions();
    CallSystemFunction();
}
</code>```

The visual distinction between our function names and Microsoft's function names was a help rather than a hindrance, as it clearly showed when the code was going into "system land".

In addition, I was able to change my editor's syntax highlighting rules to display them in  different colours, which gave further visual clues when trying to understand unfamiliar sections of code (or even my own).

Body:
I personally prefer underscore_case because I find it more readable, but agree with the other answerers who point out that consistency with the existing codebase is much more important.

However, I have a counterexample for those who say "follow the convention of your language and its libraries".

In the past we wrote C code on Windows using underscore_case, and called PascalCase Win32 functions:

if (one_of_our_conditions_is_true())
{
    call_one_of_our_functions();
    CallSystemFunction();
}

The visual distinction between our function names and Microsoft's function names was a help rather than a hindrance, as it clearly showed when the code was going into "system land".

In addition, I was able to change my editor's syntax highlighting rules to display them in  different colours, which gave further visual clues when trying to understand unfamiliar sections of code (or even my own).


答:
The caller doesn't so much need to know the implementation details of repeat(f, n) as he needs to know its return value.  In this case, the return value is a little more complicated than most, because it returns a function.  In a static language like Haskell, this is easily documented in the function signature like:

```<code>repeat :: (a -> a) -> Int -> (a -> a)
</code>```

This tells you it returns a function that takes an a and returns an a, but you don't need to know any implementation details of that function, just its signature and semantics.

The main weakness of dynamic languages like python is that their types, including their return types, are not documented in their function signatures (the main strength is the programmer isn't forced to document them).  This leaves you with either documenting return types in a comment/docstring, or reading the function body or contextual clues in the calling code to determine them.  You have always had to do this with all functions, not just higher-order ones.  You probably just didn't notice because your functions have generally been small or simple enough to not be problematic, and complex third-party code you have used has generally had good docstrings.

Python also has a grand tradition of information being hidden by convention, not by dictate of the language.  If you can't tell if something should be a private implementation detail or not, you need to document that as well.  I generally consider the body of any closure to be a private implementation detail, whether returned or not.

Body:
The caller doesn't so much need to know the implementation details of repeat(f, n) as he needs to know its return value.  In this case, the return value is a little more complicated than most, because it returns a function.  In a static language like Haskell, this is easily documented in the function signature like:

repeat :: (a -> a) -> Int -> (a -> a)

This tells you it returns a function that takes an a and returns an a, but you don't need to know any implementation details of that function, just its signature and semantics.

The main weakness of dynamic languages like python is that their types, including their return types, are not documented in their function signatures (the main strength is the programmer isn't forced to document them).  This leaves you with either documenting return types in a comment/docstring, or reading the function body or contextual clues in the calling code to determine them.  You have always had to do this with all functions, not just higher-order ones.  You probably just didn't notice because your functions have generally been small or simple enough to not be problematic, and complex third-party code you have used has generally had good docstrings.

Python also has a grand tradition of information being hidden by convention, not by dictate of the language.  If you can't tell if something should be a private implementation detail or not, you need to document that as well.  I generally consider the body of any closure to be a private implementation detail, whether returned or not.


问:
How To Avoid Dependencies between Modules
We have two modules, lets call them U and F.

Module U has entities like that:

```<code>class Upload {
    Long id;
    User uploadedBy;
    Date uploadedAt;
}
</code>```

Module F has entities like that:

```<code>class Field {
    Long id;
    String displayName;
    Type type;
}
</code>```

And both have the typical manager beans with create, edit, delete and some GUI depending on them.

So now what one customer wants to have is for us to add to the entites of module U so they will look like that:

```<code>class Upload {
    // fields as above
    List<Field> fields;
}
</code>```

I don't think that's the best idea, because it would create a dependency between F and U that is not necessary for most customers. So now we are trying to find a good architecture that allows us to model what the customer wants without creating dependencies.

One thing that came to mind was to create a Module E with entities like that:

```<code>class ExtendedUpload1 {
    Upload upload;
    List<Field> fields;
}
// or...
class ExtendedUpload2 extends Upload {
    List<Field> fields;
}
</code>```

So only that module will have dependencies to both F and U, and both F and U can live separately. But we have an API in between GUI and server, meaning separate values classes and interfaces both sides work with. And while we can inject additional functionality to both GUI and server, dynamically extending the API is the actual problem. We would need to copy all the API classes to work with the new values.

What architectural patterns apply to that use case? How could we solve the problem elegantly?

答:
If I understand correctly your question, you don't want to mention the exstince of module F in the code of module U, making them loosely coupled, i.e. the module F can be replaced some times in the future.

In that case the first one that comes to mind:

Program to an interface, not an implementation - GoF

Basically Upload::fields can be of type List<FieldInterface> and the type Field
can implement the FieldInterface. That way U doesn't need to know nothing about F, the only thing on which U is dependent on is the abstract interface FieldInterface.


问:
Communicating between browser and a native application securely
I am working on web application that needs data it can only get from its locally installed native application browser.

How can you get around the browser sandbox so that you can communicate (securely, since the data is potentially sensitive), with a native application.

In the only example that I found, the user manually move some tokens and files between the two, which is a horrible user experience that i would like to avoid.

答:
You could embed a webserver in the native application, then your client can make calls to it via hard-coded links to http://localhost/xyz (you may have to worry about cross site scripting warnings here, and/or run the server on a non-http port). If you use websockets, your native application can even push data to the web browser once the browser has initiated communication.

I do it myself locally, an embedded webbrowser control requests visualisation data from a custom webserver and when developing I run both on the same PC.

There are many tiny and efficient embedded webservers for C/C++ (Mongoose, NxWeb, civetweb etc), C# tend to go for a full-on WCF server, python comes with a little webserver in it IIRC.


答:
You should define permissions for roles, not users.  Users are assigned a role which specifies the type of access it has on a given page.  Take a look at the following diagram:

Good examples for roles might be "manager", "admin", "user", "public".  The advantage of doing it this way is that roles are easy to change later.  If you add a page and decide that only admins can access it, changing it is as simple as changing the admin role, and all users with that role will take the change.

RolePermissions is where you will put the individual page permissions.  It should have a name (that you will reference in your program as a key, or directly by resource name, though I would recommend by key), and a series of permissions.  Typical permissions would likely be view, update, create, delete, though you should create at least a couple extra fields for custom permissions that may be specific to the page.  View is a special permission that will determine whether or not the user can view that page, and if not, you should redirect to a 401 error page or a login page.

There is also the issue of what to do if you fail to find permissions for a given page.  My thoughts are that you could automatically assume that the user has no permissions to view that page, however an alternative approach could be to have a special role that cannot (or should not at least) be deleted called public.  If you find yourself in the circumstance that a user's role does not explicitly show permissions, you could refer automatically to public role permissions for the proper behavior.  In this way, ultimately you'd only need to specify permissions that grant more leniancy towards non-public permission role rather than always having to specify permissions for every page and role.

Login information should be kept in Users table and should be separate from permissions.  Also as @Encaitar mentioned in his answer, it would be wise to deal with password hashes, and not the passwords themselves, encrypted or otherwise.

Title: User roles in database


问:
Database strategy for connected but disparate applications
I'm working on a series of inter-related but separate web applications, all situated on the same host:

```<code>Super Admin
|
---Site Network Admin
|   |
|   ---Site
|   |
|   ---Site
|   |
|   ---Site
|
---Site Network Admin
    |
    ---Site
    |
    ---Site
    |
    ---Site
</code>```

All three will have access to the same core library (Zend Framework), and separate application libraries for each tier in the network - thus 3 applications and one library - but different configurations to support unique instances.

I'm interested to hear people's opinion on the best database strategy to support these applications.

On the one hand, I could deploy one database, or perhaps one for each application level (i.e. 3). This has the advantage of being easy to roll out changes, but the disadvantage that users share the access burden - i.e. if one user is really hammering the database, the performance of other applications sharing the database will suffer. Another disadvantage is that any data corruption could potentially affect all end users.

On the other, I could utilise a series of databases - one for the first two tiers to share administrative data - but separate instances for each site deployed on the network. This has the advantage that end users are isolated and thus data corruption is more easy to contain. The disadvantage is obviously the converse of the previous example - in that changes are then harder to roll out across the network.

My thinking is that it's dictated by usage vs user population. If you have low quantities of users, but they interact with the database a lot - then plan B is best. If it's the former, that you have high yields of users with low interaction rates - then plan A is best.

I'm interested to hear other people's thoughts as to the best approach for dealing with this situation.

答:
I think you've covered the major arguments for both scenarios very well.  There may also be some efficiency around database disk access for fewer databases (fewer and/or shorter seeks), but it shouldn't be dramatic.  Having more databases also probably means smaller memory usage for indexes as well - instead of (site_id, post_id) composite keys, you might just have (post_id) keys.

Depending on the likelihood of project success (ie, startup vs. internal company project), I would generally suggest going with a hybrid approach.

At first, go with a database design that allows you to store multiple instances of your application within the same database.  This is easier in the short term in terms of administration and maintenance - you don't need to repeat manual or automatic actions over a number of databases.  This allows you to focus on being successful in developing your application for your initial sites.

If you end up being successful and need more database capacity, then you can change to having multiple database servers - each database server handles multiple sites.  In the early initialisation stage of your application, you choose which database server to use based on the site.

If you go with the "each instance has its own dedicated database" approach, you will initially spend a lot of time solving the multiple database problem while you could be spending it increasing the likelihood that your project is successful.

Either way, make sure you have database backup and restore covered and well-understood.


问:
Why is base-for-all-objects discouraged in C++
Stroustrup says "Don’t immediately invent a unique base for all of your classes (an Object class). Typically, you can do better without it for many/most classes." (The C++ Programming Language Fourth Edition, Sec 1.3.4)

Why is a base-class-for-everything generally a bad idea, and when does it make sense to create one?

答:
Arguably "void" fulfils a lot of the roles of a universal base class. You can cast any pointer to a void*. You can then compare those pointers. You can static_cast back to the original class.

However what you can't do with void which you can do with Object is use RTTI to figure out what type of object you really have. This is ultimately down to how not all objects in C++ have RTTI, and indeed it's possible to have zero-width objects.


问:
Tree search for path finding - algorithm critiques
So, I'm pretty new to AI in general, and am trying to implement a tree-based search from a textfile input (a maze). An example would be:

```<code>||||||||||||||||||||||
| ||        | |      |    \
|    |||||| | |||||| |     \
||||||       |    P  |      \
|   .| |||||| || |||||       \  P = Start
| |||| |         |   |       /  . = Goal
|        ||| |||   | |      /
||||||||||    |||||| |     /
|          ||        |    /
||||||||||||||||||||||
</code>```

I understand the basic algorithms in general (BFS, DFS, A*, etc.), but I want to make sure I'm implementing them correctly, and not somehow cutting corners because "I know where the best path is". My basic idea is:

Parse the file into a 2D array

While parsing, if I encounter P, note the Start index

While parsing, if I encounter ., note the Goal index

Begin at Index(Start), and evaluate surrounding [blank] spaces

Create Nodes for these, and add the appropriate actions to the current Node's available actions --- Add these Nodes to my frontier que

[continue whichever algorithm from here]

So I guess my main question is, am I generating my "world" correctly? Is it right to not really create Nodes until I encounter them during the search? It seems wasteful to get to a [blank] space, scan the surrounding 4 directions for other [blank] spaces, and if they exist add them to the available actions and create Nodes for all possible actions.

Another alternative would be to generate Nodes as I encounter the [blank] spaces, but this would be hard (since I wouldn't be aware of the upcoming blanks) ... should I parse the file completely, and the traverse the stored array to create all possible Nodes/Links/Actions? Or is that considered cheating somehow...

答:
An object-oriented programmer's instinct on this sort of problem is that at some point they'll have to instantiate some sort of Node object, but you really don't.  You don't even need to create a 2D array.

The path-finding algorithms are described largely in terms of sets.  You can write very clear implementations by parsing your maze into sets of (row, col) tuples. This lets you write operations like the following:

```<code>(row, col) = starts.pop()
neighbors = {(row+1,col), (row-1,col), (row,col+1), (row,col-1)}
neighborSpaces = neighbors & spaces
unvisitedNeighborSpaces = neighborSpaces - visited
neighborGoals = neighbors & goals
</code>```

Here starts, spaces, and goals are sets you created from parsing the file, and visited is updated over the course of your algorithm.  Note that set operations are generally O(n), where n is the smallest operand.  That means neighbors & spaces will only do 4 comparisons, no matter how many spaces in your maze.  It's not the most efficient implementation possible, but it's efficient enough, and the clarity it buys you is well worth it.

Body:
An object-oriented programmer's instinct on this sort of problem is that at some point they'll have to instantiate some sort of Node object, but you really don't.  You don't even need to create a 2D array.

The path-finding algorithms are described largely in terms of sets.  You can write very clear implementations by parsing your maze into sets of (row, col) tuples. This lets you write operations like the following:

(row, col) = starts.pop()
neighbors = {(row+1,col), (row-1,col), (row,col+1), (row,col-1)}
neighborSpaces = neighbors & spaces
unvisitedNeighborSpaces = neighborSpaces - visited
neighborGoals = neighbors & goals

Here starts, spaces, and goals are sets you created from parsing the file, and visited is updated over the course of your algorithm.  Note that set operations are generally O(n), where n is the smallest operand.  That means neighbors & spaces will only do 4 comparisons, no matter how many spaces in your maze.  It's not the most efficient implementation possible, but it's efficient enough, and the clarity it buys you is well worth it.


问:
Accessing shared data without blocking in TPL
I am writing a class that contains data. It exposes methods that allow to query the data, while the data is also being updated from an external source (web service, for example).

All the methods expose tasks that are started on a worker thread using the default task scheduler. So the structure of the class is as follows:

```<code>public class A
{
    private object _myLock;

    public Task<int> GetSomeNumber(int aParameter)
    {
        return Task.Run(() =>
        {
            lock (_myLock)
            {
                int result = 0;
                // calculate the result...
                // ...
                return result;
            }
        });
    }

    public Task<string> GetSomeText(int aParameter)
    {
        return Task.Run(() =>
        {
            lock (_myLock)
            {
                string result = "";

                // calculate the result...
                // ...
                return result;
            }
        });
    }
}
</code>```

The methods may be called several multiple times, while the data itself is being updated, so the calculations that require the shared data are surrounded with a lock statement. The problem is that this code blocks the thread in which the task is run. Of course, these are not UI thread, so the UI remains responsive, but it does consume threads and keeps them blocked. I would prefer for the worker threads in the thread pool to remain as available as possible.

Is there a way, a best practice of some sort, that allows to write this code so that the shared data is thread safe and at the same time the tasks are not blocked? If instead of waiting for a lock, the tasks would need to wait for something else to finish (a task), I would use ContinueWith in order to create a continuation task and return it, so that it would be scheduled to run when the first task is completed. Is there a way to do the same with lock, so that the task is only scheduled when the lock is available?

Update
I have done some reading and found out about several possible options that allow for shared data sync. These include: SemaphoreSlim, AsyncLock, and ConcurrentExclusiveSchedulerPair.

I would love to see a recommendation for a best practice, of writing a service class that provides "read only" task methods that can run concurrently with a read lock, and "write" task methods that require write lock.

答:
How about:</p>

```<code>// any child object should freeze when this object freezes...
interface IFreazableCloanable
{
    bool IsFrozen { get; }
    // Any further attempts to change the object should throw an Exception
    void Freeze();

    // Creates mutable Clone of the object
    IFreazableCloanable DeepCloneMutable();
}

class SyncedObject<T> where T : class, IFreazableCloanable
{
    SemaphoreSlim _writersLock = new SemaphoreSlim(0, 1);
    volatile T _internal;

    public SyncedObject(T thing) // if writes are unsynced then only the last one counts.
    {
        _internal = (T)thing.DeepCloneMutable();
    }
    public T Read()
    {
        T result = _internal;

        result.Freeze();

        return result;
    }

    public void Write(Func<T, T> writer)
    {
        _writersLock.Wait();

        T temp = (T)_internal.DeepCloneMutable();

        temp = writer(temp);

        _internal = temp;

        _writersLock.Release();
    }
}

class Data : IFreazableCloanable
{
    private string _data = "lala";
    public string MyData
    {
        get
        {
            return _data;
        }
        set
        {
            if (IsFrozen)
            {
                throw new Exception("Very Bad");
            }
            _data = value;
        }
    }
    public bool IsFrozen
    {
        get;
        private set;
    }

    public void Freeze()
    {
        IsFrozen = true;
    }

    public IFreazableCloanable DeepCloneMutable()
    {
        return new Data();
    }
}
</code>```

Body:
How about:

// any child object should freeze when this object freezes...
interface IFreazableCloanable
{
    bool IsFrozen { get; }
    // Any further attempts to change the object should throw an Exception
    void Freeze();

    // Creates mutable Clone of the object
    IFreazableCloanable DeepCloneMutable();
}

class SyncedObject<T> where T : class, IFreazableCloanable
{
    SemaphoreSlim _writersLock = new SemaphoreSlim(0, 1);
    volatile T _internal;

    public SyncedObject(T thing) // if writes are unsynced then only the last one counts.
    {
        _internal = (T)thing.DeepCloneMutable();
    }
    public T Read()
    {
        T result = _internal;

        result.Freeze();

        return result;
    }

    public void Write(Func<T, T> writer)
    {
        _writersLock.Wait();

        T temp = (T)_internal.DeepCloneMutable();

        temp = writer(temp);

        _internal = temp;

        _writersLock.Release();
    }
}

class Data : IFreazableCloanable
{
    private string _data = "lala";
    public string MyData
    {
        get
        {
            return _data;
        }
        set
        {
            if (IsFrozen)
            {
                throw new Exception("Very Bad");
            }
            _data = value;
        }
    }
    public bool IsFrozen
    {
        get;
        private set;
    }

    public void Freeze()
    {
        IsFrozen = true;
    }

    public IFreazableCloanable DeepCloneMutable()
    {
        return new Data();
    }
}


问:
Using message queue systems - forcing synchronous processing
I have a php process producer-a which places a job on RabbitMQ a - deferring processing to a third-party service. The 3rd party service completes processing a and places a response onto queue b. I have a listener consumer-b which picks up jobs on queue b to continue processing.

I need to ensure that producer-a has completed it's process entirely before the listener consumer-b picks up the job to continue processing.

The problem which I am facing is that by using RMQ - I am asynchronously performing tasks - however I need to serialise this process whilst still using RMQ.

In case the above doesn't make sense:

Example timeline if serialised:

```<code>Process A ------> Process B ------> Process C
</code>```

Example timeline with message queue

```<code>Internal Process    Process A----------------------------------|

Deferred Process           Process B -----|

Internal Process                          |Process C---|
</code>```

Process A needs to complete fully before Process C. The problem is that Process B is deferred to a 3rd party service via a message queue, and I need to ensure that Process A which sent the job to Process B completed before Process C picks up the job from Process A. As can be seen from the timeline above, Process C has completed before Process A has completed.

Update:

I didn't think to state the obvious but seem to be getting obvious suggestions / solutions. producer-a simply needs to send a TCP message to Loggly (sometimes takes over 2s) and also needs to update the database to advise that the process was deferred. Sometimes, the message comes back and is picked up by Process C before Process A has completed.

答:
Let Producer-A put some state into DB or some other persistent store and then Consumer-B can look at that state and determine whether to pick up the job from Producer-A or not.
Another option is, since you are using a message queue, let Producer-A send another message upon its completion into queue C. Consumber-B should not pick up any message from queue B until it recieves message from queue C.</p>


答:
Symbian C++ did in fact have a universal base class, CBase, for all objects that behaved in a particular way (mainly if they alloc'd heap). It provided a virtual destructor, zeroed the memory of the class on construction, and hid the copy constructor.

The rationale behind was it was a language for embedded systems and C++ compilers and specs were really really shit 10 years ago.

Not all classes inherited from this, only some.