问:
Working with legacy code - introducing an external BDD integration test harness
Here's the scenario.

There's a large, organically grown application written in some language and manner that makes it difficult to test.  It works but is hard to maintain.

Specifications are woolly, so even if the code was amenable, it's hard to know what things should be doing without doing them.

You want to get it into a test harness so you can start to refactor and create proper unit tests.

In these cases it makes sense to build an external or superficial 'test everything' harness so you can start more aggressive refactoring to enable you to write proper unit tests.  This seems a pretty established practice of incrementally introducing tests.

"The main thing that distinguishes legacy code from non-legacy code is a lack of
comprehensive tests." - Michael C. Feathers (Working Effectively with Legacy Code)

My question is this:

Does it make sense to build a suite of Behaviour Driven tests at this point and execute them via some kind of automated button clicker?  I'm thinking something like (but not limited to) cucumber or similar where the human readable tests match executable code/scripts that prove the defined behaviour is being met.

A clear advantage of this is that a human readable specification of sorts could be developed alongside the tests and that these specifications are much easier to confirm as sane and correct with users/developers of the system.  They are essentially integration tests but perform the function that Feathers recommends.

eta: I'm not asking for a specific tool recommendation, the actual tool is irrelevant (although it would be helpful to know if they actually exist) I'm after a sanity check and recommendations around external BDD integration testing.

答:
BDD is definitely possible in Legacy system. I personally participated in uplifting multiple Legacy projects with years of history. One of the key aspects of BDD is to enrich team understanding of what is actually needed and then provide a sustainable path to do incremental change towards it and from it. In my experience, the common aspect of Legacy system is that a big chunk of it is already done with a huge fraction of it never changing again. So keeping this in mind, attempts to retrofit BDD into the use-cases that already were delivered will unavoidably result in waste - you will end up discussing a huge list of things most of which will never change and test huge list of things most of which will never break.

As Liz (lunivore) said, the key aspect of approaching such projects is to identify project capabilities. In order to move the Legacy project forward you need to close your eyes for a time being on things that were done and look at things that will change. Identify key business priorities for the next couple of months. This will help you to understand which new features will need to be added and which existing features will need to be changed. I find practices like Impact Mapping working extremely well here. Have conversations about these features, and use outcomes of these conversations to do BDD. In this regard, BDD on Brownfield projects is not that different from BDD on Greenfield ones.

The biggest difference is how you technically approach it - Legacy projects will naturally have much more end-to-end simply because of their nature, it is fine. The key practice here is to not keep these end-to-end tests for too long. As soon as you did write an end-to-end test the clock should start ticking for you to refactor the underlying code in attempt to make it unit-testable. I call this process test level migration and I wrote about it in more detail yesterday :)

In addition to covering changes and new features, you will surely encounter bugs. It's important here to understand that in most cases on the non-tested codebase you will not be able to predict them. So instead of trying to predicting bugs, try to prepare for them - be careful with critical areas. Discuss and automate broken journey as soon as defect is found, but not sooner. Otherwise it is very possible to spend too much money and time on testing things that will never break, effectively wasting resources instead of delivering value.

Hope this helps.


问:
Why is there little use of filesharing as compression (outside of libraries)?
Recently I was looking for a program that will run as a daemon and find files that have the same size/type, check if they're the same, then make both a hard link to a single copy if they are. And I started wondering why Operating Systems don't do this automatically.

I thought maybe because it would be time consuming, but it wouldn't need to check if no new files were added outside of the cache directory, and checking the size would rapidly cut the search space. Then I thought maybe because it doesn't come up very often; but if that were the case then I would expect game consoles to do this, because most games will use the same stock sound effects package for instance, but they don't. Having two games from one series takes the same amount of space as just summing the two sizes, even though tons of assets would be reused.

Or in a system like youtube, they check videos against other videos when checking for copyright violations, but they don't seem to cause two identical videos to be stored only once, considering how mirroring a video can prevent it being taken off the site, (e.g. when 'youtube vs the users' kept being mirrored they took it out of the search results rather than continuing to take them off the site).

So, what's the reason the system doesn't compress things this way?

答:
It's called deduplication.

Some filesystems do it (like ZFS), some block-level storage systems do it (like NetApp), some backup systems do it (rsnapshot), source code managment systems do it (Git, bzr, fossil)

It's not so rare, just that until recently it was an expensive option for generic filesystems.

Note that it's not a good idea to do it as you suggest (hardlinks) for general-use volumes, since editing one 'copy' would edit the other one too.  You should take care of breaking the link first.  Some applications never "edit" files in place, instead on each "save" a new file is created and afterwards it is renamed to replace the original.  In those cases yes, it would be reasonably safe to keep hardlinks; but do you want to audit every application you use on your files?  Nuch easier is to keep separate copies separate

ContentLicense: CC BY-SA 3.0


问:
Architecture for an event admission ticket scanner for events with multiple entries
I am working on a service that lets event organizers sell tickets to their events online (a lot like Eventbrite to be honest).

The customers then print the tickets themselves (each ticket has a barcode) and present them at the event, where they are scanned using a mobile app. The mobile app communicates with the server and checks in the ticket code, and the person is allowed entry to the event.

Now, we have just started developing the mobile app, and already we are at an impasse. Normally, to mitigate the effects of potential server downtime, and also to avoid making a ton of requests when a lot of people attend an event, especially when those requests might be sent over a flaky 3G connection, I would go with this approach:

Mobile app periodically polls the server and pulls the ticket codes that have been generated since the last request

The app checks its local database of ticket codes when a customer presents a ticket. If the ticket isn't found, initiate a data pull.

It also periodically sends "checked in" ticket codes, so they can also be updated on the server.

This approach would probably work just fine, if not for the possibility that an event might have multiple entry points, thus making this solution vulnerable to cheating by someone printing two copies of the same ticket and using them for two separate people at different entries. We would only discover this when both instances of the mobile app push data to the server.

One workaround would be to have the applications also communicate with each other, but this raises other problems:

Bluetooth is not feasible, because of the limited range.

3G can be flaky, just as above.

Wifi availability cannot be guaranteed at all events.

I would really like to find a solution to this that doesn't involve having to send one request for each ticket code, because I can see them now, hundreds of people lined up, the line going nowhere because the server is down, or the internet connection is down, and I can hear my phone ringing on a Saturday night, and I really, really, really don't want that.

Sorry for the long story. Any thoughts?

答:
What about an adhoc wifi network among the mobile devices essentially if a device scans something it broadcasts it to the other scanners so they know not to accept it again. You could lose data between the devices but assuming you have some level of connectivity working then you get enough data through to make attempting to exploit the system not worth it.

This solution obviously doesn't scale well, and could be difficult to physically setup.

After the event you can dump all of the records back to the server on real wifi or whatever other communication method you want.


答:
The ideal situation is to have a reliable connection to a single server so you can verify in real time that the presented ticket has not already been admitted to the event.

As you pointed out, this is not always possible.

A couple of nontechnical workarounds:

Use assigned seating.  Holders of duplicate tickets would have to sit on each other's laps.  This is probably not an option for you.

Since tickets are unique, it should be possible after the event to identify which tickets were used multiple times.  Have the business bill the ticket purchaser for the additional admission fees, plus a nuisance fee.

Assume most people are honest and don't worry about it - you'll spend more time & money preventing the problem than you'll lose by ignoring it.  (This is only sometimes true - it depends on the event and the audience)

Back to technology:

Obviously, a single device can check/prevent multiple entries since it knows which ticket holders have been admitted through that gate.  That would limit your loss to (worst case) the number of gates you have.

Code for a 3G/4G/Wifi/Internet solution, but gracefully fall back to "local enforcement only" and/or "update (both server and device - 2 way sync) when able"

Since you can't get "perfect", go for "good enough".

Title: Architecture for an event admission ticket scanner for events with multiple entries

Body:
I am working on a service that lets event organizers sell tickets to their events online (a lot like Eventbrite to be honest).

The customers then print the tickets themselves (each ticket has a barcode) and present them at the event, where they are scanned using a mobile app. The mobile app communicates with the server and checks in the ticket code, and the person is allowed entry to the event.

Now, we have just started developing the mobile app, and already we are at an impasse. Normally, to mitigate the effects of potential server downtime, and also to avoid making a ton of requests when a lot of people attend an event, especially when those requests might be sent over a flaky 3G connection, I would go with this approach:

Mobile app periodically polls the server and pulls the ticket codes that have been generated since the last request

The app checks its local database of ticket codes when a customer presents a ticket. If the ticket isn't found, initiate a data pull.

It also periodically sends "checked in" ticket codes, so they can also be updated on the server.

