答:
Edit

I want to be clear that this answer is only talking about the concept of testing your QA process, and I'm not defending the specific methodology portrayed in the question.

End Edit

There is a valid reason to check if your testing/checking is actually working.  Let me give you an example from manufacturing, but the principle is the same.

It's typical when feeding material through a machine that the feeder might not push the material through far enough. This is called a "short feed" and to prevent this we might install a "short feed sensor" (typically a through-beam type sensor that's blocked by the material).  This sensor detects the end of the material when it reaches the full feed length.  At a certain point in the machine cycle we check that the sensor is blocked, and stop the machine if the check fails.

Now you have to think about how the test itself can fail.  For instance, some dirt or other debris can block the sensor and it will always report "OK" and never stop the machine.  Also, the nature of the sensor is that the receiver turns on when the beam hits it, so depending on the type of sensor you have installed, electrically you get an "ON" input when the sensor is not blocked.  That means if the cable got cut or power was lost to that sensor, or the input failed, the logic of your program would read "OFF" and that would mean "blocked" or "OK".

To catch these failure modes of the test, we typically insert a second check to make sure the sensor is actually unblocked during a second part of the cycle.  In this way we check that the test is actually still operating (as best we can).

Similarly there are many ways that a QA department can fail.  Perhaps the automated tests didn't run and the report is looking at an old copy of the test data.  Perhaps someone isn't doing their job right.  Testing the QA department is a reasonable thing to do.

Obviously the draw-back is that a "test bug" could make it through the QA department and into the finished product.  In the manufacturing industry there are sometimes cases where a known bad part, sometimes called a "Red Rabbit", is inserted into the process (typically by someone from QA) and they watch that part go through the process and measure how long it takes to find the part and remove it.  Normally this part is painted bright red (or orange) so it can easily be tracked.  Since someone is watching the part go through process during this test, the chance of it making it into the final product is practically nil.  There are, of course, apocryphal stories of someone throwing a known bad part into the process to "see if the system can find it", and of course having to quarantine all the final parts produced that day and manually sorting them, but that's just a case of not performing your test with due diligence.


问:
Leaving intentional bugs in code for testers to find
We don't do this at our firm, but one of my friends says that his project manager asked every developer to add intentional bugs just before the product goes to QA. This is how it works:

Just before the product goes to QA, the development team adds some intentional bugs at random places in the code. They properly back up the original, working code to make sure that those bugs aren't shipped with the end product.

Testers are also informed about this. So they will test hard,
because they know there are bugs present and that not finding them might
be considered as a sign of incompetence.

If a bug (intentional or otherwise) has been found, they will be reported for the development team to fix. The development team then adds another intentional bug in a related section of the code just before the product goes to the second-level QA. The project manager says a tester should think like a developer and he/she should expect new bugs in sections where changes were made.

Well, this is how it goes. They say that this approach has following advantages.

Testers will be always on their toes and they will test like crazy.
That helps them to also find hidden (unintentional) bugs so developers
can fix them.

Testers feed on bugs. Not finding any bugs will affect their morale.
So giving them an easy one to find will help their morale.

If you ignore the scenario where one of these intentional bugs gets shipped with the final product, what are the other drawbacks we should consider before even thinking of adopting this approach?

Some clarifications:

They properly backup the original code in source control.

When a tester finds the intentional bug, the development team just ignores it. If tester finds out an unintentional (original) bug, the development team first checks whether it is caused by any of the intentional bugs. That is, the development team first tries to reproduce that on the original working code and tries to fix it if they can.

Just ignore the relationship issues between QA and development team. I specifically asked this question on Programmers, not on The Workplace. Consider that there is good rapport between QA and the development team, and they party together after working hours. The project manager is a nice, old gentleman who is always ready to support both teams (Godsend).

答:
Bad idea.

This is the sort of logical, binary approach that developers often bring, but it is demotivating for the QEs. It simply demonstrates a lack of trust. QEs often get placed in these situations without much input from them, and it assumed that they are OK with it, and it is not their place to suggest otherwise.

This kind of thinking combines to QEs being manual testers only and not being motivated to understand the actual code under test.

I am a senior QE and this is a familiar issue in most organizations I have worked in.

ContentLicense: CC BY-SA 3.0


答:
I don't really think this a bad idea. There's just a lot of things that I would speculate work better:

Make QA accountable for the quality any way you can. For example by making support their responsibility also. This will increase their motivation to make sure the products shipped have higher quality. It always takes less effort to discover an inadequacy (bug, obviously missing feature, counter-intuitive behavior) yourself then to try to understand what your upset user is trying to explain. And putting some of that responsibility even on developers might increase their motivation to help the QA do their job the best they can.

Have multiple QA teams, which can the compete. You need to find a sensible metric of course. Definitely not just the number of issues. Factoring in the severity of the defect or the business value (as determined by stakeholders) of proposed enhancements should help.

It's hard to tell whether QA is "good enough". It's easier and possibly even better in the long run to find ways for QA to be "ever improving".

Still, there's one issue to be aware of if you introduce intentional bugs: How do you know the "correct" code ever actually was correct in the first place? After the 2nd QA you remove all intentional bugs that hadn't been discovered. There's no way of knowing that you aren't either just replacing them by code that is broken in a different way or that you are not enabling broken behavior that was unreachable before (exaggerated example: some dialog did not open because of an intentional bug, but the dialog itself is broken - you just don't find out because testers didn't get to see it).

Title: Leaving intentional bugs in code for testers to find

Body:
We don't do this at our firm, but one of my friends says that his project manager asked every developer to add intentional bugs just before the product goes to QA. This is how it works:

Just before the product goes to QA, the development team adds some intentional bugs at random places in the code. They properly back up the original, working code to make sure that those bugs aren't shipped with the end product.

Testers are also informed about this. So they will test hard,
because they know there are bugs present and that not finding them might
be considered as a sign of incompetence.

If a bug (intentional or otherwise) has been found, they will be reported for the development team to fix. The development team then adds another intentional bug in a related section of the code just before the product goes to the second-level QA. The project manager says a tester should think like a developer and he/she should expect new bugs in sections where changes were made.

Well, this is how it goes. They say that this approach has following advantages.

Testers will be always on their toes and they will test like crazy.
That helps them to also find hidden (unintentional) bugs so developers
can fix them.

Testers feed on bugs. Not finding any bugs will affect their morale.
So giving them an easy one to find will help their morale.

If you ignore the scenario where one of these intentional bugs gets shipped with the final product, what are the other drawbacks we should consider before even thinking of adopting this approach?

Some clarifications:

They properly backup the original code in source control.

When a tester finds the intentional bug, the development team just ignores it. If tester finds out an unintentional (original) bug, the development team first checks whether it is caused by any of the intentional bugs. That is, the development team first tries to reproduce that on the original working code and tries to fix it if they can.

Just ignore the relationship issues between QA and development team. I specifically asked this question on Programmers, not on The Workplace. Consider that there is good rapport between QA and the development team, and they party together after working hours. The project manager is a nice, old gentleman who is always ready to support both teams (Godsend).


问:
When is it not acceptable to model physical world objects with classes?

Does Object Oriented Programming Really Model The Real World? [closed]

also

"Firstly, A represents an object in the physical world, which is a strong argument for not splitting the class up." I was, unfortunately, told this when I started programming. It took me years to realize that it's a bunch of horse hockey. It's a terrible reason to group things. I can't articulate what are good reasons to group things (at least to my satisfaction), but that one is one you should discard right now. The end all, be all of "good code" is that it works right, is relatively easy to understand, and is relatively easy to change (i.e., changes don't have weird side effects). –  jpmc26 8 hours ago

"Firstly, A represents an object in the physical world, which is a strong argument for not splitting the class up."
  I disagree with this. For example, if I had a class that represents a car, I would definitely want to split it up, because I surely want a smaller class to represent the tires. -  jpmc26 11 hours ago

source

Until now, I considered the following a good design, because it emphasizes physical hierarchy among the objects. I would expect that to be easier to understand, than some abstractions e.g.class ViewManager, class WheelsFascade.

```<code>class Car
{
public:
    void start() {assert(!m_fuel_tank.empty()); m_engine.start();};
private:
    std::vector<Wheel> m_wheels;
    Engine m_engine;
    FuelTank m_fuel_tank;
}
</code>```

Am I understanding correctly the above criticism that this is not a good design? If so, what are the actual problems? If not, what is being criticized?

答:
The first problem with trying to be true to the real world is that we don't understand it completely. There are still plenty of open problems in physics. To solve a problem tied to the real world you must first pick a model of it, and any choice will be incomplete and to a certain extent inaccurate.

The second problem is that even if you did understand the real world, you don't have the resources to simulate it.

The third problem is that in all likelihood you don't actually want to. Let's say you want to find out how long it'll take for two cars to collide; do you really care about modeling every atomic interaction involved and getting an answer to an infinite level of precision? No; you'll probably just treat both cars like points, use velocity and distance measurements that are only accurate to a handful of decimal places, and either disregard or use very simplified models of friction and wind resistance. And that'll probably be accurate enough.

You say you like your design because it "emphasizes physical hierarchy among the objects", but is a physical hierarchy even relevant to your problem? There are plenty of other relationships between real world entities that aren't physical. If it is relevant, which physical hierarchy have you emphasized, is it accurate enough, and is it simple enough?


