问:
what gets testers invested in the releases they test?
For a lot of roles in a development team it is pretty obvious how these roles are invested in the quality of releases of their software. Developers who accidentally write bugs know that when the call comes they'll have to postpone what they are working on and get to fixing and quickly deploying something. Manager-types see their planning go down the drain and risk having to do damage control on escalated calls from angry customers. Because of this these people have some serious motivation in making sure the software is as problem-free as can be, aside from their general professionalism and attitude.

There is one category where I cannot easily come up with ways they are vested in the releases and that is the testers. There are examples of companies where code quality and bugfree releases suddenly became very important to developers when they themselves started to be on-call for nighttime and weekend support. I won't say they became more professional developers, but their attitude surely shifted because they started having a more vested interest.

But how are testers, aside from attitude towards their work, vested in the releases they test?

I'm not looking for a way to place blame on testers or developers and yes, I do realize that a professional attitude goes a long way but it is not THE way. Let's look at this another way: when somebody feels like throwing up, you can quickly grab a bag for them, or can just let them throw up on the floor and clean up afterwards. I'm pretty sure that everybody would go for a bag because it's just easier to not have to clean up. But when it's not you doing the cleaning, why should you care what happens?

答:
You mean, aside from the whole "giant production bugs leads to QA people getting fired" invested?

At least in some companies I've worked, QA served as second tier technical support. They would get called alongside (or before) developers if an issue appeared in the field, since they often had a better grasp on the quirks of the shipped product than developers. This happens quite a bit when you have a bunch of old versions of the product in the field - developers tend to be very focused on the current state of the product.

Still, QA knows that (right or wrong) they're the ones people look to if a bug makes it to production - nobody else.


问:
Commit at a logical checkpoint only, or also when you're at a stopping point?
Life, the work day, and personal projects don't always give us the opportunity the commit code at a logical completion (functionality subset programmed, bug fix completely patched, etc.).

Sometimes we need to stop working half way through a new method, or through a half-baked fix. Think... The work day ends, or it is time to shut down for the evening.

I feel guilty in doing a commit at this point. Mostly because my commit message is some daft comment saying "Started to do blah" or "Did this partially but need to complete".

Committing without a nice a logical stop feels sloppy, mostly for commit log and historical purposes.

But at the same time I don't like to "disconnect" from the code or call it quits with an uncommitted working directory. Maybe unfounded, but also for the sense of not having a dvcs backup at this point in case of a hardware failure.

What is the right approach here? When you are at a force programming stopping point but not a logical stopping point in the code, commit or wait until that logical containment is done to commit? Does the latter contradict the "commit often" mantra? It just seems history and diffing this could become difficult to understand after the fact.

答:
It all depends on the meaning of "check in".

With git, you can have a private repository, so checking in is nothing more than a personal backup. I make a small change, it works so far, I check it in. I do some experiment, it doesn't work, or the experiment tells me what I want to know, I cancel the checkout. That means I have to check in when there are things I don't want to lose.

Then comes the point where you check in changes to a shared repository. If your code doesn't compile, they will be very, very annoyed. It's Ok if you have changes that compile but are incomplete, as long as they don't affect anyone (for example, you can have a half finished feature that needs a switch to turn it on, and you check it in switched off). But this depends very much on company rules. And the company rules depend on how you people work.

ContentLicense: CC BY-SA 3.0


问:
Nested classes via a getter (to emulate namespacing)
So, we all know that ES6's introduced syntax is definitely sugar over what we've been doing, previously. That being said, we still don't have namespaces (which would be nice...)

The problem that I'm trying to solve is converting old code into es6. This old code was doing something like:

```<code>window.foo = {
    init: function() {

    },
    otherFoo: {
        init: function() {

        }
    }
}
</code>```

I was able to have my "modules" in separate files, and add them to my global "foo" that existed in window.

What I'd like to do instead, is create my separate modules, import them into my main JS file, and nest my classes within foo, like so:

```<code>import OtherFoo from './otherfoo';

class Foo {
    static init() {

    }
    static get OtherFoo() {
        return OtherFoo;
    }
}
</code>```

It works, so it's not a question if how I can make it work, it's a question of whether or not I should? We in the javascript community tend to do things just because we can, but I like to avoid that line.

答:
I know of no good reasons not to do it if the organization helps. I consider your classes and static getters to be an internal implementation detail that can expose a pattern that's already used heavily in popular JS libraries. Many libraries already expose a single object hash with types, so this isn't much different.

I see no difference between that and, say:

```<code>// foo.js
module.exports = {
   OtherFoo: require('./otherFoo.js')
   OtherFoo2: require('./otherFoo2.js')
}
</code>```

Consider this fictional version of mongoose in es6 that uses classes:

```<code>// mongoose/index.js
export default class Mongoose {
    constructor() {
    }

    static get model() { return require('./model.js'); }
}

//mongoose/model.js
export default class Model {
}
</code>```

And that can be used just like the real mongoose with:

```<code>var mongoose = require('mongoose');

new mongoose.model(...);
</code>```

Body:
I know of no good reasons not to do it if the organization helps. I consider your classes and static getters to be an internal implementation detail that can expose a pattern that's already used heavily in popular JS libraries. Many libraries already expose a single object hash with types, so this isn't much different.

I see no difference between that and, say:

// foo.js
module.exports = {
   OtherFoo: require('./otherFoo.js')
   OtherFoo2: require('./otherFoo2.js')
}

Consider this fictional version of mongoose in es6 that uses classes:

// mongoose/index.js
export default class Mongoose {
    constructor() {
    }

    static get model() { return require('./model.js'); }
}

//mongoose/model.js
export default class Model {
}

And that can be used just like the real mongoose with:

var mongoose = require('mongoose');

new mongoose.model(...);


