问:
What is a good way to represent a many-to-many relationship between two classes?
Let's say I have two object types, A and B. The relationship between them is many-to-many, but neither of them is the owner of the other.

Both A and B instances need to be aware of the connection; it's not just one way.

So, we can do this:

```<code>class A
{
    ...

    private: std::vector<B *> Bs;
}

class B
{
    private: std::vector<A *> As;
}
</code>```

My question is: where do I put the functions to create and destroy the connections?

Should it be A::Attach(B), which then updates A::Bs and B::As vectors?

Or should it be B::Attach(A), which seems equally reasonable.

Neither of those feels right. If I stop working with the code, and come back after a week, I'm sure I won't be able to recall if I should be doing A.Attach(B) or B.Attach(A).

Perhaps it should be a function like this:

```<code>CreateConnection(A, B);
</code>```

But making a global function seems undesirable also, given that it's a function specifically for working with only classes A and B.

Another question: if I run into this problem/requirement often, can I somehow make a general solution for it? Perhaps a TwoWayConnection class that I can derive from or use within classes that share this type of relationship?

What are some good ways to handle this situation... I know how to handle the one-to-many "C owns D" situation quite well, but this one is trickier.

Edit: Just to make it more explicit, this question doesn't involve ownership issues. Both A and B are owned by some other object Z, and Z takes care of all ownership issues. I'm only interested in how to create/remove the many-to-many links between A and B.

答:
One way is to add a public Attach() method and also a protected AttachWithoutReciprocating() method to each class. Make A and B mutual friends so that their Attach() methods can call the other's AttachWithoutReciprocating():

```<code>A::Attach(B &b) {
    Bs.push_back(&b);
    b.AttachWithoutReciprocating(*this);
}

A::AttachWithoutReciprocating(B &b) {
    Bs.push_back(&b);
}
</code>```

If you implement similar methods for B, you won't have to remember which class to call Attach() on.

I'm sure you could wrap that behavior up in a MutuallyAttachable class that both A and B inherit from, thus avoiding repeating yourself and scoring bonus points on Judgement Day. But even the unsophisticated implement-it-in-both-places approach will get the job done.

Body:
One way is to add a public Attach() method and also a protected AttachWithoutReciprocating() method to each class. Make A and B mutual friends so that their Attach() methods can call the other's AttachWithoutReciprocating():

A::Attach(B &b) {
    Bs.push_back(&b);
    b.AttachWithoutReciprocating(*this);
}

A::AttachWithoutReciprocating(B &b) {
    Bs.push_back(&b);
}

If you implement similar methods for B, you won't have to remember which class to call Attach() on.

I'm sure you could wrap that behavior up in a MutuallyAttachable class that both A and B inherit from, thus avoiding repeating yourself and scoring bonus points on Judgement Day. But even the unsophisticated implement-it-in-both-places approach will get the job done.


答:
If I were implementing this, I would put Attach in both A and B. Inside of the Attach method, I would then call Attach on the object passed in.  That way you can call either A.Attach(B) or B.Attach(A).  My syntax may not be correct, I haven't used c++ in years:

```<code>class A {
  private: std::vector<B *> Bs;

  void Attach (B* obj) {
    // Only add obj if it's not in the vector
    if (std::find(Bs.begin(), Bs.end(), obj) == Bs.end()) {
      //Add obj to the vector
      Bs.push_back(obj);

      // Attach this class to obj
      obj->Attach(this);
    }
  }
}

class B {
  private: std::vector<A *> As;

  void Attach (A* obj) {
    // Only add obj if it's not in the vector
    if (std::find(As.begin(), As.end(), obj) == As.end()) {
      //Add obj to the vector
      As.push_back(obj);

      // Attach this class to obj
      obj->Attach(this);
    }
  }
}
</code>```

An alternate method would be to create a 3rd class, C which manages a static list of A-B pairings.

ContentLicense: CC BY-SA 3.0

Title: What is a good way to represent a many-to-many relationship between two classes?

Body:
Let's say I have two object types, A and B. The relationship between them is many-to-many, but neither of them is the owner of the other.

Both A and B instances need to be aware of the connection; it's not just one way.

So, we can do this:

```<code>class A
{
    ...

    private: std::vector<B *> Bs;
}

class B
{
    private: std::vector<A *> As;
}
</code>```

My question is: where do I put the functions to create and destroy the connections?

Should it be A::Attach(B), which then updates A::Bs and B::As vectors?

Or should it be B::Attach(A), which seems equally reasonable.

Neither of those feels right. If I stop working with the code, and come back after a week, I'm sure I won't be able to recall if I should be doing A.Attach(B) or B.Attach(A).

Perhaps it should be a function like this:

```<code>CreateConnection(A, B);
</code>```

But making a global function seems undesirable also, given that it's a function specifically for working with only classes A and B.

Another question: if I run into this problem/requirement often, can I somehow make a general solution for it? Perhaps a TwoWayConnection class that I can derive from or use within classes that share this type of relationship?

What are some good ways to handle this situation... I know how to handle the one-to-many "C owns D" situation quite well, but this one is trickier.

Edit: Just to make it more explicit, this question doesn't involve ownership issues. Both A and B are owned by some other object Z, and Z takes care of all ownership issues. I'm only interested in how to create/remove the many-to-many links between A and B.

Body:
If I were implementing this, I would put Attach in both A and B. Inside of the Attach method, I would then call Attach on the object passed in.  That way you can call either A.Attach(B) or B.Attach(A).  My syntax may not be correct, I haven't used c++ in years:

class A {
  private: std::vector<B *> Bs;

  void Attach (B* obj) {
    // Only add obj if it's not in the vector
    if (std::find(Bs.begin(), Bs.end(), obj) == Bs.end()) {
      //Add obj to the vector
      Bs.push_back(obj);

      // Attach this class to obj
      obj->Attach(this);
    }
  }
}

class B {
  private: std::vector<A *> As;

  void Attach (A* obj) {
    // Only add obj if it's not in the vector
    if (std::find(As.begin(), As.end(), obj) == As.end()) {
      //Add obj to the vector
      As.push_back(obj);

      // Attach this class to obj
      obj->Attach(this);
    }
  }
}

An alternate method would be to create a 3rd class, C which manages a static list of A-B pairings.


问:
What is the algorithm to copy a region of one bitmap, into a region in another?
In my project (and I am sure many others), I need to copy a subset (R2) of one bitmap image (R1), into a region (R3) in another, where the destination region can be any size (stretching and scaling where necessary).

I am sure this is a solved problem but I cannot find any examples; what is the most straightforward algorithm for performing this operation? (Linear interpolation would be sufficient for filling in the pixels when the source is scaled upwards, if that is the quickest (computationally) method)

答:
Perhaps the mechanism you seek is the BitBlt algorithm?

Bit blit (also written BITBLT, BIT BLT, BitBLT, Bit BLT, Bit Blt etc., which stands for bit-level block transfer) is a computer graphics operation in which several bitmaps are combined into one using a raster operator.

The operation involves at least two bitmaps, a source and destination, possibly a third that is often called the "mask" and sometimes a fourth used to create a stencil. The pixels of each are combined bitwise according to the specified raster operation (ROP) and the result is then written to the destination. The ROP is essentially a boolean formula. The most obvious ROP overwrites the destination with the source. Other ROPs may involve AND, OR, XOR, and NOT operations...


答:
Is it possible for the relationship itself to have additional properties?

If so, then it should be a separate class.

If not, then any reciprocating list-management mechanism will suffice.


问:
How does a website latency simulator work
Sites like webpagetest allow users to enter a website url and a test location, to run a speed test on the site from multiple locations using real browsers. Can anyone give me a basic idea of how sites like this work? You also have plugin's like Aptimize latency simulator  or charles web debugging proxy app, that simulate the delay while accessing a site from different locations. I am assuming since these are plugin's these function in a different way.  How do these plugin's work ? </p>

答:
Webpagetest uses Dummynet for traffic shaping the connection (only the last mile though).  Dummynet was originally built for testing networking protocols and does an excellent job at constructing a virtual network that behaves like the real world and is pretty much the gold standard for traffic shaping (which includes latency injection, bandwidth tuning and pacet loss).  It was originally part of BSD but has since been ported to Linux and Windows and is also used by Apple for the Mac traffic shaping tool in XCode.

Dummynet works at the packet level and lets you construct arbitrary "pipes" for packets to go through (and you can even chain them together).  You assign each of those pipes a latency, bandwidth, packet loss and buffer size.  Packets are added to the pipes based on rules that you define (ipfw packet matching rules) and if a pipe's buffer is full the packet will get dropped (like with real-world routers).  At a regular interval (depends on kernel Hz setting but best if it is 1ms or faster), Dummynet checks each pipe to see is packets should come out (if they have been waiting long enough and if letting the packet out will stay under the configured bandwidth limit).

In the case of Webpagetest, 2 pipes are configured.  One for the outbound packets and one for the inbound packets with the appropriate bandwidth on each and the latency is split between them (25ms in each direction for the default 50ms DSL configuration).