This approach would probably work just fine, if not for the possibility that an event might have multiple entry points, thus making this solution vulnerable to cheating by someone printing two copies of the same ticket and using them for two separate people at different entries. We would only discover this when both instances of the mobile app push data to the server.

One workaround would be to have the applications also communicate with each other, but this raises other problems:

Bluetooth is not feasible, because of the limited range.

3G can be flaky, just as above.

Wifi availability cannot be guaranteed at all events.

I would really like to find a solution to this that doesn't involve having to send one request for each ticket code, because I can see them now, hundreds of people lined up, the line going nowhere because the server is down, or the internet connection is down, and I can hear my phone ringing on a Saturday night, and I really, really, really don't want that.

Sorry for the long story. Any thoughts?


答:
As GlenH7 has already stated, given the constraints you have listed in the question your problem is effectively unsolvable.  Assuming "it can't be done" is not an acceptable answer we're left with having to change the constraints.

One option you mentioned involved getting the mobile devices to preload the entire set of tickets.  Your concern was that fraud would not be detected in realtime.

How about relaxing this constraint of "realtime fraud detection?"

To me that seems like a decent enough compromise.  Especially considering that periodic synchronizing of the system state (when possible) would help prevent most ticket fraud.

Also, the vast majority of your users 1) won't know about this vulnerability, and 2) probably wouldn't care enough to exploit it.

And finally, since there doesn't seem to be a technical solution to your problem, you could consider social or legal options.  For example, you could further mitigate the kind of abuse mentioned above by adding something to your Terms and Agreements (disclaimer: I am not a lawyer).  I doubt it would actually be enforceable, but you could add a financial penalty to anybody trying to cheat the system.


答:
The problem is, by doing this in the background you are changing the mutability semantics of the system in a way that people just wouldn't expect.

Consider the following workflow:

I create a wonderful piece of art in myasciidrawing.txt.

I decide that I want to create a similar piece of art, so I copy  myasciidrawing.txt to awesomeasciidrawing.txt and start editing it.

Some time later, happy with my creation I save it.

Later I go back to look at myasciidrawing.txt and find that it has the contents of mynewasciidrawing.txt and I've lost the original!

What happened is that between 2) and 3) the wonderful space saving background deduplication routine has identified that myasciidrawing.txt and awesomeasciidrawing.txt have the same contents, deduplicated and linked them, so that when I saved awesomeasciidrawing.txt it ovewrote myasciidrawing.txt too!

Worse than that, is that whether myasciidrawing.txt and awesomeasciidrawing.txt have the same contents after step 3 depends on what software you are using to edit.

If you are using software which edits the original in place the links will mean that both appear to be edited at the same time. If the software renames the old file '.bak' and then writes a new file with the same name, then myasciidrawing.txt and awesomeasciidrawing.txt.bak will both contain the original drawing, but awesomeasciidrawing.txt will point to the updated contents.

This is one of the reasons that deduplicating filesystems tend to use copy-on-write semantics, since any deduplicated data is, by definition, shared data.

Title: Why is there little use of filesharing as compression (outside of libraries)?

Body:
Recently I was looking for a program that will run as a daemon and find files that have the same size/type, check if they're the same, then make both a hard link to a single copy if they are. And I started wondering why Operating Systems don't do this automatically.

I thought maybe because it would be time consuming, but it wouldn't need to check if no new files were added outside of the cache directory, and checking the size would rapidly cut the search space. Then I thought maybe because it doesn't come up very often; but if that were the case then I would expect game consoles to do this, because most games will use the same stock sound effects package for instance, but they don't. Having two games from one series takes the same amount of space as just summing the two sizes, even though tons of assets would be reused.

Or in a system like youtube, they check videos against other videos when checking for copyright violations, but they don't seem to cause two identical videos to be stored only once, considering how mirroring a video can prevent it being taken off the site, (e.g. when 'youtube vs the users' kept being mirrored they took it out of the search results rather than continuing to take them off the site).

So, what's the reason the system doesn't compress things this way?


问:
How should blank/empty value objects be instantiated/structured?
I was wondering... what is considered the best practice to instantiate blank value objects? (in Java)

E.g. Assume we have some value object class Foo, that could be blank.

Would creating methods like these be a clean solution? <s>(And perhaps adding in a "Blankable" interface or something).</s>

```<code>interface Blankable {
    public Foo blankInstance();
    public boolean isBlank();
}

class Foo implements Blankable {
    public Foo blankInstance();
    public boolean isBlank();
}

Foo foo = something();
if (foo.isBlank()) // Tell the user
</code>```

Or would something more simple like this be better?

```<code>class Foo {
    public static Foo BLANK = /* Some constructor */;
}

Foo foo = something();
if (foo == Foo.BLANK) // Tell the user
</code>```

I am leaning toward the first example, but I am still not sure if it is a widely accepted technique.

I feel a bit resistant to (but still open to) using the Guava Optional< T> class because it seems like a work-around solution in this circumstance.

答:
The whole point of a value object is that equality isn't based on identity; you could very well have two distinct blank objects. In fact, whether all blank objects are the same or different objects should be an implementation detail. For those reasons, the second approach is not good. If you look at the Java 8 APIs, there's a notion of a "value-based class" with the following properties:

are final and immutable (though may contain references to mutable objects);

have implementations of equals, hashCode, and toString which are computed solely from the instance's state and not from its identity or the state of any other object or variable;

make no use of identity-sensitive operations such as reference equality (==) between instances, identity hash code of instances, or synchronization on an instances's intrinsic lock;

are considered equal solely based on equals(), not based on reference equality (==);

do not have accessible constructors, but are instead instantiated through factory methods which make no committment as to the identity of returned instances;

are freely substitutable when equal, meaning that interchanging any two instances x and y that are equal according to equals() in any computation or method invocation should produce no visible change in behavior.

The documentation further adds:

A program may produce unpredictable results if it attempts to distinguish two references to equal values of a value-based class, whether directly via reference equality or indirectly via an appeal to synchronization, identity hashing, serialization, or any other identity-sensitive mechanism. Use of such identity-sensitive operations on instances of value-based classes may have unpredictable effects and should be avoided.

There's no way to disable the == operator in Java so that warning is the best you can do.

Thus, your first approach is correct, with the caveat that foo1.equals(foo2) should always be true when foo1.isBlank() and foo2.isBlank() even if foo1 != foo2.


答:
There are filesystems that do this, btrfs or ZFS for example. Not (just) for files, also for individual extents.

Dropbox also does this (or at least used to). Uploading a large file that another user already uploaded takes only a small amount of time, because it isn't actually uploaded. The client sends a hash of the file to the server, and when the server already knows about the file, it will tell the client to stop uploading.


问:
Is there still a need for writing SQL?
With so many ORM tools for most modern languages, is there still a use case for writing and executing SQL in a program, in a language/environment that supports them?  If so why?

For clarity: I'm not asking about if programmers need to know SQL, or if I should have a SQL tool on my desktop.  I'm asking specifically why I might have it in code (or config, or whatever) as opposed to an ORM.

答:
ORMs exist due to the impedance mismatch between our common relational DB implementations and our OO language features.  They are only a bridge, yet most folks treat SQL like the Limburger cheese in the fridge.

If you can justifiably say that you will always use your ORM or other abstracted data access layer instead of treating SQL/stored procedures/views as a first-class interface(s), then you'd likely be better off without touching SQL.

In practice, I've never seen a pure-ORM project that didn't require at least SQL to query the the database for final validation.

ContentLicense: CC BY-SA 2.5

Title: Is there still a need for writing SQL?


问:
Taming the 'utility functions' classes
In our Java codebase I keep seeing the following pattern:

```<code>/**
 This is a stateless utility class
 that groups useful foo-related operations, often with side effects.
*/
public class FooUtil {
  public int foo(...) {...}
  public void bar(...) {...}
}

/**
 This class does applied foo-related things.
*/
class FooSomething {
  int DoBusinessWithFoo(FooUtil fooUtil, ...) {
    if (fooUtil.foo(...)) fooUtil.bar(...);
  }
}
</code>```

What bothers me is that I have to pass an instance of FooUtil everywhere, because testing.

I cannot make FooUtil's methods static, because I won't be able to mock them for testing of both FooUtil and its client classes.

I cannot create an instance of FooUtil at the place of consumption with a new, again because I won't be able to mock it for testing.

I suppose that my best bet is to use injection (and I do), but it adds its own set of hassles. Also, passing several util instances inflates the size of method parameter lists.

Is there a way to handle this better that I'm not seeing?

Update: since the utility classes are stateless, I could probably add a static singleton INSTANCE member, or a static getInstance() method, while retaining the ability to update the underlying static field of the class for testing. Does not seem super-clean, too.