问:
Should abstract classes be used to prevent instantiation
Is preventing the instantiation of a class a valid reason to make it abstract? For example, if I have a class called Gauge which has subclasses HeadingIndicator and AirSpeedIndicator, is it a good idea to make Gauge abstract? Because instances of Gauge are pretty useless on their own, but might be useful as references to its subclasses.

答:
Usually Abstract classes are used when one has a class which has some methods which needs to be implemented by one of its child classes, thus, when one sees an abstract class one also expects to see a series of abstract methods which must be implemented.

So although you can use abstract classes to denote non instantiable classes, I do not think that if you want to stop people from instantiating your class this would be the way to go.

Another thing you could do, if you would like to prevent instantiation would be to declare the constructor of the parent class as protected. That way, it will not be visible to outside classes other than the ones which extend it:

```<code>public class Gauge
{
    ...

    protected Gauge(...)
    {
        ...
    }

    ...
}

public class HeadingIndicator extends Gauge
{
    ...

    public HeadingIndicator(...)
    {
        super(...);
    }

    ...
}

public class AirSpeedIndicator extends Gauge
{
    ...

    public AirSpeedIndicator(...)
    {
        super(...);
    }

    ...
}
</code>```

This way, the means to create instances of the Gauge class is restricted only to the extending classes.

Body:
Usually Abstract classes are used when one has a class which has some methods which needs to be implemented by one of its child classes, thus, when one sees an abstract class one also expects to see a series of abstract methods which must be implemented.

So although you can use abstract classes to denote non instantiable classes, I do not think that if you want to stop people from instantiating your class this would be the way to go.

Another thing you could do, if you would like to prevent instantiation would be to declare the constructor of the parent class as protected. That way, it will not be visible to outside classes other than the ones which extend it:

public class Gauge
{
    ...

    protected Gauge(...)
    {
        ...
    }

    ...
}

public class HeadingIndicator extends Gauge
{
    ...

    public HeadingIndicator(...)
    {
        super(...);
    }

    ...
}

public class AirSpeedIndicator extends Gauge
{
    ...

    public AirSpeedIndicator(...)
    {
        super(...);
    }

    ...
}

This way, the means to create instances of the Gauge class is restricted only to the extending classes.


答:
From my point of view, yes it is.

The only question is, do you want a class, or an interface is enough?

So the question will be: do you have common behaviour (method implementation) between child classes, so you need a common abstract class, or just method declaration (in this case, better use an interface)?

D.

Title: Should abstract classes be used to prevent instantiation

Body: Is preventing the instantiation of a class a valid reason to make it abstract? For example, if I have a class called Gauge which has subclasses HeadingIndicator and AirSpeedIndicator, is it a good idea to make Gauge abstract? Because instances of Gauge are pretty useless on their own, but might be useful as references to its subclasses.


答:
Let's say you had a software company where you wrote software for any and all things related to cars.  Should you have one Car object that is reused in all your software?  Of course not:

On a sales floor, a Car has retail and wholesale values.

To a mechanic, a Car consists of a bunch of replaceable parts.

To an engine computer, a Car consists of a bunch of sensors and controls.

To a navigation system, a Car is a little triangle with a position, heading, and velocity.

To a racetrack, a Car has a driver, a time, and a place (first place, second place, etc.)

Sometimes developers get stuck on the real-world definition, and inappropriately create one large object instead of splitting it up into appropriate contexts.  This also happens with inheritance hierarchies, perhaps the most famous example being that a square is considered a special kind of rectangle in the real world, but a rectangle object is usually better modeled as a special kind of square object.

By all means, start by modeling your classes after real world objects.  It's a very reasonable default.  Just don't get stuck there and let it blind you to better alternatives.

Title: When is it not acceptable to model physical world objects with classes?

Body:
Does Object Oriented Programming Really Model The Real World? [closed]

also

"Firstly, A represents an object in the physical world, which is a strong argument for not splitting the class up." I was, unfortunately, told this when I started programming. It took me years to realize that it's a bunch of horse hockey. It's a terrible reason to group things. I can't articulate what are good reasons to group things (at least to my satisfaction), but that one is one you should discard right now. The end all, be all of "good code" is that it works right, is relatively easy to understand, and is relatively easy to change (i.e., changes don't have weird side effects). –  jpmc26 8 hours ago

"Firstly, A represents an object in the physical world, which is a strong argument for not splitting the class up."
  I disagree with this. For example, if I had a class that represents a car, I would definitely want to split it up, because I surely want a smaller class to represent the tires. -  jpmc26 11 hours ago

source

Until now, I considered the following a good design, because it emphasizes physical hierarchy among the objects. I would expect that to be easier to understand, than some abstractions e.g.class ViewManager, class WheelsFascade.

```<code>class Car
{
public:
    void start() {assert(!m_fuel_tank.empty()); m_engine.start();};
private:
    std::vector<Wheel> m_wheels;
    Engine m_engine;
    FuelTank m_fuel_tank;
}
</code>```

Am I understanding correctly the above criticism that this is not a good design? If so, what are the actual problems? If not, what is being criticized?


问:
Looking for a DP algorithm for a specific packing problem
I have the following problem to solve:

Given a ferry with length d and a list of n cars conataining their length we must load the cars on the ferry in an order in which they appear in the list on 2 different lanes (each one having length d). Write a program that given length d and the list of cars outputs maximal number of cars that can be loaded on the ferry.

It's quite easy to do in O(2^cars) with backtracking - we load car on the left and try all the possibilities then, we save maximum and load car on the right and do the same saving max again.

But I have a feeling this can be reduced to polynomial time with dynamic programming. How to tell whether my gut feeling is true?

答:
This is a multiple knapsack problem. Solving with Meet-in-the-middle algorithms, it takes O(2^(n/2)) for each "lane".

partition the set {1...n} into two sets A and B of approximately
equal size

compute the weights and values of all subsets of each set
for each subset of A

find the subset of B of greatest value such that the combined weight is less than W

keep track of the greatest combined value seen
so far

More details here:
http://en.wikipedia.org/wiki/Knapsack_problem#Meet-in-the-middle


答:
An abstract class mean that some parts of its implementation may be missing. IMHO, the fact that a Gauge may be useless on its own is your opinion, not the opinion of all the users of your API.

I would only declare such a class abstract if it lacked important methods, but never as a mean to prevent the user from instantiating such an object.