It is important to only simulate the last-mile of the link because the network gets REALLY complicated beyond that unless all of your content comes from a single server (CDN's and 3rd-party content usually come from different paths).  Theoretically you could build a complete simulation in dummynet but it would be quite a hairy mess.

Plugins like Charles get as close as they can from the application-level.  They will generally use similar logic but apply it when writing the data to the TCP connection. Depending on how your browser makes connections to the plugin and how that plugin makes connections to the outside world the results may differ from what you would see from applying it at the packet level.  It's a reasonable approximation but I highly recommend using a packet-level simulator when possible.


答:
In order to resize an image properly (particularly, to reduce the size of an image), you need an interpolation filter scaled to the smaller of the source and destination sizes.

Unfortunately, if your destination buffer really is a bitmap, you have no way to store the grayscale pixels you will get from your filter.  The best you can do (short of extraordinary measures) is threshold the results at 50%, in order to get a binary pixel value to store in your output buffer.

In many cases, a quick & dirty program won't bother to try resizing an arbitrarily-scaled bitmap properly at all -- they will simply grab the source pixel closest to the interpolated target location, as you describe.  This is certainly fast, but it looks quite ugly, especially for size reduction (as your question suggests), or for dynamic stretching (animated or interactive).

However, if you're doing everything with bitmaps, maybe that particular kind of ugly could be useful for a bit of 8-bit cred...

Title: What is the algorithm to copy a region of one bitmap, into a region in another?

Body:
In my project (and I am sure many others), I need to copy a subset (R2) of one bitmap image (R1), into a region (R3) in another, where the destination region can be any size (stretching and scaling where necessary).

I am sure this is a solved problem but I cannot find any examples; what is the most straightforward algorithm for performing this operation? (Linear interpolation would be sufficient for filling in the pixels when the source is scaled upwards, if that is the quickest (computationally) method)


答:
Usually when I get into situations like this that feel awkward, but I can't quite tell why, it's because I'm trying to put something in the wrong class.  There's almost always a way to move some functionality out of class A and B to make things more clear.

One candidate for moving the association to is the code that creates the association in the first place.  Maybe instead of calling attach() it simply stores a list of std::pair.  If there are multiple places creating associations it can be abstracted out into one class.

Another candidate for a move is the object that owns the associated objects, Z in your case.

Another common candidate for moving the association to is the code that is frequently calling methods on A or B objects.  For example, instead of calling a->foo(), which internally does something with all associated B objects, it already knows the associations and calls a->foo(b) for each one.  Again, if multiple places call it, it can be abstracted into a single class.

Lots of times the objects that create, own, and use the association happen to be the same object.  That can make the refactoring very easy.

The last method is to derive the relationship from other relationships.  For example, brothers and sisters are a many-to-many relationship, but rather than keeping a list of sisters in the brother class and vice versa, you derive that relationship from the parental relationship.  The other advantage of this method is that it creates a single source of truth.  There's no possible way for a bug or runtime error to create a discrepancy between the brother, sister, and parent lists, because you only have the one list.

This kind of refactoring isn't a magic formula that works every time.  You still have to experiment until you find a good fit for each individual circumstance, but I've found it to work about 95% of the time.  The remaining times you just have to live with the awkwardness.

Body:
Usually when I get into situations like this that feel awkward, but I can't quite tell why, it's because I'm trying to put something in the wrong class.  There's almost always a way to move some functionality out of class A and B to make things more clear.

One candidate for moving the association to is the code that creates the association in the first place.  Maybe instead of calling attach() it simply stores a list of std::pair<A, B>.  If there are multiple places creating associations it can be abstracted out into one class.

Another candidate for a move is the object that owns the associated objects, Z in your case.

Another common candidate for moving the association to is the code that is frequently calling methods on A or B objects.  For example, instead of calling a->foo(), which internally does something with all associated B objects, it already knows the associations and calls a->foo(b) for each one.  Again, if multiple places call it, it can be abstracted into a single class.

Lots of times the objects that create, own, and use the association happen to be the same object.  That can make the refactoring very easy.

The last method is to derive the relationship from other relationships.  For example, brothers and sisters are a many-to-many relationship, but rather than keeping a list of sisters in the brother class and vice versa, you derive that relationship from the parental relationship.  The other advantage of this method is that it creates a single source of truth.  There's no possible way for a bug or runtime error to create a discrepancy between the brother, sister, and parent lists, because you only have the one list.

This kind of refactoring isn't a magic formula that works every time.  You still have to experiment until you find a good fit for each individual circumstance, but I've found it to work about 95% of the time.  The remaining times you just have to live with the awkwardness.


问:
If you were the manager of a team of 25 developers, how would you motivate them?
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.

答:
You mean, they're building "the next big thing" and they're not motivated already?

Get rid of 'em and find people who enjoy what they do.

ContentLicense: CC BY-SA 2.5


问:
Why is Global State so Evil?
Before we start this, let me say I'm well aware of the concepts of Abstraction and Dependency Injection. I don't need my eyes opened here.

Well, most of us say, (too) many times without really understanding, "Don't use global variables", or "Singletons are evil because they are global". But what really is so bad about the ominous global state?

Let's say I need a global configuration for my application, for instance system folder paths, or application-wide database credentials.

In that case, I don't see any good solution other than providing these settings in some sort of global space, which will be commonly available to the entire application.

I know it's bad to abuse it, but is the global space really THAT evil? And if it is, what good alternatives are there?

答:
Globals aren't that bad.  As stated in several other answers, the real problem with them is that what is, today, your global folder path may, tomorrow, be one of several, or even hundreds.  If you're writing a quick, one-off program, use globals if it's easier.  Generally, though, allowing for multiples even when you only think you need one is the way to go.  It's not pleasant to have to restructure a large complex program that suddenly needs to talk to two databases.

But they do not hurt reliability.  Any data referenced from many places in your program can cause problems if it changes unexpectedly.  Enumerators choke when the collection they're enumerating is changed in mid-enumeration.  Event queue events can play tricks on each other.  Threads can always wreak havok.  Anything that is not a local variable or unchangable field is a problem.  Globals are this sort of problem, but you're not going to fix that by making them non-global.

If you are about to write to a file and the folder path changes, the change and the write need to be synchronized.  (As one of a thousand things that could go wrong, say you grab the path, then that directory gets deleted, then the folder path is changed to a good directory, then you try and write to the deleted directory.)  The problem exists whether the folder path is global or is one of a thousand the program is currently using.

There is a real problem with fields that can be accessed by different events on a queue, different levels of recursion, or different threads.  To make it simple (and simplistic):  local variables are good and fields are bad.  But former globals are still going to be fields, so this (however critically important) issue does not apply to the Good or Evil status of Global fields.

Addition: Multithreading Problems:

(Note that you can have similar problems with an event queue or recursive calls, but multithreading is by far the worst.)  Consider the following code:

```<code>if (filePath != null)  text = filePath.getName();
</code>```

If filePath is a local variable or some kind of constant, your program is not going to fail when running because filePath is null.  The check always works.  No other thread can change its value.  Otherwise, there are no guarantees.  When I started writing multithreaded programs in Java, I got NullPointerExceptions on lines like this all the time.  Any other thread can change the value at any time, and they often do.  As several other answers point out, this creates serious problems for testing.  The above statement can work a billion times, getting it through extensive and comprehensive testing, then blow up once in production.  The users won't be able to reproduce the problem, and it won't happen again until they've convinced themselves they were seeing things and forgotten it.

Globals definitely have this problem, and if you can eliminate them completely or replace them with constants or local variables, that's a very good thing.  If you have stateless code running on a web server, you probably can.  Typically, all your multithreading problems can be taken on by the database.

But if your program has to remember things from one user action to the next, you will have fields accessable by any running threads.  Switching a global to such a non-global field will not help reliability.

Title: Why is Global State so Evil?

Body:
Globals aren't that bad.  As stated in several other answers, the real problem with them is that what is, today, your global folder path may, tomorrow, be one of several, or even hundreds.  If you're writing a quick, one-off program, use globals if it's easier.  Generally, though, allowing for multiples even when you only think you need one is the way to go.  It's not pleasant to have to restructure a large complex program that suddenly needs to talk to two databases.

But they do not hurt reliability.  Any data referenced from many places in your program can cause problems if it changes unexpectedly.  Enumerators choke when the collection they're enumerating is changed in mid-enumeration.  Event queue events can play tricks on each other.  Threads can always wreak havok.  Anything that is not a local variable or unchangable field is a problem.  Globals are this sort of problem, but you're not going to fix that by making them non-global.

If you are about to write to a file and the folder path changes, the change and the write need to be synchronized.  (As one of a thousand things that could go wrong, say you grab the path, then that directory gets deleted, then the folder path is changed to a good directory, then you try and write to the deleted directory.)  The problem exists whether the folder path is global or is one of a thousand the program is currently using.

There is a real problem with fields that can be accessed by different events on a queue, different levels of recursion, or different threads.  To make it simple (and simplistic):  local variables are good and fields are bad.  But former globals are still going to be fields, so this (however critically important) issue does not apply to the Good or Evil status of Global fields.

Addition: Multithreading Problems:

(Note that you can have similar problems with an event queue or recursive calls, but multithreading is by far the worst.)  Consider the following code:

if (filePath != null)  text = filePath.getName();

If filePath is a local variable or some kind of constant, your program is not going to fail when running because filePath is null.  The check always works.  No other thread can change its value.  Otherwise, there are no guarantees.  When I started writing multithreaded programs in Java, I got NullPointerExceptions on lines like this all the time.  Any other thread can change the value at any time, and they often do.  As several other answers point out, this creates serious problems for testing.  The above statement can work a billion times, getting it through extensive and comprehensive testing, then blow up once in production.  The users won't be able to reproduce the problem, and it won't happen again until they've convinced themselves they were seeing things and forgotten it.

Globals definitely have this problem, and if you can eliminate them completely or replace them with constants or local variables, that's a very good thing.  If you have stateless code running on a web server, you probably can.  Typically, all your multithreading problems can be taken on by the database.

But if your program has to remember things from one user action to the next, you will have fields accessable by any running threads.  Switching a global to such a non-global field will not help reliability.


问:
What does this software do when it says "white labeled routing"?
I am reading about a start-up company that works with online surveys:

Fulcrum is the world’s first complete project management suite to give
  clients the power to seamlessly integrate multiple suppliers, increase
  productivity and reduce costs.  Ranging from vertically integrated
  research firms to sample suppliers, clients who license Fulcrum enjoy
  increased efficiency and with minimal technology development costs.
  This simplified survey management platform boasts white-labeled
  routing and improved respondent experience all while giving clients
  exceptional control and sample quality.

I am a little confused about what's going on. What is " white-labeled routing" ?

OK, I found out a "panel" company is a surveying company.

答: The term "white label" generally refers to a product that allows the purchaser of the product to customize the product so that it looks like their own.  In this case, if Walter's Widgets buys the product, Walter's Widgets can likely add their own logos and send the surveys through their own servers so that a customer has no idea that Fulcrum (or any other third party) is involved in the process.  This would look a lot more professional than having your customers receive mail from some third party they've never heard of or being directed to a third-party site they're not familiar with.  And it generally gives the purchaser much more control over the user experience.</p>


答:
Along the lines of a White Label Product, it means that their software can sit behind the client's software and route it to another destination transparently--that is, making it look like it was the client's software that sent it.

Really, the makers of Fulcrum are saying that their clients can use their own proprietary front end or Fulcrum's front end, and nobody at the other end will be any the wiser.

Title: What does this software do when it says "white labeled routing"?

Body:
I am reading about a start-up company that works with online surveys:

Fulcrum is the world’s first complete project management suite to give
  clients the power to seamlessly integrate multiple suppliers, increase
  productivity and reduce costs.  Ranging from vertically integrated
  research firms to sample suppliers, clients who license Fulcrum enjoy
  increased efficiency and with minimal technology development costs.
  This simplified survey management platform boasts white-labeled
  routing and improved respondent experience all while giving clients
  exceptional control and sample quality.

I am a little confused about what's going on. What is " white-labeled routing" ?

OK, I found out a "panel" company is a surveying company.


问:
Is it wrong to use a boolean parameter to determine behavior?
I have seen a practice from time to time that "feels" wrong, but I can't quite articulate what is wrong about it. Or maybe it's just my prejudice. Here goes:

A developer defines a method with a boolean as one of its parameters, and that method calls another, and so on, and eventually that boolean is used, solely to determine whether or not to take a certain action. This might be used, for example, to allow the action only if the user has certain rights, or perhaps if we are (or aren't) in test mode or batch mode or live mode, or perhaps only when the system is in a certain state.

Well there is always another way to do it, whether by querying when it is time to take the action (rather than passing the parameter), or by having multiple versions of the method, or multiple implementations of the class, etc. My question isn't so much how to improve this, but rather whether or not it really is wrong (as I suspect), and if it is, what is wrong about it.

答:
I agree with all the concerns of using Boolean Parameters to not determine performance in order to ; improve, Readability, Reliability, lowering Complexity, Lowering risks from poor Encapsulation & Cohesion and lower Total Cost of Ownership with Maintainability.

I started designing hardware in the mid 70's which we now call SCADA (supervisory control and data acquisition) and these were fine tuned hardware with machine code in EPROM running macro remote controls and collecting high speed data.

The Logic is called Mealey & Moore  machines  which we call now Finite State Machines.  These also must be done in the same rules as above, unless it is a real time machine with a finite execution time and then shortcuts must be done to serve the purpose.

The data is synchronous but commands are asynchronous and the command logic follows memoryless Boolean logic but with sequential commands based on memory of previous, present and desired next state.  In order for that to function in the most efficient machine language (only 64kB), great care was taken to define every process in a heuristic IBM HIPO fashion. That sometimes meant passing Boolean variables and doing indexed branches.

But now with lots of memory and ease of OOK, Encapsulation is an essential ingredient today but a penalty when code was counted in bytes for real time and SCADA machine code..


问:
Python 3, replace in strings
I need to transliterate a Hebrew text. So wrote a little Python script, which reads-in the Hebrew text from a text file, globally replaces the Hebrew letters with Latin ones. Now I need to do some fine tuning (replace certain things in some position but not in other, so a global replace won't do). The trouble is the following: The read-in text is a string so I cannot replace individual string elements. So, what would be the best way to do it?</p>

答:
Convert your string into a list.   Either a list of letters or (if this works in your case) a list of words.  This is a basic approach but should work if your string is stored in writing order (rather than display order).</p>

```<code>text_as_list = list(text_as_string)
replace_letters(text_as_list)  # this is the bit you're implementing
text_as_string = "".join(text_as_list)
</code>```

Title: Python 3, replace in strings

Body:
Convert your string into a list.   Either a list of letters or (if this works in your case) a list of words.  This is a basic approach but should work if your string is stored in writing order (rather than display order).

text_as_list = list(text_as_string)
replace_letters(text_as_list)  # this is the bit you're implementing
text_as_string = "".join(text_as_list)


答: Generally the best way is to work on a grid in the destination and interpolate the source pixel. That way you are sure that there are no gaps or aliasing effects in the destination.</p>


问:
Open source code with no license... can I fork it?
Years ago somebody created a bunch of really awesome and popular scripts. But they were not updated for a long, now they no-longer work (target platform were updated, and some changes are needed).

He hasn't released it under any license.  I want to fix the bug (currently, many of the target users can't use it), and post it on GitHub, preferably under a public-domain style OSS license. I wonder what the legal ramifications might be?

I have sent an email to the author, but (let's say) he didn't reply to my email.

What we should do in the following this into 2 cases:

If the script is posted on a private website (without any source control).

If the script is posted on GitHub (without any licensing hints).

However, one can clearly see, that it seems open source - intended to be used/modified/whatever.

答:
You cannot put the code under a different license. This is not your call to make; the original author still holds all the rights for his code. Since he put the code online, you can assume with good reason that the original author allows fair use and modification, and if your e-mails are not answered, you'll have to act on this assumption.

Put your changes under an OSS license, but leave a note with all the information about the original author and the missing license information in the code file. Then fix and redistribute.

ContentLicense: CC BY-SA 4.0


答:
It is clearly open source

and

he hasn't released it under any license

conflict.  Just because you can see and even modify the source, doesn't mean it is open source.  You cannot take this work and just give it a license, as it is not your work and you have not been granted a license to do so.  You need the author apply a license to the work or make his intent clear in writing.

Insert "I am not a lawyer disclaimer" here.

Title: Open source code with no license... can I fork it?

Body:
Years ago somebody created a bunch of really awesome and popular scripts. But they were not updated for a long, now they no-longer work (target platform were updated, and some changes are needed).

He hasn't released it under any license.  I want to fix the bug (currently, many of the target users can't use it), and post it on GitHub, preferably under a public-domain style OSS license. I wonder what the legal ramifications might be?

I have sent an email to the author, but (let's say) he didn't reply to my email.

What we should do in the following this into 2 cases:

If the script is posted on a private website (without any source control).

If the script is posted on GitHub (without any licensing hints).

However, one can clearly see, that it seems open source - intended to be used/modified/whatever.


问:
How to handle repetitive code dealing with object properties?
Every so often I run into a situation where I need to map a set of properties from one object to another object of a different, unrelated class. The set of properties is large enough to make typing out the code by hand tedious. Anti-DRY principle code like this is the result:

```<code>if (objectOfType1.getPropertyA() != null){objectOfType2.setSimilarlyNamedPropertyA(someMethod(objectOfType1.getPropertyA()));}
if (objectOfType1.getPropertyB() != null){objectOfType2.setSimilarlyNamedPropertyB(someMethod(objectOfType1.getPropertyB()));}
...skipping some lines...
if (objectOfType1.getPropertyZ() != null){objectOfType2.setSimilarlyNamedPropertyZ(someMethod(objectOfType1.getPropertyZ()));}
</code>```

Writing and even looking at code like this is a huge pet peeve, but I feel like using an introspection library like BeanUtils to avoid having a couple of methods like this would irritate my coworkers.

I've taken to writing one-off scripts to generate code like this for me. How have other programmers addressed this problem?

Edit: Here's the code translated to use reflection/introspection. Sure it's DRY, but it might make an enemy out of the next programmer on the project, and I can be just as productive generating code like above with a script. That said, if this is more common than I suspect, please fill me in:

```<code>    //Is this really a common technique to use when there's a simpler method?
    String[] propertyNamePartsArr = {"A","B", ...skipping some parts..., "Z"};
    List<String> propertyNameParts = new ArrayList<String> (Arrays.asList(propertyNamePartsArr));

    for (String propertyNamePart : propertyNameParts) {
        try {
            Object originalValue = BeanUtils.getProperty(objectOfType1, "property" + propertyNamePart);
            if (originalValue != null) {
                BeanUtils.setProperty(objectOfType2, "similarlyNamedProperty" + propertyNamePart, someMethod(originalValue));
            }
        } catch (IllegalAccessException e) {
            handleIllegalAccessException(e);
        } catch (InvocationTargetException e) {
            handleInvocationTargetException(e);
        } catch (NoSuchMethodException e) {
            handleNoSuchMethodException(e);
        }
    }
</code>```

答:
You should be using Reflection.

In your particular case you should create a map between methods of Type1 to methods of Type2 (if they always have the same name even better). Then using reflection you'll call getPropertyA in one object of Type1 and call the setter to put the value on the other object of Type2. It's very straight forward and this is a classic case where you need to use things at the metadata level.


答:
Here's C-like pseudocode. You can figure how to handle the edge cases (e.g. clipping, mirroring, etc). I'll leave it to you to also figure out how to make this use integer or fixed point math if performance is an issue.

```<code>struct {
    bitmap bmp;
    float x, y, width, height;
} xfer_param;

scaled_xfer(xfer_param src, xfer_param det)
{
    float src_dx = dst.width / src.width;
    float src_dy = dst.height / src.height;
    float src_maxx = src.x + src.width;
    float src_maxy = src.y + src.height;
    float dst_maxx = dst.x + dst.width;
    float dst_maxy = dst.y + dst.height;
    float src_cury = src.y;

    for (float y = dst.y; y < dst_maxy; y++)
    {
        float src_curx = src.x;
        for (float x = dst.x; x < dst_maxx; x++)
        {
            // Point sampling - you can also impl as bilinear or other
            dst.bmp[x,y] = src.bmp[src_curx, src_cury];
            src_curx += src_dx;
        }

        src_cury += src_dy;
    }
}
</code>```

To do sub-pixel interpolation, you can sample the 4 pixels around the floating-point src_curx, src_cury, and take a weighted average. One of the highest quality methods is to effectively take a sample rectangle in the source image that corresponds to a single pixel in the dest image. Then you just average all the values in that and write the destination pixel. However, that rect will likely not fall on clean pixel boundaries, so you will want to take the clipped edge pixels and weight them accordingly.

Body:
Here's C-like pseudocode. You can figure how to handle the edge cases (e.g. clipping, mirroring, etc). I'll leave it to you to also figure out how to make this use integer or fixed point math if performance is an issue.

struct {
    bitmap bmp;
    float x, y, width, height;
} xfer_param;

scaled_xfer(xfer_param src, xfer_param det)
{
    float src_dx = dst.width / src.width;
    float src_dy = dst.height / src.height;
    float src_maxx = src.x + src.width;
    float src_maxy = src.y + src.height;
    float dst_maxx = dst.x + dst.width;
    float dst_maxy = dst.y + dst.height;
    float src_cury = src.y;

    for (float y = dst.y; y < dst_maxy; y++)
    {
        float src_curx = src.x;
        for (float x = dst.x; x < dst_maxx; x++)
        {
            // Point sampling - you can also impl as bilinear or other
            dst.bmp[x,y] = src.bmp[src_curx, src_cury];
            src_curx += src_dx;
        }

        src_cury += src_dy;
    }
}

To do sub-pixel interpolation, you can sample the 4 pixels around the floating-point src_curx, src_cury, and take a weighted average. One of the highest quality methods is to effectively take a sample rectangle in the source image that corresponds to a single pixel in the dest image. Then you just average all the values in that and write the destination pixel. However, that rect will likely not fall on clean pixel boundaries, so you will want to take the clipped edge pixels and weight them accordingly.


答:
Mutable global state is evil for many reasons:

Bugs from mutable global state - a lot of tricky bugs are caused by mutability. Bugs that can be caused by mutation from anywhere in the program are even tricker, as it's often hard to track down the exact cause

Poor testability - if you have mutable global state, you will need to configure it for any tests that you write. This makes testing harder (and people being people are therefore less likely to do it!). e.g. in the case of application-wide database credentials, what if one test needs to access a specific test database different from everything else?

Inflexibility - what if one part of the code requires one value in the global state, but another part requires another value (e.g. a temporary value during a transaction)? You suddenly have a nasty bit of refactoring on your hands

Function impurity - "pure" functions (i.e. ones where the result depends only on the input parameters and have no side effects) are much easier to reason about and compose to build larger programs. Functions that read or manipulate mutable global state are inherently impure.

Code comprehension - code behaviour that depends on a lot of mutable global variables is much trickier to understand - you need to understand the range of possible interactions with the global variable before you can reason about the behaviour of the code. In some situations, this problem can become intractable.

Concurrency issues - mutable global state typically requires some form of locking when used in a concurrent situation. This is very hard to get right (is a cause of bugs) and adds considerably more complexity to your code (hard/expensive to maintain).

Performance - multiple threads continually bashing on the same global state causes cache contention and will slow down your system overall.

Alternatives to mutable global state:

Function parameters - often overlooked, but parameterising your functions better is often the best way to avoid global state. It forces you to solve the important conceptual question: what information does this function require to do its job? Sometimes it makes sense to have a data structure called "Context" that can be passed down a chain of functions that wraps up all relevant information.

Dependency injection - same as for function parameters, just done a bit earlier (at object construction rather than function invocation). Be careful if your dependencies are mutable objects though, this can quickly cause the same problems as mutable global state.....

Immutable global state is mostly harmless - it is effectively a constant. But make sure that it really is a constant, and that you aren't going to be tempted to turn it into mutable global state at a later point!

Immutable singletons - pretty much the same as immutable global state, except that you can defer instantiation until they are needed. Useful for e.g. large fixed data structures that need expensive one-off pre-calculation. Mutable singletons are of course equivalent to mutable global state and are therefore evil :-)

Dynamic binding - only available in some langauges like Common Lisp/Clojure, but this effectively lets you bind a value within a controlled scope (typically on a thread-local basis) which does not affect other threads. To some extent this is a "safe" way of getting the same effect as a global variable, since you know that only the current thread of execution will be affected. This is particularly useful in the case where you have multiple threads each handling independent transactions, for example.

Title: Why is Global State so Evil?

Body:
Before we start this, let me say I'm well aware of the concepts of Abstraction and Dependency Injection. I don't need my eyes opened here.

Well, most of us say, (too) many times without really understanding, "Don't use global variables", or "Singletons are evil because they are global". But what really is so bad about the ominous global state?

Let's say I need a global configuration for my application, for instance system folder paths, or application-wide database credentials.

In that case, I don't see any good solution other than providing these settings in some sort of global space, which will be commonly available to the entire application.

I know it's bad to abuse it, but is the global space really THAT evil? And if it is, what good alternatives are there?


答:
The other problem curiously is that they make an application difficult to scale because thay are not "global" enough. The scope of a global variable is the process.

If you want to scale your application up by using multiple processes or by running on multiple servers you cannot. At least not until you factor out all the globals and replace them with some other mechanism.

Title: Why is Global State so Evil?


问:
When should you use a document vs relational vs graph database?
For the purposes of discussion let's consider a FourSquare scenario.

Scenario

Entities:

Users

Places

Relationships:

Checkins: users <-> places, many to many

Friends: users <-> users, many to many

Database Design

These will most likely have errors, please point them out.

RDBMS

Tables:

Users

Places

Checkins (junction)

Friends (junction)

Pros:

CAP: consistency, availability

Cons:

CAP: partition tolerance, aka sharding

schemes = inflexible structure

poor replication?

Graph

Objects:

Users

Places

Edges:

Friends: User <-> User

Checkins: User -> Places

contains timestamp

Pros:

CAP: consistency, availability?

schemaless, easily mutable objects and edges

graph traversal queries, for example:

clustering

finding groups of friends

finding restaurants liked by similar people

any other common / useful queries?

Cons:

CAP: partition tolerance?

Document / Object

3 separate databases?

Users

friends list

Checkins

timestamp

user

place

Places

Pros:

CAP: availability, partition tolerance

schemaless, easily mutable objects

Cons:

CAP: consistency

Questions

For the record, they ended up using MongoDB. In addition to all those question marks above:

I'm not sure how to implement a document database.

How do document databases gain partition tolerance?

To get a single user's checkins, I assume the operation would parse all checkins and filter the metadata for username (map + filter). The performance of parsing 1,000,000+ documents for each user would be terribly poor. I assume this is not the correct behavior?

What other pro / cons are there?

答:
Your question could be the topic of a semester-long college course.  You need to break it down into manageable chunks.  As such, I will just throw out some partial answers.

One of the first things to look at in deciding which kind of database to use is what kind of queries you will run and whether you will know them all in advance of creating the database.  SQL databases have the advantage of powerful and flexible queries across all the data in the database.  Graph databases have highly specialized query capabilities that make them the best for graph data and really bad for non-graph data (though graph databases can be components in SQL databases).  NoSQL databases are much more limited in their ability to retrieve and operate on data.

The next is how you feel about the ACID properties: Atomicity, Consistency, Isolation, and Durability.  SQL databases provide strong guarantees about all 4. NoSQL databases typically do not promise all 4, and the ways they depart are among the key differences that differentiate the various NoSQL database implementations.  On the other hand, it is not possible to guarantee Consistency and Availability in the face of a Partition (see Brewer's CAP thorem), so no SQL database will do if you insist on full Availability in the face of a Partition.  Personally, I care a lot about Durability of the data in the database, as I typically work with data where even a 0.0001% data loss is unacceptable, and the data sets are small enough that I do not need to worry about partitions, so I heavily favor SQL databases.

Another very practical consideration is the quality of the server code, the availability of database administrators and programmers, the quality of the support available for problems that arise, the quality and availability of interface libraries to connect your application to the database, and so on.  MySQL has been around for almost 2 decades, has the vast majority of bugs worked out, is very widely used and so has both great support and great availability of personnel, and is likely to be supported for the next 10 years.   You cannot say any of those things about Riak.

Note that while Google practically invented NoSQL databases so they could store a cached and indexed version of the entire world wide web, they still use MySQL for some things.


问:
How do you deal with the anxiety of not knowing enough?
I just finished college a couple of months ago and I'm taking time out to improve my knowledge. I love programming but I feel like I don't know enough to be confident if I went for an interview. Last night I was browsing through questions and came across a question that asks interviewees how to work out a linked list. I learned these at college but if I was asked on the spot how to do it I wouldn't know. So that's another thing added to the list of what to learn.

This is when the anxiety hit me because I have so much to learn in so little time (at least it feels that way). Upon introspection, I think this anxiety is related to my perfectionism even though being perfect isn't rational e.g. Shakespeare and Einstein failed 80% of the time.

So the questions are, have you felt this anxiety of not knowing enough? If so, how did you deal with it? I suppose there's a point in time when you begin to feel comfortable in your abilities?

答:
It's not about knowing everything.  It's about knowing where to find the information.

I try to keep the core language I am using in memory.  The rest I am merely familiar with, so I use MSDN a lot to look up things.  Lately, I have been trying to get through the C# specification so that I can think more deeply about the language itself.

But I learn best by doing.  Which means ultimately I am doomed to re-implementing Linq to learn lambda expressions, and such.

As a programmer, I am capable of doing anything that the top developers can do.  It just takes me a little longer. :)


问:
How do programs like subversion detect when a file has been edited as opposed to created/deleted?
This is my first question here so I hope it is not off topic. Although I am using the Linux inotify library to listen for changes to files, and I compare use of that against the Subversion program, I am specifically looking for the algorithm used.

To a human it is very easy to tell if a file has been created or modified. Clicking the New button constitutes the former, and clicking the Save button constitutes the latter. To Linux, both those actions have serious overlap. In text editors, for example, generally a swap file is created and then copied/moved. This makes it difficult to distinguish via inotify between a minor edit to a file and a deliberate overwrite of a file. What I am trying to understand is how a program such as Subversion recognizes the difference between a user having modified a file with a text editor, and a user having actually deleted the file and opened a new file with the same name.

Edit:
It has been pointed out that subversion does not do what I want it to do, so it was a blunder on my part to use it as an example. Instead allow me to rephrase the question: "Is there any known program or programming approach to match high level actions such as creating new files and saving them to low level actions such as modifying, moving, copying, etc. such that I can log all the files in the system and changes to them"?

答: If you want to learn how subversion does to understand the working directory, you can look at the source pretty easily. As a longtime SVN user, I can pretty confidently say that SVN does not make any distinction at all to what happens to a file before the commit -- it just checks against what you are committing against the repository. Nothing more, nothing less.</p>


答: You could try contacting the original author and asking if he would let you use the code under some suitable license and then go from there.</p>


答:
Short answer: absolutely not.

Everything a person writes, whether it is software or text, is automatically under copyright.  The default state of any text is that it is completely owned by the author and no one has rights to do anything with it without express permission of the author.  A few decades ago, an author used to have to assert copyright in order to retain it, but this is no longer the case.

You can even see on sites like this legal text down there that states that I agree that this post I am typing is available under a certain license.  If that wasn't there, I'd retain all rights under the law.

Thus, if you cannot find any license information, then you cannot copy or modify it for any reason other than personal use.

Making something "open source" is a deliberate act and for you to treat it as such, you have to have found a license that tells you explicitly what your rights to the software are.  This is even true of "public domain" software.  That is, something is only "public domain" if it has either expired copyright (which mostly means it was written decades ago) or if the author has explicitly placed it in the public domain in writing.

In the case you describe, your only recourse is to contact the author and request that he allow you to do what you ask.  To do otherwise is flatly illegal and in theory could lead to damages.  (In practice, of course, you'd have to get caught.)

Edit: IANAL.  Talk to one if you intend to do this.


答:
When it's easy to see and access all of the global state, programmers invariably end up doing so.  What you get is unspoken and difficult to track dependencies (int blahblah means that array foo is valid in whatever).  Essentially it makes it nearly impossible to maintain program invariants since everything can be twiddled independently.  someInt has a relationship between otherInt, that's hard to manage and harder to prove if you can directly change either at any time.

That said, it can be done (way back when it was the only way in some systems), but those skills are lost.  They revolve mostly around coding and naming conventions- the field has moved on for good reason.  Your compiler and linker do a better job of checking invariants in protected/private data of classes/modules than relying on humans to follow a master plan and read source.

Title: Why is Global State so Evil?


问:
What are the roles of singletons, abstract classes and interfaces?
I am studying OOP in C++ and, even though I am aware of the definitions of these 3 concepts, I cannot really realize when or how to use it.

Let's use this class for the example:

```<code>class Person{
    private:
             string name;
             int age;
    public:
             Person(string p1, int p2){this->name=p1; this->age=p2;}
             ~Person(){}

             void set_name (string parameter){this->name=parameter;}
             void set_age (int parameter){this->age=parameter;}

             string get_name (){return this->name;}
             int get_age (){return this->age;}

             };
</code>```

1.Singleton

HOW does the restriction of the class to have only one object work?

CAN you design a class that would have ONLY 2 instances? Or maybe 3?

WHEN is using a singleton recommended/necessary? Is it good practice?

2.Abstract Class

As far as i know, if there's only one pure virtual function, the class becomes abstract.
So, adding

```<code>virtual void print ()=0;
</code>```

would do it, right?

WHY would you need a class whose object is not required?

3.Interface

If an interface is an abstract class in which all the methods are pure virtual functions, then

WHAT is the main difference between the 2 of them?

Thanks in advance!

答:
Interfaces

It's hard to understand the purpose of a tool that solves a problem that you've never had. I didn't understand interfaces for a while after I started programming. We'll I understood what they did, but I didn't know why you'd want to use one.

Here's the problem - you know what you want to do, but you have multiple ways to do it, or you may change how you do it later. It would be nice if you could play the role of the clueless manager - bark some orders and have the results you want without caring about how it's done.

Say you have a tiny little website, and you save all of your users' info in a csv file. Not the most sophisticated solution, but it works well enough to store your mom's user details. Later, your site takes off and you have 10,000 users. Maybe it's time to use a proper database.

If you were clever at first, you would have seen this coming and not made the calls to save to csv directly. Instead you'd think of what you needed it to do, no matter how it was implemented. Let's say store() and retrieve(). You make a Persister interface with abstract methods for store() and retrieve() and create a CsvPersister subclass that actually implements those methods.

Later, you can create a DbPersister that implements the actual storage and retrieval of data completely differently from how your csv class did it.

The great thing is, all you have to do now is change

```<code>Persister* prst = new CsvPersister();
</code>```

to

```<code>Persister* prst = new DbPersister();
</code>```

and then you're done. Your calls to prst.store() and prst.retrieve() will all still work, they're just handled differently "behind the scenes".

Now, you still had to create the cvs and db implementations, so you haven't experienced the luxury of being the boss yet. The real benefits are apparent when you're using interfaces that someone else created. If someone else was kind enough to create a CsvPersister() and DbPersister() already, then you just have to pick one and call the necessary methods. If you decide to use the other one later, or in another project, you already know how it works.

I'm really rusty on my C++, so I'll just use some generic programming examples. Containers are a great example of how interfaces make your life easier.

You can have Array, LinkedList, BinaryTree, etc. all subclasses of Container which has methods like insert(), find(), delete().

Now when adding something to the middle of a linked list, you don't even have to know what a linked list is. You just call myLinkedList->insert(4) and it magically iterates through the list and sticks it in there. Even if you know how a linked list works (which you really should), you don't have to look up its specific functions, because you probably already know what they are from using a different Container earlier.

Abstract Classes

Abstract classes are pretty similar to interfaces (well technically interfaces are abstract class, but here I mean base classes that have some of their methods fleshed out.

Say you're creating a game, and you need to detect when enemies are within striking distance of the player. You could create a base class Enemy that has a method inRange(). Although there are many things about the enemies that are different, the method used to check their range is consistent. Therefore your Enemy class will have a fleshed out method for checking range, but pure virtual methods for other things that share no similarities amongst the enemy types.

The nice thing about this is if you mess up the range detection code or want to tweak it, you only have to change it in one place.

Of course there are many other reasons for interfaces and abstract base classes, but those are some reasons why you might use them.

Singletons

I use them occasionally, and I've never been burned by them. That's not to say they won't ruin my life at some point, based on other peoples' experiences.

Here's a good discussion on global state from some more experienced and wary folks:
Why is Global State so Evil?

Body:
Interfaces

It's hard to understand the purpose of a tool that solves a problem that you've never had. I didn't understand interfaces for a while after I started programming. We'll I understood what they did, but I didn't know why you'd want to use one.

Here's the problem - you know what you want to do, but you have multiple ways to do it, or you may change how you do it later. It would be nice if you could play the role of the clueless manager - bark some orders and have the results you want without caring about how it's done.

Say you have a tiny little website, and you save all of your users' info in a csv file. Not the most sophisticated solution, but it works well enough to store your mom's user details. Later, your site takes off and you have 10,000 users. Maybe it's time to use a proper database.

If you were clever at first, you would have seen this coming and not made the calls to save to csv directly. Instead you'd think of what you needed it to do, no matter how it was implemented. Let's say store() and retrieve(). You make a Persister interface with abstract methods for store() and retrieve() and create a CsvPersister subclass that actually implements those methods.

Later, you can create a DbPersister that implements the actual storage and retrieval of data completely differently from how your csv class did it.

The great thing is, all you have to do now is change

Persister* prst = new CsvPersister();

to

Persister* prst = new DbPersister();

and then you're done. Your calls to prst.store() and prst.retrieve() will all still work, they're just handled differently "behind the scenes".

Now, you still had to create the cvs and db implementations, so you haven't experienced the luxury of being the boss yet. The real benefits are apparent when you're using interfaces that someone else created. If someone else was kind enough to create a CsvPersister() and DbPersister() already, then you just have to pick one and call the necessary methods. If you decide to use the other one later, or in another project, you already know how it works.

I'm really rusty on my C++, so I'll just use some generic programming examples. Containers are a great example of how interfaces make your life easier.

You can have Array, LinkedList, BinaryTree, etc. all subclasses of Container which has methods like insert(), find(), delete().

Now when adding something to the middle of a linked list, you don't even have to know what a linked list is. You just call myLinkedList->insert(4) and it magically iterates through the list and sticks it in there. Even if you know how a linked list works (which you really should), you don't have to look up its specific functions, because you probably already know what they are from using a different Container earlier.

Abstract Classes

Abstract classes are pretty similar to interfaces (well technically interfaces are abstract class, but here I mean base classes that have some of their methods fleshed out.

Say you're creating a game, and you need to detect when enemies are within striking distance of the player. You could create a base class Enemy that has a method inRange(). Although there are many things about the enemies that are different, the method used to check their range is consistent. Therefore your Enemy class will have a fleshed out method for checking range, but pure virtual methods for other things that share no similarities amongst the enemy types.

The nice thing about this is if you mess up the range detection code or want to tweak it, you only have to change it in one place.

Of course there are many other reasons for interfaces and abstract base classes, but those are some reasons why you might use them.

Singletons

I use them occasionally, and I've never been burned by them. That's not to say they won't ruin my life at some point, based on other peoples' experiences.

Here's a good discussion on global state from some more experienced and wary folks:
Why is Global State so Evil?


问:
Will the customer benefit from a DVCS in any way?
Some of us can say a Distributed Version Control System (e.g. Mercurial, git) will have a positive impact on developers only out of the experience of using one (under the right conditions: higher productivity, higher code-base stability, etc.), but, in what situations could a customer (i.e. the observer of the outcome of the software development lifecycle) tell there is a difference from using a CVCS and a DVCS?.

Anyone with empiric evidence of a customer "feeling" a difference upon DVCS adoption gets a big double-chocolate cookie with whipped cream and a cherry on top.

Note: "tell the difference" doesn't mean "know there was a DVCS involved" nor even remotely "know what a DVCS is"

答:
Absolutely.

A programmer who uses the best available tools will create a better end result. A DVCS is a very good tool with very real benefits.

Comparing DVCS to no source control at all is like comparing paint to mud. A painter who uses high quality paint on the walls of your house will do a much better job than a painter who uses mud.

Comparing DVCS to a non distributed VCS isn't quite as clear cut, more like comparing high quality paint to low quality paint... but the difference is still there.

If you use DVCS you will write code a little bit faster, and with slightly less bugs. How noticeable the effect is will depend on how complex your code is.

A programmer working by him/herself on a simple project will get less benefit (but still some) than a team of programmers working on a complex project.

There aren't any huge features that make DVCS better than VCS, but there are a million small ones. A few years ago, when they were new and possibly buggy that was a valid argument against using DVCS, but today the software is tried and true.

High quality paint is more expensive than cheap paint. But one of DVCS's benefits over VCS is it's cheaper to use a good quality tool (assuming you are paid by the hour). You should use DVCS for every project you are involve in. Even if you are the only person on the project who uses it.


问:
What is a good rule of thumb to do technical writing that doesn't confuse people
Sometimes I'm such a nerd that not even nerds understand me, or rather, sometimes I cannot put stuff in understandable and simple-enough terms... and sometimes I can but cannot really tell until after.

I like the details on technical stuff, I enjoy writing about them, but sometimes I cannot stop or tell when it is too technical or too abstract to understand. I often end up putting too much detail into stuff thinking that it will help the understanding of some concept, but it sometimes it backfires.

These are all edge cases, I'm not that bad at writing (I hope), but, what would be a good rule of thumb to know when you are probably going to make people dizzy when reading your stuff?, how do you test your analogies?, I'm looking for one or more rules of thumb to know if I'm writing technical explanations right, knowing what to reference and what not, etc.

What is your golden rule for writing about technical stuff to technical people who are not necessarily familiar with what you are writing but are also not noobies in your area?, where is the line?

答: Assuming your technical writing is for work, you can always ask a colleague to proofread. A lot easier than trying to imagine if you've went overboard or not.</p>


问:
Test-driven development: To create test when issue is filed or when issue is picked up by somebody?
I've recently been working on a web development project on a team of less-than-five people. Things are going good but now we are decided to go with test-driven development.

So far what I've learned is that one of the ultimate goal is that when you are testing your software, everything should be passed. However our current situation is that we have more open issues/stories than what we can handle within an iteration or two and we're a bit confused on how to actually handling test-driven development in this situation.

One thing we can do is that when each of us pick a story, that person will write the test for it. Each of us will working within red-green-refactor cycle. Or another thing we can do is that we try to create test cases for all open issues. Then each of us can pick that up and working on eliminating the red for that issue.

The first approach looks nice to me that we can ensure what we've done is green across the board. However the latter approach is what I've been thinking it looks more realistic as it reflects the imperfect status of your software. I am not really sure how it is managed in real world or what should be the best practice for this.

Inputs from all are welcome.

答:
I would only create tests for issues right before they start, and only for stories you plan on completing this iteration. They should probably be created by the developer who will eventually complete the functionality for the story.

The problem with creating all the tests in advance for all your stories, is that you risk the stories changing. It's better to take on things one story at a time. When you finish a sprint/iteration/whatever, you should relook the issues left to complete. Often times, they will have to change because of something that happened in the previous work cycle. If you had written tests, they would also have to change.

By writing the tests during the development of the story, you make sure that the tests and development work is in synch.


答:
I'm not sure what you mean by an algorithm, but certainly you can do this. How hard it will be depends on what operating system and file system you are using, and the level of detail you need.

If you think about it, this is just what the file system is doing anyway. A file is an abstraction. At base it's just a collection of spots on a disk. All those operations like creating a file, deleting a file, or modifying a file are just the file system managing lists of spots. What you are asking for is for the file system to share information with you as it performs its management chores.

At one level there are library calls like stat and inotify, but these are just wrapping lower level OS or device driver calls. You can tap in to those too. In the 'olden' days you would have had to write interrupt hooks to monitor the OS calls. Now a sophisticated API for hooking into the file system may be provided for you. See for example this article on the NTFS transactional file system API. I also just stumbled across this paper "VFS Interceptor: Dynamically Tracing File System Operations in real environments" which discusses the design of a tool for tracing file system operations.

Title: How do programs like subversion detect when a file has been edited as opposed to created/deleted?

Body:
This is my first question here so I hope it is not off topic. Although I am using the Linux inotify library to listen for changes to files, and I compare use of that against the Subversion program, I am specifically looking for the algorithm used.

To a human it is very easy to tell if a file has been created or modified. Clicking the New button constitutes the former, and clicking the Save button constitutes the latter. To Linux, both those actions have serious overlap. In text editors, for example, generally a swap file is created and then copied/moved. This makes it difficult to distinguish via inotify between a minor edit to a file and a deliberate overwrite of a file. What I am trying to understand is how a program such as Subversion recognizes the difference between a user having modified a file with a text editor, and a user having actually deleted the file and opened a new file with the same name.

Edit:
It has been pointed out that subversion does not do what I want it to do, so it was a blunder on my part to use it as an example. Instead allow me to rephrase the question: "Is there any known program or programming approach to match high level actions such as creating new files and saving them to low level actions such as modifying, moving, copying, etc. such that I can log all the files in the system and changes to them"?


问:
Reinvent the wheel or using the existing wheel?
I would like to ask something about project management. I got a project that has some requirements, it can be done from scratch with the use of a big framework. Maybe some tools are necessary for some of the functions. But using a framework seems very cool, it seems that reduces the amount of work, but need to study a framework first. But study a frameworks seems very big for the team. So, what do you think? Just get the thing done from scratch or study a framework and get started like 'Standing on the shoulders of giants'?</p>

答:
Using a framework suitable for the task at hand usually saves a lot of time, especially if it solves problems you are unfamiliar with.

I see the following problems:

You have a specific framework in mind.  Question is if it is the most suitable for the task at hand?

Learning curve.  How hard is it to use?  How hard is it to debug your code?

Coolness factor of big framework is deceptive, but irrelevant.  Use the best tool at hand.

Frameworks all have limits and trade-offs.  Will any of these influence what you need to do?

At this time you need more information to be able to answer the question for yourself.   I would suggest doing a quick proof-of-concept in the specific framework you consider, so you can compare effort and get an idea of how well suited it is for the task at hand.

I would also strongly suggest you keep your mind open to whether the framework you consider is the best for the task at hand or not.


答:
It's not bad to reinvent the wheel, but only when necessary.

When is it necessary?

When you find a need to compact the amount of code for program size, efficiency ( meaning you found a better way ) or for learning purposes.
These are the answers I have received from community feedback on a similar questions.

So the answer I believe you may be looking for is, NO! It's preffered to use a library or packaged framework when and if possible and to not reinvent the wheel for sake of time and money efficiency.  It will be much quicker and easier to learn new libraries then reinvent the wheel for most circumstances.  In addition you want to make sure the library or packaged framework encompasses skills your team may already have like programming knowledge and data storages.

I hope this helps.

@Ted Wong.    Please try and clean up your question.  I believe it has merit but needs to be organized and asked better.  I gave you a up vote to try and correct this before the moderator closes it.

Title: Reinvent the wheel or using the existing wheel?

Body: I would like to ask something about project management. I got a project that has some requirements, it can be done from scratch with the use of a big framework. Maybe some tools are necessary for some of the functions. But using a framework seems very cool, it seems that reduces the amount of work, but need to study a framework first. But study a frameworks seems very big for the team. So, what do you think? Just get the thing done from scratch or study a framework and get started like 'Standing on the shoulders of giants'?</p>


答:
My problem with technical writing was always that I had gathered and learnt far more information producing a project, piece of code, whatever, than was needed for the technical documentation. The rule of thumb that worked for me, was to do a "brain dump" of all the information I had. Then, before anything else (before structuring, grammar, spelling, anything) I would edit the document to remove one-third of the wording without losing any of the sense. (This figure worked for me - YMMV). Then I would start looking at the structure and form of the documentation - introducing if necessary previous examples of structure that were relevant; or standard documents that provided structures useful to what I was trying to achieve.

Once the document had been knocked into a rough first draft by the above process, and by spelling and grammar checks, I would then put the document aside for at least three days. Then I would start the revision process by reading - slowly - what I had already produced.

External editing, review, reading or some mixture of these is an essential. I found with technical writing in particular, I am totally unable to judge whether I have "hit the sweet spot" or not without external input.

Title: What is a good rule of thumb to do technical writing that doesn't confuse people

Body:
Sometimes I'm such a nerd that not even nerds understand me, or rather, sometimes I cannot put stuff in understandable and simple-enough terms... and sometimes I can but cannot really tell until after.

I like the details on technical stuff, I enjoy writing about them, but sometimes I cannot stop or tell when it is too technical or too abstract to understand. I often end up putting too much detail into stuff thinking that it will help the understanding of some concept, but it sometimes it backfires.

These are all edge cases, I'm not that bad at writing (I hope), but, what would be a good rule of thumb to know when you are probably going to make people dizzy when reading your stuff?, how do you test your analogies?, I'm looking for one or more rules of thumb to know if I'm writing technical explanations right, knowing what to reference and what not, etc.

What is your golden rule for writing about technical stuff to technical people who are not necessarily familiar with what you are writing but are also not noobies in your area?, where is the line?


问:
Persistent Storage format for (update+read)-intensive data
I am developing a Java application. While using the application, data would be generated that needs to be stored on disk. I am looking for an embedded database appropriate for a average use-case of the application.

Initially I planned to use XML for storing information. But, then after some articles, I found a general opinion that XML is not a very good way for adding information due to I dunno why :P

This is roughly the XML format, if I use it. It will give you a brief overview of the data-structure.

```<code><A>
  <B>
     <C>something</C>
  </B>
  <B>
     <C>some other thing</C>
     <C>one more thing</C>
  </B>
</A>
</code>```

The data generated would be mostly elements/objects of type C. The data would seldom be deleted. It would be mostly be added or searched upon. In such a scenario what would be a good choice for storing the data.

XML.

Embedded Database.

Something else.

I also looked up some embedded database options. The ones that I found most used are H2 and Java DB (I guess same as Apache Derby?) and SQLite. Which one in your experience has given you better results.

答:
So, the question to ask yourself is:  "What are the use cases for this data?".  Is reporting going to happen over this data?  Does it need to be transformed?  Does it need to be distributed?  Does it need to be human readable? Does it need to be written fast? Read fast?"

Also "How much hardware have I got to play with for memory and disk storage?"

In other words it depends :-).  From my personal experience I've really enjoyed using HSQL.


答:
There are many problems with Singletons - here are the two biggest problems in my mind.

It makes unit testing problematic. The global state can become contaminated from one test to the next

It enforces the "One-and-only-one" hard rule, which, even though it couldn't possibly change, suddenly does. A whole bunch of utility code that used the globally accessible object then needs to be altered.

Having said that, most systems have some need for Big Global Objects. These are items which are large and expensive (eg Database Connection Managers), or hold pervasive state information (for example, locking information).

The alternative to a Singleton is to have these Big Global Objects created on startup, and passed as parameters to all of the classes or methods that need access to this object.

The problem here is that you end up with a big game of "pass-the-parcel". You have a graph of components and their dependencies, and some classes create other classes, and each have to hold a bunch of dependency components just because their spawned components (or the spawned components' components) need them.

You run into new maintenance problems. An example: Suddenly your "WidgetFactory", component deep in the graph needs a timer object that you want to mock out. However, "WidgetFactory" is created by "WidgetBuilder" which is part of "WidgetCreationManager", and you need to have three classes knowing about this timer object even though only one actually uses it. You find yourself wanting to give up and revert back to Singletons, and just make this timer object globally accessible.

Fortunately, this is exactly the problem that is solved by a Dependency Injection framework. You can simply tell the framework what classes it needs to create, and it uses reflection to figure out the dependency graph for you, and automatically constructs each object when they are needed.

So, in summary, Singletons are bad, and the alternative is to use a Dependency Injection framework.

I happen to use Castle Windsor, but you are spoilt for choice. See this page from back in 2008 for a list of available frameworks.

Title: Why is Global State so Evil?


问:
Should one check for null if he does not expect null?
Last week, we had a heated argument about handling nulls in our application's service layer. The question is in the .NET context, but it will be the same in Java and many other technologies.

The question was: should you always check for nulls and make your code work no matter what, or let an exception bubble up when a null is received unexpectedly?

On one side, checking for null where you are not expecting it (i.e. have no user interface to handle it) is, in my opinion, the same as writing a try block with empty catch. You are just hiding an error. The error might be that something has changed in the code and null is now an expected value, or there is some other error and the wrong ID is passed to the method.

On the other hand, checking for nulls may be a good habit in general. Moreover, if there is a check the application may go on working, with just a small part of the functionality not having any effect. Then the customer might report a small bug like "cannot delete comment" instead of much more severe bug like "cannot open page X".

What practice do you follow and what are your arguments for or against either approach?

Update:

I want to add some detail about our particular case. We were retrieving some objects from the database and did some processing on them (let's say, build a collection). The developer who wrote the code did not anticipate that the object could be null so he did not include any checks, and when the page was loaded there was an error and the whole page did not load.

Obviously, in this case there should have been a check. Then we got into an argument over whether every object that is processed should be checked, even if it is not expected to be missing, and whether the eventual processing should be aborted silently.

The hypothetical benefit would be that the page will continue working. Think of a search results on Stack Exchange in different groups (users, comments, questions). The method could check for null and abort the processing of users (which due to a bug is null) but return the "comments" and "questions" sections. The page would continue working except that the "users" section will be missing (which is a bug). Should we fail early and break the whole page or continue to work and wait for someone to notice that the "users" section is missing?

答:
There are already good answers to this question, may be one addition to them: I do prefer assertions in my code. If your code can work only with valid objects, but nut with null, you should assert on null value.

Assertions in this kind of situation would let any unit and/or integration tests fail with the exact message, so you can nail down the problem pretty fast prior to production.
If such an error slips through the tests and goes to production (where assertions should be deactivated) you gonna receive NpEx, and a severe bug, but it is better, than some minor bug which is much more fuzzy and popping up somewhere else in the code, and would be more expensive to fix.

Further more if someone must work with your code assertions tells him about your assumptions you made during designing/writing your code (in this case: Hey dude, this object must be presented!), which makes it easier to maintain.


问:
What is the appeal of Systems Hungarian?
In a now deleted question titled "What naming guidelines do you follow?", the author says:

Also I prefer to code using hungarian notation from Charles Simonyi.

I've run in to several programmers who still prefer to use Hungarian, mostly of the Petzold/Systems Hungarian flavor.  Think dwLength = strlen(lpszName).

I've read Making Wrong Code Look Wrong, and I understand the rationale for Apps Hungarian, where domain-type information is included in the variable names.  But I don't understand the value in attatching the compiler type to the name.

Why do programmers still persist on using this style of notation?  Is it just inertia?  Are there any benefits that outweigh the decreased readability?  Do people just learn to ignore the decorators when reading the code, and if so, how do they continue to add value?

EDIT:
A lot of answers are explaining the history, or why it is no longer relevant, both of which are covered in the article I cited.

I'd really like to hear from anyone out there who still uses it.  Why do you use it?  Is it in your standard?  Would you use it if it wasn't required?  Would you use it on a new project?  What do you see as the advantages?

答:
The Systems Hungarian notation was in fact a bit of a cock-up, a misunderstanding of the term 'type'. The systems developers took it literally as the compiler type (word, byte, string, ...) as opposed to the apps domain type (row index, column index, ...).

But I guess that every developer goes through several phases of style that seem like a great idea at the time (and prefixing type does seem like a good idea to a novice) before falling into the pitfalls (changing type, creating new, meaningful prefixes, etc). So I guess there's an inertia: from developers that don't get better and realise why it's a poor choice, from developers stuck with coding standards that mandate the practice and from people using <windows.h>. It would be too costly for Microsoft to change  to get rid of the prefix notation (which is incorrect in many places: WPARAM?).


答:
There are only simple 3 rules for TDD.

You are not allowed to write any production code unless it is to make a failing unit test pass.

You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.

You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

Regardless if you are working on a new story or fixing an open issue, this will not change.
Do it 1 unit test at a time.

It will be easier to make unit test for new codes.  However, it can be a bit troublesome for an existing code.  As your fix go deeper in your existing code, more and more unit tests needs to be created.  Again to reiterate, Test each one before proceeding to create any new test.

Title: Test-driven development: To create test when issue is filed or when issue is picked up by somebody?

Body:
I've recently been working on a web development project on a team of less-than-five people. Things are going good but now we are decided to go with test-driven development.

So far what I've learned is that one of the ultimate goal is that when you are testing your software, everything should be passed. However our current situation is that we have more open issues/stories than what we can handle within an iteration or two and we're a bit confused on how to actually handling test-driven development in this situation.

One thing we can do is that when each of us pick a story, that person will write the test for it. Each of us will working within red-green-refactor cycle. Or another thing we can do is that we try to create test cases for all open issues. Then each of us can pick that up and working on eliminating the red for that issue.

The first approach looks nice to me that we can ensure what we've done is green across the board. However the latter approach is what I've been thinking it looks more realistic as it reflects the imperfect status of your software. I am not really sure how it is managed in real world or what should be the best practice for this.

Inputs from all are welcome.


答:
If wheels were never reinvented for good reason, Honda Civics would have wheels chiseled from stone.

One great reason to not use a framework is that a lot of frameworks suck so bad, light barely escapes them. Sadly, people who use nothing but frameworks and libraries tend to not be in a great position to evaluate them.

As a client-side web dev, I've learned to favor tools that help you get the job done fast without compromising the flexibility you get from doing things your way because the tools will stay out of your way when you need them to. Django and JQuery (not really a framework technically but fits with the discussion) are very much built on this principle. Both are also stupid popular with those of us who continue to want more granular control of how stuff is implemented.

The prefab collectoins of built-for-you stuff, particularly where UI is concerned are almost never as flexible as you wish they had been and good luck to you when you want to start customizing something. I'm not saying you shouldn't shop around, but if you know your stuff and the available tools seem kind of awkward and difficult to maintain, ditch 'em and DIY. You will save time in the long run.

But the critical thing to remember is that you can almost always have your cake and eat it too. If you're trying a new framework or library out and it seems full of unnecessary chains of dependencies and requires overly rigid implementation that puts pointless constraints on environments it lives in, toss it out. It's a bad tool.


答:
I'm not a huge fan of using hungarian notation but think this way:

We can also notice that it's faster to find a string refering to a TextBox in your code: by typing "txt" in your search box.

No imagine the opposite, where every element has its own name. It might be slower for you to find where you want to go, right?

The same goes for ddl when we want to refer to a DropDownList, its easier or not? :)

People won't spend so much time to find where is this element.

The prefix use is not usable for modern languages compilers like C#, but it is usable (readable) for human beings.

Title: What is the appeal of Systems Hungarian?

Body:
In a now deleted question titled "What naming guidelines do you follow?", the author says:

Also I prefer to code using hungarian notation from Charles Simonyi.

I've run in to several programmers who still prefer to use Hungarian, mostly of the Petzold/Systems Hungarian flavor.  Think dwLength = strlen(lpszName).

I've read Making Wrong Code Look Wrong, and I understand the rationale for Apps Hungarian, where domain-type information is included in the variable names.  But I don't understand the value in attatching the compiler type to the name.

Why do programmers still persist on using this style of notation?  Is it just inertia?  Are there any benefits that outweigh the decreased readability?  Do people just learn to ignore the decorators when reading the code, and if so, how do they continue to add value?

EDIT:
A lot of answers are explaining the history, or why it is no longer relevant, both of which are covered in the article I cited.

I'd really like to hear from anyone out there who still uses it.  Why do you use it?  Is it in your standard?  Would you use it if it wasn't required?  Would you use it on a new project?  What do you see as the advantages?


答:
In addition to the indirect better tools allowing programmers to do better job, there are some cases where there may be more direct effect. If you are developing for another company and for any reason it's not possible to access intranet of one from the other, than any time you need to debug and fix something at customer site having working version control with full history on your notebook is immensely helpful.

It happened to me a few times. In one case a colleague went to customer site to debug some problem, fixed it, but we ended up sending modified sources there and back over a file sharing server, because we needed to integrate the fix with some other changes we did in the meantime. In the other cases having reasonably recent sources on the notebook and integrating the modification after return was enough, but it would certainly have been easier with DVCS (The customer was at least 4 hours of travel away, sometimes involving flight, so it was not possible to stop by at our office at the end of the day.)

Title: Will the customer benefit from a DVCS in any way?

Body:
Some of us can say a Distributed Version Control System (e.g. Mercurial, git) will have a positive impact on developers only out of the experience of using one (under the right conditions: higher productivity, higher code-base stability, etc.), but, in what situations could a customer (i.e. the observer of the outcome of the software development lifecycle) tell there is a difference from using a CVCS and a DVCS?.

Anyone with empiric evidence of a customer "feeling" a difference upon DVCS adoption gets a big double-chocolate cookie with whipped cream and a cherry on top.

Note: "tell the difference" doesn't mean "know there was a DVCS involved" nor even remotely "know what a DVCS is"


答:
Or another thing we can do is that we try to create test cases for all open issues.

The person or people you assign to this will get very bored, very quickly. The "cover this code with unit tests" project is unexciting and without a clear goal (OK, it looks clear at the beginning, but it isn't).

In addition, this approach wastes all the knowledge the engineers gather along the way. When I've written a failing test, I've discovered:

what the software is supposed to do

how the software authors claim that should be done

what the difference is between the expectation and reality

I'm in a prime position to fix the bug and get the test to pass. If instead I move on to writing a different test, then I've squandered that opportunity.


问:
Are Java applets worth learning?
I'm on the way of learning Java myself. I find most of texts giving emphasis to Java applets. I got confused about the importance. Is it something widely used?  Do I need to spend more time on it?</p>

答: I would say not, because they're not very widely used.  If you're curious, you might want to take a look at them after you've gotten a good handle on Java.  They're not terribly hard to understand, but I wouldn't include them on my primary list of things to learn.</p>

Title: Are Java applets worth learning?


问:
How can I evaluate a candidate's knowledge of Html/CSS during an interview?
I am trying to determine some good interview questions to assess the ability of people coming in for a Html/CSS job, however that topic is extremely broad, and I'm not sure what sort of questions I can ask to properly evaluate someone's HTML/CSS knowledge.

What sort of questions can I ask to evaluate a candidate's Html/CSS abilities during an interview?

Ideally I would like to ask few questions and then give them a real life scenario to combat.

答:
There is an online test in which you must list the HTML Tags or the CSS Properties in 5 minutes.

Although this is not a fullproof test, this can let you know if the candidate is familiar enough with HTML/CSS.

About the question, you could make a test with sample code and ask him to detect syntax / structure errors.

As for the real life scenario, it all depends on what the candidate will work on in your company. If you want just a front end dev, you can ask for a website design on a random topic.


答:
it seems like your data has Hierarchical nature.
for that u can use GlobalsDB its free, Hierarchical and have java bindings. more importantly you wouldn't be requiring any Object mappings ...</p>

Title: Persistent Storage format for (update+read)-intensive data

Body:
I am developing a Java application. While using the application, data would be generated that needs to be stored on disk. I am looking for an embedded database appropriate for a average use-case of the application.

Initially I planned to use XML for storing information. But, then after some articles, I found a general opinion that XML is not a very good way for adding information due to I dunno why :P

This is roughly the XML format, if I use it. It will give you a brief overview of the data-structure.

```<code><A>
  <B>
     <C>something</C>
  </B>
  <B>
     <C>some other thing</C>
     <C>one more thing</C>
  </B>
</A>
</code>```

The data generated would be mostly elements/objects of type C. The data would seldom be deleted. It would be mostly be added or searched upon. In such a scenario what would be a good choice for storing the data.

XML.

Embedded Database.

Something else.

I also looked up some embedded database options. The ones that I found most used are H2 and Java DB (I guess same as Apache Derby?) and SQLite. Which one in your experience has given you better results.


问:
Should a web developer know how to do slicing?
I am a web developer. I'm doing all kinds of web-sites and web applications.

It's very strange for me that a lot of customers do not know the difference between a web developer and a slicer. They just want to "give you the PSD" and expect you to give them a web site with a DB back-end and so on...

I'm just asking here: am I wrong in my thinking?

Of course, a web developer MUST know html and css but I don't think that he should slice the PSD and do all the work a css guru can do...

I would like to hear your opinions on this.

答:
In a perfect world, there's a clear separation between people who do the design elements (slicing, css, graphics ... etc) and people who do coding.

We don't live in that world.

It is very common for a programmer to wear more than one hat, especially in low budget projects or small companies. No only doing design stuff, but taking on the responsibilities of a DBA and maybe even a network admin. So having a wide cross section of skills is often very beneficial for a programmer (or anyone else really).