答:
First of all let me say that there are different programming approaches for different problems. For my job I prefer a strong OO design for orginazation and maintenance and my answer reflects this.  A functional approach would have a very different answer.

I tend to find that most utility classes are created because the object the methods should be on doesn't exist.  This almost always comes from one of two cases, either someone is passing collections around or someone is passing beans around (These are often called POJOs but I believe a bunch of setters and getters is best described as a bean).

When you have a collection you are passing around, there must be code that wants to be a part of that collection, and this ends up being sprinkled throughout your system and eventually collected into utility classes.

My suggestion is to wrap your collections (Or beans) with any other closely associated data into new classes and put the "utility" code in actual objects.

You could extend the collection and add the methods there but you lose control of your object's state that way--I suggest you encapsulate it completely and only expose business logic methods that are necessary (Think "Don't ask your objects for their data, give your objects commands and let them act on their private data", an important OO tenant and one that, when you think about it, requires the approach I'm suggesting here).

This "wrapping" is useful for any general purpose library objects that hold data but you can't add code to--Putting code with the data it manipulates is another major concept in OO design.

There are many coding styles where this wrapping concept would be a bad idea--who want's to write a whole class when just implementing a one-time script or test?  But I think encapsulation of any basic types/collections that you cannot add code to yourself is mandatory for OO.

Title: Taming the 'utility functions' classes

ContentLicense: CC BY-SA 4.0


问:
How to determine if a message should be a command message or event message?
Two enterprise integration patterns are the command message and the event message. I am working on a system in which we use messaging not only for integration with other systems, but for internal communication between services. It's supposed to be an eventually consistent system, and services are supposed to be ignorant of each other (with exception to a couple special-purpose services). As such, we try to avoid things that feel like remote procedure calls (RPC or RPI). We have a bus and message-oriented middleware system, and all messages are broadcasted.

We tend to name our messages as events, that is, as a phrase in the past perfect, e.g. PurchaseOrderShipped. However, the events are often added only when some other services needs to know about them, and in the beginning, often only one service cares. Moreover, sometimes that service emits an event as a result, which is listened to by the first service. Thus if I were to diagram the interaction, it would look much more like the diagram for the command message in the link above (or even the RPC diagram) than the one for the event message, though once again, this is not actually implemented with direct messaging but broadcast on a bus. Add to that the fact that I have recently seen some messages being added that are named as commands, that is, a phrase in the imperative, e.g. BillShippedPurchaseOrder.

The odd thing is that the names of the messages and the way they flow are not changes by whether it is named as an event or as a command. So how does one determine whether something should be a command message or an event? Is this just a difference of semantics and naming, or is there an actual implementation difference between command and event messages? Given that all our messages are broadcast, does that mean than none of them are truly command messages?

答:
An Event message is something that has just happened.  You are notifying of the event that has just happened.

A Command message is a message that expects something to be done.  It may or may not expect a response.

When to use what comes down to coupling and the difference will only emerge over time as the systems evolve. Favoring events over commands results in less coupling. The emitter of the event does not care about the consumer. In a command pattern the caller knows and is therefore dependent on the existence of the provider.

Bill Poole suggests avoiding command messages all together:
http://bill-poole.blogspot.com.au/2008/04/avoid-command-messages.html

http://bill-poole.blogspot.com.au/


答:
You could use a Provider pattern and inject your FooSomething with a FooUtilProvider object (could be in a constructor; only once).

FooUtilProvider would only have one method: FooUtils get();. The class would then use whatever FooUtils instance it provides.

Now that's one step away from using a Dependency Injection framework, when you'd only have to wire DI cointainer twice: for production code, and for your tests suite. You just bind FooUtils interface to either RealFooUtils or MockedFooUtils, and the rest happens automagically. Every object that depends on FooUtilsProvider gets the proper version of FooUtils.

Title: Taming the 'utility functions' classes

Body:
In our Java codebase I keep seeing the following pattern:

```<code>/**
 This is a stateless utility class
 that groups useful foo-related operations, often with side effects.
*/
public class FooUtil {
  public int foo(...) {...}
  public void bar(...) {...}
}

/**
 This class does applied foo-related things.
*/
class FooSomething {
  int DoBusinessWithFoo(FooUtil fooUtil, ...) {
    if (fooUtil.foo(...)) fooUtil.bar(...);
  }
}
</code>```

What bothers me is that I have to pass an instance of FooUtil everywhere, because testing.

I cannot make FooUtil's methods static, because I won't be able to mock them for testing of both FooUtil and its client classes.

I cannot create an instance of FooUtil at the place of consumption with a new, again because I won't be able to mock it for testing.

I suppose that my best bet is to use injection (and I do), but it adds its own set of hassles. Also, passing several util instances inflates the size of method parameter lists.

Is there a way to handle this better that I'm not seeing?

Update: since the utility classes are stateless, I could probably add a static singleton INSTANCE member, or a static getInstance() method, while retaining the ability to update the underlying static field of the class for testing. Does not seem super-clean, too.


问:
Does using == in JavaScript ever make sense?
In JavaScript, the Good Parts, Douglas Crockford wrote:

JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=.  The good ones work the way you would expect.  If the two operands are of the same type and have the same value, then === produces true and !== produces false.  The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values.  The rules by which they do that are complicated and unmemorable.  These are some of the interesting cases:

```<code>'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == 'false'    // false
false == '0'        // true

false == undefined  // false
false == null       // false
null == undefined   // true

' \t\r\n ' == 0     // true
</code>```

The lack of transitivity is alarming.  My advice is to never use the evil twins.  Instead, always use === and !==.  All of the comparisons just shown produce false with the === operator.

Given this unequivocal observation, is there ever a time when using == might actually be appropriate?

答:
Yes, I've run across a use case for it, namely when you're comparing a key with a numerical value:

```<code>for (var key in obj) {
    var some_number = foo(key, obj[key]);  // or whatever -- this is just an example
    if (key == some_number) {
        blah();
    }
}
</code>```

I think it's a lot more natural to perform the comparison as key == some_number rather than as Number(key) === some_number or as key === String(some_number).

Body:
Yes, I've run across a use case for it, namely when you're comparing a key with a numerical value:

for (var key in obj) {
    var some_number = foo(key, obj[key]);  // or whatever -- this is just an example
    if (key == some_number) {
        blah();
    }
}

I think it's a lot more natural to perform the comparison as key == some_number rather than as Number(key) === some_number or as key === String(some_number).


问:
TDD and Writing Tests for File Processing
These questions are very similar: TDD for batch processing: How to do it? and TDD: how to test file outputs? but I'm still left wondering some things

The app processes files/pdfs. It takes them from one FTP server, processes/reads file content, places them in a destination FTP server, depending on content read.

How can I approach file processing in a TDD way? My formal education on TDD was not the best, so even "obvious" suggestions will help me.

My ideas:

The "success" of my app depends on if it reads/processes a source file properly, and also if it places it in the proper destination. So it makes sense to me to write tests for seeing if a file

is "read" correctly

ends up in the right place

I could test on specific dummy files, but does this mean I should always ship these specific files with the code, for the tests to pass? The file's name will be different after being processed, so I'm not sure how to test if it ends up in the right place -- should I eyeball the files and then hardcode expected results into the tests?

答:
I think this is a great question.  Unit testing, micro-testing, TDD, and BDD are difficult, sometimes confusing, and often not taken seriously.  So kudos for trying and asking for help!

I am by no means an expert, but I did just take a formal class and am also part of a small team that is leading an initiative to roll out unit testing and TDD within our organization.

Based on my experience and what I learned in my class, here is what I think you need to know in order to start:

Consider that there are different types of testing and they accomplish different goals.  There are lots of things that unit testing is simply a poor or incomplete solution for, which can lead one to think that unit testing is a waste of time.  However, I view it as complementary to integration testing and functional testing.

Don't stress out about coverage.  There is a time and place to think about code coverage, but if you worry about that right now, you will waste time unit testing accessors and mutating, which provides no business value.

Don't think about testing classes or methods, but think about testing behaviors.  What does this class do?  What does it not do?  (This is part of why the term BDD is used these days)

Test interesting behaviors.  What qualifies as interesting is up to you.  Many experts argue that a bug is a missing test.  Therefore, anything you feel could reasonably break is worth testing.  Would you write a test for i++?  Probably not.  Would you write a test for incrementI()?  Maybe.  If it's a calculator app, I probably would.  If it's a web app, then I wouldn't sweat something that simple.

Tests are not just about making sure your code works.  They serve as an executable specification.  Meaning, if somebody needs to understand the requirements of a class, they can look at the test.