First, I would write some documentation on that specific class, and why it should not be used as is. Then I would ask myself whether I really want to prevent anyone from using that object, and why (because it's not clearly defined in your case).

And the last step would be to either use a special constructor or make the class abstract (but this is really something that I still wouldn't do because it feels like the API and the objects are badly designed).


问:
Can we assume that all users today have Internet access?
As the Internet is pretty much ubiquitous, can we as developers assume that all users have Internet access? Now I don't mean that the code is written in such a way that if there is no connection then the whole program crashes due to lack of error code. What I mean is, can programs today be developed under the assumption that its users will always have access to the Internet?

You may ask "What do we gain by assuming that?" The reason why I'm asking is because at uni we use quite a few programs which require Internet access due to the way it checks the licenses (it checks your IP address -- if it's not an address at campus, then you you're not allowed to use it). Note that the program itself should work fine without Internet access; it's just needed for license checking.

EDIT:
I'm talking about desktop applications here.

EDIT2:
From some of the answers I get a feeling of being accused of exploiting the users in unethical ways. I'm not endorsing what I've described in this question -- I'm just asking about it because the developers of some of the programs we use at uni have done this. Personally I think doing this is plain out stupid and wrong.

答:
No!

All programs should consider access to the internet to be a best-case scenario, with a fallback mode for when the computer may not be connected.

With so many laptops out there, and with the nature of most public wireless networks to still be pay-for-use, most laptop users are going to regularly experience conditions where they need to use their computer and their programs without a connection to the internet.

As other answers have also posted, it's safe to assume that the computer will be connected at some point in the future.  Many synchronization-type apps that have an offline mode work this way.  But, as a matter of courtesy to users, don't operate this way unless it is a service to the user.  I don't think license-checking falls into that category.

ContentLicense: CC BY-SA 2.5


问:
What is the correct answer of given problem?
Consider a system having m resources of same type and 3 process A,B and C have peak demands of 3,4 and 6 respectiveley.

What should be the value of m such that the deadlock will not occur ?

My Analysis :

If we consider the worst case , 2 for A ,3 for B and 5 for C (2+3+5=10) resources are currently allocated . So in addition to that , one more resource if allocated to any one of the process will prevent the occurance of deadlock.

So , the answer is 11 . Is this correct ? or is there any other answer that contradicts above

答:
Given the assumptions that

all resources are equally acceptable to each process, and

each process gradually allocates resources up to the peak demand before releasing any resources (if not enough resources are available, the process will indefinitely wait for more without releasing any of the current resources), and

after finishing, each process releases their resources to be used again by another process

then your analysis is correct and having 11 resources available will avoid deadlocks on the resources.

If there are 10 or fewer resources, then it is possible to allocate the resources in such a way that all processes end up waiting for another process to release their resources.

If you have 11 or 12 resources, then there will always be at least one process that can reach its allocation limit and complete, after which the resources of that process become available again for the others.

If you have 13 or more resources, then all processes can always get enough resources without waiting on each other.


答:
I like the idea. Was it General Patton who said, "The more you sweat in peace, the less you bleed in war."

Putting intentional bugs "wastes time" of the testers. But that also makes them work harder, meaning that they will also do a better job of finding UNintentional bugs. (And you have a copy of the "original" so you don't have to live with what you've done.)

Finding more unintentional bugs will likely save you more grief in the long run that the cost of dealing with the intentional ones.

Plus, you can get an idea of how good your testers are, not a small benefit in itself.


答:
Personally, I feel uncomfortable with this approach.

The main thing that concerns me is the practicality of inserting intentional bugs. This seems to me to be difficult to do in any way that is predictable.

Any code changes (intentional or otherwise) risk having side-effects. These side-effects may well be revealed during testing but it may not be obvious (even to the developer who planted the bug) what the root cause is. It doesn't feel "safe", if you know what I mean (I'm speaking from my gut here).

Also, the tester will waste a lot of time testing code that isn't actually going to be released. Once the intentional bugs are removed, a complete re-test should be done anyway, in my opinion. That's the whole point of testing. Something changes, anything, and you re-test everything. Ok I know that doesn't ever happen in practice, but that's what regression testing is all about.

So, overall, not convinced.

On the other hand, we tend to let the customers verify the work of the QA teams, which is possibly not ideal. It is a very powerful feedback loop though.


问:
Does IE have more strict Javascript parsing than Chrome?
This is not meant to start a religio-technical browser war - I still prefer Chrome, at least for now, but:

Because of a perhaps Chrome-related problem with my web page (see also), I temporarily switched to IE (10) to see if it would also view the time value as invalid.

However, I didn't even get to that point - IE stopped me in my tracks before I could get there; but I found that IE was right - it is more particular/precise in validating my code. For example, I got this from IE:

```<code>SCRIPT5007: The value of the property '$' is null or undefined, not a Function object
</code>```

...which was referring to this:

答:
You were using an old version of jquery, as you admitted. The browser detection in that version was broken and so didn't define the global '$' jquery object. So when you tried to use it, it was not defined. You could put the non minified version of the js (the file without the 'min' part) and see where the $ is getting defined (or not getting defined).

Now getting onto Phil's answer, it's right but for the wrong reasons. He is saying you need to wait until dom ready by going $(document).ready. The only reason you need to do that is because you have your javascript in the head. Move it all to the bottom (which is better for speed, dom parsing). So you should have this as it will perform better.

<title>Test</title>

Test

ContentLicense: CC BY-SA 4.0

Body:
You were using an old version of jquery, as you admitted. The browser detection in that version was broken and so didn't define the global '$' jquery object. So when you tried to use it, it was not defined. You could put the non minified version of the js (the file without the 'min' part) and see where the $ is getting defined (or not getting defined).

Now getting onto Phil's answer, it's right but for the wrong reasons. He is saying you need to wait until dom ready by going $(document).ready. The only reason you need to do that is because you have your javascript in the head. Move it all to the bottom (which is better for speed, dom parsing). So you should have this as it will perform better.

<html>
<head>
<title>Test</title>
</head>
<body>
    <p>Test</p>

    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script type="text/javascript">
        // no need to wait for ready since we are AFTER the body
        $("body").css("background-color", "#405DA7");

</body>
</html>

Other problems could be that the jquery file itself was sent mangled via gzip incorrectly. Another issue IE 11 has. This would result in $ not defined.

This has nothing to do with $(document).ready


问:
What is the point of using lists over vectors, in C++?
I've run 3 different experiments involving C++ lists and vectors.

Those with vectors proved more efficient, even when a lot of insertions in the middle were involved.

Hence the question: in which case do lists make more sense than vectors?

If vectors seem more efficient in most cases, and considering how alike their members are, then which advantages are left for lists?

Generate N integers and put them in a container so that the container remains sorted. The insertion has been performed naively, by reading elements one by one and inserting the new one right before the first larger one.

With a list, time goes through the roof when dimension increases, compared to vectors.

Insert N integers at the end of the container.

For lists and vectors, time increased by the same order of magnitude, though it was 3 times faster with vectors.

Insert N integers in a container.

Start timer.

Sort the container using list.sort for lists, and std::sort for vectors.
Stop timer.

Again, time increases by the same order of magnitude, but it is in average 5 times faster with vectors.

I might continue to perform tests and figure out a couple of examples where lists would prove better.

But the joint experience of you guys reading this message might provide more productive answers.

You might have come across situations where lists were more convenient to use, or performed better?

答:
In addition to the other answers already provided, lists have certain features that don't exist in vectors (because they would be insanely expensive.)  The splice and merge operations being the most significant.  If you frequently have a bunch of lists that need to be appended or merged together, a list is probably a good choice.

But if you don't need to perform these operations, then probably not.


问:
Merging user activities into one stream with a common representation
My social network website currently has

forum threads and posts

gallery pictures

albums on the users' profiles

group discussions

classifieds

I would like to create one "stream" of activity. It would be based on friend relationships or as a subscription.
Once you are a friend with another member or you subscribe to their account, all the activity of this member would show up in your stream.

There are a couple of issues with this. It must be quite a common problem too, I suppose, although most apps only deal with one type of data (images, forum posts, ...).

The information currently is stored in separate MySQL tables. There is one table for uploads to the album pictures (and a related table about the albums), one for threads, one for posts, etc.
I would need to query all the activities of each user that a member is subscribed to.
I did try to create a VIEW with a UNION, as mentioned here.
But this will create a huge query and the page load time will be insufficient to support this feature.
What is the best and most efficient way to merge all this activity of a user?

From a graphical design perspective, what is the best way to merge these diverse datasets into a common representation?
The pictures obviously are best represented with a thumbnail. I could show them in a pinterest style gallery. The forum posts, on the other hand, may contain text only. This would break the layout.

答:
For the data side of this.  You'll have to decide whether to use a relational database?  Some other database variants might be more suited.

If you choose to use a relational database, you could use the following tables:

A table that models the temporal dimension of the activity stream, E.g.:

<activity_id, user_id, timestamp>

A table containing tumbnails/fragments to show as summary in the timeline/activity stream.  Using blobs or file system references to store the tumbnails. Checkout the question performance - Storing Documents as Blobs in a Database - Any disadvantages? on Stackoverflow.  The table would look like:

<activity_id, mime_type, summary_blob>

The mime type is used to interpret and render the summary_blob.  It allows supporting a large and extendible set of types of activities and storing all in the same table.

A table containing the full activities (e.g. textual posts, full size images, video, etc.) as blobs or as file system references, i.e.:

<activity_id, mime_type, full_blob>

To following consideration and options are available:

Combine the timestamp table with the summary_blob table.  The proposed solution has these as separate tables to allow other relations besides the temporal activity stream (e.g. activities per topic, conversations between persons, and activities explicitly linking to others).  But if you only want time based activity streams, the timestamp and summary_blob tables can be combined into a single table.

The summary and full_blob tables are separate to avoid loading the full_blob into memory when only the summary is required.  If you use filesystem resources for the full_blobs, these tables can be combined.

Alternatively you could use one activity stream table with separate tables for each type of activity referencing back to the activity stream keys.  This might be similar to you current not performing within requirements solution, depending on the current implementation.  Again you can use summaries to spead up loading.  Checkout question oop - Designing SQL database to represent OO class hierarchy on stackoverflow.  For example:

```<code>Activitystream table: <activity_id, activity_type, user_id, timestamp>
Image uploads table: <activity_id, image_data>
Text posts table: <activity_id, post>
</code>```

Here you still have to search through all tables to create the activity stream, but only in the activitystream table you have to search through the timestamps, in the other tables you can pick the relevant records by key.  Do not try to merge all tables, but let the image rendering routing use the image uploads tables, let the text post displayer use the text posts table, etc.

Body:
For the data side of this.  You'll have to decide whether to use a relational database?  Some other database variants might be more suited.

If you choose to use a relational database, you could use the following tables:

A table that models the temporal dimension of the activity stream, E.g.:

<activity_id, user_id, timestamp>

A table containing tumbnails/fragments to show as summary in the timeline/activity stream.  Using blobs or file system references to store the tumbnails. Checkout the question performance - Storing Documents as Blobs in a Database - Any disadvantages? on Stackoverflow.  The table would look like:

<activity_id, mime_type, summary_blob>

The mime type is used to interpret and render the summary_blob.  It allows supporting a large and extendible set of types of activities and storing all in the same table.

A table containing the full activities (e.g. textual posts, full size images, video, etc.) as blobs or as file system references, i.e.:

<activity_id, mime_type, full_blob>

To following consideration and options are available:

Combine the timestamp table with the summary_blob table.  The proposed solution has these as separate tables to allow other relations besides the temporal activity stream (e.g. activities per topic, conversations between persons, and activities explicitly linking to others).  But if you only want time based activity streams, the timestamp and summary_blob tables can be combined into a single table.

The summary and full_blob tables are separate to avoid loading the full_blob into memory when only the summary is required.  If you use filesystem resources for the full_blobs, these tables can be combined.

Alternatively you could use one activity stream table with separate tables for each type of activity referencing back to the activity stream keys.  This might be similar to you current not performing within requirements solution, depending on the current implementation.  Again you can use summaries to spead up loading.  Checkout question oop - Designing SQL database to represent OO class hierarchy on stackoverflow.  For example:

Activitystream table: <activity_id, activity_type, user_id, timestamp>
Image uploads table: <activity_id, image_data>
Text posts table: <activity_id, post>

Here you still have to search through all tables to create the activity stream, but only in the activitystream table you have to search through the timestamps, in the other tables you can pick the relevant records by key.  Do not try to merge all tables, but let the image rendering routing use the image uploads tables, let the text post displayer use the text posts table, etc.


答:
There is no basis for a reward or punishment on its own merit, but on the result of the behavior you're targeting. And sometimes there are unintended consequences. Is the goal to keep the QA team from slacking or to make some manager feel like he's actually contributing something without realizing he's just getting in the way.

Positive Outcome - The QA team works harder to find bugs. Who knows, maybe they see this as a challenge. It's a friendly game. Or they're just doing because they're being watched (Hawthorne Effect?).

Negative Outcome - They may not work harder and find the bug anyway. QA sees this as petty and adversarial. So now, they go into hyper-bug finding drive and return all sorts of nit-picky little problems. That font doesn't render properly when I take a screen shot and convert it to a pdf and view it at 500%.

No Impact - sound to me like this makes no difference, so why bother? You just risk wasting time and irritating people.

We could all agree that this won't work 90% of the time. That doesn't do much good to the other 10%. Test things for yourself. Are customers more satisfied with a release that has the intentional code bugs? Does it impact worker morale and productivity in other areas? Increase turnover?  You tell us.


问:
Which are the significant algorithms for humankind in past decades?
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...

答:
Insertion Sort

Easy to implement, very fast on small lists and used in Merge Sort / Quicksort implementations to speed them up. It's stable, and operates in O(n) on sorted lists (when sorted in ascending order).


答:
I agree totally with the answers above as to why this is bad for motivation and just generally awful people management.  However, there are probably sound technical reasons for not doing this as well:

Just before the product goes to QA, the dev team adds some intentional
bugs at random places in the code. They properly back up the original,
working code to make sure that those bugs aren't shipped with the end
product.

Based on the first statement, you never actually test your intended production code in these two passes.

I would imagine you vastly increase the likelihood of accidentally including an 'intentional' bug into your released production code when trying to rush through a change for a customer.  Might cause a few red cheeks at some point.

I would also think that this tends to train your testers to think like your developers (i.e. how would Tom add a bug here) which probably makes them less likely to find the bugs that Tom hasn't thought about.


答:
You should consider the size of the elements in the container.

int elements vector is very fast as most of the data fits inside the CPU cache (and SIMD instructions can probably be used for data copying).

If the element's size is greater then the result of test 1 and 3 could change significantly.

From a very comprehensive performance comparison:

This draw simple conclusions on usage of each data structure:

Number crunching: use std::vector or std::deque

Linear search: use std::vector or std::deque

Random Insert/Remove:

Small data size: use std::vector

Large element size: use std::list (unless if intended principally for searching)

Non-trivial data type: use std::list unless you need the container especially for searching. But for multiple modifications of the
  container, it will be very slow.

Push to front: use std::deque or std::list

(as a side note std::deque is a very underestimated data structure).

From a convenience point of view std::list provides the guarantee that iterators never become invalidated as you insert and remove other elements. It's often a key aspect.

Title: What is the point of using lists over vectors, in C++?

Body:
I've run 3 different experiments involving C++ lists and vectors.

Those with vectors proved more efficient, even when a lot of insertions in the middle were involved.

Hence the question: in which case do lists make more sense than vectors?

If vectors seem more efficient in most cases, and considering how alike their members are, then which advantages are left for lists?

Generate N integers and put them in a container so that the container remains sorted. The insertion has been performed naively, by reading elements one by one and inserting the new one right before the first larger one.

With a list, time goes through the roof when dimension increases, compared to vectors.

Insert N integers at the end of the container.

For lists and vectors, time increased by the same order of magnitude, though it was 3 times faster with vectors.

Insert N integers in a container.

Start timer.

Sort the container using list.sort for lists, and std::sort for vectors.
Stop timer.

Again, time increases by the same order of magnitude, but it is in average 5 times faster with vectors.

I might continue to perform tests and figure out a couple of examples where lists would prove better.

But the joint experience of you guys reading this message might provide more productive answers.

You might have come across situations where lists were more convenient to use, or performed better?


答: The only place where I usually use lists is where I need to erase elements and not invalidate iterators. std::vector invalidates all iterators on insert and erase. std::list guarantees that iterators to existing elements are still valid after insert or delete.


问:
Is having source code for a Go project outside GOPATH a bad idea
I am working on a new project using Go, and we are all new to Go. We are following the standard go directory structure, and having all code under

$GOPATH/src/github.com/companyname/projectname

which is also the root of a git repository

The standard recommended path layout does seem a bit strange, especially if we are working on a multi-language project, e.g. a Go based rest/http backend, and an html/javascript front-end. In that case I would probably want my project structure to look like this:

```<code>/
  doc/
  src/
    server/
      main.go
      module1/
        module.go
    client/
      index.html
  Makefile
</code>```

But is it actually necessary to have the code placed inside the GOPATH?

As an attempt I created a small program where the source code was outside the GOPATH. I could easily split the project into packages, so the main package could reference a foo package in a foo/ folder using import "./foo".

As far as I can see, there are two things this disallows me:

Other code cannot import this code. This is not a problem as we are building a service specifically for the company.

I cannot use go install to install it. This is not a problem either. The build pipeline installs the tool.

It does however allow the build server to not have its workspace be located inside the GOPATH

Is such an approach discouraged? If so, why so?

Are there other negative side effects than the two I have listed?

Bear in mind that this is a private project for a company, not public open source code.

Detaching the actual project from the GOPATH seems tempting, but one should be careful in breaking the rules when you are on the Shu stage

答:
You are not required to use GOPATH, but then you miss out on all the nice tooling that you get from the go command. They all expect code to be in the standard GOPATH hierarchy.

You mentioned go install, but also go test (and the nice go test -cover coverage tool) won't work go get, which allows you to download remote code will write everything to the GOPATH, so you will need to copy things over.

Sure, you can replace it all with make/scons/cmake/whatever and get things done and it will likely work for your environment, but its extra work that could be done by the go tool.


问:
Trying to Move Logic to DB - Reservation System
So I'm planning a basic resource reservation system. Basically I'm going to have a room (resource) that has X number of open spots per 30 minute increment. When someone reserves a resource I would store it as resource A is reserved from start time to end time.

Now in order to output to the end user if any open spots are available for a resource at a given time. I need to check to see if the number of reservations (Y) in that 30 minute window are less than the number of open spots (X).

The only way I can think of to do this is inefficient. That is query the reservations for the day, loop through the times of the day, and for each 30 minute block, count the number of reservations in that block (via server side code instead of in the DB). I'm less proficient at SQL.

Is there a way I can accomplish this all on the DB end in a query so the query returns something like a row for each resource and a column for each 30 min increment with the values being the number of open/taken seats?

I'm open to a different DB schema, but the way I see it I have a table or resources which state the max start-end time for reservations, number of possible openings per time period; a table of reservations stating which resource it was and the start-end time of the reservation.

答:
I would create a table to represent the room, perhaps:

```<code>Room
------------
RoomId (PK)
RoomNumber
</code>```

Then a table to represent a reservation:

```<code>Reservation
------------------
ReservationId (PK)
RoomId (FK)
StartTime
EndTime
</code>```

For any given period, you just need to search for all reservations that are valid for that period, e.g to find how many reservations between 10am and 11am, you would do:

```<code>SELECT COUNT(*) FROM Reservations
WHERE
    RoomId = Room AND
    (StartTime >= 1000 AND StartTime <= 1100) OR
    (EndTime >= 1000 AND EndTime <= 1100)
</code>```

This SQL query should execute extremely quickly, so looping over each 30 minute period would not take that long.

Body:
I would create a table to represent the room, perhaps:

Room
------------
RoomId (PK)
RoomNumber

Then a table to represent a reservation:

Reservation
------------------
ReservationId (PK)
RoomId (FK)
StartTime
EndTime

For any given period, you just need to search for all reservations that are valid for that period, e.g to find how many reservations between 10am and 11am, you would do:

SELECT COUNT(*) FROM Reservations
WHERE
    RoomId = Room AND
    (StartTime >= 1000 AND StartTime <= 1100) OR
    (EndTime >= 1000 AND EndTime <= 1100)

This SQL query should execute extremely quickly, so looping over each 30 minute period would not take that long.


问:
How to store users' info in network app?
I'm currently working on a school project that aims at creating a P2P chat client for users on the same network. For now, it will only be used by users on the same LAN network. But hopefully,I will to extend to work for users on the same public Wifi(if that's possible, is it?).What is confusing me at the moment is how to store users information like username, password, account picture, message history...etc. I was thinking of creating a database and storing them there but that seems inconvenient and since the app won't connect to some sort of server it might affect portability. So what is a convenient way of storing user info? Thanks in advance.</p>

