问:
Which hashing algorithm is best for uniqueness and speed?
Which hashing algorithm is best for uniqueness and speed? Example (good) uses include hash dictionaries.

I know there are things like SHA-256 and such, but these algorithms are designed to be secure, which usually means they are slower than algorithms that are less unique. I want a hash algorithm designed to be fast, yet remain fairly unique to avoid collisions.

答:
I tested some different algorithms, measuring speed and number of collisions.

I used three different key sets:

A list of 216,553 English words archive(in lowercase)

The numbers "1" to "216553" (think ZIP codes, and how a poor hash took down msn.com archive)

216,553 "random" (i.e. type 4 uuid) GUIDs

For each corpus, the number of collisions and the average time spent hashing was recorded.

I tested:

DJB2

DJB2a (variant using xor rather than +)

FNV-1 (32-bit)

FNV-1a (32-bit)

SDBM

CRC32

Murmur2 (32-bit)

SuperFastHash

Results

Each result contains the average hash time, and the number of collisions

```<code>Hash           Lowercase      Random UUID  Numbers
=============  =============  ===========  ==============
Murmur            145 ns      259 ns          92 ns
                    6 collis    5 collis       0 collis
FNV-1a            152 ns      504 ns          86 ns
                    4 collis    4 collis       0 collis
FNV-1             184 ns      730 ns          92 ns
                    1 collis    5 collis       0 collis▪
DBJ2a             158 ns      443 ns          91 ns
                    5 collis    6 collis       0 collis▪▪▪
DJB2              156 ns      437 ns          93 ns
                    7 collis    6 collis       0 collis▪▪▪
SDBM              148 ns      484 ns          90 ns
                    4 collis    6 collis       0 collis**
SuperFastHash     164 ns      344 ns         118 ns
                   85 collis    4 collis   18742 collis
CRC32             250 ns      946 ns         130 ns
                    2 collis    0 collis       0 collis
LoseLose          338 ns        -             -
               215178 collis
</code>```

Notes:

The LoseLose algorithm (where hash = hash+character) is truly awful. Everything collides into the same 1,375 buckets

SuperFastHash is fast, with things looking pretty scattered; by my goodness the number collisions. I'm hoping the guy who ported it got something wrong; it's pretty bad

CRC32 is pretty good. Slower, and a 1k lookup table

Do collisions actually happen?

Yes. I started writing my test program to see if hash collisions actually happen - and are not just a theoretical construct. They do indeed happen:

FNV-1 collisions

creamwove collides with quists

FNV-1a collisions

costarring collides with liquid

declinate collides with macallums

altarage collides with zinke

altarages collides with zinkes

Murmur2 collisions

cataract collides with periti

roquette collides with skivie

shawl collides with stormbound

dowlases collides with tramontane

cricketings collides with twanger

longans collides with whigs

DJB2 collisions

hetairas collides with mentioner

heliotropes collides with neurospora

depravement collides with serafins

stylist collides with subgenera

joyful collides with synaphea

redescribed collides with urites

dram collides with vivency

DJB2a collisions

haggadot collides with loathsomenesses

adorablenesses collides with rentability

playwright collides with snush

playwrighting collides with snushing

treponematoses collides with waterbeds

CRC32 collisions

codding collides with gnu

exhibiters collides with schlager

SuperFastHash collisions

dahabiah collides with drapability

encharm collides with enclave

grahams collides with gramary

...snip 79 collisions...

night collides with vigil

nights collides with vigils

finks collides with vinic

Randomnessification

The other subjective measure is how randomly distributed the hashes are. Mapping the resulting HashTables shows how evenly the data is distributed. All the hash functions show good distribution when mapping the table linearly:

Or as a Hilbert Map (XKCD is always relevant):

Except when hashing number strings ("1", "2", ..., "216553") (for example, zip codes), where patterns begin to emerge in most of the hashing algorithms:

SDBM:

DJB2a:

FNV-1:

All except FNV-1a, which still look pretty random to me:

In fact, Murmur2 seems to have even better randomness with Numbers than FNV-1a:

When I look at the FNV-1a "number" map, I think I see subtle vertical patterns. With Murmur I see no patterns at all. What do you think?

The extra * in the table denotes how bad the randomness is. With FNV-1a being the best, and DJB2x being the worst:

```<code>      Murmur2: .
       FNV-1a: .
        FNV-1: ▪
         DJB2: ▪▪
        DJB2a: ▪▪
         SDBM: ▪▪▪
SuperFastHash: .
          CRC: ▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪
     Loselose: ▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪
                                        ▪
                                 ▪▪▪▪▪▪▪▪▪▪▪▪▪
                        ▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪
          ▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪
</code>```

I originally wrote this program to decide if I even had to worry about collisions: I do.

And then it turned into making sure that the hash functions were sufficiently random.

FNV-1a algorithm

The FNV1 hash comes in variants that return 32, 64, 128, 256, 512 and 1024 bit hashes.

The FNV-1a algorithm is:

```<code>hash = FNV_offset_basis
for each octetOfData to be hashed
    hash = hash xor octetOfData
    hash = hash * FNV_prime
return hash
</code>```

Where the constants FNV_offset_basis and FNV_prime depend on the return hash size you want:

```<code>Hash Size
===========
32-bit
    prime: 2^24 + 2^8 + 0x93 = 16777619
    offset: 2166136261
64-bit
    prime: 2^40 + 2^8 + 0xb3 = 1099511628211
    offset: 14695981039346656037
128-bit
    prime: 2^88 + 2^8 + 0x3b = 309485009821345068724781371
    offset: 144066263297769815596495629667062367629
256-bit
    prime: 2^168 + 2^8 + 0x63 = 374144419156711147060143317175368453031918731002211
    offset: 100029257958052580907070968620625704837092796014241193945225284501741471925557
512-bit
    prime: 2^344 + 2^8 + 0x57 = 35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759
    offset: 9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785
1024-bit
    prime: 2^680 + 2^8 + 0x8d = 5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573
    offset: 1419779506494762106872207064140321832088062279544193396087847491461758272325229673230371772250864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915
</code>```

See the main FNV page for details.

All my results are with the 32-bit variant.

FNV-1 better than FNV-1a?

No. FNV-1a is all around better. There was more collisions with FNV-1a when using the English word corpus:

```<code>Hash    Word Collisions
======  ===============
FNV-1   1
FNV-1a  4
</code>```

Now compare lowercase and uppercase:

```<code>Hash    lowercase word Collisions  UPPERCASE word collisions
======  =========================  =========================
FNV-1   1                          9
FNV-1a  4                          11
</code>```

In this case FNV-1a isn't "400%" worse than FN-1, only 20% worse.

I think the more important takeaway is that there are two classes of algorithms when it comes to collisions:

collisions rare: FNV-1, FNV-1a, DJB2, DJB2a, SDBM

collisions common: SuperFastHash, Loselose

And then there's the how evenly distributed the hashes are:

outstanding distribution: Murmur2, FNV-1a, SuperFastHas

excellent distribution: FNV-1

good distribution: SDBM, DJB2, DJB2a

horrible distribution: Loselose

Update

Murmur? Sure, why not

Update

@whatshisname wondered how a CRC32 would perform, added numbers to the table.

CRC32 is pretty good. Few collisions, but slower, and the overhead of a 1k lookup table.

Snip all erroneous stuff about CRC distribution - my bad

Up until today I was going to use FNV-1a as my de facto hash-table hashing algorithm. But now I'm switching to Murmur2:

Faster

Better randomnessification of all classes of input

And I really, really hope there's something wrong with the SuperFastHash algorithm I found; it's too bad to be as popular as it is.

Update: From the MurmurHash3 homepage on Google:

(1) - SuperFastHash has very poor collision properties, which have been documented elsewhere.

So I guess it's not just me.

Update: I realized why Murmur is faster than the others. MurmurHash2 operates on four bytes at a time. Most algorithms are byte by byte:

```<code>for each octet in Key
   AddTheOctetToTheHash
</code>```

This means that as keys get longer Murmur gets its chance to shine.

Update

GUIDs are designed to be unique, not random

A timely post by Raymond Chen reiterates the fact that "random" GUIDs are not meant to be used for their randomness. They, or a subset of them, are unsuitable as a hash key:

Even the Version 4 GUID algorithm is not guaranteed to be unpredictable, because the algorithm does not specify the quality of the random number generator. The Wikipedia article for GUID contains primary research which suggests that future and previous GUIDs can be predicted based on knowledge of the random number generator state, since the generator is not cryptographically strong.

Randomess is not the same as collision avoidance; which is why it would be a mistake to try to invent your own "hashing" algorithm by taking some subset of a "random" guid:

```<code>int HashKeyFromGuid(Guid type4uuid)
{
   //A "4" is put somewhere in the GUID.
   //I can't remember exactly where, but it doesn't matter for
   //the illustrative purposes of this pseudocode
   int guidVersion = ((type4uuid.D3 & 0x0f00) >> 8);
   Assert(guidVersion == 4);

   return (int)GetFirstFourBytesOfGuid(type4uuid);
}
</code>```

Note: Again, I put "random GUID" in quotes, because it's the "random" variant of GUIDs. A more accurate description would be Type 4 UUID. But nobody knows what type 4, or types 1, 3 and 5 are. So it's just easier to call them "random" GUIDs.

All English Words mirrors

https://web.archive.org/web/20070221060514/http://www.sitopreferito.it/html/all_english_words.html

https://drive.google.com/file/d/0B3BLwu7Vb2U-dEw1VkUxc3U4SG8/view?usp=sharing