It is ok for a test to assume that a dependency works.  If that worries you, then maybe you should unit test the dependency as well.  But keep it separate.  For example, one could argue that testing the data processing without a real file is bad because you don't know if the file parsing works.  But if you have a unit test which verifies that file parsing works, and a unit test that verifies the processing of the file's data works, then clearly both work.  Granted, this does not prove that they work together.  But that's ok.  That is integration testing.

Unit tests should be repeatable and isolated.  A unit test that makes a web service call, then writes to a database, and then prints some result to the console is not a unit test.  It's a test, sure, but not a unit test.  Don't get so hung up on testing everything that you write fragile tests which do a ton of work.  So if a method does those things, how do you unit test it?  This leads to the next topic...

Separating out dependencies - Write small units which can be called independently, with dependencies passed in.  If you design so that the processing is independent of the source file itself, you can test the processing logic without needing files.  For example, instead of the file processing taking a java.io.File object, parsing it, and doing all the work, perhaps it could take a java.io.InputStream, parse it, and do all the work?  Or a method which reads the file's contents into an array or other data structure, then passes that into the processing?

Mocking out dependencies - ultimately, somebody needs to talk to the external world.  Ideally, you will separate your dependencies, but sometimes you reach points where the complexity introduced by doing so is counter-productive.  For example, a method which several levels down the call stack needs to talk to the database and separating that out is unreasonable, then mock it out with a fake implementation that returns test data.  I've gone as far as creating a MockDatabase class before, which lets me map stored procedure names to hard-coded, in-memory result sets.

Realize when you have mocked so much that unit testing is pointless.  If you have mocked out everything a method does, then you are left testing an empty method.  If that is the case, maybe that method is not interesting to test?  Trust that an integration test, automated functional test, or even manual testing will catch any problems with it, and don't worry about unit testing it.

I could go on forever.  Hopefully that helps.

Remember, this is not easy.  If it was easy, everybody would do it.


问:
Metric by which to hold developers accountable
I asked a question on lines of code per hour and got torn a new one.  So my matured follow-up question is this:

If not lines of code, then what is a good metric by which to measure (by the hour/day/unit-of-time) the effectiveness of remote programmers?

答:
Writing code/Programming is not like putting a hammer to a nail.  Much like "writing" in general, it's not something that you can apply typically metrics too - in my opinion.

Couldn't you simply look at their check-ins, or what they've done through peer-review, code-review?

Or you know, if they actually produce working code and solutions that fix problems?


问:
What is abstraction?
Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?

答:
As a way of explaining it to another person I would go the other way around, from the outcomes back:

Abstraction in computer programming is the act of generalizing something to the point that more than one similar thing can be generally treated as the same and handled the same.

If you want to expand on that you can add:

Sometimes this is done to achieve polymorphic behavior (interfaces and inheritance) to cut down on repetitive code up front, other times it is done so that the inner workings of something could be replaced at a future date with a similar solution without having to alter the code on the other side of the abstracted container or wrapper, hopefully cutting down on rework in the future.

Beyond that, I think you have to start into examples...

Title: What is abstraction?


问:
"Comments are a code smell"
A coworker of mine believes that any use of in-code comments (ie, not javadoc style method or class comments) is a code smell.  What do you think?

答:
In some cases, no amount of good naming, refactoring etc. can replace a comment. Just look at this real-world example (language is Groovy):

```<code>  response.contentType="text/html"
  render '{"success":true}'
</code>```

Looks strange, doesn't it? Probably a copy-paste-error? Cries for a bugfix?

Now the same with comments:

```<code>  // DO NOT TOUCH THE FOLLOWING TWO LINES; the ExtJS UploadForm requires it exactly like that!!!
  response.contentType="text/html"  // must be text/html so the browser renders the response within the invisible iframe, where ExtJS can access it
  render '{"success":true}'         // ExtJS expects that, otherwise it will call the failure handler instead of the succss handler
</code>```

Title: "Comments are a code smell"

Body:
In some cases, no amount of good naming, refactoring etc. can replace a comment. Just look at this real-world example (language is Groovy):

  response.contentType="text/html"
  render '{"success":true}'

Looks strange, doesn't it? Probably a copy-paste-error? Cries for a bugfix?

Now the same with comments:

  // DO NOT TOUCH THE FOLLOWING TWO LINES; the ExtJS UploadForm requires it exactly like that!!!
  response.contentType="text/html"  // must be text/html so the browser renders the response within the invisible iframe, where ExtJS can access it
  render '{"success":true}'         // ExtJS expects that, otherwise it will call the failure handler instead of the succss handler


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答: I was asked by my manager, a VP with connections to a support company in China, to transfer the support of my products to an external company.  When I tried to explain to him that this was not possible given our contractual obligations to our customers, his response was, "Of course we can do it - we did it at "xxx company" (his previous employer)  Never mind that the two companies made different classes of software, and had different licensing models.</p>

OwnerDisplayName: VJN


问:
Would a statically typed alternative to JavaScript on webpages be practical?
Preference for dynamic and static typing is largely a matter of taste, and different people find them more or less suitable in different situations.

My question is, would it be technically possible to have a statically-typed alternative to JavaScript for client-side web page augmentation etc.?

Body:
In theory, you can stick any scripts on a page you want. The <script> tag has a type attribute, after all.

The only barrier is getting enough market share in terms of implementation in different browsers to make it worthwhile to use.

So yeah, it's kind of unlikely at this point.


答:
Since it's highly unlikely that another language will find broad adoption, your best bet would be to create a statically typed version of JavaScript (i.e. a language close to java) and a preprocessor that converts that to normal JavaScript.

For example, your script looks like that:

```<code><script type="text/staticjavascript">
   String foobar(int foo, String bar) {
      String result="";
      for (int i=0; i<foo; i++) {
         result += bar;
      }
      return result;
   }
</script>
</code>```

and the preprocessor checks that every variable, function, object etc. is used correctly according to it's type, and changes the script to

```<code><script type="text/javascript">
   function foobar(foo, bar) {
      var result="";
      for (var i=0; i<foo; i++) {
         result += bar;
      }
      return result;
   }
</script>
</code>```

which every browser can handle.

Title: Would a statically typed alternative to JavaScript on webpages be practical?

Body:
Preference for dynamic and static typing is largely a matter of taste, and different people find them more or less suitable in different situations.

My question is, would it be technically possible to have a statically-typed alternative to JavaScript for client-side web page augmentation etc.?

Body:
Since it's highly unlikely that another language will find broad adoption, your best bet would be to create a statically typed version of JavaScript (i.e. a language close to java) and a preprocessor that converts that to normal JavaScript.

For example, your script looks like that:

<script type="text/staticjavascript">
   String foobar(int foo, String bar) {
      String result="";
      for (int i=0; i<foo; i++) {
         result += bar;
      }
      return result;
   }
</script>

and the preprocessor checks that every variable, function, object etc. is used correctly according to it's type, and changes the script to

<script type="text/javascript">
   function foobar(foo, bar) {
      var result="";
      for (var i=0; i<foo; i++) {
         result += bar;
      }
      return result;
   }
</script>

which every browser can handle.


问:
What is the path to JavaScript mastery?
I know how we start with JavaScript, we cut-and-paste a snippit to gain a little client-side functionality or validation.

But if you follow this path in trying to implement rich interactive behavior, it doesn't take long before you realize that you are creating a Big Ball Of Mud.

So what is the path towards expertise in programming the interaction layer?  What books, tutorials, exercises, and processes contribute towards the ability to program robust, maintainable JavaScript?

We all know that practice is important in any endeavor, but I'm looking for a path similar to the answer here: https://stackoverflow.com/questions/2573135/

答:
Much of what you do in JavaScript is essentially intertwined with DOM, CSS and browser compatibility, so understanding the DOM is one of the primary requirements to mastering JavaScript.

Learning the core features of the language, such as prototype based object orientation, anonymous functions, and more general language features such as loops, conditions etc. is the key to understanding any code that you read that isn't specifically interacting with DOM/CSS.

You will also need to learn the language standard library, e.g. the String and Math and other core object functions.

You should also study algorithms, if you wish to gain a true and complete understanding of how things are being done, and how to implement more advanced solutions, this knowledge is fundamental to understanding advanced programming, and goes beyond language specific syntax.

Title: What is the path to JavaScript mastery?


答:
How about Rate of sales of the product/service.

Sometimes I've heard it's called a commission/percentage of the gross

People buy good products, don't they ?

The business wants to sell the product ( or maybe service, same difference for this)

So if that is what you want, measure it.

A bit like saying people who design a car that gets good reviews & sells well have done a good job really.

Now adopt this metric and programming team will want to interact with sales guy for two reasons.

Promsing underliverable

Not selling product to customers effectively

Title: Metric by which to hold developers accountable