答:
Something to consider, are you using distributed version control or centralized? (Edit: I realize this was tagged as git, but I still feel there's relevant information about deciding when to commit in my post.) If it's on your local machine or your own personal branch then do what feel right, but I'd still lean towards to following below.

At my job we use SVN, because my commits could end up in a build I don't like to check things in unless they are mostly done. The whole story/feature doesn't need to be implemented, but I like to at least have logical subtasks complete, things like

Makes schema change for new product

Adds ui element for new product

Adds processing for product

as opposed to

Started ui changes for product

Partially implemented new processing for product

To me, if I can't phrase my commits in a way like "Adds x", "Removes x", "fixes x" then I take it as a red flag. Each commit should be clear about how much it does.

I'm new to professional development, so this might all be phrased poorly, sorry. Really it comes down to two questions,

How "public" is the commit?

local vs. shared?

is it to some master branch or a personal branch?

is it likely to end up in a build?

is it likely to end up in a build handed to QA?

How fleshed out is the feature?

completely done and tested?

completely done but untested?

mostly done?

likely to break other components?

The stronger your answer to question 1 the stronger your response to question 2 needs to be to check in.

Title: Commit at a logical checkpoint only, or also when you're at a stopping point?

Body:
Life, the work day, and personal projects don't always give us the opportunity the commit code at a logical completion (functionality subset programmed, bug fix completely patched, etc.).

Sometimes we need to stop working half way through a new method, or through a half-baked fix. Think... The work day ends, or it is time to shut down for the evening.

I feel guilty in doing a commit at this point. Mostly because my commit message is some daft comment saying "Started to do blah" or "Did this partially but need to complete".

Committing without a nice a logical stop feels sloppy, mostly for commit log and historical purposes.

But at the same time I don't like to "disconnect" from the code or call it quits with an uncommitted working directory. Maybe unfounded, but also for the sense of not having a dvcs backup at this point in case of a hardware failure.

What is the right approach here? When you are at a force programming stopping point but not a logical stopping point in the code, commit or wait until that logical containment is done to commit? Does the latter contradict the "commit often" mantra? It just seems history and diffing this could become difficult to understand after the fact.


答:
But how are testers, aside from attitude towards their work, vested in the releases they test?

So your developers only care because they might be oncall for night/weekends?

If this is the case you are in a very rough situation. Because that team is much less vested in their work than you realize. If they only thing holding them accountable is a fear of working outside work this is not a good situation. It is providing considerably less motivation than you realize.

It's not a good situation because you want your employees to care, not about a fear of consequences, but in the workmanship of their craft. This is true whether you write code, test software, or make pizzas - better employees take pride in their work, whatever it is.

Finding bugs can be a source of pride for test teams, amongst other things..  do they get recognized for their role in quality software releases? In identifying bugs/problems?

Most workplaces with unvested, disillusioned or disengaged employees have bad management, lack of recognition, or are overworked.

Title: what gets testers invested in the releases they test?

Body:
For a lot of roles in a development team it is pretty obvious how these roles are invested in the quality of releases of their software. Developers who accidentally write bugs know that when the call comes they'll have to postpone what they are working on and get to fixing and quickly deploying something. Manager-types see their planning go down the drain and risk having to do damage control on escalated calls from angry customers. Because of this these people have some serious motivation in making sure the software is as problem-free as can be, aside from their general professionalism and attitude.

There is one category where I cannot easily come up with ways they are vested in the releases and that is the testers. There are examples of companies where code quality and bugfree releases suddenly became very important to developers when they themselves started to be on-call for nighttime and weekend support. I won't say they became more professional developers, but their attitude surely shifted because they started having a more vested interest.

But how are testers, aside from attitude towards their work, vested in the releases they test?

I'm not looking for a way to place blame on testers or developers and yes, I do realize that a professional attitude goes a long way but it is not THE way. Let's look at this another way: when somebody feels like throwing up, you can quickly grab a bag for them, or can just let them throw up on the floor and clean up afterwards. I'm pretty sure that everybody would go for a bag because it's just easier to not have to clean up. But when it's not you doing the cleaning, why should you care what happens?


答:
Involve them in every step of the process.

Have them attend future design meetings.

Have them present during pre-grooming and grooming if doing agile

Emphasize the importance of always asking question "So, how will we test this?" during grooming.

Have them present during daily scrum if you have one

Have them work on test plans with developers - before the code is written!

Have them work with devops on deployments

Give them real say on when something meets the definition of done

Make sure that the definition of done includes input from QA for testing

Don't use time estimates from developers without including the same from QA

find ways to show how they are helping developer but being a roadblock for features

define their role as Quality Engineer, not "testers"

empower them by providing support and training so they can learn technical and development task

give them a source of ideas for testing using test heuristics - http://testobsessed.com/wp-content/uploads/2011/04/testheuristicscheatsheetv1.pdf

send them to conferences about the profession of QA and testing, e.g. devops, velocity

Have them work closely with the customers and customer support so that they can understand and then be able to present things from a customer viewpoint

teach them about how to provide high quality bug reports with stuff like screenshots, steps to reproduce, initial variables to know about.  This will make it easier and more enjoyable for developers to work with them.  It will halp reduce the "but what were you doing when you get that" scenarios.

provide them with a reasonable tester to dev ratio (say from 0.5 - 3 developers) so they can get into details.  If the ratio is more like 1 tester to 10-20 devs, they will be more likely to be doing rote tasks that are not really testing the product in useful ways that continue to add value over time.

keep a log of stuff they have found and present it to larger groups and iterate on it

make sure testers have the full power to add a bug to the bug tracking system and that it is easy for them to do so.  Of course it should be reviewed (groomed) before being worked on by devs.

make sure that they have good tools and processes to do their work.  If they don't, for example there isn't a UI automation framework, make setting it up a task that developers pair on with them.

emphasize to them that they are saving the customer and the company from bad things happening and thus they are a key part of the company.

Change "throwing the code over the wall for qa", to pairing with QE throughout the process


问:
Is MVC controller an use case controller?
In GRASP (http://en.wikipedia.org/wiki/GRASP_(object-oriented_design) ), a controller (use case controller) is defined as:

A use case controller should be used to deal with all system events of
  a use case, and may be used for more than one use case (for instance,
  for use cases Create User and Delete User, one can have a single
  UserController, instead of two separate use case controllers)

I can see some similarities of this and MVC controller. However I don't see a standard guideline on how to design a MVC controller. Most of the time people just say it's up to the developer and the design of the application. So I'm wondering whether I can use guideline above to design MVC controller?

To be more specific, let's say an application has a page to display a list of products in a table. Each product is displayed as a row. Each row has a button to restock that product (or any other business operation that makes sense). So as I see, this page has 2 use cases (2 business operations): list products and restock product.

From the guideline above, probably I'll have 2 use case controllers for 2 use cases. Are those mapped to 2 MVC controllers? Or just need one Product controller with 2 actions for 2 use cases?

If just need one Product controller, how about a page that has many business operations in the same page? Soon the controller will become too big. Of course if a page has too many operations, it might not be a good UI design, but sometimes developers don't have a choice because clients want it that way to be convenient

答:
You quoted the Wikipedia article out of context.  It actually says:

The Controller pattern assigns the responsibility of dealing with system events to a non-UI class that represents the overall system or a use case scenario. A Controller object is a non-user interface object responsible for receiving or handling a system event.

A use case controller should be used to deal with all system events of a use case, and may be used for more than one use case (for instance, for use cases Create User and Delete User, one can have a single UserController, instead of two separate use case controllers).

So a Use Case Controller is a specific type of controller.  It doesn't necessarily mean that's how you will organize your controllers, only that it is one way of organizing them.

Controllers can be organized by functional responsibility, department, or whatever organizational pattern makes the most sense for your particular requirements.  There is no "standard" way of doing it.


答:
If a defect is found it's the developer's fault, if a defect isn't found it's the tester's fault, and when anything happens it's management's fault.

Developers are motivated to make bug-free code, testers are motivated to find the bug-filled code, managers are motivated to find bug-filled employees.


问:
How do you maintain productivity outside of work? (Programming Schedule)
I enjoy programming, but programming at work is just that, work. I would like to further develop my own personal interests in programming. Throughout the week I imagine myself completing a small project on the weekend or finishing up a programming related book. However, in reality I often fall short of my expectations. I often will get just one or two chapters of reading done and even less coding. In reality I will spend time surfing the net, watching television, or visiting friends and slacking off... because it is the weekend. But when Sunday evening rolls around I often reflect on my weekend and I am sorely disappointed with my use of time.

So my question is how do you maintain your productivity outside of work? I am sure some programmers could care less about programming on their free time. Although, I think the majority of programmers, especially on stackexchange, are passionate about programming.

Should I spend the weekend programming, or will I burn out and resent programming if I dedicate that much time to it?

How should I go about programming on my free time? Should I set a schedule? How much time should I dedicate to it? Most importantly how do I follow that schedule? Its only human nature to procrastinate.

I know there is a lot of questions here. Feel free to answer the ones that relate to how you remained focused outside of work. I am passionate about programming but after 40 hours of programming it can be difficult to maintain that enthusiasm.

答:
Another tip would be to study some "new" technology or concept that could benefit you and your colleagues at work. Read books and do some Proof-Of-Concept-programming with that technology. Just doing ASP.NET Web Forms development? Learn ASP.NET MVC and demonstrate it to your colleagues!

Then, most importantly, set a date and time and give a presentation at work on the subject. (Perhaps you can get your company to sponsor the lunch? Mine does.) I find that an excellent motivator to get some learning done in your free time.

ContentLicense: CC BY-SA 2.5


答:
You want to eliminate "professionalism and attitude" from the equation which is the only thing that will stand the test of time. It doesn't matter what job you do, if you treat your job as a profession you will always be looking to improve, which naturally makes one vested. Those who treat their job as a job, tend to just do what is necessary and may or may not actually become vested in the outcome. So you eliminated the key means of getting your testers vested. Hire for attitude in addition to skill.

You can get short term upticks by offering bonuses or threatening to punish but the effectiveness of these approaches wane over time.

Another thing to work with is to make sure RESPONSIBILITIES are clearly assigned and known. Most managers simply hold their people accountable for not meeting their responsibilities. But that isn't enough to instill the proper motivation. To quote Office Space - "Bob, that will only make someone work just hard enough not to get fired". The part that is usually missed and is the most important part of assigning responsibilities is to MAKE SURE PEOPLE HAVE THE AUTHORITY TO ENFORCE THEIR RESPONSIBILITIES ON THE PROGRAM. If you blame people for not performing their responsibilities but they believe they didn't meet the responsibilities because their ideas were rejected, thus not meeting the responsibility was something out of their control, definitely leads to lack of ownership/vested interest.  Whereas, if the person pushed to get their ideas incorporated, they will certainly have a vested interest in making sure they succeed.

OTHER INFO / ODDS & ENDS

Sorry if I don't attribute some of these findings, but I sometimes copy and paste things like these for my own purposes without thinking to capture the source.

There was a 10 year survey of 200,000 managers and employees by the Jackson Organization that showed that companies that consistently recognize excellence generate a return on equity more than 3 times higher than those who don't.

I kind of question this study because I have been at companies where they tried to do this and it may well have helped motivate those receiving the recognition, it had the opposite affect on those who didn't receive the recognition that they felt they deserved.

Although, just a general feeling that one's efforts are appreciated, and not simply expected, does go a really long ways.

Rewards geared towards the employee's family have the potential of being significantly more beneficial than something directed at the employee. For example, for a company in Florida, sending the employee and family on an all expense paid weekend to a Disney Resort Hotel and park entrance would probably cost the company less than $1,000 but will probably make the spouse and kids somewhat forget that the employee hasn't been around much over the last couple of months. Happy family, equals less stress at home, which means happier employee, which means more productive employee.

Whereas, a $1,000 bonus probably won't even be seen by the family, so all they think about is mom/dad works too much. Unhappy family, equals stressed out employee.

Studies have shown that when rewards are on the line, people tend to be less helpful.


问:
Is it okay to have objects that cast themselves, even if it pollutes the API of their subclasses?
I have a base class, Base.  It has two subclasses, Sub1 and Sub2.  Each subclass has some additional methods.  For example, Sub1 has Sandwich makeASandwich(Ingredients... ingredients), and Sub2 has boolean contactAliens(Frequency onFrequency).

Since these methods take different parameters and do entirely different things, they're completely incompatible, and I can't just use polymorphism to solve this problem.

Base provides most of the functionality, and I have a large collection of Base objects.  However, all Base objects are either a Sub1 or a Sub2, and sometimes I need to know which they are.

It seems like a bad idea to do the following:

```<code>for (Base base : bases) {
    if (base instanceof Sub1) {
        ((Sub1) base).makeASandwich(getRandomIngredients());
        // ... etc.
    } else { // must be Sub2
        ((Sub2) base).contactAliens(getFrequency());
        // ... etc.
    }
}
</code>```

So I came up with a strategy to avoid this without casting.  Base now has these methods:

```<code>boolean isSub1();
Sub1 asSub1();
Sub2 asSub2();
</code>```

And of course, Sub1 implements these methods as

```<code>boolean isSub1() { return true; }
Sub1 asSub1();   { return this; }
Sub2 asSub2();   { throw new IllegalStateException(); }
</code>```

And Sub2 implements them in the opposite way.

Unfortunately, now Sub1 and Sub2 have these methods in their own API.  So I can do this, for example, on Sub1.

```<code>/** no need to use this if object is known to be Sub1 */
@Deprecated
boolean isSub1() { return true; }

/** no need to use this if object is known to be Sub1 */
@Deprecated
Sub1 asSub1();   { return this; }

/** no need to use this if object is known to be Sub1 */
@Deprecated
Sub2 asSub2();   { throw new IllegalStateException(); }
</code>```

This way, if the object is known to be only a Base, these methods are un-deprecated, and can be used to "cast" itself to a different type so I can invoke the subclass's methods on it.  This seems elegant to me in a way, but on the other hand, I'm kind of abusing Deprecated annotations as a way to "remove" methods from a class.

Since a Sub1 instance really is a Base, it does make sense to use inheritance rather than encapsulation.  Is what I'm doing good?  Is there a better way to solve this problem?

答:
Ignoring the issue of whether you have a good design or not, and supposing it's good or at least acceptable, I would want to consider the capabilities of the subclasses, not the type.

Therefore, either:

Move some knowledge of the existence of sandwiches and aliens into the base class, even though you know some instances of the base class can't do it. Implement it in the base class to throw exceptions, and change the code to:

```<code>if (base.canMakeASandwich()) {
    base.makeASandwich(getRandomIngredients());
    // ... etc.
} else { // can't make sandwiches, must be able to contact aliens
    base.contactAliens(getFrequency());
    // ... etc.
}
</code>```

Then one or both subclasses overrides canMakeASandwich(), and only one implements each of makeASandwich() and contactAliens().

Use interfaces, not concrete subclasses, to detect what capabilities a type has. Leave the base class alone, and change the code to:

```<code>if (base instanceof SandwichMaker) {
    ((SandwichMaker)base).makeASandwich(getRandomIngredients());
    // ... etc.
} else { // can't make sandwiches, must be able to contact aliens
    ((AlienContacter)base).contactAliens(getFrequency());
    // ... etc.
}
</code>```

or possibly (and feel free to ignore this option if it doesn't suit your style, or for that matter any Java style you'd consider sensible):

```<code>try {
    ((SandwichMaker)base).makeASandwich(getRandomIngredients());
} catch (ClassCastException e) {
    ((AlienContacter)base).contactAliens(getFrequency());
}
</code>```

Personally I don't usually like the latter style of catching a half-expected exception, because of the risk of inappropriately catching a ClassCastException coming out of getRandomIngredients or makeASandwich, but YMMV.

Body:
Ignoring the issue of whether you have a good design or not, and supposing it's good or at least acceptable, I would want to consider the capabilities of the subclasses, not the type.

Therefore, either:

Move some knowledge of the existence of sandwiches and aliens into the base class, even though you know some instances of the base class can't do it. Implement it in the base class to throw exceptions, and change the code to:

if (base.canMakeASandwich()) {
    base.makeASandwich(getRandomIngredients());
    // ... etc.
} else { // can't make sandwiches, must be able to contact aliens
    base.contactAliens(getFrequency());
    // ... etc.
}

Then one or both subclasses overrides canMakeASandwich(), and only one implements each of makeASandwich() and contactAliens().

Use interfaces, not concrete subclasses, to detect what capabilities a type has. Leave the base class alone, and change the code to:

if (base instanceof SandwichMaker) {
    ((SandwichMaker)base).makeASandwich(getRandomIngredients());
    // ... etc.
} else { // can't make sandwiches, must be able to contact aliens
    ((AlienContacter)base).contactAliens(getFrequency());
    // ... etc.
}

or possibly (and feel free to ignore this option if it doesn't suit your style, or for that matter any Java style you'd consider sensible):

try {
    ((SandwichMaker)base).makeASandwich(getRandomIngredients());
} catch (ClassCastException e) {
    ((AlienContacter)base).contactAliens(getFrequency());
}

Personally I don't usually like the latter style of catching a half-expected exception, because of the risk of inappropriately catching a ClassCastException coming out of getRandomIngredients or makeASandwich, but YMMV.


问:
When designing a replacement application, how can I compare its performance to the original, if there are no existing statistics?
I don't believe there are any performance statistics kept for the application I'm being asked to replace, and don't want to ask the individuals doing the work to manually record things like how long it takes them to perform a given task.  However, the main objective of my project is to make it easier for the users to get their work done.  If I don't know how difficult or time consuming it is for them now, how can I objectively show that the new system fulfills that objective?

Would adding a few high-level logging statements and analyzing the logs be straightforward enough?  I'm not sure how much effort it would take to do that much, let alone setup anything more sophisticated.  Or, are there existing tools out there for this scenario?  It seems like something that would be relatively (if not quite) common.

答:
and don't want to ask the individuals doing the work to manually record things like how long it takes them to perform a given task

Here's the problem.

You basically want to create meaningful metrics, without measuring the only thing that matters. Nearly all of your users won't care about how fast the code itself is unless it causes a noticeable impact on their activities.

A good question would be to whoever is requesting you of this project - sometimes the information you are looking for (task X takes 10 minutes) is used as justification for replacing existing software, especially internal software.

You might be able to do some profiling or basic logging. Depending on the type of rerwite, if you have tests you could compare test runtimes (won't be as effective if you are starting from scratch and/or have none).

If each user action has simple entry/exit points you could calculate the time for the entire action (maybe filling out a purchase request, whatever your app does) and log this. You don't necessarily need to worry as much about the individual parts of those actions.

You could also request whoever is requesting this rewrite to either give you a list of times or a list of tasks they want to compare. This is probably advisable even if you end up finding the metrics yourself. You want to make sure you are putting effort in fixing actual problems - with application rewriting you need to justify yourself continuously, because the "well it worked before why are you rewriting it?" question will always be present (and legitimate).


问:
Using System.err.println() for debugging in Java

System.err

The "standard" error output stream. This stream is already open and
  ready to accept output data. Typically this stream corresponds to
  display output or another output destination specified by the host
  environment or user. By convention, this output stream is used to
  display error messages or other information that should come to the
  immediate attention of a user even if the principal output stream, the
  value of the variable out, has been redirected to a file or other
  destination that is typically not continuously monitored.

So, I usually use System.err.println() while debugging (mostly web apps) in my development environment. In most IDEs like Eclipse. System.out and System.err are both print in the same console and since System.err are uniquely highlighted in a different color (red), I find it easier to print out values using System.err as they are visually highlighted and I don't have to go through the whole log to search for my outputs. This always doesn't require me to start my server in debug mode and for cases where I can just determine looking at certain values that I've outputted and not actually break the execution to inspect for states.

Is this a really bad practice, should I not do it? I've been doing this for a long time and I find this very helpful, at times.

答:
Don't just use the default streams directly. Do you have any simple way of preventing this from happening when you don't actually want to debug your application? Is there any way for you to change the log output target without going over each line and changing it? Are all of the messages you're logging that way actually very serious and require immediate attention in all environments?

You should use a logging framework that abstracts away the actual stream and provides configuration for logging levels.

This way you'll be able to configure just how much information you want. IDEs also allow you to display logs like this in a readable manner and give you filtering capabilities (only showing messages at a certain logging level, text-search, etc.). Just how much support you'll get from an IDE probably depends on the platform you're working on and its specific tooling. For example, LogCat gives you some really nice options for android development. Even if whatever frameworks or servers you're using do not give you this much support, I'd rather get a simple log viewing plugin with colouring and filtering capabilities than use the default stream directly. Or even a standalone tool like BareTail (if you're on Windows). Or even tail -f log_file| grep --line-buffered some_regex_pattern if you're desperate or just want something lightweight and have a Unix terminal.

When managed properly, messages logged by an actual logger can be useful anywhere from development to production.

Just pick log4j, SL4J, Logback or even the classes from java.util.logging

Which one you chose is a wider subject but I find every one of them better than simply using System.err without any layer of abstraction above it.

And for actual debugging, a debugger just works better for me. You don't have to change and recompile the code like you do with those println statements to check the state of variables in scope of the lines being analysed or to inspect a different place. Using it also removes the need for cluttering your code with such statements. They take unnecessary space and, whether you want it or not, you have to visually parse them when trying to understand the logic behind the code.


问:
Version controlling a database's contents
I'm working on a web project that involves user-editable content, and I'd like to be able to do version-tracking of the actual content, which lives in a database. Basically, I want to implement wiki-style change histories.

Doing some background research, I see a lot of documentation about how to version your database schema (mine is actually already controlled), but any existing strategies about how to track your database content changes are lost in the avalanche of schema versioning stuff, at least in my searches.

I can think of a few ways to implement my own change tracking, but they all seem rather crude:

Save the entire row on each change, relate row back to source id with a Primary key (what I'm leaning towards currently, it's the simplest). Lots of small changes could produce a lot of table bloat, though.

save before/after/user/timestamp for each change, with a column name to relate the change back to the relevant column.

save before/after/user/timestamp with a table for each column (would result in too many tables).

save diffs/user/timestamp for each change with a column (this would mean that you'd have to walk the entire intervening change history to go back to a certain date).

What is the best approach here? Rolling my own seems like I'm probably reinventing someone else's (better) codebase.

Bonus points for PostgreSQL.

答:
There's a PostgreSQL wiki page for an audit tracking trigger which walks you through how to set up an audit log that will do what you need.

It tracks the full original data of a change, as well as the list of new values for updates (for inserts and deletes, there's only one value). If you want to restore an old version, you can grab the copy of the original data from the audit record. Note that if your data involves foreign keys, those records may also have to be rolled back to maintain consistency.

Generally speaking, if your database application spends most of its time on just the current data, I think you are better off tracking alternate versions in a separate table from the current data. This will keep your active table indices more manageable.

If the rows you are tracking are very big and space is a serious concern, you could try to break down the changes and store minimal diffs/patches, but that's definitely more work to cover all your kinds of datatypes. I have done this before, and it was a pain to rebuild old versions of data by walking through all of the changes backwards, one at a time.


问:
Grouping and nesting of REST APIs
My question is around best practice of aggregating or grouping REST APIs.
I have a scenario where there are many different vendors, data sources, etc. and I think grouping REST APIs would make a lot of sense to keep the system maintainable.

I have many scenarios where there will be a single API call triggering many other (similar) API calls to create the same entity in another system. For example for an example entity "user":

Front-end calls REST API: PUT .../user

What I envision is that the code listening on the above API will then make multiple REST PUT calls to let's say vendorA/user, vendorB/user, vendorC/user, internalSystemA/user, internalSystemB/user, etc.

Like this:

```<code>                                                            +-------------------+
+--------+                   PUT     +-----------+  CALL    | Vendor A API      |
|        |                 +-------> | user      +--------> |                   |
|        |                 |         +-----------+          +-------------------+
|        |                 |
| Front  | PUT    +--------++  PUT   +-----------+  INSERT  +-------------------+
| End    +------> | user    +------> | user      +--------> | Internal System   |
|        |        +--------++        +-----------+          +-------------------+
|        |                 |
|        |                 |         +-----------+  CALL    +-------------------+
|        |                 +-------> | user      +--------> | Vendor B API      |
+--------+                   PUT     +-----------+          |                   |
                                                            +-------------------+
                 +                                 +
                 +---------------------------------+
                         Internal REST APIs
</code>```

Note that the example entity doesn't have to be "user", there are many entities that are going to have a counterpart on the vendor APIs.

The vendors in this scenario provide different functionality. But there might be multiple vendors who provide the same functionality (and the user will chose the vendor he wishes to use). For simplicity let's say example functionalities are

Procurement,

Human Resources,

Management,

Payment.

What is the best practice to group and nest REST APIs in such a scenario?
Is it a good idea to group them by vendor or should they be grouped functional or by business entity? How would the URL look like?

答:
The answer depends on some assumptions not described in the question:
1. You don't have the liberty to change the vendor or internal API
2. The grouping has to be performed in a single transaction. i.e., how strict should the API be against vendor API failures. What happens if 1 vendor fails and the rest succeeds. Do we still consider this a success or initiate a rollback API (e.g., delete user)

Based on the assumptions I will not design my API based on the implementation, such as having a vendor API etc.., But purely based on functionality, i.e., who are users of the new API and their requirements.

OwnerDisplayName: phpPhil

Title: Grouping and nesting of REST APIs


问:
Retry design for high volume
I have a Java system using ActiveMQ for messaging. And the system processes about 400 to 600 transactions a second and we have no issue when everything is running smoothly. The system also got to send these transactions to an external system.

When the external System is down for a prolonged time (say an hour or two), what we do is that we drop off failed messages that were not successfully sent to the external system during the outage to a queue (what we call Retry queue).

We need to process these messages in a timely manner so that we give the external system ample time to recover.

We tried several approaches and none seems to work perfectly. Most of them work when we deal with a fewer number of messages.

Approach #1:
We used ActiveMQ delay where we set timestamp in the JMS header (Please see here for more details: http://activemq.apache.org/delay-and-schedule-message-delivery.html) and it worked when there are like a few hundred or thousand messages in the queue.

We found message loss when there were like 500k or more messages.We found that messages appear mysteriously without giving us any clue.

For example, I see that messages disappeared even for 20k messages.

We set the delay as 5 minutes so that messages are tried for up to 12 times in an hour.
When the external system was down for an hour, we expected that all 20k messages were retried at least for 12 times.

What we observed was that when we consume every 5 minutes:

Attempt 1: 20k messages
Attempt 2: 20k messages

Attempt 7: 19987 messages
Attempt 10: 19960 messages
Attempt 12: 19957 messages

Sometimes all the 20k messages were processed but the test results were inconsistent.

Approach #2:

We used ActiveMQ's redelivery policy where we set the policy at the connection factory level, make the session transacted, throw an exception when the external system is down, so that the broker keeps redelivering the messages based on the redelivery policy configuration.
This approach too didn't work well when the outage lasts for a longer duration and we need t to have non-blocking consumers. It works at the dispatch queue level itself, straining the queue when there are a lot of incoming transactions.

Approach #3:

We used Quartz scheduler that wakes up every X minutes and it creates connection, consumers to get messages from the Retry queue, try processing them further and if the external system is still down, they put the failed message to the back of the queue. This approach has lot of issues such that it forced us to manage connections, consumers etc.,

For example, when there are a couple of messages in the queue, when we have more consumers than the number of messages, it resulted in a message picked up by a consumer, again the same consumer dropping off the message back into Retry (as the external system is still down) with another consumer picking it up, resulting in back and forth traveling of message between Consumer and Broker.

Approach #4:

We tried off storing the failed messages in DB and have the quartz scheduler run every X minutes to pick up the messages from the DB.

This is not optimized as well as it involves a lot of transaction check between DB consumer(s) running across multiple nodes and the DB.

My environment is Java, JBoss, ActiveMQ 5.9, MySQL 5.6 and  Spring 3.2.

I went thru several other approaches such as Retry template (from Spring) and Asynchronous Retry pattern with Java 7/8

My take on the issue is that most solutions work when there is minimum load and they seem to break when the outage lasts longer or when message volume is really high.

I am looking for something where I can store and forward failed messages.
For a 400 TPS system, in an hour, I may have 1.44 million messages.

If the external System is down, then how I process these 1.44 million messages giving each message an equal chance to be retried without losing messages or performance.

I am looking for a solution within the scope of the environment I have.

答:
The issue here is with throttling. When the system comes up, the application needs to be designed in such a way as not to be overwhelmed on both the publisher and consumer.

You could get clever with your algorithm. If you have the ability to classify a message by priority then the failed messages could be saved with a lower priority. So after the publisher has publishing a new message, it can look into the lower priority queue to check if any failed messages need republishing and republish them.

This is one well known approach to throttling messages. I am sure there are other throttling algorithms that can be applied here based on your specific needs.

Title: Retry design for high volume


问:
Should method names getX and setX only be used for fields and have no other effects?
Should I avoid using getX() and setX() as names for methods that aren't "traditional" getters or setters? (Let's define traditional as it only gets/sets the field and has no other effects.) I guess the question is does a method being named as such imply that it's a field of the object? Also, is it bad practice to do other things in them?

```<code>class Foo {
    private Object bar;
    private Object bazz;

    // "traditional"
    public Object getBar() {
        return bar;
    }

    // bad practice?
    public Object getBazz() {
        doSomeOtherThing();
        return bazz;
    }

    // not a field
    public Object getJazz() {
        return makeSomeJazz();
    }

    // ...
}
</code>```

If getX() isn't appropriate if it's not a field, what is? (Probably too broad, I realize.) Obviously something like makeJazz() is probably better than getJazz() if getJazz() is considered bad here.

I guess another question is does it really matter? I like the idea of "self documenting code", but maybe I'm just worrying too much about something minor.

答:
Let's say you're writing a GUI control, and you want to be able to resize it.  Intuitively, you should have a setHeight method and a setWidth method for the dimensions.  These should set a value on the control, but if they don't also cause the control to recalculate and redraw itself, you're violating the heck out of POLS, because your user is going to expect changing the size of the control to visibly change the size of the control.  (Not to mention leaving the control in an inconsistent state, because the backing field value doesn't match what's shown on screen.)

Instead of "set a value and have no other effects," your rule of thumb should be "do what is necessary to bring the object into a fully consistent state, but nothing more."  Sometimes this will only require setting a value.  Other times, it'll take a lot more work.


答:
Solve the problem "philosophically" and in code first. And then "negotiate" with code and database to make it happen.

As as example, if you're dealing with generic articles, an initial concept for an article might look like this:

```<code>class Article {
  public Int32 Id;
  public String Body;
}
</code>```

And at the next most basic level, I want to keep a list of revisions:

```<code>class Article {
  public Int32 Id;
  public String Body;
  public List<String> Revisions;
}
</code>```

And it might dawn on me that the current body is just the latest revision. And that means two things: I need each Revision to be dated or numbered:

```<code>class Revision {
  public Int32 Id;
  public Article ParentArticle;
  public DateTime Created;
  public String Body;
}
</code>```

And ... and article's current body doesn't need to be distinct from the latest revision:

```<code>class Article {
  public Int32 Id;
  public String Body {
    get {
      return (Revisions.OrderByDesc(r => r.Created))[0];
    }
    set {
      Revisions.Add(new Revision(value));
    }
  }
  public List<Revision> Revisions;
}
</code>```

A few details are missing; but it illustrates that you probably want two entities. One represents the article (or other header-type), and the other is a list of revisions (grouping whatever fields make good "philosophical" sense to group). You don't need special database constraints initially, because your code doesn't care about any of the revisions in and of themselves -- they're properties of an article that knows about revisions.

So, you don't need to worry about flagging revisions in any special way or leaning on a database constraint to mark the "current" article. You just timestamp them (even an auto-inc'd ID would be OK), make them related to their parent Article, and let the article be in charge of knowing the "latest" one is the most relevant one.

And you let an ORM handle the less philosophical details -- or you hide them in a custom utility class if you're not using an out-of-the-box ORM.

Much much later, after you've done some stress testing, you may think about making that revision property lazy-load, or having your Body attribute lazy-load only the topmost revision. But, your data structure in this case shouldn't have to change to accommodate those optimizations.

Title: Version controlling a database's contents

Body:
I'm working on a web project that involves user-editable content, and I'd like to be able to do version-tracking of the actual content, which lives in a database. Basically, I want to implement wiki-style change histories.

Doing some background research, I see a lot of documentation about how to version your database schema (mine is actually already controlled), but any existing strategies about how to track your database content changes are lost in the avalanche of schema versioning stuff, at least in my searches.

I can think of a few ways to implement my own change tracking, but they all seem rather crude:

Save the entire row on each change, relate row back to source id with a Primary key (what I'm leaning towards currently, it's the simplest). Lots of small changes could produce a lot of table bloat, though.

save before/after/user/timestamp for each change, with a column name to relate the change back to the relevant column.

save before/after/user/timestamp with a table for each column (would result in too many tables).

save diffs/user/timestamp for each change with a column (this would mean that you'd have to walk the entire intervening change history to go back to a certain date).

What is the best approach here? Rolling my own seems like I'm probably reinventing someone else's (better) codebase.

Bonus points for PostgreSQL.

Body:
Solve the problem "philosophically" and in code first. And then "negotiate" with code and database to make it happen.

As as example, if you're dealing with generic articles, an initial concept for an article might look like this:

class Article {
  public Int32 Id;
  public String Body;
}

And at the next most basic level, I want to keep a list of revisions:

class Article {
  public Int32 Id;
  public String Body;
  public List<String> Revisions;
}

And it might dawn on me that the current body is just the latest revision. And that means two things: I need each Revision to be dated or numbered:

class Revision {
  public Int32 Id;
  public Article ParentArticle;
  public DateTime Created;
  public String Body;
}

And ... and article's current body doesn't need to be distinct from the latest revision:

class Article {
  public Int32 Id;
  public String Body {
    get {
      return (Revisions.OrderByDesc(r => r.Created))[0];
    }
    set {
      Revisions.Add(new Revision(value));
    }
  }
  public List<Revision> Revisions;
}

A few details are missing; but it illustrates that you probably want two entities. One represents the article (or other header-type), and the other is a list of revisions (grouping whatever fields make good "philosophical" sense to group). You don't need special database constraints initially, because your code doesn't care about any of the revisions in and of themselves -- they're properties of an article that knows about revisions.

So, you don't need to worry about flagging revisions in any special way or leaning on a database constraint to mark the "current" article. You just timestamp them (even an auto-inc'd ID would be OK), make them related to their parent Article, and let the article be in charge of knowing the "latest" one is the most relevant one.

And you let an ORM handle the less philosophical details -- or you hide them in a custom utility class if you're not using an out-of-the-box ORM.

Much much later, after you've done some stress testing, you may think about making that revision property lazy-load, or having your Body attribute lazy-load only the topmost revision. But, your data structure in this case shouldn't have to change to accommodate those optimizations.


问:
Is it better to make database calls or external API calls first in the context of a single Web request?
Say you have a Web app that uses data from both a database and an external API, and for certain pieces of functionality, you need to call in to both in order to read/write the necessary data.

Is it better to:

A) First start a DB transaction and then make all of the necessary calls to the DB BEFORE calling in to the API, and then roll the transaction back if the API call fails.

OR

B) Make the API call first and then call in to the DB upon success.

Pros and Cons of each option as I see them:

The big Pro with A is that data integrity remains intact, regardless of any failures.  If the DB calls fail before I hit the API, then I return before making the call, and if the API call fails, I can roll back my DB transaction.  If everything succeeds, then I commit the DB transaction and go on my merry way.

The big Con with A is that due to the transaction, the DB will be locked for an uncontrollable amount of time during the external API call, potentially affecting performance.

The Pros and Cons of B are essentially the opposite of the Ps and Cs for A. The Pro is that you avoid a DB lock during the API call.  The Con is that if the API call succeeds but your DB calls fail, you essentially need to roll back the changes you just made thru the API, which may or may not be possible for any given context.

I'm partial to option A personally, as I'm a big fan of "better safe than sorry" approaches, but what do you all think?

答:
From your statement " the DB will be locked for an uncontrollable amount of time during the external API call, potentially affecting performance" I infer that the external call could take a lot longer than the DB call.

So if this is the case, then I would make the request asynchronous and send a response to the user/UI saying that the request has been submitted. On the backend, an async call is made to the external API and when the API returns and depending on the response the DB call can be made.

If this a UI application, it can periodically refresh the data using an AJAX call or if the user has registered a listener, it can be notified of the completion of the request.


问:
Do named arguments replace the builder pattern?
When using a language that supports named and optional arguments, does the builder pattern no longer have a practical use?

Builder:

new Builder(requiredA, requiredB).setOptionalA("optional").Build();
```
<p><strong>Optional/named arguments:</strong></p>
<pre class="lang-cs prettyprint-override"><code>new Object(requiredA, requiredB, optionalA: "optional");
</code>```

答: The builder pattern is essential when working with immutable objects. There are a lot of benefits working with immutable objects, especially in making your program be more robust executing in a concurrent environment (i.e., threads)</p>

ContentLicense: CC BY-SA 4.0


问:
Architecting a SaaS for backwards-compatibility in regards to data and business logic
I have a SaaS platform where the user fills out a form and data entered into the form is saved to a database. The form UI has a large amount of config (originates from the DB but ends up in JavaScript) and business logic (in JavaScript). After a form is filled out and saved, the user can go back at any time and edit it.

The wrinkle is that an old form entry needs to behave like it did when it was first filled out - it needs the same config and business logic - Even if the SaaS has gone through a data schema change and changes to business logic since then.

To confirm, new forms filled out by the user would use the new/current data schema and business logic of course. But previous forms needs to behave as they did when they were created.

So I need a sensible way to version config, business logic and any dependencies.

The best I've come up with is, when the user saves their entry, to save the form's config as JSON along with the entry. When the user goes back to edit an old entry, I do not load the config from current database schema but simply dump the JSON config that was saved with the entry.

For the business logic, I save a system version number along with the entry, for example "01". When the user loads an old form, I check the version of the form and I then load the form JavaScript from a path like "js/main_01.js". When I make a non-backwards-compatible change to the business logic, I increase the system's version number to, for example, "02". New forms would then use "js/main_02.js". I also use this cheap versioning approach for HTML view templates which is getting hairy.

This approach works but it seems a bit flimsy or homegrown. I'm trying to avoid conditionals in my business logic like if version==2: do this. This approach avoids that but also has it's downsides.

I don't think the stack really matters for this convo but just in case, I'm using django/mysql.

答:
Assuming that you're already in this situation:

Store form config in a DB and reference the version number, rather than serialize it to Json over and over again.

Don't use conditionals, just have completely separate html/js pairs and backend end points. You might have to do some internal rewrite if you want to have the forms appear under a single url.

You're facing the reality of legacy/long living/ non trivial systems. The idea is to design for changes to begin with. I'm almost certain you can refactor this into sanity. Separate the form into logical modules; each would inject it's needed markup, js (well, business logic in js is another topic) and backend processing dependencies; then mix and match via some straight forward configuration. If you don't have the time to go back and refactor, start with version N+1.


问:
Pattern to add custom attributes to Forms control classes, without having same code everywhere?
I am creating custom winforms designer. I use label, textbox, combobox, listbox, button and checkbox on the designer. I don't want to show all their properties on PropertyGrid, so I created a custom attribute and set the grid to show only properties marked with that.

```<code>propertyGrid1.BrowsableAttributes = new AttributeCollection(
    new MyAttribute()
);
</code>```

Problem is, that now i have to create exactly same code for each of the controls. I have own wrapper class for every control i need, derived from the existing control.

```<code>class MyButton : Button
{
    [MyAttribute]
    [Category("Common properties")]
    public new string Name { get { return base.Name; } set { base.Name = value; } }
}
class MyLabel : Label
{
    [MyAttribute]
    [Category("Common properties")]
    public new string Name { get { return base.Name; } set { base.Name = value; } }
}
...
</code>```

I have currently 7 properties from every control, that i always need to show.

The question:

Is there a pattern that i can use to have just one class that has those properties and "inject" those somehow, instead of copy pasting same code for all the controls? I only have 6-8 controls, but i dislike the idea of having exactly same code written in many places.

Should I somehow find the properties I need and add my custom attribute ( and category ) to those at runtime? That would be "bit" hacky, but could work?

Using interface: I would still have to implement it, thus resulting same amount of code.
I can't use generics: I am using original controls as base, because designer code handles them out of the box nicely and using generics causes a mess and lots of customization.

答: The ICustomTypeDescriptor interface implemented on your components will allow you to show only those properties you wish, or to inject properties on other objects. However, it is only for the property grid. It won't help you with the API or code serialization.</p>


答:
Here we have an interesting case of a base class that downcasts itself to its own derived classes. We know full well this is normally bad, but if we want to say we found a good reason, let us look and see what the constraints on this might be:

We can cover all the cases in the base class.

No foreign derived class would have to add a new case, ever.

We can live with the policy for which call to make being under the control of the base class.

But we know from our science that the policy of what to do in a derived class for a method not in the base class is that of the derived class and not the base class.

If 4 then we have:
5. The policy of the derived class is always under the same political control as the policy of the base class.

2 and 5 both directly imply that we can enumerate all derived classes, which means that there aren't supposed to be any outside derived classes.

But here's the thing. If they're all yours you can replace the if with an abstraction that is a virtual method call (even if it's a nonsense one) and get rid of the if and self-cast. Therefore, don't do it. A better design is available.

Title: Is it okay to have objects that cast themselves, even if it pollutes the API of their subclasses?

Body:
I have a base class, Base.  It has two subclasses, Sub1 and Sub2.  Each subclass has some additional methods.  For example, Sub1 has Sandwich makeASandwich(Ingredients... ingredients), and Sub2 has boolean contactAliens(Frequency onFrequency).

Since these methods take different parameters and do entirely different things, they're completely incompatible, and I can't just use polymorphism to solve this problem.

Base provides most of the functionality, and I have a large collection of Base objects.  However, all Base objects are either a Sub1 or a Sub2, and sometimes I need to know which they are.

It seems like a bad idea to do the following:

```<code>for (Base base : bases) {
    if (base instanceof Sub1) {
        ((Sub1) base).makeASandwich(getRandomIngredients());
        // ... etc.
    } else { // must be Sub2
        ((Sub2) base).contactAliens(getFrequency());
        // ... etc.
    }
}
</code>```

So I came up with a strategy to avoid this without casting.  Base now has these methods:

```<code>boolean isSub1();
Sub1 asSub1();
Sub2 asSub2();
</code>```

And of course, Sub1 implements these methods as

```<code>boolean isSub1() { return true; }
Sub1 asSub1();   { return this; }
Sub2 asSub2();   { throw new IllegalStateException(); }
</code>```

And Sub2 implements them in the opposite way.

Unfortunately, now Sub1 and Sub2 have these methods in their own API.  So I can do this, for example, on Sub1.

```<code>/** no need to use this if object is known to be Sub1 */
@Deprecated
boolean isSub1() { return true; }

/** no need to use this if object is known to be Sub1 */
@Deprecated
Sub1 asSub1();   { return this; }

/** no need to use this if object is known to be Sub1 */
@Deprecated
Sub2 asSub2();   { throw new IllegalStateException(); }
</code>```

This way, if the object is known to be only a Base, these methods are un-deprecated, and can be used to "cast" itself to a different type so I can invoke the subclass's methods on it.  This seems elegant to me in a way, but on the other hand, I'm kind of abusing Deprecated annotations as a way to "remove" methods from a class.

Since a Sub1 instance really is a Base, it does make sense to use inheritance rather than encapsulation.  Is what I'm doing good?  Is there a better way to solve this problem?


答:
It's not a particularly bad habit to have to want to get output when debugging (the worse habit is to not debug).

Its just that we programmers are just so gosh darn lazy.  Want output? Look there...

```<code>System.err.println("Got an error: " + e);
</code>```

That's really easy. You don't need to worry about what logging framework you have, nor what log level it should be at.  And this is why we do it all over.

But here's the thing... if you have a project of reasonable size, you have logging in it.  If you don't, that's a bad habit.  Once you have this logging, and it is something sensible (i.e. not java.util.logging), its really easy to set up an appender that spits out to standard error.

And to this, there's not really an excuse why not to do it that way.

```<code>package c.s.p.m.logging;

import org.apache.log4j.Logger;

public class Main {
    private final static Logger LOG = Logger.getLogger(Main.class);

    public static void main(String[] args) {
        LOG.debug("Oops");
        LOG.info("This is awkward");
        LOG.error("This is bad");
    }
}
</code>```

and (yep, I'm one of those oddballs that uses the xml format - note that this may not be the optimal one)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.err" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
        </layout>
    </appender>

    <appender name="file" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false" />
        <param name="maxFileSize" value="10MB" />
        <param name="maxBackupIndex" value="10" />
        <param name="file" value="logs/someFile.log" />
        <param name="threshold" value="ERROR" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                   value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
        </layout>
    </appender>

    <logger name="c.s.p.m">
        <level value="DEBUG" />
        <appender-ref ref="console" />
    </logger>

    <root>
        <level value="ERROR" />
        <appender-ref ref="file" />
    </root>

</log4j:configuration>
```

<p>and there, in red on my console, I see:</p>

```
2015-04-30 20:18:34 DEBUG Main:9 - Oops
2015-04-30 20:18:34 INFO  Main:10 - This is awkward
2015-04-30 20:18:34 ERROR Main:11 - This is bad
```

<p>Meanwhile, in my log file:</p>

```
2015-04-30 20:18:34 ERROR Main:11 - This is bad
```

The thing is, there's not really an excuse if you've set it up to just use logging.  It's a few more lines in the config file for the console appender.

Once you've got that as a habit to set it up, the logger is much better than System.err ever was and you wonder what took you so long to step away from the println.  Time stamps, log levels, line numbers... all for free.  You'll find yourself stepping away from that console appender too with a little bit of time.  You'll have different log files for different classes (and the aggregate log file too) with a log file watcher.  You'll debate putting in crazy appenders...

And best of all, no more silly looks from co-workers because you accidentally checked in a System.err.println() that filled up the console in production.

While System.err.println() isn't bad and isn't a habit that you need to break (as long as you make sure you clean up after yourself and wash your hands afterwards), you will find that once you step away from it there are so many better options out there that are even fewer characters to type.

Title: Using System.err.println() for debugging in Java

Body:
System.err

The "standard" error output stream. This stream is already open and
  ready to accept output data. Typically this stream corresponds to
  display output or another output destination specified by the host
  environment or user. By convention, this output stream is used to
  display error messages or other information that should come to the
  immediate attention of a user even if the principal output stream, the
  value of the variable out, has been redirected to a file or other
  destination that is typically not continuously monitored.

So, I usually use System.err.println() while debugging (mostly web apps) in my development environment. In most IDEs like Eclipse. System.out and System.err are both print in the same console and since System.err are uniquely highlighted in a different color (red), I find it easier to print out values using System.err as they are visually highlighted and I don't have to go through the whole log to search for my outputs. This always doesn't require me to start my server in debug mode and for cases where I can just determine looking at certain values that I've outputted and not actually break the execution to inspect for states.

Is this a really bad practice, should I not do it? I've been doing this for a long time and I find this very helpful, at times.

Body:
It's not a particularly bad habit to have to want to get output when debugging (the worse habit is to not debug).

Its just that we programmers are just so gosh darn lazy.  Want output? Look there...

System.err.println("Got an error: " + e);

That's really easy. You don't need to worry about what logging framework you have, nor what log level it should be at.  And this is why we do it all over.

But here's the thing... if you have a project of reasonable size, you have logging in it.  If you don't, that's a bad habit.  Once you have this logging, and it is something sensible (i.e. not java.util.logging), its really easy to set up an appender that spits out to standard error.

And to this, there's not really an excuse why not to do it that way.

package c.s.p.m.logging;

import org.apache.log4j.Logger;

public class Main {
    private final static Logger LOG = Logger.getLogger(Main.class);

    public static void main(String[] args) {
        LOG.debug("Oops");
        LOG.info("This is awkward");
        LOG.error("This is bad");
    }
}

and (yep, I'm one of those oddballs that uses the xml format - note that this may not be the optimal one)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.err" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
        </layout>
    </appender>

    <appender name="file" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false" />
        <param name="maxFileSize" value="10MB" />
        <param name="maxBackupIndex" value="10" />
        <param name="file" value="logs/someFile.log" />
        <param name="threshold" value="ERROR" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                   value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
        </layout>
    </appender>

    <logger name="c.s.p.m">
        <level value="DEBUG" />
        <appender-ref ref="console" />
    </logger>

    <root>
        <level value="ERROR" />
        <appender-ref ref="file" />
    </root>

</log4j:configuration>

and there, in red on my console, I see:

2015-04-30 20:18:34 DEBUG Main:9 - Oops
2015-04-30 20:18:34 INFO  Main:10 - This is awkward
2015-04-30 20:18:34 ERROR Main:11 - This is bad

Meanwhile, in my log file:

2015-04-30 20:18:34 ERROR Main:11 - This is bad

The thing is, there's not really an excuse if you've set it up to just use logging.  It's a few more lines in the config file for the console appender.

Once you've got that as a habit to set it up, the logger is much better than System.err ever was and you wonder what took you so long to step away from the println.  Time stamps, log levels, line numbers... all for free.  You'll find yourself stepping away from that console appender too with a little bit of time.  You'll have different log files for different classes (and the aggregate log file too) with a log file watcher.  You'll debate putting in crazy appenders...

And best of all, no more silly looks from co-workers because you accidentally checked in a System.err.println() that filled up the console in production.

While System.err.println() isn't bad and isn't a habit that you need to break (as long as you make sure you clean up after yourself and wash your hands afterwards), you will find that once you step away from it there are so many better options out there that are even fewer characters to type.


问:
Check if a variable is equal to any of several values
I'm trying to check if an integer is equal to any of several values and don't want to do this:

```<code>int d = 0;
if(d == 3 || d == 8 || d == 1) {
    System.out.println("d is one of the special numbers!");
}
</code>```

How can I accomplish this when it comes to hundreds or thousands of values?

答:
There are two diverging approaches to this based on the key question of "are false positives acceptable?"  This means "If I want to test if 42 is one of your special numbers, and it isn't in your special number set, is it ok to say 'yes'?"

If it is, you fall into the realm of the bloom filter.  This has the advantage that it is small, and fast, and will probably get it right.  It will come back with an answer of "possibly in the set" or "definitely not in the set."  Early spell checkers used this to compress huge dictionaries down to a few kilobytes (can't fit too much on a 140k floppy).

But, as this pointed out, again, it may say 'yes' when the answer is 'no'.

A more conventional approach is to use a Set.  In Java, this is found in the java.util.Set interface and there are quite a few of implementing classes.  Most commonly used, the HashSet and TreeSet.

The set contains, well, a set of values.  It has a method to add them (and remove them) and test to see if the set contains a given value (or values).  Its really a rather straight forward data structure.

```<code>Set<Integer> foo = new HashSet<Integer>();
foo.add(3);
foo.add(8);
foo.add(1);

...

if (foo.contains(d)) { ... }
</code>```

Doesn't matter how big the Set is.  Be it three or three thousand (or more) values. It works just as well.

To this end, I would suggest reading more about the Java Collections Framework.  There are a lot of classes there that have a number of uses. You will find yourself often using these classes - Lists, Sets, and Maps are the fundamentals of a large part of programming problems.  Understanding which List or Set or Map to use can be quite important in the behavior (do you want the results back when iterating in insert order? sorted order? don't care?).

Body:
There are two diverging approaches to this based on the key question of "are false positives acceptable?"  This means "If I want to test if 42 is one of your special numbers, and it isn't in your special number set, is it ok to say 'yes'?"

If it is, you fall into the realm of the bloom filter.  This has the advantage that it is small, and fast, and will probably get it right.  It will come back with an answer of "possibly in the set" or "definitely not in the set."  Early spell checkers used this to compress huge dictionaries down to a few kilobytes (can't fit too much on a 140k floppy).

But, as this pointed out, again, it may say 'yes' when the answer is 'no'.

A more conventional approach is to use a Set.  In Java, this is found in the java.util.Set interface and there are quite a few of implementing classes.  Most commonly used, the HashSet and TreeSet.

The set contains, well, a set of values.  It has a method to add them (and remove them) and test to see if the set contains a given value (or values).  Its really a rather straight forward data structure.

Set<Integer> foo = new HashSet<Integer>();
foo.add(3);
foo.add(8);
foo.add(1);

...

if (foo.contains(d)) { ... }

Doesn't matter how big the Set is.  Be it three or three thousand (or more) values. It works just as well.

To this end, I would suggest reading more about the Java Collections Framework.  There are a lot of classes there that have a number of uses. You will find yourself often using these classes - Lists, Sets, and Maps are the fundamentals of a large part of programming problems.  Understanding which List or Set or Map to use can be quite important in the behavior (do you want the results back when iterating in insert order? sorted order? don't care?).


问:
Should my application's README be for developers or users
My application is meant to be used by regular everyday users, but may also me modified freely by developers. These two audiences (users and developers) require different information.

Should my README be targeted towards users or is it more proper to target the README towards developers?

答:
A "readme" file is simply "what to read first." Who you are means nothing: open the readme first.

From there you should direct users to the proper documentation:

Have links to more appropriate documentation. README simply is a starting point. Explain where to find the installation documentation. Explain where to find developer documentation. Usage documentation. Changelogs. README should be a signpost: the one place you can look to be directed to where you really need to go.

Many pieces of software have HTML READMEs with navigation and such, often included with the software or source code. This is good because formatting and hyperlinks are more useful than plain text. Your simple README text file might direct someone toward a more expressive document.

Perhaps have links to GitHub or wherever the software lives, which generally also has more documentation as well. GitHub documentation is more closely tied to the structure of the code, since its markdown files live in source folders. This would be a great place to put developer documentation.

Whatever the documentation, have links to documents for "I just want to install, what do I do?" and "how to compile from scratch on supported platforms."

Finally, developer documentation is well-placed in Doxygen, JavaDoc, or GitHub documentats. These are standard documentation formats that developers are expected to know how to build and read. Being more technical users, developers require less hand-holding. Provide a makefile, Ant script, or Visual Studio solution, and they should be able to figure it out.

As Robert Harvey alluded to in his comment, there is no standard thing to do. Do what makes sense for your software and its intended audience, but provide useful information regardless. As long as you leave some breadcrumbs in your README, you should be fine: its purpose is to be a signpost.


答:
If you have the freedom, you can try separating out your 'work' programming from your weekends. For example, if you are primarily .NET coder at work, look at other avenues such as Ruby on the weekends. I've found that that helps keep things separate without that little nagging feeling that you should be learning something 'for the job'.

Also, take a look at the projects and OSS tools (if you use any) from the work week. Sometimes you can achieve both goals (learning and coding) by reading, reviewing, and participating in open source projects.  In my experience, reviewing how other projects work--especially if they're outside your comfort zone--is a fantastic way to learn while not having a predefined expectation to produce.

Title: How do you maintain productivity outside of work? (Programming Schedule)

Body:
I enjoy programming, but programming at work is just that, work. I would like to further develop my own personal interests in programming. Throughout the week I imagine myself completing a small project on the weekend or finishing up a programming related book. However, in reality I often fall short of my expectations. I often will get just one or two chapters of reading done and even less coding. In reality I will spend time surfing the net, watching television, or visiting friends and slacking off... because it is the weekend. But when Sunday evening rolls around I often reflect on my weekend and I am sorely disappointed with my use of time.

So my question is how do you maintain your productivity outside of work? I am sure some programmers could care less about programming on their free time. Although, I think the majority of programmers, especially on stackexchange, are passionate about programming.

Should I spend the weekend programming, or will I burn out and resent programming if I dedicate that much time to it?

How should I go about programming on my free time? Should I set a schedule? How much time should I dedicate to it? Most importantly how do I follow that schedule? Its only human nature to procrastinate.

I know there is a lot of questions here. Feel free to answer the ones that relate to how you remained focused outside of work. I am passionate about programming but after 40 hours of programming it can be difficult to maintain that enthusiasm.


问:
Social network notification system

Background

I am working on an app for a client that includes some social networking features. I was originally developing the mobile front-end, but circumstances have left me in charge of developing the back end as well.

As a general background, our system allows users to follow other users and receive notifications about those that they are following, as you'd expect from a social network. A caveat is that only a small subset (at most a few hundred) users will be followable, with the expectation that most of the user base will be following at least one of these individuals.

On the UI side, we will have a notification button with a number on it, and clicking the button will take you to the notification screen.

The problem

I've been researching strategies for implementing notifications and most resources I have found point to creating one or more notification tables in the database. (An example I like is the accepted answer here: https://stackoverflow.com/questions/9735578/building-a-notification-system ).

The thing that is throwing me off is that most database-driven strategies for notifications require inserting a row for each notification for each follower. So if a thousand people are following Sally, we insert a thousand rows into the corresponding table. Is that scalable? What happens if we get to the point where tens or hundreds of thousands of users are following Sally and she's making a few dozen posts per day?

My original idea had been to handle everything with queries: the number on the notification button would be obtained by requesting row-counts on content posted more recently than the last time you visited the notification screen, while individual notifications would be generated from more detailed queries when you visited the notification screen. This approach would require no writes or extra storage, but is inflexible and would probably hammer the server pretty hard.

SETUP

The backend (as established by the previous developer) uses CodeIgniter and a MySQL database. It is currently running on a crappy GoDaddy shared hosting account, but I assume (hope?) this will be upgraded before we go into production and the hosting package will be scaled with user growth.

Currently our only front-end is a mobile app, but we plan to later build a website as well. I am not concerned at this time with obtaining real-time push updates from the server about the notifications.

ADDENDUM

I do not specialize in backends and I'm in over my head in that department. The client knows it, and I've done my best to try to explain the scope of a project of this nature, but they have made it clear that at this point they will not trust anyone else to work on the project. We probably have another month of work to do before we can start adding testers and I can get any kind of performance metrics. I really can't estimate how many users we might have or what hardware we might be on in the next 5 years, but I think the client is hoping for hundreds of thousands of users or more.

I hope this is specific enough of a problem to be posted here; I can refine it if need be. Please ask if you have any questions or I've omitted important details.

tl;dr

Does a database-driven notification system have negative implications for long-term scalability when all of the users are only following some of the same few hundred people?

Is there a way to make the notifications database-driven without needing a separate notification row for each notification for each follower?

Would an entirely query-driven notification system be scalable, or have any advantages besides not writing any data to the DB?

Am I overthinking this too early? Should I just build something that works for now and we can worry about optimizing it if it becomes a problem, given that the client has a limited budget and we don't know yet if the final product will be popular?

答:
So if a thousand people are following Sally, we insert a thousand rows into the corresponding table. Is that scalable?

Yes, provided the database tables are properly indexed.

What happens if we get to the point where tens or hundreds of thousands of users are following Sally and she's making a few dozen posts per day?

You'll generate a few dozen tens or hundreds of thousands of notification records per day for Sally, assuming you want to keep track of every notification in perpetuity.  The percentage of users like Sally with that kind of traffic is always very small.

My original idea had been to handle everything with queries: the number on the notification button would be obtained by requesting row-counts on content posted more recently than the last time you visited the notification screen, while individual notifications would be generated from more detailed queries when you visited the notification screen.

This seems unnecessarily complicated.  If you need detailed statistics about notifications, just store the notifications.

Does a database-driven notification system have negative implications for long-term scalability when all of the users are only following some of the same few hundred people?

That's why it works... a small number of people always generate the vast majority of the traffic.

Is there a way to make the notifications database-driven without needing a separate notification row for each notification for each follower?

Yes... Don't store the notifications; just send the notification emails, in fire-and-forget style.  Or, store the notifications for a certain period of time, and then discard them. Or, discard each notification after it has been read.

Would an entirely query-driven notification system be scalable, or have any advantages besides not writing any data to the DB?

I'm not sure what you mean by this.  If you want to query notifications, you have to store them in the database.  Otherwise, there is nothing to query.

Am I overthinking this too early?

Talk to someone who can help you design a properly normalized, indexed database with the correct tables in it.  I see no reason why such a database couldn't effectively handle the scenarios you describe.

A real-life example

As far as I know, Stack Exchange stores everything in perpetuity, including all notifications.  They use database technology similar to MySql, and some caching technologies.  While their hardware and storage space is substantial, the amount of traffic they get is a good problem.

Title: Social network notification system


问:
Cache policy categorization
From what I search online, there are 2 most common policies used in cache access:

Cache aside

Read through + Write through

But there are some other policies like:

For write hit case:

Write through

Write back (Write behind)

For write miss case:

Write allocate

No write allocate (write around)

My questions are:

Why cache aside and read through + write through are most commonly used?

Is cache aside only referring to cache read policy (.i.e. only read case, comparable to read through)? Is it possible to use cache aside with other write policy, e.g. cache aside + write through? .i.e. when application has a write miss, it writes to both cache and data store.

Reference:

Read-through/Write-through vs Cache-Aside

Write policies

答:
The policies you're citing concern themselves primarily with what has responsibility for maintaining the cache and deciding when and how to read data from the main memory.

In Cache Aside, the application assumes the responsibility.  The application will look at the cache and see if it has the data it needs.  If the cache doesn't contain the required data, the application will read the data and copy the data to the cache.

In Read-through/Write-through caching, the application communicates with the cache directly.  It is the cache's responsibility to determine whether or not it already contains the data.  If the cache doesn't contain the data, it will get the data from main memory, retain a copy of the data, and return the data to the application.

There are two ways you can write data: Write-through and Write-Behind.  Write-through means that the data is written to main memory immediately. It doesn't provide any speed improvement, but is safer.  Write-behind means that data is written to the cache, but only written back to main memory after a certain period of time, or when the block is evicted from the cache.

If you reflect on this a bit, you will see that there are advantages to dealing directly with the cache, and letting it have the responsibility of reading and writing main memory.  If all memory access goes through the cache, the cache can guarantee data integrity, because it has knowledge of every main memory access.  In other words, there is no possibility of getting stale data.

As far as I can tell, there is no issue of popularity.  Each approach to caching has its advantages and disadvantages.  If there is a strategy that is observed more often than the others, it is because that strategy more commonly satisfies the programmer's objectives.

Title: Cache policy categorization


问:
Equivalent translation of Asynchronous behaviour in C
As a follow-up to my other question, if one were to build a general-purpose translator from a language that has support (be it with an external library or otherwise) for asynchronous behaviour to a language that may or may not natively support it (let's use C as an example), then is it a semantically equivalent translation of an asynchronous callback to simply invoke the callback function before returning/completing from the successor? Note that in the example to follow I refer to JavaScript as a language that has support for asynchronous behaviour although it does not natively support asynchronous behaviour but in practice is used frequently through some libraries.

For example, given the following JavaScript program (from this simple example of an asynchronous JavaScript function)

```<code>window.setTimeout(function() {
    console.log("World");
}, 1000);
console.log("Hello");
</code>```

would it be a semantically equivalent translation of the above to use fork in the above such that the child process sleeps for 1000 milliseconds and then invokes prints "World" to stdout, and in the parent process continue with printing "Hello" to stdout? Are there any problems with this specific translation? Does this give rise to any  problems with translation in the general case?

Note that my motivation is to find a way to implement asynchronous behaviour, not to outsource the implementation to the use of a library.

答:
Here's a program that implements a similar code in C. Note that I removed all error checking for brevity:

```<code>#include <sys/timerfd.h>
#include <stdlib.h>
#include <sys/epoll.h>

static int pending_jobs;
static int efd;
struct cb_data {
    int fd;
    void (*fn)(void);
};

static void set_timeout(void (*fn)(void), int secs)
{
    struct epoll_event ev;
    int fd;
    struct itimerspec sleep_time;
    struct timespec now;
    struct cb_data *d;

    /* Setup a timer */
    clock_gettime(CLOCK_REALTIME, &now);

    sleep_time.it_value.tv_sec = now.tv_sec + secs;
    sleep_time.it_value.tv_nsec = now.tv_nsec;
    sleep_time.it_interval.tv_sec = 0;
    sleep_time.it_interval.tv_nsec = 0;

    fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
    timerfd_settime(fd, TFD_TIMER_ABSTIME, &sleep_time, NULL);

    /* Add it to epoll */
    ev.events = EPOLLIN;
    d = malloc(sizeof(*d));
    d->fd = fd;
    d->fn = fn;
    ev.data.ptr = d;
    pending_jobs++;
    epoll_ctl(efd, EPOLL_CTL_ADD, fd, &ev);

}

static void main_program_loop(void)
{
    /* Loop around epoll wait until there are no more jobs */
    while (pending_jobs > 0) {
        struct epoll_event events[10];
        int n, nfds;
        nfds = epoll_wait(efd, events, 10, -1);
        for (n = 0; n < nfds; ++n) {
            struct cb_data *d = events[n].data.ptr;
            epoll_ctl(efd, EPOLL_CTL_DEL, d->fd, NULL);
            pending_jobs--;
            close(d->fd);
            d->fn();
            free(d);
        }

    }
    /* No more jobs pending, exit */
}

void print_world(void)
{
    puts("World");
}

int main(void)
{
    pending_jobs = 0;
    efd = epoll_create1(0);

    /* The JS equivalent */
    set_timeout(print_world, 1);
    puts("hello");

    /* loop until all pending events are done */
    main_program_loop();

    close(efd);
}
</code>```

You can see that the C equivalent to the javascript snippet is:

```<code>void print_world(void)
{
    puts("World");
}
...
set_timeout(print_world, 1);
puts("hello");
</code>```

So it's pretty close. All the rest is the instrumentation that's needed both in C and Javascript. Except in Javascript it's bundled in the engine. In C, you can roll your own (something similar to the program above), or use a library such a libev or libevent.

Body:
Here's a program that implements a similar code in C. Note that I removed all error checking for brevity:

#include <sys/timerfd.h>
#include <stdlib.h>
#include <sys/epoll.h>

static int pending_jobs;
static int efd;
struct cb_data {
    int fd;
    void (*fn)(void);
};

static void set_timeout(void (*fn)(void), int secs)
{
    struct epoll_event ev;
    int fd;
    struct itimerspec sleep_time;
    struct timespec now;
    struct cb_data *d;

    /* Setup a timer */
    clock_gettime(CLOCK_REALTIME, &now);

    sleep_time.it_value.tv_sec = now.tv_sec + secs;
    sleep_time.it_value.tv_nsec = now.tv_nsec;
    sleep_time.it_interval.tv_sec = 0;
    sleep_time.it_interval.tv_nsec = 0;

    fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
    timerfd_settime(fd, TFD_TIMER_ABSTIME, &sleep_time, NULL);

    /* Add it to epoll */
    ev.events = EPOLLIN;
    d = malloc(sizeof(*d));
    d->fd = fd;
    d->fn = fn;
    ev.data.ptr = d;
    pending_jobs++;
    epoll_ctl(efd, EPOLL_CTL_ADD, fd, &ev);

}

static void main_program_loop(void)
{
    /* Loop around epoll wait until there are no more jobs */
    while (pending_jobs > 0) {
        struct epoll_event events[10];
        int n, nfds;
        nfds = epoll_wait(efd, events, 10, -1);
        for (n = 0; n < nfds; ++n) {
            struct cb_data *d = events[n].data.ptr;
            epoll_ctl(efd, EPOLL_CTL_DEL, d->fd, NULL);
            pending_jobs--;
            close(d->fd);
            d->fn();
            free(d);
        }

    }
    /* No more jobs pending, exit */
}

void print_world(void)
{
    puts("World");
}

int main(void)
{
    pending_jobs = 0;
    efd = epoll_create1(0);

    /* The JS equivalent */
    set_timeout(print_world, 1);
    puts("hello");

    /* loop until all pending events are done */
    main_program_loop();

    close(efd);
}

You can see that the C equivalent to the javascript snippet is:

void print_world(void)
{
    puts("World");
}
...
set_timeout(print_world, 1);
puts("hello");

So it's pretty close. All the rest is the instrumentation that's needed both in C and Javascript. Except in Javascript it's bundled in the engine. In C, you can roll your own (something similar to the program above), or use a library such a libev or libevent.


问:
Whether to abstract small repeating code segments in HTML templates?
(The framework used in question is AngularJS so the question can be translated as "Whether to introduce Directives for small repeating code segments in Views")

As a developer who focuses on Java backend development, I am very used to the DRY principle -- even the smallest repetition (long object access paths, logic used only twice, etc.) are often extracted.

However, in front-end HTML templating, the cost of reusing code is unbelievably high. In the case of AngularJS, the Directives syntax is extremely cumbersome (requires defining a JS object with nonsensical fields and a separate HTML file for the contents). For a small amount of code repeated a limited number of times, abstraction seems to harm maintainability.

Question is should I still abstract and hope for the frameworks to get better (e.g. Angular 2.0 have a much better syntax or the project could switch to React), or just repeat the code for readability?

答:
If you abstract/DRY and hope to switch to Angular 2 or React you will have to touch your code when that happens. If you repeat the code you might not have to touch it much, maybe a simple search/replace on the whole project with a pinch of regex.

You really need to know the specifics (project size, cost of changing code, testing methods) and guess how each instance of that copy-pasted code might evolve in the future (remain the same?, add lots of parameters to your abstraction?).