答: It's pretty common to store stuff you want in a database, on a client, in something like sqlite. It's a database that is pretty lite, and very common for desktop apps. </p>


问:
Image uploads - preoptimize with CDN or host on same machine?
I'm working on a personal blog that will be used for reviewing various goods/services and as a dev journal. I'm writing this in Angularjs and Nodejs as a learning experience, but I plan on using it for a long time as well.

I have a section like a newspaper column where authenticated users can write their own mini blog and can also upload their own images. I plan on limiting all images on the blogs to 4 files (max) at 1MB (max) each.

I've seen a lot of angular file upload plugins, which is nice, but my primary concern is whether I should serve the images through a cdn now or to just store everything (the site, database, images, etc) on a single VPS instance. Digital Ocean gives 2 TB transfer (incoming + outgoing combined), and disk storage is pretty cheap.

I guess I'm not sure when to optimize bandwidth costs and server loads? If I do it now, there's an extra upfront cost in dev time and monetary costs, but in the long run things may be easier to manage. If instead I deploy everything on one instance and then migrate the site to a CDN when there's a consistent traffic increase, this may be cheaper upfront, but migrating the database may be a huge pain/testing nightmare? I don't expect much traffic. Maybe 100k-200k daily views at best after a few years(optimistically speaking).

答: I'd follow the YAGNI approach for this (You Aint Gonna Need It). If you don't need a CDN right now, keep it all on your server.  There's no need to carry extra expense and complication for something you don't even know you'll need for sure.  Just be sure to code the site and set up the database with the notion that you may do a migration someday in the future</p>