Body:
I tested some different algorithms, measuring speed and number of collisions.

I used three different key sets:

A list of 216,553 English words archive(in lowercase)

The numbers "1" to "216553" (think ZIP codes, and how a poor hash took down msn.com archive)

216,553 "random" (i.e. type 4 uuid) GUIDs

For each corpus, the number of collisions and the average time spent hashing was recorded.

I tested:

DJB2

DJB2a (variant using xor rather than +)

FNV-1 (32-bit)

FNV-1a (32-bit)

SDBM

CRC32

Murmur2 (32-bit)

SuperFastHash

Results

Each result contains the average hash time, and the number of collisions

Hash           Lowercase      Random UUID  Numbers
=============  =============  ===========  ==============
Murmur            145 ns      259 ns          92 ns
                    6 collis    5 collis       0 collis
FNV-1a            152 ns      504 ns          86 ns
                    4 collis    4 collis       0 collis
FNV-1             184 ns      730 ns          92 ns
                    1 collis    5 collis       0 collis▪
DBJ2a             158 ns      443 ns          91 ns
                    5 collis    6 collis       0 collis▪▪▪
DJB2              156 ns      437 ns          93 ns
                    7 collis    6 collis       0 collis▪▪▪
SDBM              148 ns      484 ns          90 ns
                    4 collis    6 collis       0 collis**
SuperFastHash     164 ns      344 ns         118 ns
                   85 collis    4 collis   18742 collis
CRC32             250 ns      946 ns         130 ns
                    2 collis    0 collis       0 collis
LoseLose          338 ns        -             -
               215178 collis

Notes:

The LoseLose algorithm (where hash = hash+character) is truly awful. Everything collides into the same 1,375 buckets

SuperFastHash is fast, with things looking pretty scattered; by my goodness the number collisions. I'm hoping the guy who ported it got something wrong; it's pretty bad

CRC32 is pretty good. Slower, and a 1k lookup table

Do collisions actually happen?

Yes. I started writing my test program to see if hash collisions actually happen - and are not just a theoretical construct. They do indeed happen:

FNV-1 collisions

creamwove collides with quists

FNV-1a collisions

costarring collides with liquid

declinate collides with macallums

altarage collides with zinke

altarages collides with zinkes

Murmur2 collisions

cataract collides with periti

roquette collides with skivie

shawl collides with stormbound

dowlases collides with tramontane

cricketings collides with twanger

longans collides with whigs

DJB2 collisions

hetairas collides with mentioner

heliotropes collides with neurospora

depravement collides with serafins

stylist collides with subgenera

joyful collides with synaphea

redescribed collides with urites

dram collides with vivency

DJB2a collisions

haggadot collides with loathsomenesses

adorablenesses collides with rentability

playwright collides with snush

playwrighting collides with snushing

treponematoses collides with waterbeds

CRC32 collisions

codding collides with gnu

exhibiters collides with schlager

SuperFastHash collisions

dahabiah collides with drapability

encharm collides with enclave

grahams collides with gramary

...snip 79 collisions...

night collides with vigil

nights collides with vigils

finks collides with vinic

Randomnessification

The other subjective measure is how randomly distributed the hashes are. Mapping the resulting HashTables shows how evenly the data is distributed. All the hash functions show good distribution when mapping the table linearly:

Or as a Hilbert Map (XKCD is always relevant):

Except when hashing number strings ("1", "2", ..., "216553") (for example, zip codes), where patterns begin to emerge in most of the hashing algorithms:

SDBM:

DJB2a:

FNV-1:

All except FNV-1a, which still look pretty random to me:

In fact, Murmur2 seems to have even better randomness with Numbers than FNV-1a:

When I look at the FNV-1a "number" map, I think I see subtle vertical patterns. With Murmur I see no patterns at all. What do you think?

The extra * in the table denotes how bad the randomness is. With FNV-1a being the best, and DJB2x being the worst:

      Murmur2: .
       FNV-1a: .
        FNV-1: ▪
         DJB2: ▪▪
        DJB2a: ▪▪
         SDBM: ▪▪▪
SuperFastHash: .
          CRC: ▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪
     Loselose: ▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪
                                        ▪
                                 ▪▪▪▪▪▪▪▪▪▪▪▪▪
                        ▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪
          ▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪

I originally wrote this program to decide if I even had to worry about collisions: I do.

And then it turned into making sure that the hash functions were sufficiently random.

FNV-1a algorithm

The FNV1 hash comes in variants that return 32, 64, 128, 256, 512 and 1024 bit hashes.

The FNV-1a algorithm is:

hash = FNV_offset_basis
for each octetOfData to be hashed
    hash = hash xor octetOfData
    hash = hash * FNV_prime
return hash

Where the constants FNV_offset_basis and FNV_prime depend on the return hash size you want:

Hash Size
===========
32-bit
    prime: 2^24 + 2^8 + 0x93 = 16777619
    offset: 2166136261
64-bit
    prime: 2^40 + 2^8 + 0xb3 = 1099511628211
    offset: 14695981039346656037
128-bit
    prime: 2^88 + 2^8 + 0x3b = 309485009821345068724781371
    offset: 144066263297769815596495629667062367629
256-bit
    prime: 2^168 + 2^8 + 0x63 = 374144419156711147060143317175368453031918731002211
    offset: 100029257958052580907070968620625704837092796014241193945225284501741471925557
512-bit
    prime: 2^344 + 2^8 + 0x57 = 35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759
    offset: 9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785
1024-bit
    prime: 2^680 + 2^8 + 0x8d = 5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573
    offset: 1419779506494762106872207064140321832088062279544193396087847491461758272325229673230371772250864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915

See the main FNV page for details.

All my results are with the 32-bit variant.

FNV-1 better than FNV-1a?

No. FNV-1a is all around better. There was more collisions with FNV-1a when using the English word corpus:

Hash    Word Collisions
======  ===============
FNV-1   1
FNV-1a  4

Now compare lowercase and uppercase:

Hash    lowercase word Collisions  UPPERCASE word collisions
======  =========================  =========================
FNV-1   1                          9
FNV-1a  4                          11

In this case FNV-1a isn't "400%" worse than FN-1, only 20% worse.

I think the more important takeaway is that there are two classes of algorithms when it comes to collisions:

collisions rare: FNV-1, FNV-1a, DJB2, DJB2a, SDBM

collisions common: SuperFastHash, Loselose

And then there's the how evenly distributed the hashes are:

outstanding distribution: Murmur2, FNV-1a, SuperFastHas

excellent distribution: FNV-1

good distribution: SDBM, DJB2, DJB2a

horrible distribution: Loselose

Update

Murmur? Sure, why not

Update

@whatshisname wondered how a CRC32 would perform, added numbers to the table.

CRC32 is pretty good. Few collisions, but slower, and the overhead of a 1k lookup table.

Snip all erroneous stuff about CRC distribution - my bad

Up until today I was going to use FNV-1a as my de facto hash-table hashing algorithm. But now I'm switching to Murmur2:

Faster

Better randomnessification of all classes of input

And I really, really hope there's something wrong with the SuperFastHash algorithm I found; it's too bad to be as popular as it is.

Update: From the MurmurHash3 homepage on Google:

(1) - SuperFastHash has very poor collision properties, which have been documented elsewhere.

So I guess it's not just me.

Update: I realized why Murmur is faster than the others. MurmurHash2 operates on four bytes at a time. Most algorithms are byte by byte:

for each octet in Key
   AddTheOctetToTheHash

This means that as keys get longer Murmur gets its chance to shine.

Update

GUIDs are designed to be unique, not random

A timely post by Raymond Chen reiterates the fact that "random" GUIDs are not meant to be used for their randomness. They, or a subset of them, are unsuitable as a hash key:

Even the Version 4 GUID algorithm is not guaranteed to be unpredictable, because the algorithm does not specify the quality of the random number generator. The Wikipedia article for GUID contains primary research which suggests that future and previous GUIDs can be predicted based on knowledge of the random number generator state, since the generator is not cryptographically strong.

Randomess is not the same as collision avoidance; which is why it would be a mistake to try to invent your own "hashing" algorithm by taking some subset of a "random" guid:

int HashKeyFromGuid(Guid type4uuid)
{
   //A "4" is put somewhere in the GUID.
   //I can't remember exactly where, but it doesn't matter for
   //the illustrative purposes of this pseudocode
   int guidVersion = ((type4uuid.D3 & 0x0f00) >> 8);
   Assert(guidVersion == 4);

   return (int)GetFirstFourBytesOfGuid(type4uuid);
}

Note: Again, I put "random GUID" in quotes, because it's the "random" variant of GUIDs. A more accurate description would be Type 4 UUID. But nobody knows what type 4, or types 1, 3 and 5 are. So it's just easier to call them "random" GUIDs.

All English Words mirrors

https://web.archive.org/web/20070221060514/http://www.sitopreferito.it/html/all_english_words.html

https://drive.google.com/file/d/0B3BLwu7Vb2U-dEw1VkUxc3U4SG8/view?usp=sharing

ContentLicense: CC BY-SA 4.0


问:
Pattern for select case on object type (of interface)
I have read that doing a select case is often a code smell. There are cases however where an interface cannot solve my problem.

For instance, I have a set of date filter objects (last 7 days, last year, ect.) that implement a IDateFilter interface. In another part of the code, I need to determine the type of date filter so that the chart properties can be set. I may want to use a different chart tick interval for instance depending on the date filter.