Body:
I asked a question on lines of code per hour and got torn a new one.  So my matured follow-up question is this:

If not lines of code, then what is a good metric by which to measure (by the hour/day/unit-of-time) the effectiveness of remote programmers?


答:
Would it be practical?  No.

Is it possible?  Yes!

Developing your own statically-typed alternative to JavaScript would be time-consuming, at best.  At worst, you wouldn't be able to convince any existing browsers to implement your client scripting language, and would have to write your own.


答: There's certainly no technical reason such a thing couldnt exist.  There's nothing particular about client-side code that mandates the use of dynamically typed languages.


问:
How do you respond to a request for 'emergency contact information' for when you are on vacation?
I want to go on vacation and not think about work at all but they want me to provide them a contact number in the event of an emergency (server goes down, web service malfunctions, etc). I am afraid that it will be abused (they will contact me before trying everything for example) but I also think that if I am on vacation I should not be bothered even if there is an outage. Does anyone have experience with situations like this? What's the tactful approach? Any creative solutions?</p>

答:
I say tough luck!

Your job might not be like the doctor, but even though you don't save lives, some things come attached with your career choice.

IMHO the most ethical thing to do (though I understand it's difficult in many cases) is give the whatever contact number they need, clarify VERY well what they can expect from you in a holiday (availability for a major outage etc), you must manage it carefully and politely but you can avoid any abuse by stating than you are on you vacations and this does not correspond.

I you do this, firm but gently, (normal) people get and won't bother again.


问:
Best way to work easily with a database in remote programs?
In Database 101 you learned never to distribute the sensitive database password along with your program, since all a person has to do is reverse engineer the program, find where you actually need the original password for authentication, then echo/print that line. However when you have multiple remote programs that need to talk to a central database, what do you do?

My hackish solutions used to involve PHP, tons of GET variables, and JSON. I would make a request to the server with a set mode and parameters, then parse the JSON output. It was buggy, not entirely secure (only slowed an attacker down) since I didn't have any registration mechanism, hard to scale, and made all existing ORM's useless. Besides, it was attempting to reinvent SSH or SSL, not something that's too terribly smart.

What's the alternative though? What other options are out there that can provide security for the database while making it easy on me?

答:
The biggest thing I can comment on with databases and applications is to have multiple accounts.  Separate accounts for read and write access also and give these accounts the least required access to complete the given task.

You do have alternatives such as VPN's/SSH tunnels too have a more secure channel for distributed remote access to your central database.

Also, you should never really in your applications directly deal with the database, rather your applications should have a database abstraction layer or some sort which interacts with database.  This is one: good design, and two: a better approach as you place all the DB interaction in one place and provide your application with an API to use the database interaction layer.


答:
For building large scale web applications its completely unnecessary and can make things much more stressful and time wasting than they need to be. The reason for this is that any large-scale app should be making use of a memory persistence layer (in RAM) which should be memory caching parts of the DB that are frequently used.

If you have to do things with mobile devices, etc that don't have a lot of memory to work with, where the application that is being programmed is running as a "client" or standalone app on a mobile device, tablet, etc than things like using SQL are still common and are important because the memory on the device is so small that you can't cache a lot of things in memory.

Title: Is there still a need for writing SQL?

Body:
With so many ORM tools for most modern languages, is there still a use case for writing and executing SQL in a program, in a language/environment that supports them?  If so why?

For clarity: I'm not asking about if programmers need to know SQL, or if I should have a SQL tool on my desktop.  I'm asking specifically why I might have it in code (or config, or whatever) as opposed to an ORM.


问:
Best way to transport response data from an AJAX request?
Some possibilities are JSON, XML, HTML and/or Javascript fragments.
The democratic answer to this question is "it depends on the situation," but I am looking for why one may be better than the others.</p>

答:
I prefer JSON

Many many libraries out there for it in all languages

Doesn't require a complicated schema

Usually can be converted into an associate array or language equivalent quite easily. This is what makes JSON in PHP so easy

Compact: Not a lot of boilerplate

Easy to use: XML is notoriously hard to work with in any language, while JSON is very easy, especially if your language has associate arrays


问:
How to deal with project managers who micromanage?
Perhaps I'm just naive, but when I try to decipher the wall of tasks I'm targeted to do over the course of a week, I just can't help but think whoever builds the project schedule needs to get some remedial training on basic project management.

For example, I am assigned 13 tasks today, the shortest lasting .13 days (default time metric in Microsoft Project), and the longest lasting .75 days. I can't help but think that it is blatant micromanagement scheduling projects in sub 10 minute intervals.

The effects of management are becoming evident in slipped tasks, resource assignment exceeding capacity by a factor of two at some points in time, and spending more time clearing tasks and figuring out what comes next than actually doing work.

How can I convince the project manager to create tasks with larger duration and to see the larger picture?

答:
Perhaps you could try to argue that there is a lot of overhead on defining and estimating tasks that are so small.  That instead of writing out all the details and estimates for 4 tasks that are each to take .125 days, it may be better to have 1 task estimated at .5 day that can be set up much faster.  Now, this does have a few caveats:

Larger estimates still have to be close to right.  If in bundling things together the estimates get less accurate this could be a problem as there is a trust that the developers want but the project manager may now want to give.  This is more about addressing a fear before the project manager has the precedence to say, "Look you already messed this up before.  Why should I trust you now?" with some evidence.

That the people that look at the work done such as the Project Manager and sponsors can understand there may be a minimal difference between doing 101 tiny tasks and 10 large work items as it could be the same work at times.  Some people may view quantity as what counts and unfortunately that is where the catch comes in play here as I see it.  I'm not sure how to resolve this issue as the typical solution I'd see is trying to get the other person to see the logic which may or may not go over well.

How technically savvy is the PM?  This can be another point as if the PM isn't that savvy, then there is a concern that this may come off as snobby or arrogant which isn't the intent as you want the freedom to do something as you see rather than being given the to-do list with 10 steps of how to do something from a to j.

Those would be the areas of concern I'd be sure to know how to handle questions he may have in wanting to put this into practice as what I think you want is fair and realistic to my mind.


答:
Ask your manager to set priorities on each one of the tasks.  Then, agree to complete the tasks in priority order.

He won't do it.

You could try introducing management to CCPM.  They'll find out in a hurry that the single biggest bleeder of productivity is interruptions.

But seriously, do you really think you can change that kind of mindset?  Lives have been squandered trying.

Title: How to deal with project managers who micromanage?

Body:
Perhaps I'm just naive, but when I try to decipher the wall of tasks I'm targeted to do over the course of a week, I just can't help but think whoever builds the project schedule needs to get some remedial training on basic project management.

For example, I am assigned 13 tasks today, the shortest lasting .13 days (default time metric in Microsoft Project), and the longest lasting .75 days. I can't help but think that it is blatant micromanagement scheduling projects in sub 10 minute intervals.

The effects of management are becoming evident in slipped tasks, resource assignment exceeding capacity by a factor of two at some points in time, and spending more time clearing tasks and figuring out what comes next than actually doing work.

How can I convince the project manager to create tasks with larger duration and to see the larger picture?


答:
When it comes to JSON vs. XML, I also prefer JSON (see TheLQs excellent answer), but when some people prefer XML for whatever reason, I'm fine with that.

Returning HTML can be okay in some situations, but I dislike it for a simple reason: it violates the MVC distribution of responsibilities; i.e. the controler does something (creating a layout) that should be up to the view.

Returning JavaScript fragments, except for the special case of JSON, is very questionable and should be avoided IMO. In my current project, I've done it once, but I consider it a bad idea and will probably refactor it soon. Doing that on a large scale creates systems that are hard to understand, difficult to debug and a nightmare to maintain.

Title: Best way to transport response data from an AJAX request?

Body:
Some possibilities are JSON, XML, HTML and/or Javascript fragments.
The democratic answer to this question is "it depends on the situation," but I am looking for why one may be better than the others.</p>


答:
.13 days @ 8 hours per day (480 minutes per day) = 62.4 minutes (just over an hour).  Planning down to one-hour tasks isn't that bad.

More importantly, how are the tasks getting onto the schedule in the first place?  And how are the durations being assigned?  If your project manager is coming up with the list of tasks and what the durations should be, then that's a problem.  It's your PM's job to track these items, but it's the team's responsibility to come up with the list of tasks and estimates for those tasks.  Planning is a team sport.

It sounds like there are some other issues at play here also, and you may have some very valid complaints.  Have you tried talking with the PM one-on-one about your concerns?


答:
My question is, would it be technically possible to have a statically-typed alternative to JavaScript for client-side web page augmentation etc.?

Sure. The Google Web Toolkit compiles statically-typed Java to JavaScript... Just think of it: all the beauty and flexibility of Java, with all the performance of machine-generated JavaScript!

Seriously though, you could do this for all sorts of languages, and many have tried (there are, or have been, compilers for C and C# as well). Whether the end result is practical or not depends on what you're trying to accomplish: Google's after a consistent platform for developing very large client-side apps, and has their own JavaScript engine to boot; you may well find that adopting such a beast for hover-effects and the odd AJAX call introduces far more pain than simply learning to live with a bit of untyped code...


问:
Why aren't databases integrated as a language feature?
Are there any programming languages that have a built-in database as a first-class language feature rather than connecting to an external SQL (or other) database? What would be the drawbacks and benefits to such a feature? What would such a feature look like and how would it change the way we program?</p>

答:
As written, the question is partly wrong, as some counterexamples above have shown.

So I'd first refine the question to read, "Why is a DBMS usually not integrated as a feature of a general-purpose, high-level programming languages?"

This is for the same reason that other software products such as operating systems, file systems, web servers, caching layers, etc. are usually not built-in. General purpose languages generally operate at a level of abstraction above that of such products . So it's reasonable for a programmer to implement a DBMS in a general-purpose language, and that DBMS might even expose aspects of its parent language or a DB-specific, declarative language for use by DB programmers. But there are too many design options in writing a DBMS for it to be wise to fix them in a general-purpose programming language. If you do fix them, you wind up with a case like MUMPS, where the entanglement of the two results in an entire industry mired in a chicken-and-egg problem, stuck with an obsolete DBMS and an obsolete programming language.


答:
The complexity and the amount of the SQL I write is not sufficient to make hooking an ORM framework in reasonable.

(I write SQL maybe once per month, if)

Title: Is there still a need for writing SQL?


答: About 12 years ago when I was in college I worked on a data modelling application for Windows.  The project was nearly complete after about 60,000 lines of Win32 code, you know, code targeting the Windows platform.  Then the client said the application also needs to run "on the web".  She had a hard time understanding how this one "minor little" requirements change could have such a big impact on the project.  I started over from scratch in Java but ended up quiting the project before it was ever finished.</p>

Title: What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?

Body:
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.


答:
It exists already.

ActionScript 3 (the scripting language behind Flash and Flex) is a dialect of ECMAScript that implements strong types, and you can use it in more or less the same client-side way as JavaScript (the difference being that AS3 requires a flash plugin, and is compiled). I personally try to steer away from it these days, but if you're in the "static" camp, give it a whirl.

That answers the principal question, and now that we have that, your secondary question becomes "Is Flash practical?" The answer is "yes", with a few "if"s and "but"s

...if you need to hide your code for whatever reason.

...if you want a very, very (past jQuery level) high level of interactivity

...but even without HTML5, the cross-browser compatibilities are getting much better lately.

...but HTML5 is coming soon.

...but one of the big draws of static typing/compilation (as opposed to interpretation) is the added speed it allows through optimizations (and Flash doesn't really have very good speed, despite the type system)


答:
At my last job, I never had a single day off work (whether sick, or booked annual leave) without a phonecall to fix something.

You get sick of that.

Title: How do you respond to a request for 'emergency contact information' for when you are on vacation?

Body: I want to go on vacation and not think about work at all but they want me to provide them a contact number in the event of an emergency (server goes down, web service malfunctions, etc). I am afraid that it will be abused (they will contact me before trying everything for example) but I also think that if I am on vacation I should not be bothered even if there is an outage. Does anyone have experience with situations like this? What's the tactful approach? Any creative solutions?</p>


答:
"I don't like the way this Oracle database works.  Why don't we just write our own database?"

(Admittedly, this was over 15 years ago, but still!)


答:
Enough commiserating...

How fortunate you are that you are so vital to the continued success of your organization. They need your contact info because what you do might as well be black magic or voodoo to them, and they are totally afraid that if they can't get to you in the case of an emergency, that everything will come crashing down around their ears..

I won't lie, I originally got into this business solely for the money, and then realized how much I loved it. My first employer in systems realized how much I loved it, and exploited my work ethic for as long as they could. Until of course my quality of life became so bad, that I had to force myself to drive to work every day. Vacations? Bah! No one could take care of the system as well as I could myself! Needless to say, that didn't last very long.

This may be a bitter pill to swallow, but what has worked for me in the past is to train a backup. Depending on where you work, and the kind of people that you work with, that perfect vacation covering helper maybe right around the corner.

At one place where I was a sys admin for several years, I was usually working 10-12 hour days EVERY day because I didn't have backup helper. When I finally gave in and found someone, I was shocked that they were excited to do all of those mundane tasks that I didn't have time to automate. Every single one of those tasks that I thought 'why would anyone that is non-technical want to do this?', they took care of, and asked for more. You probably won't even have to give them any money for it, they will probably do it for the thrill of being needed. Or better yet, probably for just a referral for some other job they really want.

Start hinting around the office that you want to train someone to be able to help you out. A good place to start is usually the head administrative assistant, or an HR manager. Tell them that you want to try to help someone out and 'see if they can rise to the occasion', and that you want to make sure that if anything happens to you that there is a contingency in place. HR people and administrative assistants eat that stuff up, they might even have someone already in mind.

Good luck, your sanity isn't worth a paycheck. It's up to you to have the strength to create the work environment where you can take a vacation when you want, and not have to worry about getting called.


答:
Sorry, but sometimes you just gotta deal with it.  Get on the PM's good side.  Sometimes no matter what your position you just simply ain't gonna like for whom you're doing work.

I can almost guarantee you the PM has a limited budget, has been given a horribly inadequate budget to begin-with, or has a fixed # of hours that he has to meet and for which his job and his pay is accountable.  I would also bet that management like that comes down from his management chain, doubtful the PM likes to be tracking things to that level either, in fact they're probably being micromanaged to an even finer degree.


答: I give them what they want.</p>

Body: I give them what they want.


答:
Got a task that reduced down to the Halting Problem. I had just finished a Ph.D. in Recursion Theory. So funny!

We settled for a (cheesy) approximation.

Stephan


问:
How do you explain the source of an identifed problem without making it an "excuse"?
As practicing (as much as I can at least) "egoless programming", I'm focused on solving problems whoever wrote the code related (if that person don't make dangerous code) and I like to understand the problem fully to be sure to solve the source of this problem.

However, when someone point my code to show an error, I often try to remember what was my mindset while writing the defect code and I try to explain it to the guy pointing the error to make clear what was the error source (for example when some names are badly choosen, you might use them in a way they were not intended too and with apparent success...).

Now, I do this by reflex and most of my coworkers does understand this reflex. But I also worked in companies where coworkers were in a mentality of blaming the people that made the identified problems, with or without humour (for me it have the same not-sane effect anyway).

In this kind of environnement, explaining why you got to write wrong code makes others think that you're trying to build an excuse. I remarked that most non-technical people (or non domain-expert, not sure, it's only personal experience) also react exactly like that when you try to explain why you did something wrong.

So, when dealing with this kind of people/environnement, how do you manage to explain the real source of the error without looking like "making an excuse"? (and is it even worth trying to explain?)

答:
These kinds of misunderstandings are common between pragmatists and idealists. The pragmatists just think, “something went wrong... who can we blame?” The idealists are already trying to figure out how to prevent that thing from going wrong ever again.

Ashton got into San Francisco in the afternoon. He took a SuperShuttle to Fisherman’s Wharf and, famished, went into a restaurant and ordered a big stack of pancakes.

That’s when the implications of abandoning his former life in Michigan really started to sink in. He had no job, no place to sleep, his car was gone, he owed $40,000 in student loans, and had exactly $173 in his wallet.

But goll-ee, they sure do have pretty waitresses in San Francisco, he thought, admiring the strawberry curls of the Molly Ringwald-lookalike standing by the front cash register. A little over five feet tall, maybe. Crazy freckles.

While Ashton stared at her from across the deserted restaurant, a couple of well dressed boys came in and started talking to her. Tourists, maybe, or students? Were there any schools around here? There must be schools in San Francisco. He couldn’t hear what they were saying, but it seemed a little bit more complicated than “can we have a table and buy some pancakes please.”

“Molly” got out her purse and rummaged around. She gave the kids some money. The conversation continued. She tried to make a phone call; nobody answers. Eventually she opened the cash register and counted out rather a lot of money, which she gave to them.

“That’s weird,” Ashton thought, but he paid the check, and went across the street to an Internet cafe to look for an apartment on Craigslist.

The first thing that hit him was that the prices for apartments were insane. Back in Michigan, he was paying $475 for a really nice one bedroom, but in San Francisco, things seemed to be triple that. Without a job, he wasn’t even sure if anyone would rent to him. While he was pondering this problem, he noticed the waitress from the pancake place come out, clearly distraught. She sat down at a bus stop and started crying.

Now, the old Ashton would never, never just go up to a random girl on the street, least of all one who was crying, but the magical spell of San Francisco somehow made him lose his inhibitions, so he bought two cups of peppermint tea, went to the bus stop, sat down next to her, and said, “I seem to have an extra cup of peppermint tea. Would you like it?”

The girl looked at him, perplexed, and then laughed a little bit.

“I’m sorry,” Ashton said. “I don’t usually do this. I saw you working in the IHOP, and then when I saw you out here.... Oh. I’m Ashton, by the way. With an N.”

“I’m Becca,” she said. “With an M.”

Ashton said, “The M is silent, I assume?” They laugh a little bit. Becca sniffs. Ashton finds a handkerchief in his coat pocket, a vestige of living in a really cold climate.

They start talking. It turns out Becca just got fired.

“That stupid old man. He wouldn’t listen to me! I took some money out of the register to bail out his own son, but he didn’t want to hear about it. He just assumed I stole it.”

“What?”

“Well, these kids came into the restaurant, they were schoolmates of Daryl, Mr. Dimitrious’s son.”

“That’s the owner?”

“Right. Anyway these kids seemed nice, they said that some drug dealers got pissed off at Daryl for some reason and they needed $200 to rescue him.”

“Rescue him from what? I don’t get it. How does that work?” Ashton asked. It didn’t sound like a real story. But maybe this was how things worked in California.

“I gave them $40 of my own, but they were very insistent that if they didn’t come up with $200, Daryl would be hurt. I couldn’t reach Mr. Dimitrious by phone, and I was scared, so I took $160 out of the register and gave it to them. But when I tried to explain that to him, he just flipped out and wouldn’t listen to me. I was trying to tell him that Daryl was in trouble, and all he wanted to talk about was that I was stealing from him. How could he fire me for trying to help his own son? What is wrong with that man?”

Ashton was pretty sure Becca had just gotten scammed, but he couldn’t quite bring himself to break it to her. And even though she was visibly upset, he was really enjoying talking to her, so he dragged the conversation on. He started blabbing about how, when he was working at the furniture company in Michigan, everyone had to take a course called “Five Whys.” The idea was that every time something went wrong, you had to ask why to get the immediate cause. Then you asked why again, to figure out what caused that, and you kept doing that, about five times, until you found the root problem.

“So, for example, you got fired. Why? Because money was missing from the cash register. Why? Because you gave it to some kids. Why? Because they told you Daryl was in trouble. Why?”

“Wait, why what?” Becca asked.

“Why did they tell you Daryl was in trouble?”

Becca thought for a minute.

“I got scammed, didn’t I.”

“I think maybe you did.”

Becca was silent for a really, really long time. Then she started laughing, and it infected Ashton, and they were both laughing like crazy, and it felt great, after a stressful day.

“You’re a total nerd,” she said. “Five whys.” He had to concur.

They were having a good time. They walked all over the North End, and they talked for hours.
He told her about being a programmer, and the furniture company, and how, in two years, not a single thing he did at work mattered, and he was sick of it, and starting a new life, and here he was, without a place to stay, on a winter night in San Francisco.

“Oh gosh,” Becca said, “I know just the place. I’m living in a big shared house in Russian Hill. There’s an empty room now.”

“Where’s Russian Hill?” Ashton asked.

“It’s not far. I’ll take you. But wait... would you mind waiting so I can go try one more time to get my job back?”

Ashton was happier than he had been all day. Things really do have a way of working out.

“Sure!” he said, almost giddy. “Just a sec.” And he took out $160 from his wallet, leaving exactly three dollars, and he gave it to Becca, and said, “Take this, it might help you get your job back.”

“Oh I couldn’t!” she said, but Ashton insisted, and they agreed to meet in half an hour at the Steps of Rome on Columbus Ave., where Ashton went to sit and nursed a single cup of espresso while Becca walked back towards the restaurant.

And it got kind of late.

And an hour passed, then another, and the Italian waiter obviously had a crush on Ashton, so he didn’t bother him about just ordering one coffee and sitting at the table for hours, and it’s midnight, then it’s one a.m., then it’s two a.m., and the waiter finally says, “Look, I’m sorry guy, we’re closing, you have to leave.”


答:
Most of the times errors are there, because programmer forget to consider all the cases. Sometimes you write the code keeping one scenario in mind and then the other scenario failed. In this case if one asks your answer should be "That case was not considered. Let me correct it, and we will document that whoever is touching this part of the code should code according to this case also".

Normally making mistakes are not the issues, but repeating them is problem. Hence when someone shows you the mistake you should say, "Thanks for finding that out. I will correct it, and mention it in the coding guideline."

But if someone is continuously finding the stupid errors and if that bothers you, then every time you change the code, go to that person and tell him to check the code for errors. Some day he/she will get frustrated and stop it.

Title: How do you explain the source of an identifed problem without making it an "excuse"?

Body:
As practicing (as much as I can at least) "egoless programming", I'm focused on solving problems whoever wrote the code related (if that person don't make dangerous code) and I like to understand the problem fully to be sure to solve the source of this problem.