问:
Resolve dependencies using before-after constraints
What i would like to do is the following.

(Not sure if this question should go to StackOverflow, or here)

Consider a datastructure like this:

```<code>interface IAction {
    IAction[] afterActions()
    IAction[] beforeActions()
    void execute()
}
</code>```

What I would like to do is execute() a IAction collection, in the manner, that

All beforeActions() are executed before the supplier of the beforeActions() calls result.

All afterActions() are executed after the supplier of the afterActions() calls result.

Be able to detect "cyclic dependencies", so if one should execute before and after another, or after itself, or after another action, that on any path should execute before, etc.

In other worlds I would like to "sort" these actions in an executable order.

I would like to get only an explanation on how I should (could) do this, I don't expect anyone to implement anything for me (notice, that I intentionally didn't specify a language).

If you know about any generic algorithm for this purpose, that you think is suitable for the problem, please feel free to share with a minimal explanation, on how you would translate it to this problem

EDIT

After thinking a lot about the problem, I figured out, that dependency-wise the afterActions() is absolutely useless (an action shouldn't know about what executes after it, it should only describe what it needs to be completed before, to successfully execute). Knowing this I ended up doing something like what @Rafael Eyng suggested:

I created an Iterator, which wrapped the original collection, and had a next(), which always returned the next (resolved) action. The iterator was not stateless, it had a reference to the collection with all the action, and had a (growing) Set of actions, which are resolved. To achieve this, every time next() was called i did the following:

Iterate on all the actions

If one has no dependencies, or all of them are in the already resolved list, then it can be returned as next.

If it has dependencies, then recursively do this for all the prerequisites.

I was also collecting the already visited actions, from the root of the recursive call, so cycles could be detected

答:
For question 3, you will need to recursively iterate over the graph of IAction instances entirely. Recursive iteration is a basic operation. If you don't know how to do that, read up on recursive tree traversal. You can detect cyclic dependencies in at least two ways:

Use a class instead of an interface, and use a boolean field in the class to indicate that instance has been visited already. If during the iteration, you visit the same instance twice, you have detected a cycle.

Use a collection of IAction instances, and add each instance to the collection when you visit it. You can detect cycles by noticing that an instance is already present in the collection, before you add it.


答:
You will want to store the users data locally.  And as people come online they broadcast their information.  If the local client needs to update your friends profile information it can do so then.

As for storing the information locally here are a two options:

text file although not generally recommended for normal production deployment but does work for smaller proof-of-concept type projects such as yours.

HSQLDB is a what I often turn to as a quick alternative.  No install needed. surprisingly powerful.

Title: How to store users' info in network app?

Body: I'm currently working on a school project that aims at creating a P2P chat client for users on the same network. For now, it will only be used by users on the same LAN network. But hopefully,I will to extend to work for users on the same public Wifi(if that's possible, is it?).What is confusing me at the moment is how to store users information like username, password, account picture, message history...etc. I was thinking of creating a database and storing them there but that seems inconvenient and since the app won't connect to some sort of server it might affect portability. So what is a convenient way of storing user info? Thanks in advance.</p>


答:
I'd say bad idea.

One: Programmers are going to spend time putting deliberate bugs in the code, and some effort to save the good version. While the testers should presumably be testing everything, including the features with the planted bug, when they find one they will presumably have to go back and re-run that test to verify that this was indeed a bug (and not that the tester got confused in some way). At a minimum, testers are going to spend time writing up the planted bugs. Then the programmers have to spend time fixing the bug that they planted. This is a lot of effort that could be spent trying to write good code and write up real bugs.

Two: It sends a clear message to the testers that the programmers and/or management think they are not doing their jobs and must be treated as children. I can't imagine that this is good for morale. As a programmer, if I was given ambiguous or contradictory specs for a program and had to spend a bunch of time getting them clarified, and then after wasting hours or days my boss told me, "Oh, yeah, I deliberately put contradictory statements in the specs just to make sure you were really reading them", I think I would be really annoyed. If that happened regularly, that might well be enough to make me look for another job.

In real life, all but the most trivial code changes WILL have bugs. I have never had a problem with testers getting complacent because the first draft code they were given was so often 100% perfect. I've had to deal with lazy testers who don't do an adequate job, but they didn't get that way because the programmers were so perfect. The best testing person I ever worked with once told me that for a new software release, he set himself a personal goal to find 100 bugs. Okay, whether 100 is a realistic number depends on how big the product is and how extensive the changes are, but in our case, he almost always managed to meet that goal. Sometimes he had to stretch things, like calling a mis-spelled word in a message a "bug", but hey, it did have to be fixed.

Post script: If you do this, I bet that sooner or later the programmers are going to deliberately plant a bug, the testers don't find that particular one, and the programmers forget to put the good code back. So now a deliberately planted bug gets shipped to the customer.


问:
Is it a good practice to burn business logic into Enums?
Let's have a simplified business logic like this:

```<code>public enum BusinessLogic {
   STAGE_ONE(true, false, false),
   STAGE_TWO(true, true, false),
   STAGE_THREE(false, false, true);

  private final Boolean canStartProcessing;
  private final Boolean canDoStuff;
  private final Boolean canFinish;

  private BusinessLogic(Boolean canStartProcessing, Boolean canDoStuff, Boolean canFinish){
     ... usual simple constructor
  }
  ... getters
}
</code>```

And let's say it is mapped to my Business Object like this:

```<code>public class BusinessObject {
  ... constructors, fields, getters, setters, etc...

  private BusinessLogic logic

  @Enumerated(EnumType.STRING)
  @Column(name = "LOGIC")
  public BusinessLogic getLogic(){...usual getter...}

  public BusinessLogic setLogic(){...usual setter...}
}
</code>```

When the workflow arrives for example Stage two, the BusinessObject will be updated and LOGIC field should be set to BusinessLogic.STAGE_TWO, therefore you can use functions like "start process" and "do stuff", before that you can't "do stuff", altough when it reached stage three, you can't do anything else, but "finish" the process.

Does this kind of business logic structure has something to do against good practice?

I mean for example: maintainability, not fully represented in Database or anything else I didn't think of?

答:
I use enums this way all the time. Enums are a great way to write immutable helper objects that you only need exactly one copy of; they help reduce the chance of memory leaks and easily group many related classes together in a clear way.

What I would not do is expose the control of which particular BusinessLogic you're using to external classes using a public getter and setter method; that is violating encapsulation.

It looks like your use case uses the State Pattern, which is a great use for enums in Java. However, by removing the state transition logic from the class, you can't guarantee that other code will change the state when you don't expect. Fix this by having the state transition code inside the BusinessObject class itself, or at least in a package private object that you inject into the BusinessObject class.


问:
When to fix something that is "wrong" but works fine

Short version:

I wrote some code that is not done "the right way" because, when I wrote it, I didn't know how to do it. Now that I know how to do it "the right way", how do I decide how to fix it?

Longer version with details:

java.util.DecimalFormat is not Thread safe. I have what's essentially an immutable Description object that is used all over my code over many different threads. To fix this problem, I created a wrapper class SynchronizedFormatter that basically just wraps a lock around the methods of DecimalFormat that I use.

The right way to do this is to use a ThreadLocal. I didn't even know what that was when I wrote the code the first time. Is it worth it to fix? The synchronized version works just fine. How do I decide, about this in specific and about this situation more generally?

Also, I should mention that I do need to make other changes to this class for more important reasons than "I did this bit wrong the first time". That's what got me thinking - if I'm mucking about in this class anyway, maybe I should fix these other things that are on my bucket list. But then I fear slippery slope...

This is not a duplicate of When to refactor because Refactoring means:

Improving a computer program by reorganising its internal structure without altering its external behaviour.