The problem is I do not want to store this information in the date filter object as it is interface related and I do not want to couple the two.

How could a select case be avoided in this instance? Other than using select case on gettype or creating some enumeration for all the types and then exposing the type and doing a select case on that, I do not see a clean way to do this?

The decorator pattern comes to mind but even then I would still need a select case.

Any ideas?

```<code>if (type = last 7 days)
 set this property
else if (type = last year)
 set this property to something different
</code>```

I'm using asp net c# in case that makes a difference.

答: I would make the IDateFilter interface include a method/property for querying the timespan or something.  You should be able to ask the object when the start and end dates are, or the number of days back, etc.

ContentLicense: CC BY-SA 3.0


问:
Biggest mistake you've ever made
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…

答:
I wanted to create metadata files for each file in a directory (i.e. for every file somedir/foo.bin, I'd want to create a file somedir/foo.bin.meta). For some stupid reason I decided to create the files by opening and closing a file stream via Python:

```<code>for fn in os.listdir(path):
    open(os.path.join(path, fn), 'w').close()
</code>```

For some even stupider reason I thought it was clever to test this script against a directory on my harddrive with several gigs of personal data on it. Only after running it I realized that I had forgot to actually modify the filename prior to passing it to open and that I had just truncated every single file in that directory (ouch).

Luckily that was on a personal computer and didn't cause any damage to anything important, but I still learned my lesson.

ContentLicense: CC BY-SA 2.5

Title: Biggest mistake you've ever made

Body:
I wanted to create metadata files for each file in a directory (i.e. for every file somedir/foo.bin, I'd want to create a file somedir/foo.bin.meta). For some stupid reason I decided to create the files by opening and closing a file stream via Python:

for fn in os.listdir(path):
    open(os.path.join(path, fn), 'w').close()

For some even stupider reason I thought it was clever to test this script against a directory on my harddrive with several gigs of personal data on it. Only after running it I realized that I had forgot to actually modify the filename prior to passing it to open and that I had just truncated every single file in that directory (ouch).

Luckily that was on a personal computer and didn't cause any damage to anything important, but I still learned my lesson.


问:
How to model two similar tasks with the Use-case diagram
I am trying to draw a use-case diagram for a software project.

Two requirements for the software I am trying to model in use-case diagram are:

A customer (i.e. Client) should be able to cancel its previous request. In this case, the client must select the relevant request from their list of request.

A travel agent should be able to cancel a request. in this case, the agent must the client from the list of clients and the request from the list of request issued by that client.

How should I model this two requirements in a UML user-case diagram? I've ended up to something like this:

答:
The two users do not interact in this use case and should both be on the left (neither are an external system that is invoked).

You could say that the two users have slightly different use cases - clients can only cancel their requests, travel agents can cancel any request. You can then say they both extend the same basic use case.

See approximate diagram bellow (their should only be one use case "Cancel a request" at the right with two arrows entering it).

Also, don't forget to box the system's boundaries.

```<code>               ---------------------------------------------------------------
               |                                                             |
Client --------|--> (Cancel own request)--<<includes>>-->(Cancel a request)  |
               |                                                             |
Travel agent --|--> (Cancel any request)--<<includes>>-->(Cancel a request)  |
               |                                                             |
               ---------------------------------------------------------------
</code>```

Body:
The two users do not interact in this use case and should both be on the left (neither are an external system that is invoked).

You could say that the two users have slightly different use cases - clients can only cancel their requests, travel agents can cancel any request. You can then say they both extend the same basic use case.

See approximate diagram bellow (their should only be one use case "Cancel a request" at the right with two arrows entering it).

Also, don't forget to box the system's boundaries.

               ---------------------------------------------------------------
               |                                                             |
Client --------|--> (Cancel own request)--<<includes>>-->(Cancel a request)  |
               |                                                             |
Travel agent --|--> (Cancel any request)--<<includes>>-->(Cancel a request)  |
               |                                                             |
               ---------------------------------------------------------------


问:
Recommendations for teaching junior programmers good coding style
I am a big fan of good coding style, producing clean, clear code that runs well and is easy to use and integrate into larger systems. I believe that we programmers are essentially craftspeople who should take pride in our work, every line. I am not fond of code that is inconsistently formatted, cluttered with commented out experimental code, and rife with unhelpful or misleading function and variable names. But I sometimes find it hard to argue with code like this that basically works.

If you think that coding style matters, I am looking for recommendations for ways of teaching good, professional coding style to the junior programmers under me. I want them to take pride in their work, but my concern is that they appear to become satisfied when their code just barely works, and seem to have no interest in producing what professionals like me would consider professional code. On the other hand, if you think coding style is not particularly valuable, I welcome your comments and am open to reconsidering my standards and tolerances.

I know the usual arguments in favor of good code: comprehensibility, ease of maintenance, etc., but I would also like to hear some rebuttals to arguments like "it works, what more do you want?"

In our industry we can use the compiler to hide a multitude of sins. Clean code and messy code can both lead to identically functioning programs, so does cleanliness matter, and if so, why?

[While there are several existing questions on coding style, I didn't find any that related to teaching methods and ways to instill good coding style in junior programmers.]

答:
Give them a really badly written unit of code to modify (and test) and then to rewrite (and test) and then give them a really well written unit of code with unit tests to modify (and test) and ask them about the experience.

After this give them a list of standards to read and refactor their code (from the previous exercise) to match those standards as practice.

You will need an organized documentation of your standards prior to this.


答:
I have learnt good coding style from one of the senior developers from one of my past projects.  He reviews my code for every commit during code review meeting and he will explain me line by line if something can be improved there.

He goes thru each naming of the variables and methods and explains
how to name them better.

He goes thru each methods and tells me how to make more readable and
more efficient.

He was very polite but his mentoring helped me a lot.

It took only three months for me to align myself with him and now he
rarely finds mistakes in my code.

I follow the same method of teaching my junior developers and it works.

Title: Recommendations for teaching junior programmers good coding style

Body:
I am a big fan of good coding style, producing clean, clear code that runs well and is easy to use and integrate into larger systems. I believe that we programmers are essentially craftspeople who should take pride in our work, every line. I am not fond of code that is inconsistently formatted, cluttered with commented out experimental code, and rife with unhelpful or misleading function and variable names. But I sometimes find it hard to argue with code like this that basically works.

If you think that coding style matters, I am looking for recommendations for ways of teaching good, professional coding style to the junior programmers under me. I want them to take pride in their work, but my concern is that they appear to become satisfied when their code just barely works, and seem to have no interest in producing what professionals like me would consider professional code. On the other hand, if you think coding style is not particularly valuable, I welcome your comments and am open to reconsidering my standards and tolerances.

I know the usual arguments in favor of good code: comprehensibility, ease of maintenance, etc., but I would also like to hear some rebuttals to arguments like "it works, what more do you want?"

In our industry we can use the compiler to hide a multitude of sins. Clean code and messy code can both lead to identically functioning programs, so does cleanliness matter, and if so, why?

[While there are several existing questions on coding style, I didn't find any that related to teaching methods and ways to instill good coding style in junior programmers.]


问:
What kind of problems does MapReduce solve?
I have been reading about MapReduce for a while -- but what I can't understand is how someone would make a decision to use (or not use) MapReduce.

I mean, what are the problem patterns that signal that MapReduce could be used.

答:
If you do much functional programming, you start running into situations that call for a general map and reduce.  You probably even see them in imperative programming, but don't recognize them behind the mask of loops and accumulators.

As an example of one that came up for me recently, I've been working on a parser in Haskell.  To test my parser, I pump a list of string fragments through the parser, and then I want to get a single string that I can output of my results to see if it parsed right.  So that looks like:

```<code>--my initial set of test data, a list
tests = ["string1", "string2", "string3", ...]

--Map Step: turn strings into parsed results
--note the type, which demonstrates the map
applyParser :: [String] -> [Token]
--The actual function
applyParser input = map parser input

--Second map, turn tokens into output
showTokens :: [Token] -> [String]
showTokens t = map show t

--Reduce step, concat the results
combineResults :: [String] -> String
--In haskell, reduce is the foldl function, which takes an operation to fold with, a starting element, and a list to fold on
combineResults strings = foldl concat "" strings

--Finished program
testParser = print (combineResults(showTokens(applyParser tests)))
</code>```

Of course, this is just pedagogical.  My actual code looks a bit different, and uses more internal functions (like fold concat isn't needed since Haskell already includes unlines that does [String]->String).  My main point was that I didn't anticipate using a map/reduce when I started, it just aligned to my needs.  I wanted to do some stuff with lists, then turn my list into a single element of output.  The use of map/reduce emerged naturally.

String processing (like parsing) is one very obvious use of map reduction, mapping is the application of various transformations on the input text, and reduce it putting the result text back together again as output.  Likewise, a compiler could be similar, using folds to turn a stream of Abstract Syntax Tree elements into a better form (optimizing).

Body:
If you do much functional programming, you start running into situations that call for a general map and reduce.  You probably even see them in imperative programming, but don't recognize them behind the mask of loops and accumulators.

As an example of one that came up for me recently, I've been working on a parser in Haskell.  To test my parser, I pump a list of string fragments through the parser, and then I want to get a single string that I can output of my results to see if it parsed right.  So that looks like:

--my initial set of test data, a list
tests = ["string1", "string2", "string3", ...]

--Map Step: turn strings into parsed results
--note the type, which demonstrates the map
applyParser :: [String] -> [Token]
--The actual function
applyParser input = map parser input

--Second map, turn tokens into output
showTokens :: [Token] -> [String]
showTokens t = map show t

--Reduce step, concat the results
combineResults :: [String] -> String
--In haskell, reduce is the foldl function, which takes an operation to fold with, a starting element, and a list to fold on
combineResults strings = foldl concat "" strings

--Finished program
testParser = print (combineResults(showTokens(applyParser tests)))

Of course, this is just pedagogical.  My actual code looks a bit different, and uses more internal functions (like fold concat isn't needed since Haskell already includes unlines that does [String]->String).  My main point was that I didn't anticipate using a map/reduce when I started, it just aligned to my needs.  I wanted to do some stuff with lists, then turn my list into a single element of output.  The use of map/reduce emerged naturally.

String processing (like parsing) is one very obvious use of map reduction, mapping is the application of various transformations on the input text, and reduce it putting the result text back together again as output.  Likewise, a compiler could be similar, using folds to turn a stream of Abstract Syntax Tree elements into a better form (optimizing).


问:
What is your approach to multi-paradigm programming?
I have been learning some Ruby recently and I had the following experience.
I had written a small tool of about 200 lines of code and, as an inexperienced Ruby programmer, I had used several loops to build arrays from other arrays.
E.g.

```<code>gs = ... # Some array of input data.
l  = gs.size
i  = 0
r  = Array.new
while (i < l) do
  if (cond(gs[i]))
    r.push(gs[i])
  end
  i = i + 1
end

# r contains the result now.
</code>```

Then I discovered that I can do it in a functional style:

```<code>gs = ... # Some array
r  = gs.select { |g| cond(g) }

# r contains the result now.
</code>```

So I immediately replaced most of my loops in the code with constructs like each, select, take_while, drop_while, and so on. I have decided to use a functional style in Ruby whenever possible and try to avoid an imperative style.

As another example, in C++ I tend to use classes and methods everywhere and use functions only for small utility tasks that are private to the implementation of some class. So I tend to think object-oriented when working in C++ and avoid
a procedural style almost completely.

More in general, when working on a given project in a given language, I tend to pick one paradigm and stick to it throughout the project: I find this makes my code more uniform, easier to read and to debug, which, IMO, is very important, especially for production code.

Yet, I often think that maybe I should explore more and try out different possibilities offered by a language, e.g. use different paradigms and try out different solutions. For me this involves some overhead both while coding (should I make it procedural or object-oriented? imperative or functional?) and when reviewing or debugging code (what did I want to do here?) because of the increased complexity.

So my question is: do you also tend to select a preferred programming paradigm
when coding and stick to it, or do you tend to explore more and mix different paradigms?

If you mix different paradigms, do you have the feeling that there is some overhead in terms of how fast you can write and debug code (added complexity, switching between different mindsets) or is it just a matter of learning how to do it and then you can even be more productive?

Or do you mix different paradigms in a more structured way, e.g. you apply each paradigm to a specific class of problems (e.g. functional for queries, object-oriented for architectural aspects, and so on)?

答:
As in your example, I think each language pushes you towards a particular paradigm.  If you're smart, you'll figure out how the language wants you to solve the problem and either do it that way or abandon the language.  I suppose some languages are a bit more neutral.  I found C could be bent in any direction, but it was a lot of work.  If I'd stuck with it a couple more years, I'd have written my own garbage collector for it.

Currently, I split my time between C# and Java.  To, say, a C++ programmer, these two langauges must look almost identical, but I find I write very differently in each.  I have trouble saying why.

Most languages, however, have obvious differences--in the type of data they are intended to handle--in their tradeoffs between performance, ease of programming, hardware needs, etc.  Hence their paradigm differences are obvious and understandable--and even predictable.


问:
Do records showing the daily work of programmers exist?
Are there screencasts on the Internet showing screens of programmers that decided to record their daily work and show their programming style?

I'm interested in seeing how other programmers effectively use tools like an editor with various features, debugger, looking for bugs, profiler etc.

Maybe such "crazy programmers" exist that record everything they do and in the evening they realize that they did great mental job very efficiently and have the record, can additionally comment their intents which they still remember and share their effective hacks and coding style with other programmers.

Is there such a resource for learning (doesn't matter if free or payable)?

One particular portal or company which is focusing on this particular type of training and is leading in this area is sufficient for the answer.

答:
There are (commercial) sites that offer video training that do have "watch my screen" style videos:

TekPub by Rob Conery (These ones specifically are $12.00 each, or subscription plans are avilable) - Has a "Full Throttle" series where you watch a developer's screen while they work through real-world problems.  Not exactly "day-to-day" operations, but definitely a "true" experience.  Featuring:

Ayende Rahien

Brad Wilson

Rob Sullivan

PeepCode (various plans available)  - Has a similar "Play by Play" series.  Featuring:

Jim Weirich

Aaron Patterson

Ryan Singer (UI)

Zed Shaw

Francis Hwang

John Barnette

Gary Bernhardt

WatchMeCode (Free to $12) - Not super familiar with this site, but it sounds like what you want given the name.  It does look like they have some "real-world" videos.

I've watched TekPub's video with Ayende and I think it's great.


问:
My colleague doesn't understand things he works with. What to do?
I've spent 3 days debugging one very obscure bug in a library made by my colleague, this bug happens very infrequently. After all I found that this bug happens due to cross-thread access to an object without any lock. Actually this is not a first bug of this kind, there were similar bugs before. He just runs his unit tests, and if something fails puts somewhere a lock. And if nothing fails, ughm, then his code is perfect. It seems he has no idea about threading safety. I'm 100% sure there are many similar bugs that just haven't surfaced yet. It seems PM doesn't understand threading stuff too.

The problem is, he works much more time in the company than I do. Anyway, I can't just say "this guy is incompetent in this area", because this always shows you as a "bad team player", etc.

Any ideas, what I can do?

答:
I think your company should not be using multithreading.

After doing a massively multithreaded project, I found two techniques were critical to making things work.  First, the code had to be written right.  Every field had to be manually checked to make sure it was declared properly and properly synchronized whereever referenced.  (Warning:  I am simplifying things a bit here to keep my answer short--or at any rate, shorter.)  Second, the code had to be tested by running it flat out on single and multicore machines--many minutes using 100% of each core.  (And if it only uses 2% of each core, as it often did for me, that's a bug too.)

You might be able to manage this, but your organization can't.  Even if they understood the problem, which they don't, they don't have the expertise.

Most languages provide ways to avoid this.  If you have a socket reader, which usually has its own thread, have it get the info to the main thread as quickly and simply as possible.  Better yet, look for system classes/functions that will handle the thread-part of the reading for you.  Use a queue that runs "events" one after the other, like most GUI API's do.  (Use the GUI API's event queue itself, for that matter.)  If you need parallel processing, you can probably find some kind of "worker thread" that will let you keep data/fields in a single thread, handling all transfers for you.

Emphasise to all the dangers of multithreading.  (Scary stories:  My favorite bug involved a couple of lines like:  int i = 5; i = i * i;, which resulted in i having a value of 35.  One I saw a lot was: if (thing != null)  thing.reset(); throwing a null pointer exception.)  I think your only hope is making them understand they're stepping into a whole, new, strange world, and that maybe they should take one big step back.

I'm not real sure how multithreading should be handled.  If the job can be given to one person, and everything they do thrown away if they fail, fine.  But a team is only going to be as strong as its weakest member, and even a good programmer will have trouble with full-blown multithreading.  I hope the language people will find a way to make it safe.  I have seen some helpful software out there.  But I think it best to avoid multithreading unless execution time is critical and a good programmer or a proven team is available.


问:
What is REST (in simple English)
Lately I have become interested in familiarizing myself with REST. I tried reading wiki entry on REST, but it was of no help. I would really appreciate it if someone can explain in simple English (that is without unnecessary tech jargon)

What is REST?

What position it occupies in web architecture ecosystem?

How tightly (or loosely) it is coupled with protocol?

What are the alternatives to REST and how does REST compare with them?

I understand it may not be possible to answer this in one or two paragraphs, in that case relevant links will be highly appreciated.

答:
What is REST?

REpresentational State Transfer. It describes how one system can communicate state with another. One example would be the state of a product (its name, description etc) represented as XML, JSON, or plain text. The generalised idea of state is termed a resource.

What position does it occupy in a web architecture ecosystem?

REST is commonly associated with the web services interface since HTTP is by far the most common carrier protocol. In the 7-layer model it exists at the application layer. However, see the next section.

How tightly (or loosely) it is coupled with protocol?

REST is not HTTP. It uses HTTP because in its most general form REST exists to assist a machine in mapping the concept of a verb against an arbitrary collection of nouns. HTTP contains a useful set of generic verbs (GET, PUT, PATCH etc) that can applied to arbitrary nouns expresssed as URIs using HTTP e.g. GET http://example.org/Product(54).

What are the alternatives to REST and how does REST compare with them

This is akin to asking "How RESTful is my approach?" Use the following list (summarised from the Richardson Maturity Model as described by Martin Fowler):

Level 0 - The swamp of POX

Use POST for everything (reads, writes, deletes). This is SOAP, POX, RPI etc. You're just using HTTP as a tunnel for your own protocol. You target a single endpoint that does everything based on the contents of the request body.

Level 1 - Resources

Use POST for everything. Target multiple endpoints designed to serve up information about a particular thing. You've just discovered resources.

Level 2 - HTTP verbs

Use HTTP verbs against resources. Now you're GETing it. POST is to create, PUT is to overwrite, OPTIONS for available operations, DELETE to, well, delete the resource. As a result of the use of these verbs different HTTP status codes start to become more relevant (202 ACCEPTED anyone?).

Level 3 - Hypermedia control (HATEOAS)

At this point you make the final leap and introduce hypermedia as a flow control mechanism. A REST client needs no prior knowledge about how to interact with any particular application or server beyond a generic understanding of hypermedia. This can be communicated in HTTP through the Content-Type header field. Text formats include AtomPub and (more concise) HAL, while HyperAudio works well for audio streams (see SoundCloud et al)

Title: What is REST (in simple English)


答:
MapReduce works on any problem that is made up of exactly 2 functions at some level of abstraction. The first function is is applied to each of the items in the input set, and the second function aggregates the results.

So, any time you want to get (1) result from (n) inputs, and all inputs can be examined/used by (1) function, you can use MapReduce. Again, this is at some specific level of abstraction. The (1) function may be some grouping function that checks the input and decides which of several other functions to use.

This is useful when you don't know in advance how much input you will have, when you need to share out discreet "units" of work, or when you want a single return to represent the entire result (I.E. running five thousand unit tests, and if less than x% fail, return success).

Title: What kind of problems does MapReduce solve?

Body:
I have been reading about MapReduce for a while -- but what I can't understand is how someone would make a decision to use (or not use) MapReduce.

I mean, what are the problem patterns that signal that MapReduce could be used.


问:
How a freelancer can learn industry standards?
Being a freelancer, I don't have access to corporate training programs where employees learn best practices. Most of the time I am advised to look into the available code on the Internet. Ideal places would be: CodePlex and SourceForge.

But this proves to be of limited rather very little help. I want my existing code to be analyzed and a better solution be suggested to improve the quality of the code.

How to learn coding that matches standards?

答:
For C# code as well as FxCop (as mentioned by Todd) there's StyleCop.

StyleCop analyzes C# source code to enforce a set of style and consistency rules. It can be run from inside of Visual Studio or integrated into an MSBuild project.

It checks for different, complementary, things and can be useful.

Though, as for FxCop, don't run all your code through it in one go. The "errors" will overwhelm you.


问:
Why does iPhone and iPad apps have a Free version and a full version, instead of "unlocking" it through in-app purchase?
Many apps have a Free version and a Full version.  How is it compared to, installing a single version, and use an in-app purchase of $0.99 or $1.99 to unlock to the program to make it a full version?  It does have the advantage that the user doesn't have to go to the App Store and install the program one more time and thus making it easier for the users to purchase.</p>

答: One obvious answer: if the full version isn't included in the free version, no one can gain unpaid access to the full version by cracking the free version.</p>


答:
One thing I don't understand is, many apps have a Free version and a Full version.

Some do, some don't. There's not one specific reason, like "the app store guidelines say you have to do it this way." There are several reasons, including but not limited to:

Setting up and administering in-app purchase can be a bit complicated and an ongoing hassle, especially compared to just selling something through the app store.

Building two versions of an app from a common code base may be simpler than building one version that dynamically switches from "free" mode to "paid" mode.

Having two apps in the app store gets you a little more exposure than just having one. Your apps can be listed in both the "free" and "paid" categories, and searches that find your app will often display both versions.

It may be advantageous to have two different bundle identifiers in some cases.

Title: Why does iPhone and iPad apps have a Free version and a full version, instead of "unlocking" it through in-app purchase?

Body: Many apps have a Free version and a Full version.  How is it compared to, installing a single version, and use an in-app purchase of $0.99 or $1.99 to unlock to the program to make it a full version?  It does have the advantage that the user doesn't have to go to the App Store and install the program one more time and thus making it easier for the users to purchase.</p>


答: Some of these apps may have been created before Apple allowed in-app purchases, and the developers don't want to orphan existing users by removing the old paid version from the store.  In-app purchasing also requires the use of a few more APIs and lines of code that some developers may not want to or know how to add.  The use of the IAP API can also increase the number of test scenarios needed, and thus test and QA time and/or cost.</p>


答:
I believe that you should not be teaching a specific coding style for the following reasons:

Junior programmers need to learn from their mistakes. They will continuously improve by evaluating their work and doing code reviews with senior developers.

Coding guidelines will vary with a culture of a company you are working for. I might argue against what you consider to be a clean code.

Junior programmers normally don't get much exposure to the enterprise systems, and that's where the clean code normally lives.

Quite often university lecturers have been stuck in the academic world for decades. I have personally found their guidelines and feedback to be rather unhelpful and poor in comparison to current industry's standards. Some, of course, are very good.

To summarise:

I think the solution is not to teach any specific guidelines or coding styles, but try to explain their importance in projects of various sizes.

There is only so much you can explain in the classroom and from the books.

Developers will have to get their hands dirty to see the real benefit for themeselves.

Allocate junior developers to pair program, then review their work and give them feedback. Eventually they should start seeing the benefit.

There isn't a silver bullet coding style that will always work, just like anything in systems engineering.


答:
Can the problem be solved efficiently using distributed computing?

If the answer to this question is yes, then you have a candidate problem for MapReduce. That is because the problem pattern lends itself to being split into smaller isolated problems.

Your task: Parse this book

An example works well to ilustrate this. You have a large document (Moby Dick by Herman Melville) and your job is to perform a frequency analysis of all the words used in it.

The sequential approach

You can do this sequentially by getting your fastest machine (you've got plenty lying around) and running over the text from start to finish maintaining a hash map of every word you find (the key) and incrementing the frequency (value) every time you parse a word. Simple, straightforward and slow.

The MapReduce approach

Approaching this from a different perspective, you note that you have all these spare machines lying around and you could split this task up into chunks. Give each machine a 1Mb block of text to parse into a hash map and then collate all the hash maps from each into a single result. This is a layered MapReduce solution.

The process of reading a line of text and gathering the words is the Map phase (you create a simple map representing the words in the line with their frequency 1,2,3 etc), then the Reduce phase is when each machine collates their line maps into a single aggregate map.

The overall solution comes from a further Reduce phase where all the aggregate maps are aggregated (that word again) into a final map. Slightly more complex, massively parallel and quick.

Summary

So, to summarise, if your problem lends itself to being represented by keys, values, aggregate operations on those values in isolation then you have a candidate problem for MapReduce.


问:
Are using <<include>> and <<extend>> relationship in this use-case diagram actually same?
I am trying to draw a UML use-case diagram to model requirements for a software project.

The two requirements I have issue to model are:

TravelAgent creates a booking for a [old] client who is requesting a home.

When a new client wishes to make a booking, the TravelAgent register him/her to the system before doing the booking.

I have two approaches to model these requirements:

Modeling the first use-case as a sub-procedure of the second use-case (Figure 1).

Extending the first use-case (Figure 2).

Both approach imply that the first use-case could be perform independently, but when the second use-case is executed, the first one MUST be executed too.

Are they actually same and both correct?

P.S. As another question, since the NewClient converts to a Client after the registration, should I show the NewClient as subclass of Client or something?

Figure 1

Figure 2

答:
Beware that extend is used in UML quite differently than in e.g. Java.

Your diagrams are probably not expressing what you would like them to. You used the generalization relationship (the arrow with a hollow triangle). This implies a "is a" relationship. But clearly neither is "Register a client" a case of "Create a booking" nor the other way round.

The correct way to indicate a "include" or "extend" relationship is with a dashed line e.g. - - - > .  Now the difference between the two is the following. Suppose A includes B. This means that whenever somebody does A she will do B too. On the other hand, if A extends B, than whenever somebody does A, B has nothing to do with it. But if you do B, you might do A additionally during the course of B. You should specify a condition under which A actually extends B.

In your case you could actually use both as long as you indicate in the condition of the extends version that this depends on the customer being new.

About your modeling of the new client. I do not believe that there is much value in expressing the difference between the two here. BTW "subclassing" is not the correct term, it is (again) generalization. Adding such a generalization implies that every new customer is a customer and can do whatever a regular customer can do. I cannot decide if this is what you want.


答:
First of all - why aren't you computing the tick interval from the actual data returned by the filter? But okay, I suppose you have your reasons.

Select case statements are a code smell because you might end up having more than one if these statements selecting on the same type. If you add another case branch to one of them, you must add one to all of these statements. This is more error-prone than the alternative - adding an abstract method to an interface. In the latter case the compiler will help you find all the relevant sites in your code.

If there is no chance to integrate the computation in the IDateFilter by a method like getIntervalSize, you could split the client of the IDateFilter interface into a class hierarchy. Whether this is a viable solution depends on the client its creator and the creator of the concrete filter. However, I should warn you that you might run into a different code smell, the duplicated class hierarchy. But this might be either preferable or (more likely) an indication of a bigger design flaw.

Title: Pattern for select case on object type (of interface)

Body:
I have read that doing a select case is often a code smell. There are cases however where an interface cannot solve my problem.

For instance, I have a set of date filter objects (last 7 days, last year, ect.) that implement a IDateFilter interface. In another part of the code, I need to determine the type of date filter so that the chart properties can be set. I may want to use a different chart tick interval for instance depending on the date filter.

The problem is I do not want to store this information in the date filter object as it is interface related and I do not want to couple the two.

How could a select case be avoided in this instance? Other than using select case on gettype or creating some enumeration for all the types and then exposing the type and doing a select case on that, I do not see a clean way to do this?

The decorator pattern comes to mind but even then I would still need a select case.

Any ideas?

```<code>if (type = last 7 days)
 set this property
else if (type = last year)
 set this property to something different
</code>```

I'm using asp net c# in case that makes a difference.


问:
What is the minumum code/operations to have in a separate thread?
I understand that threading is needed to get the maximum performance out of today's multicore processors but starting a thread is rather costly so you can't put every single calculation that can be done in parallel in an own thread. For example

```<code>answer = new thread(plus(1,2)) + new thread(plus(3,4))
</code>```

will run much slower than the simple single-threaded

```<code>answer = 1+2+3+4
</code>```

but if plus was some really complicated calculation the threaded variant might be faster.

Now to the questions

Are there any convention or standards about what the minimum length of code, operations or execution time that are defendable to put in its own thread?

Do I even have to worry about this or are the compiler/processor so smart that they do all the work for me?

The reason I ask this question is that I saw an implementation of quicksort that started a new thread for every recursive call ending up with (n²) threads and there many of this threads just returned some value.

答:
If you're only creating a couple of threads, the overhead is negligible. So in your example,
answer = new thread(plus(1,2)) + new thread(plus(3,4)) is roughly equivalent to answer = 1+2+3+4 (as long as you're not running this multiple times). This operation runs in a constant number of instructions so there is really no need to thread.

Threading is more appropriate when you are performing calculations on large (variable) sets of data where the running time for the algorithm is not constant. For any such calculation, your aim should be to have all cores at 100% over the duration of the calculation, so that there is no need to create 8000 threads to sort a list. Create one thread per processor and divide the work evenly.


问:
is it possible for the author to trademark the name of an open-source application?
I would like to know if the name of an open-source application can be trademarked by the original author and what it means when it comes to distributing it through major linux distros, that is, will they accept this kind of software? </p>

答:
Yes, the name of an open-source app can be trademarked. As an example, see Linux itself: http://assignments.uspto.gov/assignments/q?db=tm&rno=1916230

I hope this also answers your second question :)


答:
There are no conventions, every program is a different story, there is no quick and dirty rule that will let you skip the "careful planning" part.

Unfortunately no. To take advantage of threads you have to use them manually. However, there are languages or libraries that facilitate this e.g. a construct that runs a loop in parallel (but you still have to make sure that it makes sense).

Title: What is the minumum code/operations to have in a separate thread?

Body:
I understand that threading is needed to get the maximum performance out of today's multicore processors but starting a thread is rather costly so you can't put every single calculation that can be done in parallel in an own thread. For example

```<code>answer = new thread(plus(1,2)) + new thread(plus(3,4))
</code>```

will run much slower than the simple single-threaded

```<code>answer = 1+2+3+4
</code>```

but if plus was some really complicated calculation the threaded variant might be faster.

Now to the questions

Are there any convention or standards about what the minimum length of code, operations or execution time that are defendable to put in its own thread?

Do I even have to worry about this or are the compiler/processor so smart that they do all the work for me?

The reason I ask this question is that I saw an implementation of quicksort that started a new thread for every recursive call ending up with (n²) threads and there many of this threads just returned some value.


答:
Open source organizations certainly trademark their names and the software names.  Take a look at the Mozilla Trademark Policy, specifically their list of trademarks.  The reason for trademarking is actually quite realistic.  The point of a trademark is to communicate who is providing a product or service.  By downloading Firefox, you're supposed to know where it came from.

Someone else is welcome to take the code and modify it, but they should release it under a different name to distinguish it.  There would be a danger if someone took the Firefox code, put in a vulnerability, and released it as "Firefox" and distributed it, making everyone think it was from Mozilla.  Mozilla has a reputation, and over time people start to trust it.  It's that reputation that trademarks protect.

Title: is it possible for the author to trademark the name of an open-source application?

Body: I would like to know if the name of an open-source application can be trademarked by the original author and what it means when it comes to distributing it through major linux distros, that is, will they accept this kind of software? </p>


答: Definitely TSQL mishap - too many TSQL statements in one editor window.  Was a bit tired, and people were interrupting me left and right, and I issued a command that updated 47,000 records address, city, state, and zip - oops.  Had it fixed in about 25 minutes, though.</p>

Title: Biggest mistake you've ever made

Body:
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…


答:
Create a data structure, such as a dictionary, which uses the type as the key and the value is the chart property. If you have multiple chart properties associated with a given type, then the value could be a ChartProperties object.  So you have something like this:

```<code>ChartProperties chartProp;
if (propertiesMap.containsKey(currentFilter.getType()){
  chartProp = propertiesMap(currentFilter.getType());
}
</code>```

I would make the properties map a subclass of a dictionary and then put the above code in a method on that class.

Body:
Create a data structure, such as a dictionary, which uses the type as the key and the value is the chart property. If you have multiple chart properties associated with a given type, then the value could be a ChartProperties object.  So you have something like this:

ChartProperties chartProp;
if (propertiesMap.containsKey(currentFilter.getType()){
  chartProp = propertiesMap(currentFilter.getType());
}

I would make the properties map a subclass of a dictionary and then put the above code in a method on that class.


问:
Diving into microcontroller programming
I just got a batch of LED matrix modules from Sure Electronics (http://www.sureelectronics.net/goods.php?id=1120) and a driver board (http://www.sureelectronics.net/goods.php?id=972).

I've got it wired up, and connected to my Mac. I found the right drivers, and I'm now able to send text to the displays using the virtual COM port, as per the documentation from Sure Electronic's website:

```<code>start with "0xFE,0x47 (G) 0x01,0x01" followed by 16 characters - display the 16 characters in the first row
start with "0xFE,0x47 (G) 0x01,0x02" followed by 16 characters - display the 16 characters in the second row
</code>```

The plan is to hook it all up to a Raspberry Pi (when I eventually get one) and use it all to display information from a web service.

However, this setup is not optimal. The driver board requires some initialization each time it is powered up, in order to be available via USB. Also, I'd like more control over the display of characters (this setup, for instance, does not support non-ASCII characters, or text scrolling).

Heavy googling has led me to believe that I need to go deeper into the HT1632 chip on the driver board. The documentation from Sure Electronics is sparse.

The goal would be to be able to address each LED pixel individually from my code running on my computer (as in a 2D array of booleans, for example).

I'm totally new to micro programming, so I have no idea where to start.
What do I need to do in order to program it? Can I even modify the code of the driver board, or do I need another kind of driver board? And how do I automate the boot up sequence, so that the board is automatically USB enabled?

Also, I'm mostly a Java/Web developer guy, so I would like to avoid as much C programming as possible.

If anyone with experience with this kind of programming could point me in the right direction to start, I would be grateful.

答:
I do not know the HT1632, but you should be able to get hold of the data sheet for it. Firstly you need to find out if the device is field programmable. Some (most?) are these days, but it's significantly cheaper to produce from One Time Programmable devices.  From there, work out how to get a simple program to run - such as toggle a port pin and monitor it with an oscilloscope, then you may be able to get the LED display to work.

From the HT1632 data sheet, you may be able to find a way to get it into debug/programming mode. Does it have JTag?

Given your lack of experience, you will need to rely on perspiration and inspiration. To achieve what you are trying you would almost certainly need details from Sure Electronics about the board schematics.

EDIT:
I scanned the manual. It appears that the driver board starts in serial mode- it has a serial port with no connector, but I did not find out if the serial is RS232 ot TTL level signals. What you should be able to do is attach your Mac to the serial port (You can by an RS232 dongle for this).

Title: Diving into microcontroller programming


答:
when parallelizing there are 3 different timings to take into consideration

the serial time: this is the time spent doing stuff that cannot be parallelized and where you cannot get below (getting the input, writing the output)

the parallel time: this is the part where you can parallelize, this you can get down to 0 by throwing more processors at it

overhead: the time spent communicating between processes/threads, this is very dependent on the algorithm used and the distribution of the work

basically you can add threads until the overhead becomes too big compared to actual gain from parallelization there are formulas for that

but really this is a job for profiling as every algorithm is different


答:
After giving it some further thought, if you want to do this in the cleanest way possible, you could use a combination of the Strategy and Service Locator pattern to accomplish your goal in an object-oriented manner.

Here is the overall strategy (no pun intended):

Put your implementation for each strategy in a separate class.

Register each strategy in a static list.

When you need to handle an object of an unknown type, iterate through the registered strategies until you find one that works.

The neat part about this approach is that you can make the condition of whether or not to follow a specific strategy based on criteria more custom than just Type.  Let's say you have one interface that you actually want to handle in two different ways depending on the value of a property, or if you want to apply the same strategy to multiple interfaces.  It's all about how you implement it.

This is definitely overkill for classes like factories, etc., where the if/else if pattern should suffice and is in fact quite appropriate.  Assuming you've explored other options that are simpler or more oo-friendly, here's a thoroughly over-engineered example with the pure purpose of avoiding a switch on Type, resulting in Ultimately Extensible Code (TM).

Let's say you are dealing with two external, non-related interfaces, IBlinger and ISnapper:

```<code>interface IBlinger
{
    public string BlingName { get; }
}

interface ISnapper
{
    public string SnapName { get; }
}
</code>```

And you are trying to write a class that handles writing each interface to the console in a custom way.  You would first define an interface IWriteHandler as follows:

```<code>interface IWriteHandler
{
    bool Write(object target);
}
</code>```

And then provide implementations:

```<code>class BlingWriter : IWriteHandler
{
    public bool Write(object target)
    {
        var bling = target as IBlinger;
        if (bling == null)
            return false;

        Console.WriteLine("BLING: " + bling.BlingName);

        return true;
    }
}

class SnapWriter : IWriteHandler
{
    public bool Write(object target)
    {
        var snap = target as ISnapper;
        if (snap == null)
            return false;

        Console.WriteLine("SNAP: " + snap.SnapName);

        return true;
    }
}
</code>```

And here's an example usage:

```<code>class Writer
{
    static List<IWriteHandler> _handlers = new List<IWriteHandler>();

    static Writer()
    {
        //add them to the list in order of preference, in case the types overlap
        //due to inheritance.
        _handlers.Add(new BlingWriter());
        _handlers.Add(new SnapWriter());
    }

    public void Write(object unknown)
    {
        foreach (var handler in _handlers)
        {
            if (handler.Write(unknown))
                return;
        }

        //default
        Console.WriteLine("UNKNOWN: " + unknown.ToString());
    }
}
</code>```

And if that seems too "boilerplatey", you could make it more generic:

```<code>abstract class GenericWriteHandler<T> : IWriteHandler where T : class
{
    public bool Write(object target)
    {
        var asT = target as T;
        if (asT == null)
            return false;

        WriteInternal(asT);

        return true;
    }

    protected abstract void WriteInternal(T target);
}
</code>```

Which could be implemented as:

```<code>class SnapWriter : GenericWriteHandler<ISnapper>
{
    protected override void WriteInternal(ISnapper target)
    {
        Console.WriteLine("SNAP: " + target.SnapName);
    }
}
</code>```

OR, if you like lambdas/don't like creating lots of classes, you could make:

```<code>class ActionWriteHandler<T> : IWriteHandler where T : class
{
    Action<T> _a;

    public ActionWriteHandler(Action<T> action)
    {
        _a = action;
    }

    public bool Write(object target)
    {
        var asT = target as T;
        if (asT == null)
            return false;

        _a(asT);

        return true;
    }

    protected abstract void WriteInternal(T target);
}
</code>```

Where the Writer class is initialized like:

```<code>static Writer()
{
    _handlers.Add(new ActionWriteHandler<IBlinger>(b => Console.WriteLine(b.BlingName)));
    _handlers.Add(new ActionWriteHandler<ISnapper>(s => Console.WriteLine(s.SnapName)));
}
</code>```

In fact, you could make the entire Writer class generic too, but that is for another day...

Related question (which happens to have a similar answer): https://stackoverflow.com/questions/3834091/strategy-pattern-with-no-switch-statements

Body:
After giving it some further thought, if you want to do this in the cleanest way possible, you could use a combination of the Strategy and Service Locator pattern to accomplish your goal in an object-oriented manner.

Here is the overall strategy (no pun intended):

Put your implementation for each strategy in a separate class.

Register each strategy in a static list.

When you need to handle an object of an unknown type, iterate through the registered strategies until you find one that works.

The neat part about this approach is that you can make the condition of whether or not to follow a specific strategy based on criteria more custom than just Type.  Let's say you have one interface that you actually want to handle in two different ways depending on the value of a property, or if you want to apply the same strategy to multiple interfaces.  It's all about how you implement it.

This is definitely overkill for classes like factories, etc., where the if/else if pattern should suffice and is in fact quite appropriate.  Assuming you've explored other options that are simpler or more oo-friendly, here's a thoroughly over-engineered example with the pure purpose of avoiding a switch on Type, resulting in Ultimately Extensible Code (TM).

Let's say you are dealing with two external, non-related interfaces, IBlinger and ISnapper:

interface IBlinger
{
    public string BlingName { get; }
}

interface ISnapper
{
    public string SnapName { get; }
}

And you are trying to write a class that handles writing each interface to the console in a custom way.  You would first define an interface IWriteHandler as follows:

interface IWriteHandler
{
    bool Write(object target);
}

And then provide implementations:

class BlingWriter : IWriteHandler
{
    public bool Write(object target)
    {
        var bling = target as IBlinger;
        if (bling == null)
            return false;

        Console.WriteLine("BLING: " + bling.BlingName);

        return true;
    }
}

class SnapWriter : IWriteHandler
{
    public bool Write(object target)
    {
        var snap = target as ISnapper;
        if (snap == null)
            return false;

        Console.WriteLine("SNAP: " + snap.SnapName);

        return true;
    }
}

And here's an example usage:

class Writer
{
    static List<IWriteHandler> _handlers = new List<IWriteHandler>();

    static Writer()
    {
        //add them to the list in order of preference, in case the types overlap
        //due to inheritance.
        _handlers.Add(new BlingWriter());
        _handlers.Add(new SnapWriter());
    }

    public void Write(object unknown)
    {
        foreach (var handler in _handlers)
        {
            if (handler.Write(unknown))
                return;
        }

        //default
        Console.WriteLine("UNKNOWN: " + unknown.ToString());
    }
}

And if that seems too "boilerplatey", you could make it more generic:

abstract class GenericWriteHandler<T> : IWriteHandler where T : class
{
    public bool Write(object target)
    {
        var asT = target as T;
        if (asT == null)
            return false;

        WriteInternal(asT);

        return true;
    }

    protected abstract void WriteInternal(T target);
}

Which could be implemented as:

class SnapWriter : GenericWriteHandler<ISnapper>
{
    protected override void WriteInternal(ISnapper target)
    {
        Console.WriteLine("SNAP: " + target.SnapName);
    }
}

OR, if you like lambdas/don't like creating lots of classes, you could make:

class ActionWriteHandler<T> : IWriteHandler where T : class
{
    Action<T> _a;

    public ActionWriteHandler(Action<T> action)
    {
        _a = action;
    }

    public bool Write(object target)
    {
        var asT = target as T;
        if (asT == null)
            return false;

        _a(asT);

        return true;
    }

    protected abstract void WriteInternal(T target);
}

Where the Writer class is initialized like:

static Writer()
{
    _handlers.Add(new ActionWriteHandler<IBlinger>(b => Console.WriteLine(b.BlingName)));
    _handlers.Add(new ActionWriteHandler<ISnapper>(s => Console.WriteLine(s.SnapName)));
}

In fact, you could make the entire Writer class generic too, but that is for another day...

Related question (which happens to have a similar answer): https://stackoverflow.com/questions/3834091/strategy-pattern-with-no-switch-statements


答:
Multithreading is not only about performance. It's also about user-experience. One of the main reasons to use multithreading is for applications to remain responsive. You wouldn't want your browser to become totally unresponsive until your next webpage has loaded.

So those situations need their own metric.


问:
The Wikipedia animation for Maze generation using DFS isn't consistent wrt the written algorithm given there, isn't it?
Please have a look at this link:

http://en.wikipedia.org/wiki/Maze_generation#Depth-first_search

Here, the theoretical algorithm given is:

Consider the space for a maze being a large grid of cells (like a
  large chess board), each cell starting with four walls. Starting from
  a random cell, the computer then selects a random neighbouring cell
  that has not yet been visited. The computer removes the 'wall' between
  the two cells and adds the new cell to a stack (this is analogous to
  drawing the line on the floor). The computer continues this process,
  with a cell that has no unvisited neighbours being considered a
  dead-end. When at a dead-end it backtracks through the path until it
  reaches a cell with an unvisited neighbour, continuing the path
  generation by visiting this new, unvisited cell (creating a new
  junction). This process continues until every cell has been visited,
  causing the computer to backtrack all the way back to the beginning
  cell.

But I don't think the animation on it's right uses the same algorithm to generate the maze, though it's not incorrect.

I feel the animation uses this algorithm:

Start with any unvisited cell, make it a part of the maze and mark it visited.

Add the unvisited neighbours of that cell to the set of cells that can be considered next

Choose any one of cells from the set and mark it visited.

Check if that cell does not have any neighbours that are visited except ONE (the one which caused this cell to be added to the set in the first place). Else go to 3.

Continue till all cells are visited.

Am I wrong?

答:
The animation uses the algorithm that the article describes.
Their stack consists of the cells that have been visited. When they reach a dead end, they backtrack by popping cells off the stack until they come across one that has an unvisited neighbor and then start exploring a path beginning at that cell (by pushing that cell onto the stack).

They are not keeping a set of unvisited cells and randomly choosing another one to visit.
If you look closely, they always choose to explore starting at a cell closest to the  red square.

If we label the cells so that the bottom left cell is (1, 1) and the top right cell is (30, 20) you notice that its first 'decision' at time 0:03 when it hits a dead-end at (1, 5). It backtracks to the last cell with an unvisited neighbor (1, 7) and is forced to explore (1, 8) next. If I understand the algorithm you describe, you would be randomly choosing a any cell which touched part of the path that was generated already.


问:
Is there a semi-scientific term for this filtering behavior?
I'm looking for the term that applies to a certain kind of filtering behavior. It's often used in webshop-like interfaces, where large amounts of data are filtered based on a selection of filter criteria. The most distinguishing feature is that it's impossible to pick a filter criterium that leads to no results, as the filters that would do so are hidden with real-time updates.

To see an example look at this boot finder section on the blue-tomato.com webshop.

Is there a term for this kind of filtering?

答:
I don't think there is an official name for this type of filtering. The type of filtering you refer to is called "Active Filtering" on Quince and as "Attribute-Based Filtering or Faceted Search Filters" on UX-Matters-Best Practices for Designing Faceted Search Filters.

The fact that you always get results with different combinations is because the system uses current inventory to build filtering options. So if a specific size is not in the inventory, it won't be shown on the filter and you won't be able to choose it.


问:
How Do You Estimate Project Hours Using Pivotal Tracker If You Are a Services Firm?
I am new to Pivotal Tracker and trying to learn how best to use it for our business. We are an app development consulting services firm. As you guys know, clients want to have an idea of total time and cost before they sign any contract.

How are you guys mapping your project on Pivotal to total hours and timelines? Any best practices? Pointers?

Right now my team and I have broke the project into stories (love how Pivotal gets us thinking on a much lower level) and have roughly mapped out points to hours.

1 - 1 hour

2 - 2 hours

3 - 6 hours

5 - 10 hours

Then we are basically thinking of 2 as a quarter day, 3 as 3/4 a day, and 5 as a full day or a bit longer.

I then calculate how many 1s, 2s, 3s and 5s we have to get a rough estimate of total hours. Pivotal gives me an estimated completion date based on default velocity (I know this can change). I then report the rough total hours, cost, and due date to my client. I do understand that this is agile and iterative where things change, but when people hire you as a consultant they want costs up front.

答:
Basically you are trying to do both Agile and Waterfall at the same time which is a bad idea.

This is detailed here:
http://www.halfarsedagilemanifesto.org/


问:
optimizing webapp workflow
I have a debug and a live server running a LAMP setup with some python scripts. By now I'm working with eclipse and Expandrive (via SSH) on the debug server. Whenever I want to release new code on the live server, I copy and paste the code via windows explorer from debugdrive to livedrive.

I think this environment really sucks, what are good alternatives?

答:
on your dev machine, use some sort of source control (eg git, mercurial) to manage your code. Commit often.

when you have your dev code in a state where you want to deploy, tag or branch the code in a good state in your repo.

write some sort of script (eg python, could be anything) to run on your live machine to pull code from the repo, taking the tag or the branch as an argument

you haven't asked about db changes and the like so I won't comment :)

you could set all this up on jenkins or hudson or whatever

Title: optimizing webapp workflow


问:
Does having to scroll horizontally make code less readable?
Well, does it? Is it considered bad practice?

IMO, it is less readable. I hate having to scroll to the right, then back left, right, left, and so on. It makes coding more painful and confuses me sometimes.

For example, anytime I am coding a long string, I will do the following...

```<code>bigLongSqlStatement = "select * from sometable st inner join anothertable at" +
"on st.id = at.id" +
"and so on..." +
"and so on..." +
"and so on..."
</code>```

答:
No, it doesn't.

I have an editor. Not only does it have line wrap, it has line wrap indentation, which (if the screen is say 100 chars wide) would cause

```<code>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</code>```

to appear as

```<code>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
    labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
    laboris nisi ut aliquip ex ea commodo consequat.
</code>```

or with whatever indentation level is set as default for the current language.

Lines wider than my screen never makes code less readable versus manually line-wrap-indented code.

edit: ooooh, I knew this answer would be unpopular :)

Body:
No, it doesn't.

I have an editor. Not only does it have line wrap, it has line wrap indentation, which (if the screen is say 100 chars wide) would cause

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

to appear as

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
    labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
    laboris nisi ut aliquip ex ea commodo consequat.

or with whatever indentation level is set as default for the current language.

Lines wider than my screen never makes code less readable versus manually line-wrap-indented code.

edit: ooooh, I knew this answer would be unpopular :)


问:
Freelancing - Share the source code?

Possible Duplicate:

Hand over source code to customer

I have developed a couple of form based windows application in vb.net for a client and they all work well and he paid me through a freelance site. I have handed over the executable and the setup to the client and all was well. Now the client wants the source code for the application. Is there a general practice on sharing the source code with the client?

Please note - the client never mentioned he needs the source code and he is now asking for it after a week after the app was completed and he made the payment.

I don't mind sharing the source code, but I am not sure if I should. This probably means the client would not hire me again and the bigger question is the source code really his property?

This question may have been asked a few times, but I cannot still draw a conclusion on what is right.

update

To answer some of the questions:

The source code was not mentioned at all. There was no exclusive contract signed except for the usual agreement of the freelance site.

I am not sure if software development comes under work for hire and is it valid for users outside of the US?

The reason for not sharing the source code was this was a very small project and I got paid for a mere few hours. So if I have an option then definitely I would want to keep the source code to myself as that gives a possibility of the client coming back. The application works flawlessly and the code is solid. Also, the task that the client wanted to achieve was very challenging and I would not like other programmers (competitors) to know how I achieved it.

So unless I get the confirmation that the source code is purely the property of the client, I would not be willing to share it.

答:
In my experience, the source code IS typically handed over.

The reason for this is that the person hiring you is buying your time to write source code.  Usually if someone only gets the application and NOT the source code, they are buying a license to use the software, which is essentially what you're doing giving him the executable, but retaining all the source code.

That being said, what is written in the contract?  If it doesn't say specifically, then it's a legal gray area.  Legal gray areas mean that you probably can't get sued, and the only thing that's really on the line is your relationship with the client and your reputation.

Title: Freelancing - Share the source code?


答:
On "work made for hire" projects, it's not a matter of sharing the source code, the source code belongs to them.  For example, on the vWorker site, under Legal,  it says: "Employer will receive exclusive and complete copyrights to all work purchased."  The source code is part of the deliverable.

I don't know which freelancer site you did this through, but it's likely they have similar language.

Title: Freelancing - Share the source code?

Body:
Possible Duplicate:

Hand over source code to customer

I have developed a couple of form based windows application in vb.net for a client and they all work well and he paid me through a freelance site. I have handed over the executable and the setup to the client and all was well. Now the client wants the source code for the application. Is there a general practice on sharing the source code with the client?

Please note - the client never mentioned he needs the source code and he is now asking for it after a week after the app was completed and he made the payment.

I don't mind sharing the source code, but I am not sure if I should. This probably means the client would not hire me again and the bigger question is the source code really his property?

This question may have been asked a few times, but I cannot still draw a conclusion on what is right.

update

To answer some of the questions:

The source code was not mentioned at all. There was no exclusive contract signed except for the usual agreement of the freelance site.

I am not sure if software development comes under work for hire and is it valid for users outside of the US?

The reason for not sharing the source code was this was a very small project and I got paid for a mere few hours. So if I have an option then definitely I would want to keep the source code to myself as that gives a possibility of the client coming back. The application works flawlessly and the code is solid. Also, the task that the client wanted to achieve was very challenging and I would not like other programmers (competitors) to know how I achieved it.

So unless I get the confirmation that the source code is purely the property of the client, I would not be willing to share it.


问:
I target short projects, but fail miserably on projects that requires persistence
I know this is kind of time-management question. I do well in short assignments, but fail miserably, when it comes to projects that require hours and hours of work to be done day after day.

I cannot code more than 10 minutes, unless there is a deadline. I kinda wander and come back and code. It takes me ridiculously large amount of time even for simple project. I kinda lack persistence. I have my thesis coming up in December. The more time I spend, the better my publication will be.

I was wondering, may be I could get some help on how to code persistently?

I just get out of my chair and start doing other things, when I see a bug or when I have a module that requires thinking and it takes me long time to come back sit and put my thought back to the code.

Any advice on how to improve my persistent coding skills?

答:
I don't know what your field of study is but if it's anything related to Computer Science or Engineering I would question your future happiness in that field. I think I speak for many other programmers when I say that a programming problem that isn't solved in a couple of minutes is far more interesting and even enjoyable than routine coding. This is the reason many people want to develop, because they can use their brain and 'crack the code'.

Of course if your field of study only requires you to write some code now then I can understand your problem more clearly. Everyone has had to do things they really didn't want to do, when I'm faced with something like that I try to isolate the crappy part of that thing and really mentally challenge myself to do it as well as I possibly can. This sounds like very obvious advice, but if you're a competitive person you can really motivate yourself to put more effort into something than you would otherwise.


问:
Subrepositories (submodules) as a dependency tracking solution - yes or no?
What do you think about SCM-based (subrepositories in mercurial, submodules in git) dependencies management?

Is it definitely a good way of managing dependencies? Or definitely bad way?

Should I prefer some build system (ant/phing/rake) over subrepositories?

Some particular example for you to have a context:

I have several web applications that share across reusable components, say jquery plugins.

答:
When we switched from SVN to Kiln (Mercurial) a year ago we re-implemented our subrepositories also. I can honestly say that I wish I hadn't. Subrepositories quickly become a hassle to deal with keeping them up to date when the dependencies change. This is especially true when dealing with internal "third part" libraries that are under active development.

We are currently gradually converting over our dependencies to be NuGet packages built and hosted by our TeamCity server.

Before I could recommend subrepositories as a preferred solution choice, I would need to see a good argument in their favor.


答:
git submodules are great for this.  It allows you to keep all of your code in a bundle, upgrade with simplicity, do it on a per-project basis, not worry about the others, and basically keep everything sane.

A couple of caveats:

git pull && git submodule init && git submodule update --- these need to be part of your STANDARD workflow.

Submodules are hard if people are changing them resulting in conflicts.  Not too hard, but all you get is two SHA1's and you have to pick the best one, or manually merge them and upgrade the base repo.

Github is a great place to put all your git stuff.  That's just a side note, but I use a mix of public repos for open source submodules and private repose for the main project.

Hope this helps!

Title: Subrepositories (submodules) as a dependency tracking solution - yes or no?

Body:
What do you think about SCM-based (subrepositories in mercurial, submodules in git) dependencies management?

Is it definitely a good way of managing dependencies? Or definitely bad way?

Should I prefer some build system (ant/phing/rake) over subrepositories?

Some particular example for you to have a context:

I have several web applications that share across reusable components, say jquery plugins.