However, when someone point my code to show an error, I often try to remember what was my mindset while writing the defect code and I try to explain it to the guy pointing the error to make clear what was the error source (for example when some names are badly choosen, you might use them in a way they were not intended too and with apparent success...).

Now, I do this by reflex and most of my coworkers does understand this reflex. But I also worked in companies where coworkers were in a mentality of blaming the people that made the identified problems, with or without humour (for me it have the same not-sane effect anyway).

In this kind of environnement, explaining why you got to write wrong code makes others think that you're trying to build an excuse. I remarked that most non-technical people (or non domain-expert, not sure, it's only personal experience) also react exactly like that when you try to explain why you did something wrong.

So, when dealing with this kind of people/environnement, how do you manage to explain the real source of the error without looking like "making an excuse"? (and is it even worth trying to explain?)


答:
The concept of a Holiday is to NOT have to worry for that week your off!

Though centuries ago vacations could last for months, in todays rushed up digital society vacations last only one or two weeks. Comon!!! Everything needs urgent fix. Yeah right! tell that to the hotel lady who is now massaging you and asking wether you prefer Mango or Cranberries baby!!

Only take the responsibility, if its your own private service/company, then i can image you bring your cellular phone with you. Otherwise let the owner/boss worry and take the risk of their own service!

Bon Voyage!