This question talks about actually modifying the behavior of the code (e.g. using synchronized vs. ThreadLocal. Perhaps it should not be tagged refactoring.

答:
A simple fix would be to replace the internals of your wrapper to use Threadlocal.

So the format() changes from:

```<code>private DecimalFormat format = new ...;

private final Object lock = new Object();

public String format(double value){
    synchronized(lock) {
        return format.format(value);
    }
}
</code>```

to

```<code>private ThreadLocal<DecimalFormat> format = new ThreadLocal(){
    public DecimalFormat initialValue(){
        return new ...;
    }
};

public String format(double value){
    return threadLocalFormat.get().format(value);
}
</code>```

This has the upside that the new implementation is threadsafe without the cost of synchronizing the calls and the interface for all the other classes remains the same. Thus the change is localized to only 1 class.

Body:
A simple fix would be to replace the internals of your wrapper to use Threadlocal.

So the format() changes from:

private DecimalFormat format = new ...;

private final Object lock = new Object();

public String format(double value){
    synchronized(lock) {
        return format.format(value);
    }
}

to

private ThreadLocal<DecimalFormat> format = new ThreadLocal(){
    public DecimalFormat initialValue(){
        return new ...;
    }
};

public String format(double value){
    return threadLocalFormat.get().format(value);
}

This has the upside that the new implementation is threadsafe without the cost of synchronizing the calls and the interface for all the other classes remains the same. Thus the change is localized to only 1 class.


问:
Derive from a base class but not include a condition in the base class's method
The current code looks like this:

```<code>public class Details
{
    Public void Populate()
    {
         WriteChapterDetails();
    }

    public void WriteChapterDetails()
    {
       if ( includeHighDetails)
       {
         \\Do something
       }

       if (includeLowDetails)
       {
         \\Do something
       }
    }
}
</code>```

I now want to write a new class named HighDetails which will be copy of the Details class except I don't want it to go to the if (includeLowDetails) condition.

I am thinking of deriving a class from Details class like:

```<code>public class HighDetails()
{
  Public void Populate()
    {
         WriteChapterDetails();
    }

    public void WriteChapterDetails()
    {
       if ( includeHighDetails)
       {
         \\Do something
       }
}
</code>```

The Details class is a huge class and I don't want to repeat all the methods in the HighDetails class. I want to derive from the Details class and somehow not include the LowDetails. How can I do that?

答:
This is sort of problems intended to be dealt with using Template method pattern:

...behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure...

Applied to your case, it could look like as follows. First, you define algorithm steps that you may need to modify / redefine in subclasses by extracting involved code into separate methods.

That way, WriteChapterDetails becomes a skeleton like mentioned above:

```<code>    public void WriteChapterDetails()
    {
       WriteHighDetails();
       WriteLowDetails();
    }

    protected void WriteHighDetails()
    {
       if ( includeHighDetails)
       {
         //Do something
       }
    }

    protected void WriteLowDetails()
    {
       if (includeLowDetails)
       {
         //Do something
       }
    }
</code>```

This way opens the code for extension in subclasses.

Next, you define subclass to override desired step of the skeleton:

```<code>public class HighDetails : Details
{
    protected override void WriteLowDetails()
    {
       //Do nothing
    }
}
</code>```

That way, HighDetails inherits everything from Details except for the feature you wanted to do differently (WriteLowDetails).

Side note. This is not directly related to what you asked about, but conditional checks like one for includeHighDetails in your code snippet are code-smell, suggesting that you might be interested to learn about approach of replacing conditional with polymorphism.

I was also somewhat surprised to read your complaint about Details class being huge. Thing is, design sketched in the question seems to be compact and pretty much autonomous. If real code has it mixed in an "omelette" with barely related / unrelated stuff, you better invest some effort in extracting this functionality into a dedicated class.

Body:
This is sort of problems intended to be dealt with using Template method pattern:

...behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure...

Applied to your case, it could look like as follows. First, you define algorithm steps that you may need to modify / redefine in subclasses by extracting involved code into separate methods.

That way, WriteChapterDetails becomes a skeleton like mentioned above:

    public void WriteChapterDetails()
    {
       WriteHighDetails();
       WriteLowDetails();
    }

    protected void WriteHighDetails()
    {
       if ( includeHighDetails)
       {
         //Do something
       }
    }

    protected void WriteLowDetails()
    {
       if (includeLowDetails)
       {
         //Do something
       }
    }

This way opens the code for extension in subclasses.

Next, you define subclass to override desired step of the skeleton:

public class HighDetails : Details
{
    protected override void WriteLowDetails()
    {
       //Do nothing
    }
}

That way, HighDetails inherits everything from Details except for the feature you wanted to do differently (WriteLowDetails).

Side note. This is not directly related to what you asked about, but conditional checks like one for includeHighDetails in your code snippet are code-smell, suggesting that you might be interested to learn about approach of replacing conditional with polymorphism.

I was also somewhat surprised to read your complaint about Details class being huge. Thing is, design sketched in the question seems to be compact and pretty much autonomous. If real code has it mixed in an "omelette" with barely related / unrelated stuff, you better invest some effort in extracting this functionality into a dedicated class.


问:
What to learn to become freelancer?
I have around 8 years experience in software development. I have worked on application development all these years using C++ /win32.

I few years from now I want to become a freelancer . I tried to look into some freelance sites and I am not able to find any projects on C++/win32. I feel C++/Win32 wont help me much and I need to learn new skills . But my job require me to still work on C++ , so I cann't learn any new skills. I can still learn some new skills but without good project , it won't make any sense.

I have shortlisted few skills

php

jquery

perl

python

android

I am still confused which one to start and how to get expertise in them.Any suggestions?

答: I don't understand how working in C++ application development precludes you from learning new skills and languages. Picking up a new language usually takes less than a few days for an experienced programmer as far as syntax is concerend. Why don't you start by trying to build a dynamic website for yourself. Maybe an imitation of wordpress. It's an interesting project from several perspectives. You get to learn things like PHP, SQL, JavaScript, HTML, etc. and at the end you actually will have a usable product that you built which you can later turn into a platform for showing off your work to clients.</p>

Title: What to learn to become freelancer?


答:
It may be a good idea to encapsulate behavior into a Java enum (or C++ enum class) when you find yourself writing switch statements like the following, especially when the switch is repeated in different parts of the code.

```<code>MyEnum x = ...;
switch (x) {
  case A:
    // Do something
    break;
  case B:
    // Do something
    break;
  case C:
    // Do something
    break;
  default:
}
</code>```

It may make sense to change it to the following:

```<code>public enum MyEnum {
  A {
    public void doAction() { ... }
  },
  B {
    public void doAction() { ... }
  },
  C {
    public void doAction() { ... }
  },
  public abstract void doAction();
}
</code>```

Then instead of a switch, you do this:

```<code>MyEnum x = ...;
x.doAction();
</code>```

Essentially, you are abstracting a switch statement using dynamic dispatch instead.

Note that this is a simple example, the enum method may take parameters and return a value. This is only the general structure.

Title: Is it a good practice to burn business logic into Enums?

Body:
Let's have a simplified business logic like this:

```<code>public enum BusinessLogic {
   STAGE_ONE(true, false, false),
   STAGE_TWO(true, true, false),
   STAGE_THREE(false, false, true);

  private final Boolean canStartProcessing;
  private final Boolean canDoStuff;
  private final Boolean canFinish;

  private BusinessLogic(Boolean canStartProcessing, Boolean canDoStuff, Boolean canFinish){
     ... usual simple constructor
  }
  ... getters
}
</code>```

And let's say it is mapped to my Business Object like this:

```<code>public class BusinessObject {
  ... constructors, fields, getters, setters, etc...

  private BusinessLogic logic

  @Enumerated(EnumType.STRING)
  @Column(name = "LOGIC")
  public BusinessLogic getLogic(){...usual getter...}

  public BusinessLogic setLogic(){...usual setter...}
}
</code>```

When the workflow arrives for example Stage two, the BusinessObject will be updated and LOGIC field should be set to BusinessLogic.STAGE_TWO, therefore you can use functions like "start process" and "do stuff", before that you can't "do stuff", altough when it reached stage three, you can't do anything else, but "finish" the process.

Does this kind of business logic structure has something to do against good practice?

I mean for example: maintainability, not fully represented in Database or anything else I didn't think of?

Body:
It may be a good idea to encapsulate behavior into a Java enum (or C++ enum class) when you find yourself writing switch statements like the following, especially when the switch is repeated in different parts of the code.

MyEnum x = ...;
switch (x) {
  case A:
    // Do something
    break;
  case B:
    // Do something
    break;
  case C:
    // Do something
    break;
  default:
}

It may make sense to change it to the following:

public enum MyEnum {
  A {
    public void doAction() { ... }
  },
  B {
    public void doAction() { ... }
  },
  C {
    public void doAction() { ... }
  },
  public abstract void doAction();
}

Then instead of a switch, you do this:

MyEnum x = ...;
x.doAction();

Essentially, you are abstracting a switch statement using dynamic dispatch instead.

Note that this is a simple example, the enum method may take parameters and return a value. This is only the general structure.


问:
Software previously licensed under GPL now APL2, can I use it in a commercial application?
A software I would like to use in a commercial project switched from GPL to APL2. The news cites:

Please note that the new code that is currently developed as part of the 2.0 code base is licensed under APL 2, the previous code was and remains GPL.

Does this mean that I can use a new code version in a commercial application or that I can only use the newly released code (from the GPL->APL2 switching on) in a commercial application and not the old one?

答:
Does this mean that I can use a new code version in a commercial application or that I can only use the newly released code (from the GPL->APL2 switching on) in a commercial application and not the old one?

Exactly; What you are allowed to do with a piece of software depends on the license you got it under.

For example if the software under the new license removed a feature then you can't copy it in from the old version to add it back again (unless the license before and after allows it).


问:
Empty except block vs. huge except block
Which of these is easier to read?

An empty except block:

```<code>try:
    foo = do_foo()
except FooError:
    pass  # see below
else:
    return do_bar(foo)
# Recover from the FooError (long, complicated)
</code>```

Or this:

```<code>try:
    foo = do_foo()
except FooError:
    # Recover from the FooError (long, complicated)
else:
    return do_bar(foo)
</code>```

Note that the recovery is significantly more complex than the one-line else block.  It may itself involve indented blocks or other complications.  The first option has the advantage of eliminating a level of indentation.  But the second option is probably closer to what the average developer expects to see.  I'm uncertain which of these concerns is more important for readability.

答:
I think you are accurate about the trade-off involved - neither is ideal. Out of those two, I personally prefer the first one since the control flow is easier to follow.

That said, I'd suggest considering a third option that you didn't mention: factor out some or all of the recovery logic into a separate function.  That keeps the control flow simple and avoids having a big block of recovery code in the except clause.


答:
Explicit is better than implicit.

If you are handling an exception, handle it. Right there, right then.

Title: Empty except block vs. huge except block

Body:
Which of these is easier to read?

An empty except block:

```<code>try:
    foo = do_foo()
except FooError:
    pass  # see below
else:
    return do_bar(foo)
# Recover from the FooError (long, complicated)
</code>```

Or this:

```<code>try:
    foo = do_foo()
except FooError:
    # Recover from the FooError (long, complicated)
else:
    return do_bar(foo)
</code>```

Note that the recovery is significantly more complex than the one-line else block.  It may itself involve indented blocks or other complications.  The first option has the advantage of eliminating a level of indentation.  But the second option is probably closer to what the average developer expects to see.  I'm uncertain which of these concerns is more important for readability.


问:
Is it good to split big repository into smaller ones to have separate history/issue etc or keep it big?
We are currently porting our huge svn repo to git and we are thinking to export subdirectories of repository, each one containing source code of independent binaries, documentation or robot tests, into separate git projects.

One of those is a library that is currently being developed and all of the binaries depend on it.

All of those directories/binaries/docs etc are currently developed.

Should we separate all of those into separate git repos or add submodules or keep it as it is one huge repo?

Catalog structure:

```<code>/trunk/src/
    binary1/
    binary2/
    binary3/
    binary4/
    binary5/
    library/
    TA_tests/
    docs/
    scripts/
</code>```

答:
Keeping only one big repository is an error for me because your commit timeline will be burdened by many commits that have nothing to do with you project and you will be blocked often at push-time for no reason.

I think you have three choices:

git submodules: if you want a certain degree of separation between your librairy and your repository. It can be justified if you want to slightly decouple them. It offers a managed way to deal with your dependency but does give you a fix point for your updates.

Having a dependendy manager that fix the version you want to use (as Composer does). The benefit here is to be able to control the version you use and to not have bad surprise when you update your repository. But you have to remember to update it when it changes.

git subtree: that is the most coupled solution, if you want to a transparent way to deal with this dependency. The benefit here is to not be able to forget to update the dependency but you might run in trouble if your library breaks you code.

It really depends of you workflow.
If the library and the repository are tightly coupled, choose git subtree, if you want strict control of your dependancy, choose a dependy manager-like, if not choose git submodules.


问:
Using "Return" over "Break" or a combination
When using the Switch statement, is using return instead of break or a combination of the two considered bad form?

```<code>while (true)
{
    var operation = Randomness.Next(0, 3);
    switch (operation)
    {
        case 0:
            return result + number;
        case 1:
            if ((result - number) > 0)
            {
                return result - number;
            }
            break;
        case 2:
            return result * number;
        case 3:
            if ((result % number) == 0)
            {
                return result / number;
            }
            break;
    }
}
</code>```

答:
The break statement is required in case 1 and case 3.  If you omit it, the code will not compile, because the if body is not guaranteed to execute, and fall-through in switch statements is not allowed in C#.

The break statement is not required in case 0 and case 2, because the return always executes; code execution will never reach the break statement.  The compiler will issue a warning if you include the break statement, but the code will compile.

Not having break statements can be useful in simplifying certain mapping or factory functions:

```<code>public string NumericString(int digit)
{
    switch (digit)
    {
        case 1: return "one";
        case 2: return "two";
        case 3: return "three";
        // ..etc.
    }
}
</code>```

If you need fall-through behavior, you can simulate it with a goto, one of the few places in the C# language where using a goto actually makes sense, though it's arguable whether or not that constitutes good style.

Body:
The break statement is required in case 1 and case 3.  If you omit it, the code will not compile, because the if body is not guaranteed to execute, and fall-through in switch statements is not allowed in C#.

The break statement is not required in case 0 and case 2, because the return always executes; code execution will never reach the break statement.  The compiler will issue a warning if you include the break statement, but the code will compile.

Not having break statements can be useful in simplifying certain mapping or factory functions:

public string NumericString(int digit)
{
    switch (digit)
    {
        case 1: return "one";
        case 2: return "two";
        case 3: return "three";
        // ..etc.
    }
}

If you need fall-through behavior, you can simulate it with a goto, one of the few places in the C# language where using a goto actually makes sense, though it's arguable whether or not that constitutes good style.


问:
Leaving intentional bugs in code for testers to find
We don't do this at our firm, but one of my friends says that his project manager asked every developer to add intentional bugs just before the product goes to QA. This is how it works:

Just before the product goes to QA, the development team adds some intentional bugs at random places in the code. They properly back up the original, working code to make sure that those bugs aren't shipped with the end product.

Testers are also informed about this. So they will test hard,
because they know there are bugs present and that not finding them might
be considered as a sign of incompetence.

If a bug (intentional or otherwise) has been found, they will be reported for the development team to fix. The development team then adds another intentional bug in a related section of the code just before the product goes to the second-level QA. The project manager says a tester should think like a developer and he/she should expect new bugs in sections where changes were made.

Well, this is how it goes. They say that this approach has following advantages.

Testers will be always on their toes and they will test like crazy.
That helps them to also find hidden (unintentional) bugs so developers
can fix them.

Testers feed on bugs. Not finding any bugs will affect their morale.
So giving them an easy one to find will help their morale.

If you ignore the scenario where one of these intentional bugs gets shipped with the final product, what are the other drawbacks we should consider before even thinking of adopting this approach?

Some clarifications:

They properly backup the original code in source control.

When a tester finds the intentional bug, the development team just ignores it. If tester finds out an unintentional (original) bug, the development team first checks whether it is caused by any of the intentional bugs. That is, the development team first tries to reproduce that on the original working code and tries to fix it if they can.

Just ignore the relationship issues between QA and development team. I specifically asked this question on Programmers, not on The Workplace. Consider that there is good rapport between QA and the development team, and they party together after working hours. The project manager is a nice, old gentleman who is always ready to support both teams (Godsend).

答:
Coming from a world where developers are expected to write and run the tests themselves, this "testing" "QA" silo you are referring to frightens and confuses me, so I'll try to answer from this perspective. As an aside, qualified QA engineers, from my perspective, (as is described well in @SparK's answer), should focus on the larger issues of making sure that the software fully satisfies the user stories and has overall "quality" (in regard to the domain the software is intended for), instead of hunting for bugs.