答:
Few links for JS mastery

What "Hidden Features" of JavaScript do you think every programmer should know?

Advanced JavaScript Interview Questions

Best resources to learn JavaScript - Douglas Crockford's JavaScript videos

What questions should a JavaScript programmer be able to answer?

Learning Advanced JavaScript

6 Advanced JavaScript Techniques You Should Know

Title: What is the path to JavaScript mastery?

Body:
I know how we start with JavaScript, we cut-and-paste a snippit to gain a little client-side functionality or validation.

But if you follow this path in trying to implement rich interactive behavior, it doesn't take long before you realize that you are creating a Big Ball Of Mud.

So what is the path towards expertise in programming the interaction layer?  What books, tutorials, exercises, and processes contribute towards the ability to program robust, maintainable JavaScript?

We all know that practice is important in any endeavor, but I'm looking for a path similar to the answer here: https://stackoverflow.com/questions/2573135/


答:
When you go to the garage, you don't tell the guy:

"please change the oil, the filters. And check the a/c system, it makes some strange noise. In addition of that do a wheel alignment check and automatic transmission flush. You have 1.23 hours and I'll pay you $97"

You ask him how much time he will need, and how much he will asks. Even if your are a specialist yourself knowing how much time he should take, and how much he should charge.

If you doesn't agree with the time he needs and/or the amount he charges, you go to another garage right?

That's pretty much the same here. Your worker, the specialist, the one that will do the task, should estimate it himself.

At a team level, team should be responsible of it. To avoid too much variation in estimations between team members, a consensus based estimation methodology should be used like Planning Poker.

Now how to deal with your current manager?

Unless you are able to convince him using the argument above just by telling him, you will have to work with it. Very few managers are able to "change" on the impulsion of their people so fast. Most of them will never change.

Each time you are assigned with tasks along with his estimations send him your figures back politely.

Use evidence of your allegations by pointing past experience on tasks that takes more time than initially planned.

You will have to repeat the cycle above a lot of time

You will need patience, determination and courage. Ivan Pavlov is your friend here.

Eventually, he will change his mind and adopt the system described above.

But your manager is probably a parkinsonian. In that case, call Ashton, and ask him for advices. Because he is probably not going to change.

Don't worry for him after you left, he will find another developer to abuse.


问:
Will Java still be relevant in 5 years?
Will Java have the same importance it had in the past, or it will be less relevant than nowadays?</p>

答: I would say it's on a decline.  It's not gone, but it's past its peak.</p>

Title: Will Java still be relevant in 5 years?


答:
Client: We've been using your database software for a couple of years, developing our own applications with it, and calling you from time to time for help.

Me: Yes, we appreciate doing business with you.

Client: Yeah.  Every time we call, you tell us how to use a new feature, or you help us debug our usage, or provide a workaround for some issue.

Me:  Sure, we're always happy to be of assistance.

Client: Occasionally, your product has an actual bug in it, and your company fixes it and gives us a software update.

Me:  We do our best.

Client:  Well, what we need from you now is some assurance that we won't have any more issues.

Me: . . .


答: Find a job where they will not abuse the emergency contact and let you relax on your holidays. If you are the only one person, who can help them, something is wrong. </p>


问:
What is the proper relationship between the software developer and the business customer?
IT professionals are experts who are trusted with the IT assets of a business or organisation. As trusted professionals we have responsibilities that extend beyond things that a non-IT customer can be expected to understand or be aware of. So I think the proper relationship between an IT professional and his internal/external customers is more like that between a doctor and patient than a servant and master. Am I right?

Here's an analogy to think about. A patient insists that his leg needs to be amputated. His doctor disagrees but the patient cannot be persuaded. Should the doctor amputate the leg just to satisfy the patient?

Another analogy. A customer wants a civil engineer to build a bridge to an unsafe design. Even when the engineer explains that it is unsafe the customer doesn't believe him. Should the engineer build the bridge anyway?

I think the right answer in both these analogies is NO. The medical professional and engineering professional are supposed to be in a position of trust and ought to exercise their own judgement, even in the face of patient/customer disapproval. Shouldn't the same apply to IT professionals when the IT professional is qualified to make the decision but his customer is not?

答:
It's a bit more complicated than in your examples. That's because in many cases, the software developer is an expert in IT-related things (i.e. programming, database design etc.), but the business customer is an expert in the problem domain. In such cases, the proper relationship is that of two experts in different fields that work together to create a good solution.

Anyway, like any good craftsman, the software developer is obliged to warn the customer when the customers wants things that are inappropriate. If you ask your painter and decorator to wallpaper the bathroom, he is also obliged to warn you that this won't work out well. But when the client stubbornly insist on his bad idea, it's ok to have him sign a "you have been explicitely warned" form and implement what he wants (as long as there is no health risk, legal risk etc. in doing that).


答:
Shouldn't the same apply to IT professionals when the IT professional is qualified to make the decision but his customer is not?

In my opinion YES!

If you are going to have a long relationship with your customer.

Title: What is the proper relationship between the software developer and the business customer?

Body:
IT professionals are experts who are trusted with the IT assets of a business or organisation. As trusted professionals we have responsibilities that extend beyond things that a non-IT customer can be expected to understand or be aware of. So I think the proper relationship between an IT professional and his internal/external customers is more like that between a doctor and patient than a servant and master. Am I right?

Here's an analogy to think about. A patient insists that his leg needs to be amputated. His doctor disagrees but the patient cannot be persuaded. Should the doctor amputate the leg just to satisfy the patient?

Another analogy. A customer wants a civil engineer to build a bridge to an unsafe design. Even when the engineer explains that it is unsafe the customer doesn't believe him. Should the engineer build the bridge anyway?

I think the right answer in both these analogies is NO. The medical professional and engineering professional are supposed to be in a position of trust and ought to exercise their own judgement, even in the face of patient/customer disapproval. Shouldn't the same apply to IT professionals when the IT professional is qualified to make the decision but his customer is not?


答:
In both the doctor and engineer examples, the professional is a consultant refusing to perform a service. In an IT shop, you're not.

We're employees, not consultants, so we're subject to the golden rule: he who gives us gold rules. Programmers who ignore that are being arrogant and foolish. I've heard innumerable complaints about that from businesspeople who are fed up with IT staff who won't explain their decisions to anyone outside their insular priesthood, and who blow off requests everybody outside their organization considers perfectly reasonable. I've seen IT managers sacked over that kind of thing.

As an employee, your equivalent to a consultant refusing to perform a service is covered by a quote from Napoleon Bonaparte:

Every commander responsible for
  executing a plan that he considers bad
  or disastrous is criminal. He must
  point out the flaws, insist that it be
  changed and at last resort resign
  rather than be the instrument of the
  destruction of his own men.

You have to pick your battles. Is what you've been asked to do so heinous and unethical that you'd rather quit? If not, then either explain the problem to the stakeholders and negotiate something reasonable, or just do it.

And don't go doing things you haven't gotten buy-off on. People who do that are called "loose cannons".

Incidentally, I have quit one job because they killed a project and I thought it was a really stupid move. A couple of months after I left, they came to agree with me, and asked me to come back as a contractor to do the project, but I was already committed elsewhere.


答: My suggestion in this situation will be to warn the customer in written communication and keep copy of it (e-mail, agreement anything). If the customer insists it then go ahead and do it (This is sometimes known as disagreement and commit). Just make sure that if any bad thing happens, you should be properly able to defend yourself. </p>


答:
I used to be that guy... The one who the business absolutely needs to have access to, and I used to enjoy it.

But now, my response would be:

Give them the number for your insurance company. Since an emergency of the magnitude required to bother you on vacation, should probably require submitting a claim to the insurance company anway. And maybe a call to the official emergency services (fire/police/ambulance) as well.

Thats right, something better be burning or somebody died, before they interrupt your vacation.

Sombody's worried about the information only you have? They should prepare for that before you go on vacation. And make darn sure they show their appreciation - and start by not bugging you on vacation.


答:
Doctors take an oath to 'do no harm' and are legally required to put the best interest of the patient first. A doctor that performed a needless and harmful operation (even if the patient demanded it) would be opening himself up to a malpractice suit and could lose his license.

Similarly, a civil engineer, that is responsible for a construction project, has a legal obligation to ensure that it meets all applicable building codes. As with the doctor, an engineer that does what is suggested in the question, would likely face legal action.

This is very different from the situation of a software developer being asked to do something that they know is impractical. There are no legal ramifications to taking on a project, even if you know it is essentially a waste of money.

That said, a software developer should always provide his best advice on any project. However, if the people paying the bills are unwilling to listen and insist on an unwise course of action, the developer has no moral or legal obligation to refuse.


答:
Why not define backup staff that takes over your part when you are on vacation? Then, announce that only the backup people are allowed to call you. This means everybody has to "mess around" with the resources they have before doing that annoying call.

Secondly, I think a phone is a horrible medium for things like that. Be lazy answering calls, but take 5 minutes every day to check and reply to emails, and you will see the quality of the requests skyrock immediately (because a written mail forces the sender to re-think the situation in order to specify it in written form, and because they see they get replies as time allows).

If you crash with your car, and are dead, nobody will reach you on the phone. That's why every organization should have backup staff members that can take over the job of other key players. It's not just the holiday question.

Note that many people running from vacation phone calls LOVE being important. They are not really annoyed, they love being sought after, and they often do their part to manifest this bug as a feature in their career. This is unsincere because when they say "don't call me, I am on vacation" they really say "I love being rare, and I improve that state all the time, because that enables me to be annoyed, and I love that too because it shows how important, and ruling I am!". Bah. The fact that it is rather easy to find backup people for 99% of even the most insane job's tasks underscores this...most "heroes" prefer to whine and run instead of building and living a backup solution.


答:
If you feel that it's your company then give your phone number and say when they can call you - what kind of problems you can solve on holidays an what not.
If you feel that you just work for someone just give phone number, and turn it off. Because you need get better job.</p>


问:
Is it possible to protect client side algorithms 100%?
If you had a pretty novel idea that involved a new algorithm. Like lets say you were the first person to think of orbitz.com or kayak.com (travel sites) and you were able to and wanted to implement all of the novel algorithm clientside in javascript. </p>

<p>Is it possible to obfuscate it 100% where you cant reverse engineer it like this reverse engineer javascript obfuscators  , or are developers still forced to keep sensitive algorithms server side if they want to completely protect them (or at least have a better chance of doing so)? </p>

答:
Client-side Javascript cannot be secured - ever.  If the browser can run it, that means that the Javascript instructions are 100% available to anyone who wants them.

You can compress and obscure the Javascript.  That is merely an obstacle that any talented developer can get around with some extra investment of time.  So, a novel algorithm cannot be protected in browser-based Javascript.

If you want an algorithm protected, it must reside on the server and be run there - delivering only results to the client, not delivering code to the client.