What drew me here is @JamesMcleod's mention of "defect injection" in the comments to the question. I actually think that having the developers think how they could inject bugs into the system is a great idea for targeting the concept of defense in depth. No single bug should ever be enough to bring down the entire system in an uncontrolled fashion (without clear actionable logging), cause any data corruption, or by itself expose a security vulnerability.

Having the developers of each component create intentional defects, handle those of other components and overall enter a more adversarial mindset about their software could possibly do much towards improving the robustness of the software. Even the immediate benefit could be significant - I'd require that during each such injection of a new kind of defect (that was hitherto untested), the developer would immediately cover it by a new test, which will be set with a flag that will allow the bug to live in the code base undisturbed for a short while, and then switched on before delivery (and the defect removed), to turn into a regular test that will make the test suite more comprehensive.

A related option is the use of feature flags to intentionally turn off features in particular components to examine how other components deal with that. I would also like to highly recommend reading the free book/article "Learning from First Responders: When Your Systems Have to Work" which describes such extensive testing of the software infrastructure to be used by Obama team for the 2012 election.


答:
First of all, you should have a (let's call it) ready collection of IAction's whose dependencies were already met. This collection starts empty, of course. Then you should iterate over your IAction instances and check whether all of its dependencies were met. You do this by iterating over all the dependencies and checking whether all of them are present in the ready collection. If all dependencies of some IAction instance are present in the ready collection, you can put this IAction instance in the ready collection as well. Now on, you don't check this IAction dependencies anymore, by removing it of your unresolved IAction's collections or flagging it as ready to run.

Of course this assumes that there will be some IAction's that doesn't have any dependencies (that will be the first ones to be inserted in the ready collection), or more broadly, there are no ciclic dependencies. But I think it might give you a good first implementation to work on top of.

Title: Resolve dependencies using before-after constraints

Body:
What i would like to do is the following.

(Not sure if this question should go to StackOverflow, or here)

Consider a datastructure like this:

```<code>interface IAction {
    IAction[] afterActions()
    IAction[] beforeActions()
    void execute()
}
</code>```

What I would like to do is execute() a IAction collection, in the manner, that

All beforeActions() are executed before the supplier of the beforeActions() calls result.

All afterActions() are executed after the supplier of the afterActions() calls result.

Be able to detect "cyclic dependencies", so if one should execute before and after another, or after itself, or after another action, that on any path should execute before, etc.

In other worlds I would like to "sort" these actions in an executable order.

I would like to get only an explanation on how I should (could) do this, I don't expect anyone to implement anything for me (notice, that I intentionally didn't specify a language).

If you know about any generic algorithm for this purpose, that you think is suitable for the problem, please feel free to share with a minimal explanation, on how you would translate it to this problem

EDIT

After thinking a lot about the problem, I figured out, that dependency-wise the afterActions() is absolutely useless (an action shouldn't know about what executes after it, it should only describe what it needs to be completed before, to successfully execute). Knowing this I ended up doing something like what @Rafael Eyng suggested:

I created an Iterator, which wrapped the original collection, and had a next(), which always returned the next (resolved) action. The iterator was not stateless, it had a reference to the collection with all the action, and had a (growing) Set of actions, which are resolved. To achieve this, every time next() was called i did the following:

Iterate on all the actions

If one has no dependencies, or all of them are in the already resolved list, then it can be returned as next.

If it has dependencies, then recursively do this for all the prerequisites.

I was also collecting the already visited actions, from the root of the recursive call, so cycles could be detected


答:
It's a bad idea for all the reasons already given, but bug seeding is a useful tool for a different purpose.  You can use it to get a rough metric of how effective the QA process is.

In its simplest case, let's say you seed 100 bugs and they're representative of the full span of real bugs (I know, unlikely, but I'm simplifying).  You do not tell QA you're doing this to avoid spoiling the experiment.  At the end of the QA process let's say they found 60 of the 100 seeded bugs (and other real bugs).  Now you know QA is finding 60% of the bugs.

You can extend this further by counting the number of real bugs QA found and apply the fake bug ratio.  In our example, if QA found 200 real bugs then you can conclude they only found 60% of them, so 133 remain.

Of course, this is just a broad estimate with huge error bars.  Writing realistic, representative bugs is hard.  The bugs you write are likely to be easier for QA to find because developers are trained to not write bugs.  It may be better to simulate a class of bugs such as off-by-one errors, Unicode mistakes, buffer overflows, and so on.

This should be applied to the entire QA process which would include developer unit testing, continuous integration, and, if available, a dedicated QA team.

This is a metric, and should not be hijacked as a management motivational tool.


问:
Is there a way to document required properties in traits (PHP)?
I'm fairly new to using traits in PHP and am wondering if there is a way to ensure that a class including a trait has particular properties.

I know that you can use something like the following to ensure the using class has particular methods.

```<code>protected abstract function some_function();
</code>```

Is there a way to do the same kind of thing for member variables, since a trait has access to the member variables in the using class?

I can just document the requirement, but it would be nice to throw an exception in case a class trying to use a trait is missing a required property.

The closest that I can find is to create a function in the trait that attempts to grab the variable and return it ... and throw an exception if it is not found. Then the methods in the trait can use that to access the parent classes property instead of accessing them directly.

Thoughts, suggestions, and recommendations welcome ... as I am just getting used to traits.

The use case is that I have certain things that only run on the public face of the site and certain other things that only run on the private face of the site, but both share a common set of base functionality (various configuration settings, error handling, etc).

I could avoid using traits by making the class files for each of the inherited classes extremely long, but I'm trying to keep like functionality together in smaller files if possible.

I suppose one possibility would be to require an accessor variable in the calling class to return the wanted property.

```<code>abstract function get_my_value();
</code>```

Anything else that might work cleanly?

Thanks in advance!

答:
The best way I have found to do this is as follows:

```<code>class This_Is_My_Class {
    use My_Trait;

    protected $prefix = '';

    function __construct() {
        $this->prefix = 'not_empty';
    }

    protected function get_prefix() {
       if ( empty($this->prefix) ) {
           throw new Exception("Prefix must be non empty.");
       }
       return $this->prefix;
    }

    ... rest of class here
}

trait My_Trait {

    abstract protected function get_prefix();

    protected function do_whatever() {
        $prefix = $this->get_prefix();
        ... do stuff
    }
}
</code>```

Now, when using the trait, you properly get an exception when attempting to do things with it when the class using it either lacks the get_prefix function (due to the abstract declaration) or tries to use the prefix (due to the exception in the parent class).

Of course, if there is a cleaner solution to enforce that a class using a trait has a particular property, I'd love to hear it.

Body:
The best way I have found to do this is as follows:

class This_Is_My_Class {
    use My_Trait;

    protected $prefix = '';

    function __construct() {
        $this->prefix = 'not_empty';
    }

    protected function get_prefix() {
       if ( empty($this->prefix) ) {
           throw new Exception("Prefix must be non empty.");
       }
       return $this->prefix;
    }

    ... rest of class here
}

trait My_Trait {

    abstract protected function get_prefix();

    protected function do_whatever() {
        $prefix = $this->get_prefix();
        ... do stuff
    }
}

Now, when using the trait, you properly get an exception when attempting to do things with it when the class using it either lacks the get_prefix function (due to the abstract declaration) or tries to use the prefix (due to the exception in the parent class).

Of course, if there is a cleaner solution to enforce that a class using a trait has a particular property, I'd love to hear it.


问:
Is it reliable to use and download libraries needed from GitHub and copy-pasting codes in order to increase productivity?
I'm just wondering. Is it okay or true that some of the best programmers once taught that to become an effective programmer is through being a lazy programmer rather than spend time memorizing lots of code and get through to deadlines? For example, a programmer relied on research and downloading libraries needed for his or her project, read some instructions or document on how to use the library, and then sometimes whether he or she knows the math will copy-paste the samples. Afterwards, he or she will review its structure's source on how this code used it. Some contribution for help and tips in effective programming to complete the project's deadline would be much appreciated.</p>

答:
Of course - it's not very effective to reinvent the wheel. If someone else has already solved the problem and made it freely available, why not take advantage of that?

However, that road is full of pitfalls. If you don't truly understand what the code is doing and how, or it's a trusted and well known library, you don't want that in your production code. When the system fails and the owner comes asking why is this part of the system killing our business you don't want to answer "Dunno, I didn't write that, just copied it from GitHub to get past your deadline".

I guess the lazy/smart programmer tries to optimize to write as little code as possible over a long period of time, including code written for future bugfixes, upgrades and maint.


问:
Can we assume that all users today have Internet access?
As the Internet is pretty much ubiquitous, can we as developers assume that all users have Internet access? Now I don't mean that the code is written in such a way that if there is no connection then the whole program crashes due to lack of error code. What I mean is, can programs today be developed under the assumption that its users will always have access to the Internet?

You may ask "What do we gain by assuming that?" The reason why I'm asking is because at uni we use quite a few programs which require Internet access due to the way it checks the licenses (it checks your IP address -- if it's not an address at campus, then you you're not allowed to use it). Note that the program itself should work fine without Internet access; it's just needed for license checking.

EDIT:
I'm talking about desktop applications here.

EDIT2:
From some of the answers I get a feeling of being accused of exploiting the users in unethical ways. I'm not endorsing what I've described in this question -- I'm just asking about it because the developers of some of the programs we use at uni have done this. Personally I think doing this is plain out stupid and wrong.

答:
No

you can not assume all users have internet access.
  For basic Stats click here

Excluding web applications, a desktop application should not assume in my mind that it has internet access.


问:
What's the best way to avoid catastrophe caused by negligence?
I have been a programmer for almost 1 year.

As an ADHD adult, naturally I don't have the same strength of attention on ordinary stuffs as my colleagues do.

And I find the catastrophe made by me are usually caused by trivial negligence.

Like for today, I found the cron process on the server collapsed in the morning.

After half hour of debugging. I found I wrote in the cron

* 4 * * * sh daily_task.sh

instead of

0 4 * * * sh daily_task.sh

Which runs the huge shell 59 times in the morning instead of the intended 1 time.

Is there some kind of cultivatable behaviour or some tools or anything that can help me at least reduce such kind of  mistake?

How do you do to avoid such kind of mistake?

答:
You don't need ADHD to have this problem. It might be that you are working in environment where you get interrupted often or where you have to work on many things at the same time. So loosing track of your progress or making small mistakes is almost guaranteed.

There is one thing you can do to reduce those errors : tests based on specification.

First, you write down the specification in the most detailed way you can. In case of code, this should be in form of automated tests. Best way is to follow TDD. So when you suddenly get distracted, then your tests will tell you what you have already done and allow you to quickly pick up where you ended. Also, it makes regression testing easier.

In a case, where testing code is not possible, make sure you have someone else to go over what you have created and have them test the software according to the specification. You should always test software in testing environment before it goes into production. The issue you are talking about would be easily caught by running it for a day in testing environment and checking the logs.


答:
Is there some kind of cultivatable behaviour [...] that can help me at least reduce such kind of mistake

Absolutely, it is called four-eyes-principle.

If you had you shown your crontab entry to a second person (a person knowing cron, of course), chances are high the mistake would have been avoided.

In programming, when it comes to this, people mostly think of code-reviews, but that is actually the same thing.

Title: What's the best way to avoid catastrophe caused by negligence?

Body:
I have been a programmer for almost 1 year.

As an ADHD adult, naturally I don't have the same strength of attention on ordinary stuffs as my colleagues do.

And I find the catastrophe made by me are usually caused by trivial negligence.

Like for today, I found the cron process on the server collapsed in the morning.

After half hour of debugging. I found I wrote in the cron

* 4 * * * sh daily_task.sh

instead of

0 4 * * * sh daily_task.sh

Which runs the huge shell 59 times in the morning instead of the intended 1 time.

Is there some kind of cultivatable behaviour or some tools or anything that can help me at least reduce such kind of  mistake?

How do you do to avoid such kind of mistake?