问:
I don't understand how TDD helps me get a good design if I need a design to start testing it
I'm trying to wrap my head around TDD, specifically the development part. I've looked at some books, but the ones I found mainly tackle the testing part - the History of NUnit, why testing is good, Red/Green/Refactor and how to create a String Calculator.

Good stuff, but that's "just" Unit Testing, not TDD. Specifically, I don't understand how TDD helps me get a good design if I need a Design to start testing it.

To illustrate, imagine these 3 requirements:

A catalog needs to have a list of products

The catalog should remember which products a user viewed

Users should be able to search for a product

At this points, many books pull a magic rabbit out of a hat and just dive into "Testing the ProductService", but they don't explain how they came to the conclusion that there is a ProductService in the first place. That is the "Development" part in TDD that I'm trying to understand.

There needs to be an existing design, but stuff outside of entity-services (that is: There is a Product, so there should be a ProductService) is nowhere to be found (e.g., the second requirement requires me to have some concept of a User, but where would I put the functionality to remind? And is Search a feature of the ProductService or a separate SearchService? How would I know which I should choose?)

According to SOLID, I would need a UserService, but if I design a system without TDD, I might end up with a whole bunch of Single-Method Services. Isn't TDD intended to make me discover my design in the first place?

I'm a .net developer, but Java resources would also work. I feel that there doesn't seem to be a real sample application or book that deals with a real line of business application.  Can someone provide a clear example that illustrates the process of creating a design using TDD?

答:
I am convinced that TDD is a very valuable approach to the detailed design of the system - i.e. the APIs and the object model.  However, to get to the point in a project where you would begin to use TDD, you need to have the big picture of the design already modeled in some fashion and you need to have the big picture of the architecture already modeled in some fashion.  @user414076 paraphrases Robert Martin as having a design idea in mind, but not being married to it.  Exactly.  Conclusion - TDD is not the only design activity going on, it is how the details of the design get fleshed out.  TDD must be preceded by other design activities and fit into an overall approach (such as Agile) that addresses how the overall design gets created and evolved.

FYI - two books I recommend on the topic that give tangible and realistic examples:

Growing Object-Oriented Software, Guided by Tests - explains and gives a full project example.  This is a book about design, not testing.  Testing is used as a means of specifying expected behavior during design activities.

test-driven development A Practical Guide - a slow and step-by-step walk through developing a complete, albeit small, app.


问:
Optimal way to store 18 billion key, value pairs
I have around 200 million new objects coming in, and a 90 day retention policy, so that leaves me with 18 billion records to be stored in the form of key-value pairs.

Key and value both will be a string. It is basically a mapping between a unique identifier for the object in the application to the unique identifier for the object in the actual object storage.

There is an application which loads objects into a Web OS. For each object it loads, it creates a 16 character string key, say DataID. The Web OS itself creates a 40 character string key, say ObjectID. So what I'm trying to do is create a mapping between DataID -> ObjectID for 18 billion objects. I'm don't know the mechanism being used to create the IDs.

I will have to deal with:

```<code>write(key,value)
read(key)
delete(key,value)
</code>```

I am looking for ideas for an optimal way to implement this. It should be optimized for reads & writes. Space optimization is secondary.

I know Hadoop/NoSQL is one way to go, and probably another solution would be distributed Hash tables, but a few more options would help me decide which is the best solution. A relational database is not an option as we don't have an existing RDBMS in the current environment.

答:
Look at these key-value stores: Berkeley DB Java Edition, or JDBM (JDBM3 is the latest), or MapDB (JDBM successor). Tokyo Cabinet is not native Java but has a Java wrapper.

For an overview see http://en.wikipedia.org/wiki/Dbm.

ContentLicense: CC BY-SA 3.0


问:
How would you get all your expectations done within a user story?
I'm setting up some requirements for a software extension and try to use user stories to describe what I want to achieve.

As a creator I want to add a new entry, to let users access it through the main page.

I have the idea of adding an entry via Drag&Drop. My company has some guidelines, to have every command always available via context menu and ribbon.

Should I split up my origin story into separate actions?

As a creator I want to drag a new entry onto the main page, to let users access it.

As a creator I want to create a new entry on the main page via ribbon, to let users access it.

As a creator I want to create a new entry on the main page via context menu, to let users access it.

That approach would result in at least three user stories per feature what won't feel comfortable to me.

I could add these expectations during the discussion, but then it seems like giving a "way-to-follow" for developers.

So how would I ensure that the required quality/user experience is achieved?

答:
What does your team think?  For some features, maybe a single story will be fine.  For other, more complicated functions, you may need three (or more) stories (One for command line, one for Web UI, one for Android, etc.).  Stories should not be written in a vacuum, include your technical minded folks as well and the process will flow much smoother.  At the beginning of each iteration, spend some time going over the stories with the team, and they will let you know if multiple stories are needed, or if one is fine.

Do not assume anything for a story, over-arching story requirements can often be overlooked, conflict with the story, or cause other complications.  Spend your time focusing on the end user experience, ideally create test cases/scenarios to accompany the story.  This will help guide the team to create the experience you want.

To assure quality you stop by to visit with the team, or even better sit with the team to be available anytime a question comes up.  The more time you are able to spend with the team, the more satisfied you are likely to be with the quality.  I'm not saying to micromanage every activity of ever minute, but rather to be available as discussions are taking place and questions come up.  Ask to see the product as it is being developed, don't wait for an iteration review or showcase.  In the end, Agile is about producing a quality product, that is why principles 1 and 2 are:

Individuals and interactions over processes and tools

Working software over comprehensive documentation

Cheers!


答:
Try redis. Its all in memory and dumps data so it can be hot on reset. However you might need to be careful and change the settings if you need to not lose data as it normally waits a second or two before dumping (or did i remember the default settings wrong?).

Use a hash where GUID/6 or 7 bits is the key and the remaining is a field http://redis.io/commands/hmset. Note having more field names make it slower so stick to <=128 as my personal rule of thumb. I recommend having 64 or 32bit but test with the keylength.

The reason I say use a hash is to decrease memory usage. More fields = less pointers (and an increase in CPU time)

Title: Optimal way to store 18 billion key, value pairs

Body:
I have around 200 million new objects coming in, and a 90 day retention policy, so that leaves me with 18 billion records to be stored in the form of key-value pairs.

Key and value both will be a string. It is basically a mapping between a unique identifier for the object in the application to the unique identifier for the object in the actual object storage.

There is an application which loads objects into a Web OS. For each object it loads, it creates a 16 character string key, say DataID. The Web OS itself creates a 40 character string key, say ObjectID. So what I'm trying to do is create a mapping between DataID -> ObjectID for 18 billion objects. I'm don't know the mechanism being used to create the IDs.

I will have to deal with:

```<code>write(key,value)
read(key)
delete(key,value)
</code>```

I am looking for ideas for an optimal way to implement this. It should be optimized for reads & writes. Space optimization is secondary.

I know Hadoop/NoSQL is one way to go, and probably another solution would be distributed Hash tables, but a few more options would help me decide which is the best solution. A relational database is not an option as we don't have an existing RDBMS in the current environment.


问:
How to generate random numbers with a (negative) sloping distribution?
Given a maximum integer value M, I want to generate N integer values that are distributed with a lower frequency when approaching M (preferably M should still have a non-zero probability).
I don't really care much about the probability function, let's assume (half of) a normal distribution.

How would I do that if I don't want to keep a history?

for i := 1 to N do GetNextTestValue(M)

What could GetNextTestValue look like?

FWIW I'm doing this in Delphi

答:
Building off of GrandmasterB's comment about pick two and select the lowest, I wrote a quick perl script to plot the random numbers and see the distributions - Pick the lowest of two provides one distribution, but others provide other distributions...

First, the code to see how it works and reproduce the results if you so desire.

```<code>#!/usr/bin/perl

use strict;
my $count = shift @ARGV;
my $nth = shift @ARGV;

my @nums = ();

for(my $i = 0; $i < 10_000; $i++) {
    my @rnd;
    for(my $j = 0; $j < $count; $j++) {
        push @rnd, int(rand(100));
    }
    @rnd = sort { $a <=> $b } @rnd;
    $nums[$rnd[$nth]]++;
}

for(my $i = 0; $i < 100; $i++) {
    print "$i\t" . (defined $nums[$i] ? $nums[$i] : 0) . "\n";
}
</code>```

The pick min(rand(100),rand(100)) produces a straight line distribution sloping down.

If you min(rand(100),rand(100), rand(100)), you can see a bit of a curve to it.

Exploring this just a bit further...
Picking the middle number of 7 produces something that looks more like a nice bell curve.

While the 2nd number of 7 produces a skewed one.

So, from this and the application of some stats to decide what shape you want it (or throwing out samples that don't meet the desired range to get the desired shape and skew)

Body:
Building off of GrandmasterB's comment about pick two and select the lowest, I wrote a quick perl script to plot the random numbers and see the distributions - Pick the lowest of two provides one distribution, but others provide other distributions...

First, the code to see how it works and reproduce the results if you so desire.

#!/usr/bin/perl

use strict;
my $count = shift @ARGV;
my $nth = shift @ARGV;

my @nums = ();

for(my $i = 0; $i < 10_000; $i++) {
    my @rnd;
    for(my $j = 0; $j < $count; $j++) {
        push @rnd, int(rand(100));
    }
    @rnd = sort { $a <=> $b } @rnd;
    $nums[$rnd[$nth]]++;
}

for(my $i = 0; $i < 100; $i++) {
    print "$i\t" . (defined $nums[$i] ? $nums[$i] : 0) . "\n";
}

The pick min(rand(100),rand(100)) produces a straight line distribution sloping down.

If you min(rand(100),rand(100), rand(100)), you can see a bit of a curve to it.

Exploring this just a bit further...
Picking the middle number of 7 produces something that looks more like a nice bell curve.

While the 2nd number of 7 produces a skewed one.

So, from this and the application of some stats to decide what shape you want it (or throwing out samples that don't meet the desired range to get the desired shape and skew)


问:
Why the current enthusiasm for Functional Programming?
I've been hearing a lot of enthusiasm about functional programming languages lately, with regards to Scala, Clojure, and F#.  I've recently started studying Haskell, to learn the FP paradigm.

I love it, it's really fun, and fits my math background.

But will it ever really matter?  Obviously, it's hardly a new idea.

Here's my questions:

What has contributed to the recent FP enthusiasm?  Is is merely boredom with OO, or has something changed to make FP more needed than before?

Is this indicative of a FP future?  Or is this a fad, like object orient databases?

In other words, can anyone help me understand where this comes from and where it might be going?

答:
I think it's a combination of two trends:

Functional features being added to mainstream languages (e.g. C#).

New functional languages being created.

There's probably a natural limit on the first trend, but my guess is that any new language will have to support functional programming, at least as an option, in order to be taken seriously.

ContentLicense: CC BY-SA 2.5


问:
Refactoring C++
I know that there are some other questions about C++ refactoring, but none satisfies my needs.

I have a background in Java and Python programming, but now I'm approaching C++. I've read (and absolutely love) books about agile coding, test-driven development (TDD), refactoring, etc. The first that comes in my mind is "Clean Code". From this I have learned a lot of things: keep my functions short, keep my classes short, keep names of variables/classes consistent, etc..

I like very much this way of working: first resolve the problem, then refactor in small functions (and one function does only one thing), adding subclasses, etc.

I strongly believe that this way of working is made easy by modern IDEs: add file, rename function, rename classes, etc..

I'm now coding in C++ with CMake inside Qt Creator. All of those things are more difficult. Even adding a file is "more difficult" (I have to generate one header file, one source file, add them to cmakelist.txt, run again cmake, etc.). Thinking about renaming files (I have to manually change all includes) or some strong refactoring methods that in Java with Eclipse has no cost now gives me a headache.

I mean.. it is not "difficult" in the meaning that are "hard task", but the human mind is kind of lazy: if I can do other easiest way..

In Java with some modern IDE like Eclipse.. refactor is the fun part; some clicks and voilà, it is done. I do it every time I pass a test. It is easy, fun, and I like reading my clean code with small functions and nice names.

Now everything is more difficult mainly because there are no tools that can do it without cost. I bare myself in bad attitudes driven by lazyness: write several classes in a single super-long .h file because I don't want to create new files, spent hours in modifying classes/functions/variables with more appropriate names and manually change all includes, write long functions because when I automatically change a function's attributes that concerns the std lib Qt Creator is deleting the templates so I avoid it, and many others..

This is quite frustrating.. What can you advice me? Do I have to get more relaxed in the "rules" of writing clean code? Do I have to does not think about this stuff and thinking only in getting things works? Or (maybe this is the more importart question) do I have to be thinking about some other way of working? No more incremental/iterative/agile way, but more waterfall and spend more time in designing stuff before coding in the hope of minimize the refactoring when the tests are passed?

Anyway, any comment are welcome because I am very far from being a good programmer : )

答:
Now everything is more difficult mainly because there is no tools that can do it without cost. I bare myself in bad attitudes driven by lazyness: write several classes in a single super-long .h file because I don't want to create new files,

Let me just reflect on this. It keeps popping up and I remain baffled. Why people are obsessed with packaging things in separate files. Here in 2013? Why putting more than one classes in a header considered lazy or bad?

And while for headers I could find some excuses but same applies to implementation files too. I ask why and a common answer I dread is "so I find my stuff easily". And demo looks like he summons the solution explorer, spends a minute closing irrelevant branches, thinks another minute which project it will be, then locates it on three, inside tries different subbranches, and eventually searches (using eye) the file matching the class name from a list of 50 similar names. Finally opening it with a small hooray. While I want to shoot myself six times in the back and jump in the river.

While we have VA-X "open file in project" and the way better "locate symbol", and 1-click navigation, or as last resort the old-style find-in-files, all could produce anything from anywhere in seconds. And even with the just described WTF method it would be way faster to find the thing if all the 50 files were just concatenated to one.

Those who fiddle with build with C++ know well that the time is quite proportional with the number of .cpp files while length of a file is irrelevant. 50 classes put in 50 files will compile 50 times slower than if we put them all in one file. Ok, maybe only 25 times, but that is still a huge figure.

With really old editors it could be a problem to work on multiple places unless in separate files. But I can ask unlimited number of windows on the same file, and usually split any window to multiple panes too. And drop bookmarks with a single stroke that are preserved until deleted.

And for documentation/reading purposes we have doxygen -- it will show the classes separately, with inline code removed, etc. Regardless of how classes appear in sources.

Even if I chose to read the source directly, since when is a "class" a basic unit? It was always "package", "module, "library"  or something alike that, having a concise philosophy, and a fair collection of classes, functions supporting enums, macros and other gizmos. Best if all co-located rather than spread all over the place.

A set of problems referred in the question is actually coming from this artificial split. Declarations must be maintained in headers? How many of those is actually for "export" and how many for internal use inside a component? Majority of the latter ones is not necessary without the split, as the function will just be a static one defined early on. What is so much lighter maintenance-wise.

The only drawback from join is that static/at-namespace object could clash. But those are hopefully blacklisted long time ago.

How about refactoring the system toward a state that causes less trouble? And not introducing headaches artificially following some ideas left behind by Noah?

Title: Refactoring C++


答: You are quite correct TDD will result in a good implementation of a given design. It will not help your design process.

Title: I don't understand how TDD helps me get a good design if I need a design to start testing it

Body:
I'm trying to wrap my head around TDD, specifically the development part. I've looked at some books, but the ones I found mainly tackle the testing part - the History of NUnit, why testing is good, Red/Green/Refactor and how to create a String Calculator.

Good stuff, but that's "just" Unit Testing, not TDD. Specifically, I don't understand how TDD helps me get a good design if I need a Design to start testing it.

To illustrate, imagine these 3 requirements:

A catalog needs to have a list of products

The catalog should remember which products a user viewed

Users should be able to search for a product

At this points, many books pull a magic rabbit out of a hat and just dive into "Testing the ProductService", but they don't explain how they came to the conclusion that there is a ProductService in the first place. That is the "Development" part in TDD that I'm trying to understand.

There needs to be an existing design, but stuff outside of entity-services (that is: There is a Product, so there should be a ProductService) is nowhere to be found (e.g., the second requirement requires me to have some concept of a User, but where would I put the functionality to remind? And is Search a feature of the ProductService or a separate SearchService? How would I know which I should choose?)

According to SOLID, I would need a UserService, but if I design a system without TDD, I might end up with a whole bunch of Single-Method Services. Isn't TDD intended to make me discover my design in the first place?

I'm a .net developer, but Java resources would also work. I feel that there doesn't seem to be a real sample application or book that deals with a real line of business application.  Can someone provide a clear example that illustrates the process of creating a design using TDD?


问:
Aren't structured programming and object oriented programming complementary?
It seems there is a lot of discussion on the web about the differences between these two paradigms, and how OOP is somewhat better than structured programming.

But aren't they complementary? From my point of view one could organize his application following OOP principles and implement its logic using structured programming, couldn't he?

答:
You can argue that OOP builds upon structured programming in general - so yes they are complementary in that sense.

Remember that programming paradigms are mostly about what you don't do:

Structured programming removes unconstrained branching and jumping (so that code executes in well-defined structured blocks such as while loops)

OOP removes polymorphism via function pointers (instead relying on object methods and virtual dispatch to achieve polymorphism)

You could theoretically conceive of a language that encourages unconstrained branching and jumping but uses objects and OOP-style method dispatch. It would then be OOP but not structured... however it would be a very strange language. I'm not aware of anything like it.


问:
Designing a robust architecture for multiple export types?
I'm looking for patterns or architectural guidance for an upcoming feature I'm designing. Basically, it's an export feature with multiple export targets, and I'm looking to find a way to make it generic enough where plugging in new export targets don't require a lot of core changes. By export targets, I'm simply referring to different types of output, whether that be PDFs, PowerPoint presentations, Word documents, RSS, etc. I have a base set of data, which is represented in JSON and XML. This data are used to construct images (using any number or export types [e.g., PNG, JPG, GIF, etc), graphs, textual representations, tables, and more.

I'm trying to find a way to abstract all the rendering and layout into some kind of rendering or layout engine that handles the addition of further export targets. Any help/suggestions/resources as to how to approach this would be greatly appreciated. Thanks in advance.

For a pictorial representation of what I'm trying to achieve.

答:
While I agree that more information is needed to think about an architecture, the most simple way to create different kind of objects that behave the same (i.e. all of them  will generate an output) is using the factory pattern. More info here

The factory method pattern is an object-oriented creational design
  pattern to implement the concept of factories and deals with the
  problem of creating objects (products) without specifying the exact
  class of object that will be created. The essence of this pattern is
  to "Define an interface for creating an object, but let the classes
  that implement the interface decide which class to instantiate. The
  Factory method lets a class defer instantiation to subclasses."
  From wikipedia


问:
Can you close branches in Git?
In Mercurial you can close a branch like this: hg commit --close-branch, this means the the branch will not be listed anymore but will still exist, and can still be listed if you use hg branches --closed

I have learned that in Git generally branches are not kept, they disappear, specially when doing fast-forward merges.

So my question is: can you keep branches in git but in a way that you don't list them anymore?

Edit: Some additional context: In Mercurial branches are metadata, so each commit always knows it's branch. In Mercurial if you want to delete a branch, you strip the base branch revision. You can also rebase and end up with the same result as with Git. Mercurial Bookmarks are pointers, so they have the exact same behavior than a Git Branch.

答:
I know it's not exactly the same, but could you use a workflow where you tag the feature branches before ‘closing’ them?

For example:

```<code>git merge feature-wxyz -m "Merge message"
git tag closed-feature-wxyz feature-wxyz
git branch -d feature-wxyz
</code>```

Of course, you could also annotate the tag (git tag -a closed-feature-wxyz -m "Description of closed branch" feature-wxyz) if you wish.

I know it's not exactly what you asked for, but this would satisfy:

a record of the branch is kept

the branch is no longer visible in git branch

you can still base a new branch on the closed one: git checkout -b new-feature-ghij closed-feature-wxyz

Title: Can you close branches in Git?

Body:
I know it's not exactly the same, but could you use a workflow where you tag the feature branches before ‘closing’ them?

For example:

git merge feature-wxyz -m "Merge message"
git tag closed-feature-wxyz feature-wxyz
git branch -d feature-wxyz

Of course, you could also annotate the tag (git tag -a closed-feature-wxyz -m "Description of closed branch" feature-wxyz) if you wish.

I know it's not exactly what you asked for, but this would satisfy:

a record of the branch is kept

the branch is no longer visible in git branch

you can still base a new branch on the closed one: git checkout -b new-feature-ghij closed-feature-wxyz


问:
Where is Waterfall failing us and can Scrum help us have success in our projects?
Let me explain our situation. We are small company with about 20+ staff and all the while we have been practicing the standard waterfall model with not much success (due to frequent changes of requirements and lack of direction).

So one day our CTO came in and he briefed us about SCRUM and all of us were convinced that this model will work great for a small team like us. Unfortunately all of us do not have any experience practicing SCRUM and we have been relying mostly on online resources and books.

Then we come to a new project that we are about to get started and we are doing something like:

Gather requirements from  business domain user

Prepare a requirement spec with UI and features (this already took us like weeks)

Meet up again  business domain user to see if there is any changes required

Once the business user agrees to the specs we will key in those feature in to product catalog

Break those features into tasks and assign to sprint

Should we instead take the more agile approach? like

Gather requirements from stakeholders

Start to create epic user stories and run through with stake holders

Break those epic stories into smaller stories (supported with some ui) and
   assign to a  short sprint(2 weeks)

We show them what we have done for the 2 weeks, get their feedback and plan for the next sprint

Given the nature of our projects where we are constantly faced with the challenges of volatile requirements and a lack of direction, where will the above Scrum/Agile points benefit us and why are the above Waterfall methods failing us?

答:
The main advantage of SCRUM (and agile methods in general) is that you get better and quicker feedback (on implementations, not just specs) from the stakeholders, and thus there is less risk of working weeks and months on something that ends up being not what they wanted. Additionally, you often deliver the most useful features sooner (due to prioritization and the sprint release cycle).

If you all agree that you will benefit from these advantages, and if the stakeholders are willing to do their part (give more frequent feedback), then yes, you should to SCRUM (the second process you describe) instead of waterfall (the first process you describe has nothing to do with SCRUM).


答:
It seems as you were falling back to old/known procedures.
One key concept of SCRUM / agile development is that you don't have a big upfront specification. Of course you need to know about the whole view from the beginning, but you must not put every detail into specification. That is what leads to a waterfall process, which is bad because it is not flexible and changes or new insights are expensive.

When starting with Scrum, you should have an expert Scrum-Master - one who does that quite some time. If you don't have one in your team, you should hire one. At least for the first few sprints.

You also should have the support of your management (as you do), AND the support of your customer, because (s)he needs to provide the product owner. This last point (availability of the customer/product owner) is in my experience very often not the case. Agile still could make sense in those cases, because you can change direction more easily and you could get fast feedback to your work.

BTW: usually you don't specify how the UI should look like. This is an implicit requirement that stems from the feature description. Of course there will be a style-guide that covers all basic UI concepts, but you don't do special UI things for different features, unless this is the aim of the feature.

Title: Where is Waterfall failing us and can Scrum help us have success in our projects?

Body:
Let me explain our situation. We are small company with about 20+ staff and all the while we have been practicing the standard waterfall model with not much success (due to frequent changes of requirements and lack of direction).

So one day our CTO came in and he briefed us about SCRUM and all of us were convinced that this model will work great for a small team like us. Unfortunately all of us do not have any experience practicing SCRUM and we have been relying mostly on online resources and books.

Then we come to a new project that we are about to get started and we are doing something like:

Gather requirements from  business domain user

Prepare a requirement spec with UI and features (this already took us like weeks)

Meet up again  business domain user to see if there is any changes required

Once the business user agrees to the specs we will key in those feature in to product catalog

Break those features into tasks and assign to sprint

Should we instead take the more agile approach? like

Gather requirements from stakeholders

Start to create epic user stories and run through with stake holders

Break those epic stories into smaller stories (supported with some ui) and
   assign to a  short sprint(2 weeks)

We show them what we have done for the 2 weeks, get their feedback and plan for the next sprint

Given the nature of our projects where we are constantly faced with the challenges of volatile requirements and a lack of direction, where will the above Scrum/Agile points benefit us and why are the above Waterfall methods failing us?


问:
Why is the factory method design pattern more useful than having classes and calling them individually?
From the "Gang of Four" design patterns, there's the Factory method:

```<code>class Factory(product)
  case product
  when a
    new A
  when b
    new B
  when c
    new C
end

new Factory(a)
</code>```

Why is this more useful than having three classes, a, b, and c and calling them individually?

答:
Because your example is not complicated enough. For such a simple scenario it doesn't even make sense to use an advanced pattern.

But if you have to know more than the product to construct A, B or C, and you can't have direct access to that knowledge, then it is useful. Then you are using the factory to act as a knowledge center for producing needed objects.

Maybe those objects need a reference to some object X, which the factory can provide, but your code in the place where you want to construct A, B or C can't or shouldn't have access to X. Maybe when you have X you create A and B but if you have Y type then you create C.

Also consider that some objects might need 20 dependencies to create; what then?
Going to hunt for those dependencies in a place where they should not be accessible might be problematic.


答:
The second approach is much more in the spirit of agile/scrum, but it also requires a commitment from the customer to visit regularly to see the progress and discuss further features.

If the customer is uncomfortable with such a commitment of effort on their side, or if they already have a very good idea of what they want to have, then your first approach might be more constructive.

One of the key points of scrum is that the customer gets a big say in the order in which things are produced, so let them clearly indicate which features they would rather have sooner and which features might end up in the bin if the budget gets too stretched. And don't kick up a fuss if the customer changes his mind on some requirements/stories, especially if they haven't been implemented yet.

An alternative approach, in a more scrum-like manner, but similar to the first approach, is like this:

Gather requirements

Split requirements into stories and put them on a backlog

Start first sprint with stories "create architecture" and "UI proposal"

During the sprint, discuss your proposals with the customer

Refine the backlog

As each sprint ends, pick the next top X stories from the backlog to implement.


答:
The key advantages of the Factory pattern are twofold:

The places that need an implementation of the product do not need to know how to construct one. The factory holds that information.

Do you want to know what arguments to pass to the particular constructor? Or what dependencies you have to inject? Or how to register the implementation class with the database after it is fully configured? No? Let the factory look after all that stuff.

The places that need an implementation of the product do not need to know at the time of module description (i.e., at compilation time) what the name of the implementation class is.

Thus, a need not have anything to do with A; the “what to build” can be described in terms of the desired non-functional properties, and not just the name. This is much more flexible.

The downside is that where you know what to make and how to do it, you get more complexity when you use a factory. The fix to that is simple though: don't use a factory when it doesn't make sense!

Title: Why is the factory method design pattern more useful than having classes and calling them individually?

Body:
From the "Gang of Four" design patterns, there's the Factory method:

```<code>class Factory(product)
  case product
  when a
    new A
  when b
    new B
  when c
    new C
end

new Factory(a)
</code>```

Why is this more useful than having three classes, a, b, and c and calling them individually?


答:
A factory pattern is usually more complex than that. A factory decides on certain criteria which instance to create/return. Instead, when you don't use the factory, you would have that code repeatedly used in several locations in your code.

As an example consider the following: you need to load data from a DB, but you have one central DB for integration with lots of data, and one smaller one in memory on each dev-PC. In your code you ask a factory to get a DB-handle and the factory returns one of those depending on e.g. a configuration file.


问:
Does the WTFPL free the author from liability?
A group of us were wondering whether or not to go with CC0 or WTFPL because the CC0 explicitly states lack of liability.

Does the WTFPL, if used properly, also free the author(s) from liability of usage?

答:
No. if WTFPL is used as it is, it does not free the author from liabilities. Check the answer for Why is there no “no warranty” clause? in FAQ.

You are required to add (explicitly) NO WARRANTY clause.


问:
Can one forget programming if it is not practiced for some time?
Someone told me that easiest way to 'destroy' a programmer is to prevent them from programming for a month or so. Is that correct? What should I do to make sure I stay in practice if I'm not in a position to program as part of my job?</p>

答:
I've been reading through this thread and I realize I was suffering the same problem as many programmers does? I'm sure, the one who puts this topic is also facing this problem, however he would not ask this question if he's not, :)

Well in my case, I'm working as a corporate information person in our company, my work here is not related to my field which is software development such as Java SE,Visual Basic, Mysql, IReport etc..  I almost stop programming for almost 2 years.. then I came to realize that i want to go back to developing software because its my passion, it's what I've worked so hard during my college days.

Suddenly, I can manage to create the program. But! not as good as I was before, maybe because I lack practice, programs that are simple to me before were complicated to me now, so I'm planning on getting back to basics. Just as before to familiarize things and practice my rusty skills and get back to business.

How long will it takes for me? well I don't know,? maybe? If I put pressure on myself to speed up my career I may get back to where I was in software development just like the old times or even better. All we need is an opportunity to get back. To all those facing the same scenario as mine,

don't lose hope.

in our profession. We know to ourselves how good are we before or now, and no one can take that away from us. "Once a Programmer, Always a Programmer"


问:
Writing code based on code snippet from the internet without license
I'm working on an assembly project and I need to write code to switch from text to VGA mode. This is fairly complex and requires setting up a lot of data, so I'd rather not write it myself.

Fortunately I found a snippet of code on the internet that does exactly what I want. Unfortunately it does have a copyright notice, but no license is anywhere to be found.

I've currently written my own code with the snippet as a reference, but in the end it's basically the same code with different variable names and comments. Then again, with assembly there's only so many ways you can introduce variation in your code.

Is it okay if I publish my code with for example a notice that it was inspired by that snippet? Or am I not allowed to do this at all?

答:
For a definitive answer, you will need to consult a lawyer.

The fact that your code is not a literal copy is a good start. The two remaining questions are

Are the differences of such a nature that they are not the result of a mechanical process but required original thought?

Given sufficient time and effort, could you have written this code without referencing the snippet you found? This question is more borderline between copyright and patent issues.

If the answer to both is 'yes', chances are that you can publish your code.


问:
IDE Generated Code
Many IDEs have the ability to spit out automatically written pieces of code. For example, it might generate a getter/setter pair for you. I wonder whether it isn't an attempt to work around some flaws in the language. If your IDE can figure out what the code should be without your help, why can't the compiler?

Are there cases where this is a really good idea? What kind of code generation does your IDE provide? Would the same thing be better provided as a feature of the language?

答: I can't improve on Charles Petzold's excellent "Does Visual Studio Rot The Mind?" (http://www.charlespetzold.com/etc/DoesVisualStudioRotTheMind.html). I think that the IDE and code generation in general has its place but if you as a developer do not already know why it is doing what it's doing (in the case of code generation having written the templates yourself, preferably) then you are flying blind. Being able to build something from scratch in a text editor is a good indication that you understand what's going on. That said it would be foolish to insist on only ever writing every last line from scratch by yourself every time you have to get something done.</p>

Title: IDE Generated Code


答: I'm not aware of this feature directly but as in git tag and branch is essentially the same except for the latter not being a head, if you create a tag and remove he branch, IMO you get the same behavior. Unless I misunderstood the real goal.</p>

Title: Can you close branches in Git?

Body:
In Mercurial you can close a branch like this: hg commit --close-branch, this means the the branch will not be listed anymore but will still exist, and can still be listed if you use hg branches --closed

I have learned that in Git generally branches are not kept, they disappear, specially when doing fast-forward merges.

So my question is: can you keep branches in git but in a way that you don't list them anymore?

Edit: Some additional context: In Mercurial branches are metadata, so each commit always knows it's branch. In Mercurial if you want to delete a branch, you strip the base branch revision. You can also rebase and end up with the same result as with Git. Mercurial Bookmarks are pointers, so they have the exact same behavior than a Git Branch.


答:
Big Fat Warning

IANAL and I might be a dog.

While I agree with Bart's answer, mostly for his "you will need to consult a lawyer" because that's what you should do when you have concerns about legal matters, your question can be answered a bit more clearly.

On Copyright

If you find something which isn't explicitly stated as being in the public domain or with other copyright information, then it belongs to whoever published it, unless proof of the contrary exists.

Of course, that's only the tip of the iceberg, as something you found online could very well be reproduced by someone who malevolently decided to say "here, I make this PD" even though they took it from a non-PD source. Also, the thing with law is that it isn't universal and  varies from one country to another, and international copyright laws are murky waters.

See the Berne Convention for a classic example of international copyright agreements.

On Licensing

Regarding the right to re-use and re-distribute, the general rule is that if someone made something publicly visible in sime form, you are entitled to reproduce and use it privately, unless otherwise stated (this is a common concept for instance for taking photos of publicly visible items or people (see: 1, 2, 3), duplication of CDs for private use or backup purposes, etc...).

For commercial re-use and public re-distribution, however, if there's no clarifiaction you will need to get a licensing right granted by the copyright holder (did you try to contact that person), unless in some circumstances:

your use of the material falls under the "fair use" conditions (quite unlikely for source code re-used in a program)

your use of the material is in a derivative work and is transformative,

you can provide sufficient proof that you made all possible attempts to contact the copyright holders (and transitive right holders) and they could not be located (meaning you can actually prove that nobody else owns the copyright, which is going to be a long and difficult process).

Get in Touch

So, easiest routes for you:

contact the owner and ask for an explicit re-use and re-distribution license (with modification rights, if necessary),

contact a lawyer.

Title: Writing code based on code snippet from the internet without license

Body:
I'm working on an assembly project and I need to write code to switch from text to VGA mode. This is fairly complex and requires setting up a lot of data, so I'd rather not write it myself.

Fortunately I found a snippet of code on the internet that does exactly what I want. Unfortunately it does have a copyright notice, but no license is anywhere to be found.

I've currently written my own code with the snippet as a reference, but in the end it's basically the same code with different variable names and comments. Then again, with assembly there's only so many ways you can introduce variation in your code.

Is it okay if I publish my code with for example a notice that it was inspired by that snippet? Or am I not allowed to do this at all?


答:
The Factory Method pattern abstracts the decision-making process from the calling class. This has several advantages:

Reuse. If I want to instantiate in many places, I don't have to repeat my condition, so when I come to add a new class, I don't run the risk of missing one.

Unit-Testability. I can write 3 tests for the factory, to make sure it returns the correct types on the correct conditions, then my calling class only needs to be tested to see if it calls the factory and then the required methods on the returned class. It needs to know nothing about the implementation of the factory itself or the concrete classes.

Extensibility. When someone decides we need to add a new class D to this factory, none of the calling code, neither unit tests or implementation, ever needs to be told. We simply create a new class D and extend our factory method. This is the very definition of Open-Closed Principle.

You can even create a new factory class and make them hot-swappable, if the situation requires it -- for example, if you want to be able to switch class D on and off, while testing. I have run into this situation only once, but it was extremely useful.

As has been said, the Factory Pattern isn't always the way to go. But, wherever you see conditional instantiation, you should give it a moment's thought.


问:
Why do people fork repositories on GitHub?
I noticed that a lot of GitHub accounts only have repositories which are forked from other accounts. In addition the people who do this usually don't make any contributions to the forked repositories.

I've heard of people collecting stamps and seashells, but why would anybody want to collect repositories? Personally I would only fork a repository if I wanted to make some changes to it.

答:
As you mentioned in your question, people fork repositories when they want to make a change the code, because you
don't have write access to the original repository (unless you've been added as a collaborator by the owner of the repository).

In the forked repository they have write access and can push changes. They may even contribute
back to the original repository using pull requests.

I think there are multiple reasons why people fork repositories but don't change them:

they might fork a repository which looks cool, simply fork it (because it's easy (only one click)) and want
to make a change later (and then probably forget it/didn't have time to do so)

they fork a repository to make a change and then discover that the change is unnecessary and forget to delete
the own repository

they might fork a repository because one of the projects depends on an other repository (maybe via submodules) and
they want total control over the repository used as a dependency (the owners of the original repository might decide to move from github to google code etc.)

they might simply forget to push the commits


答: One possible reason: they have running code that depends on those projects and their build process involves pulling the dependencies from github. Having the fork protects them against breaking changes. For projects that don't tag versions, this is the easiest way to achieve that.</p>

Title: Why do people fork repositories on GitHub?

Body:
I noticed that a lot of GitHub accounts only have repositories which are forked from other accounts. In addition the people who do this usually don't make any contributions to the forked repositories.

I've heard of people collecting stamps and seashells, but why would anybody want to collect repositories? Personally I would only fork a repository if I wanted to make some changes to it.


问:
Java generalization
I have a question regarding generalization. I know when it is needed to be done, but is it worth having an extra class for 1 field?

e.g.:

StatisticsCustomer has fields: Customer customer and int projectCount
StatisticsCountry has fields: Country country and int projectCount

What is best in this situation? Creating an extra class just for projectCount or keeping it twice in the two classes?

答:
You are giving far too little context to make that decision.

That said, whether to model things as different classes of the same class has little to do with how many different fields they have, and very much with how you expect to use them in your program. The canonical example is a Point class with Cartesian versus polar coordinates; both will probably have two numeric private fields, but those two pairs of numbers don't mean the same, so it would be terrible to use only one class and try to keep track of what the fields mean - two structurally identical classes that are different according to the type system are clearly the right thing to do.

In your example, all I can say is that I can see no circumstance in which you would want to treat a customer and a country interchangeably, except maybe if all you want to do is create viewgraphs of distributed data where the type of data doesn't matter at all (maybe you work in the U.N. statistics office?). In almost any program I can imagine, customers and countries need to be kept separate, and using the type system to make that distinction is virtually always a good idea.

Title: Java generalization


答:
We're moving to an era where multi-core processing isn't just something done in the back rooms of science labs or on specialty hardware.  It's now being done with commodity processors.  Functional programming, at least most of the variants I've been exposed to, generally attempts to push a view on side-effect free, stateless computational units.  This is the quintessential paradigm for multi-core work as there is no need to keep state commingled between processors.

This is only one of the reasons but a damn good reason to see functional programming taking hold.

Title: Why the current enthusiasm for Functional Programming?

Body:
I've been hearing a lot of enthusiasm about functional programming languages lately, with regards to Scala, Clojure, and F#.  I've recently started studying Haskell, to learn the FP paradigm.

I love it, it's really fun, and fits my math background.

But will it ever really matter?  Obviously, it's hardly a new idea.

Here's my questions:

What has contributed to the recent FP enthusiasm?  Is is merely boredom with OO, or has something changed to make FP more needed than before?

Is this indicative of a FP future?  Or is this a fad, like object orient databases?

In other words, can anyone help me understand where this comes from and where it might be going?


答:
Why not a generic class that works for any type of statistics? So that you always have a single class.</p>

```<code>public class Statistics<E>
{
   private E element;
   private int projectCount;

   ...
}

Statistic<Customer> myStCustomer = new Statistic<Customer>(...)
Statistic<Country> myStCountry = new Statistic<Country>(...)
</code>```

Title: Java generalization

Body:
I have a question regarding generalization. I know when it is needed to be done, but is it worth having an extra class for 1 field?

e.g.:

StatisticsCustomer has fields: Customer customer and int projectCount
StatisticsCountry has fields: Country country and int projectCount

What is best in this situation? Creating an extra class just for projectCount or keeping it twice in the two classes?

Body:
Why not a generic class that works for any type of statistics? So that you always have a single class.

public class Statistics<E>
{
   private E element;
   private int projectCount;

   ...
}

Statistic<Customer> myStCustomer = new Statistic<Customer>(...)
Statistic<Country> myStCountry = new Statistic<Country>(...)


问:
Why is it a good idea for "lower" application layers not to be aware of "higher" ones?
In a typical (well-designed) MVC web app, the database is not aware of the model code, the model code is not aware of the controller code, and the controller code is not aware of the view code. (I imagine you could even start as far down as the hardware, or perhaps even further, and the pattern might be the same.)

Going the other direction, you can go just one layer down. The view can be aware of the controller but not the model; the controller can be aware of the model but not the database; the model can be aware of the database but not the OS. (Anything deeper is probably irrelevant.)

I can intuitively grasp why this is a good idea but I can't articulate it. Why is this unidirectional style of layering a good idea?

答:
Expanding on Kilian Foth's answer, this direction of layering corresponds to a direction in which a human explores a system.

Imagine that you are a new developer tasked with fixing a bug in the layered system.

Bugs are usually a mismatch between what customer needs and what he gets. As the customer communicates with the system through UI, and gets result through UI (UI literally means 'user interface'), the bugs are reported in terms of UI too. So, as a developer, you don't have much choice but to start looking at UI too, to figure out what happened.

That is why having top-down layer connections is necessary. Now, why don't we have connections going both ways?

Well, you have three scenarios how that bug could ever occur.

It could occur in UI code itself, and so be localised there. This is easy, you just need to find a place and fix it.

It could occur in other parts of the system as a result of calls made from UI. Which is moderately difficult, you trace a tree of calls, find a place where the error occurs, and fix it.

And it could occur as a result of a call INTO your UI code. Which is hard, you have to catch the call, find its source, then figure out where the error occurs. Considering that a point you start at is situated deep down in a single branch of a call tree, AND you need to find a correct call tree first, there could be several calls into the UI code, you have your debugging cut out for you.

To eliminate the hardest case as much as possible, the circular dependencies are strongly discouraged, layers connect mostly in top-down fashion. Even when a connection the other way is needed, it is usually limited and clearly defined. For example, even with callbacks, which are a sort of reverse connection, the code being called in callback usually provides this callback in the first place, implementing a sort of "opt-in" for reverse connections, and limiting their impact on understanding a system.

Layering is a tool, and primarily aimed at developers supporting an existing system. Well, connections between layers reflect that, too.


问:
Request - Reply vs Publish-subscribe
We are working on a integration between two large systems.
System A is a database with employee data, and System B is an external system that is used for the daily contact with the customers (i.e meetings, locationdata,work order,work status, and so on). We will deploy a ESB in the middle.

There are 3 instances of System A, and 1 instance of System B.
This is due to legal restrictions and we cannot have all System A data in the same database.

In System B we have 20-30 active contacts each day, where some of the data from System A is used continously.

We need to update meeting, location, and work status in System B throughout the day. And have two proposed solutions for integrating these systems.

Solution A:
Publish-Subscribe - System A sends out update messages (This is based on HL7 ADT Standards) and the instance of System B picks up the data that is for them. This is done as broadcast and will generate 1000-10000 messages pr day. It will send information from System A on all employees, thus generating a message for every employee in System A (1,2,3). There is only a subset of employees from System A that is "active" and interesting for updates in System B. But messages will flow on ALL employees since data is updated by other systems aswell.

Soltion B:
System B ask for updated information through a request-reply solution. Will generate empty calls, but will only ask for the employees "active" in System B on given day.

Comments on solutions? Pros - Cons?
What is the most infrastructure "heavy" solution between these two?

Hope there is someone out there who could give me som pointers  :)

答:
Since you are using System B in real-time, you should chose whatever architecture you can technically implement, that will give you the most up-to-date data in System B, whilst using the least resources.

You need to look at the implementation details of Solution A and B, and see what gives a better current-data to resource(memory, CPU) consumption. Ideally you'd have a publish service  on System A per record, that informs System B when an individual record in System A has been changed... but that is neither of your proposed solutions.

Title: Request - Reply vs Publish-subscribe


答:
While ease of understanding and to some degree replaceable components are certainly good reasons an equally important reason (and probably the reason that layers were invented in the first place) is from the software maintenance viewpoint. The bottom line is that dependencies cause the potential to break things.

For example, suppose A depends on B. Since nothing depends on A, developers are free to change A to their hearts content without having to worry that they could break anything other than A. However, if the developer wants to change B then any change in B that is made could potentially break A. This was frequent problem in early computer days (think structured development) where developers would fix a bug in one part of the program and it would raise bugs in apparently totally unrelated parts of the program elsewhere. All because of dependencies.

To continue with the example, now suppose A depends on B AND B depends on A. IOW, a circular dependency. Now, anytime a change is made anywhere it could potentially break the other module. A change in B could still break A, but now a change in A could also break B.

So in your original question, if you are on a small team for a small project then all this is pretty much overkill because you can freely change modules at your whim. However, if you are on a sizeable project, if all modules depended on the others then everytime a change was needed it could potentially break the other modules. On a large project, knowing all the impacts could be difficult to determine so you'll likely miss some impacts.

It gets worse on a large project where there are many developers, (e.g. some who only work layer A, some layer B and some layer C). As it becomes likely that each change has to be reviewed/discussed with members on the other layers in order to make sure your changes don't break or force rework on what they are working on. If your changes do force changes on others, then you have to convince them that they should make the change, because they aren't going to want to take on more work just because you have this great new way of doing things in your module. IOW, a bureaucratic nightmare.

But if you limited dependencies to A depends on B, B depends on C then only layer C people need to coordinate their changes to both teams. Layer B only needs to coordinate changes with the Layer A team and the layer A team is free to do whatever they want because their code doesn't affect layer B or C. So ideally, you'll design your layers so layer C changes very little, layer B changes somewhat and layer A does most of the changing.

Title: Why is it a good idea for "lower" application layers not to be aware of "higher" ones?

Body:
In a typical (well-designed) MVC web app, the database is not aware of the model code, the model code is not aware of the controller code, and the controller code is not aware of the view code. (I imagine you could even start as far down as the hardware, or perhaps even further, and the pattern might be the same.)

Going the other direction, you can go just one layer down. The view can be aware of the controller but not the model; the controller can be aware of the model but not the database; the model can be aware of the database but not the OS. (Anything deeper is probably irrelevant.)

I can intuitively grasp why this is a good idea but I can't articulate it. Why is this unidirectional style of layering a good idea?


问:
What to do when a company request permission to use open source code without attribution?
I have an opensource project currently under MIT license. I have received a request from a company to use my code for their commercial project without having to give any attribution or credit.

To be honest, when I released the code, my sole intention was only to help a fellow programmer, and I didn't really think about if I was credited. Choosing the license was just one of the step I had to do to set up the project on codeplex.

On one hand, I feel honored and appreciate that they actually bothered to ask, on the other hand, I felt if I just allowed them to do so without any cost may just destroy the spirit of open source.

What are the typical things I or other code owners can do or request from the company to make it a fair trade? Should I even allow it?

I am thinking of asking the company to write a official letter of intent and I will sign against it just to make it more formal; and also to request a donation to project/charity of my choice or buy something on my wishlist as compensation (not very expensive). Will that be too much?

答:
If you're the only contributer it is up to you. You can request anything to change the license for the asking company.

If there're other contributers you have to ask also them.


答:
Many open source applications have closed source licensing options for just this scenario. How much you charge them is dependent on:

the size of the company (how much can they afford)

what they're going to do with it (if they're stealing it or just using it)

what they expect you to do (support/updates/extensions? what contractual level?)

a ton of other things.

Do you want to avoid tax implications of income? Do you hate the company? etc.

In general, I would treat it as a business deal while knowing that you've got all the leverage. The mindset of "I'd like to promote open source, so I'm charging you $5k (or whatever else high quote seems appropriate for that company for your project) - do you really not just want to give me attribution?"

Title: What to do when a company request permission to use open source code without attribution?

Body:
I have an opensource project currently under MIT license. I have received a request from a company to use my code for their commercial project without having to give any attribution or credit.

To be honest, when I released the code, my sole intention was only to help a fellow programmer, and I didn't really think about if I was credited. Choosing the license was just one of the step I had to do to set up the project on codeplex.

On one hand, I feel honored and appreciate that they actually bothered to ask, on the other hand, I felt if I just allowed them to do so without any cost may just destroy the spirit of open source.

What are the typical things I or other code owners can do or request from the company to make it a fair trade? Should I even allow it?

I am thinking of asking the company to write a official letter of intent and I will sign against it just to make it more formal; and also to request a donation to project/charity of my choice or buy something on my wishlist as compensation (not very expensive). Will that be too much?


问:
Why does it matter that HTML and CSS are not programming languages?
Example here:

What languages should I know if I'm interested in building web applications?

Yes, I understand that HTML and CSS are not Turing-complete.  Yes, I understand that they are declarative, not imperative languages.  But why are people always clubbed over the head with this pedantic (and arguably obvious) fact when they ask a question about these languages?

答:
The logical "left-brain" or creative "right-brain" pigeonhole/stereotype accurately describes many people's skill sets.  In my experience, "is HTML/CSS a programming language" is more about whether people who are good at HTML/CSS can also be good at other programming tasks.

Most of the web designers I worked with in the last 13 years I've been doing web development have been able to create working HTML and CSS, but are not able to handle more demanding programming challenges (anything more than the simplest cut-and-pasted JavaScript).  Most of the hot-shot programmers and database designers don't care enough about visual presentation to do a good job with HTML/CSS or presentation in general.  Most actually refuse to try.

HTML and CSS require some programming skills: experimentation, problem-solving, careful testing, an understanding of inheritance...  But they require at least an equal number of design skills: sensitivity to color, line, spacing, balance - most of the same kinds of visual composition skills that make a good photograph.

Since HTML/CSS is a layout or presentation language, it is at the end of the data flow diagram.  No other code sits downstream of it.  The larger-level design skills that someone needs in order to design a good API, service, or database schema are not used in HTML and CSS.  There is generally no need to modularize anything HTML or CSS related, or if there is, it's not up to the graphic designer to do that.  It is rare that any functionality is made with HTML/CSS.  Drop-down menus are probably the most common exception, but they can be made by cutting and pasting a recipe off the web rather than by designing code.

It is unusual, but not impossible for a programmer to have some visual design or layout skills or for a designer to have some programming skills.  These people are especially valuable on a web team because they help bridge a gap that most of us have.  But they are often subject to stereotypes, that being able to do HTML/CSS is impossible for a "real programmer," or vice-versa.  But this skill combination is no more impossible than for that same programmer to be a decent sailor, painter, cook, or to have some other skill that they practice in their spare time.

As other people have said, this distinction comes into focus most when hiring.  Since people with crossover talents are rare, most job postings have to target one skill set or the other.  If a programmer lists HTML/CSS under "Programming Languages" it raises a red flag that they can't accomplish general programming tasks, or that maybe their definition of programming is very narrow.  Maybe they can, it just raises a question.  If a designer lists HTML/CSS you definitely want to look at their portfolio to see that they have the artistic ability to create the desired visual effect.

HTML/CSS may be repeatedly trashed as not being real programming languages because it is safer and more socially acceptable than trashing people who can't cross the hemisphere divide that they represent.  Of course, some people may not have that inhibition.  I actually worked with one manager who often said, "He wrote [insert department backbone functionality here]?  I thought he just did HTML?"

Great question!


问:
What is a good rule-of-thumb for naming link-tables?
In the same way that a publication table might relate to a person table via subscriptions, or a company table might relate to a person table via employee, I'm wondering if there is a descriptive way to relate a company table to a company_type table.

Here are some rough (and simplified) examples of the relevant tables.

company:

 - |id|name|

company_type:

 - |type|description|

{name needed}:

 - |id|company_id|type|

Also, I realize that not all relationships can be as succinctly named as subscriptions or employee, so if that's the case here, what would be a good rule of thumb to avoid a near name-collision with something like company_types?

Additional Details:

Company types, in our current case, are somewhat convoluted. This industry has multiple supply channels and multiple customer channels, so while "vendor" is a valid company_type, a vendor can also be "independent", "authorized", or "franchised" ... or any mix of the three.

Customer types are very similarly multi-faceted, and to further compound the issue, a single company can simultaneously be of some vendor and customer types.

答:
You seem to have one to many relationship between company and company_type. One company can be of multiple types? Perhaps you could give the set of types for a given company a name, "profile", "classification".

company_profile or company_classification

Alternatively you could describe the relationship e.g:

company_link_company_type


答:
In our line of work we tend to look for technical reasons, but in my opinion the primary reason isn't technical.  If you look at GitHub Help or other GitHub tutorials, forking a repo is one of the major steps for how you "do" GitHub.

When people are learning and evaluating GitHub, just about every tutorial out there is going to tell them to fork a repo as part of that learning process.  Since the primary purpose of GitHub is to contribute, a lot of people working through the standard tutorials don't realize if you just want a read-only clone you don't have to do a fork first.


答:
Questions of these kind can occur when you have no clear naming convention for your link tables. But for a database schema of a certain size, it really helps to have such conventions, especially when you have more than one person working on that schema. Moreover, you should have some other, more general naming conventions, like when to use singular and when plural, how to name your primary keys and your foreign keys etc.

For link tables, this may result in "technical" names name like the suggestion of @Joppe, or in a name like company_company_type or  company_to_company_type. But when you communicate that convention within your organisation, this should not become much of a problem. Just make sure you stick to that convention once you made the decision.

Title: What is a good rule-of-thumb for naming link-tables?

Body:
In the same way that a publication table might relate to a person table via subscriptions, or a company table might relate to a person table via employee, I'm wondering if there is a descriptive way to relate a company table to a company_type table.

Here are some rough (and simplified) examples of the relevant tables.

company:

 - |id|name|

company_type:

 - |type|description|

{name needed}:

 - |id|company_id|type|

Also, I realize that not all relationships can be as succinctly named as subscriptions or employee, so if that's the case here, what would be a good rule of thumb to avoid a near name-collision with something like company_types?

Additional Details:

Company types, in our current case, are somewhat convoluted. This industry has multiple supply channels and multiple customer channels, so while "vendor" is a valid company_type, a vendor can also be "independent", "authorized", or "franchised" ... or any mix of the three.

Customer types are very similarly multi-faceted, and to further compound the issue, a single company can simultaneously be of some vendor and customer types.


答:
The entire point of Github is "social coding".

Personally, I fork repositories when:

I want to make a change.

I think the project is interesting and may want to use it in the future, but have no easier way of saving it for later on the device I'm currently using.

I want to use some or all of the code in that repository as a starting point for my own project.

Now I've heard of people collecting stamps and seashells, but why would anybody want to collect repositories?

Why not?

There's nothing (that I can think of) that can go wrong from forking repositories for personal pleasure. Honestly, I keep a folder of interesting projects that I see on Github and other places simply for inspirational purposes, and partly because I'm a geek. I understand that I don't have to fork the project to read the code, but I may actually want to edit that in the future.

Now start forking.


问:
Radix exchange sort implementation?
I need a little help understanding the implementation of radix exchange sort algorithm.

Radix exchange (I don't know if it's the exact name in english based literature) is a lot similar to quicksort, but uses binary representation of numbers.

Firts we look the highest digit in binary representation, and then using two indexes (from the beginning of the array and from the end, we increment the first if the given digit is 0, and decrement the other if the given digit is 1). Then we swap two numbers, and then continue the work until i = j (the indexes are equal). Then we have two separate partitions and sort them using the second most important digit and so on...

Mainly, I have a few questions:

Is this algorithm really called radix exchange or does it have some other, more commonly used name?

What are the advantages of this algorithm? It seems like a lot of work, and not very effective?

Where can I see an example of implementation of the algorithm? Maybe it will be a little more clearer on what it really is, because it's really confusing for me at the moment.

答:
In contrast to quick-sort, radix sort uses "internal representation" of the values which are sorted. I.e. it doesn't simply compare them with < >. And it is really effective when you take several bits, not one, on each sorting pass. 4 bits, maybe 8. So you will divide the array onto 256 groups on each pass in the latter case. And have only 4 passes for 32-bit integers.

https://en.wikipedia.org/wiki/Radix_sort

Title: Radix exchange sort implementation?


答:
Looks like the MIT license won't allow no attribution of the copyright holder.

Assuming you are the copyright holder, your name would have to appear in the copyright line of the license and, the license has to be included in every copy of the software.

Key points in the license related to your concerns:

"Copyright (c) year copyright holders"

"free of charge"

"subject to the following conditions"

"The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software."

So, either the company includes attribution if using your MIT licensed software or, you create a version of the software with another kind of license that you could sell to the company including the copyright.

Below is the MIT License (from page http://opensource.org/licenses/MIT)

```<code>The MIT License (MIT)

Copyright (c) <year> <copyright holders>

Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
</code>```

Body:
Looks like the MIT license won't allow no attribution of the copyright holder.

Assuming you are the copyright holder, your name would have to appear in the copyright line of the license and, the license has to be included in every copy of the software.

Key points in the license related to your concerns:

"Copyright (c) year copyright holders"

"free of charge"

"subject to the following conditions"

"The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software."

So, either the company includes attribution if using your MIT licensed software or, you create a version of the software with another kind of license that you could sell to the company including the copyright.

Below is the MIT License (from page http://opensource.org/licenses/MIT)

The MIT License (MIT)

Copyright (c) <year> <copyright holders>

Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.


答:
IDE code generation is indispensable for generating things like method stubs for SOAP endpoints or serialization classes from an XML schema.  These are things that are outside the scope of a language but are certainly within the purview of a "development environment".

I do think Java's accessors are clumsy, though.  I always thought they should be more "virtual": that is, obj.field = value implicitly calls obj.setField(value).  If the class declares a setField(), then that is used, otherwise the run-time just conses one up.  ISTR Ruby does something like this.  The JSTL EL does this, but it just generates a call to a setter, and if that doesn't exist the call fails.

Title: IDE Generated Code

Body:
Many IDEs have the ability to spit out automatically written pieces of code. For example, it might generate a getter/setter pair for you. I wonder whether it isn't an attempt to work around some flaws in the language. If your IDE can figure out what the code should be without your help, why can't the compiler?

Are there cases where this is a really good idea? What kind of code generation does your IDE provide? Would the same thing be better provided as a feature of the language?


问:
Copyright/Licensing on a complete rewrite
There was an application for PalmPilots that I liked back when PalmPilots were a thing. I want to recreate it (or at least what I remember of it) for modern mobile devices. The problem is, after scouring the internet for any information on the application or the original author, I am unable to find anything. I can't even find any binaries for the app. Since I have absolutely nothing but memories to work with, I'll have to write this from scratch, but my intention is to make it as similar as possible to the original.

Since I have no idea who the original author was or what the original license was (I do know that it was at least freeware), I wonder to what extent I can do this. I don't plan on charging for my rewrite and I would like to license it under the GPL or similar. I know this is probably a gray issue, but is it closer to light gray or dark gray?

EDIT: I should also add that I know for a fact that any text or graphics (ie. anything except code/functionality/UI layout/general concept) would have been licensed to the author in such a way that, without question, I would also be able to use them.

答:
The basis for copyright law is that, if you create something by means of a process that is not entirely mechanical (i.e. it required you to think), then the copyright belongs to you (or your employer, if the work was created as part of your employment/job).

With that basis, there are no obstacles in copyright law to re-create a program based on your memory of it.

If you make it similar enough, you could run into issues with trademarks and such, but that can usually be mitigated without compromising functionality.


答:
Labeling things is easy.  Naming things is hard.  So many times, we rely on adjacent terminology or unspoken assumptions to provide a technical distinction without providing a clear, categorical distinction.  A quote from an unrelated context exemplifies this quite well:

The following note has made a deal of fun in London: ‘Dear Sir: How
  comes it that I have had no proofs of Love from you since last
  Saturday? I have waited with the utmost impatience.’ Signed, Charlotte
  Burry.

But the fun vanishes when the reader learns that Lady Charlotte Burry
  had a novel entitled Love in press, and that the note was to her
  printer.

– Kazlitt Arvine, The Cyclopaedia of Anecdotes of Literature and the Fine Arts, 1853

The source of the post is from Futility Closet

Tautology

Among varied forms and applications, tautology refers to redundant usage:  red blood, kind of type, type of class.  There is no clarification by using that particular descriptor.

Taxonomy

Taxonomy is a scheme that includes a set of structured rules for describing things.  This scheme might be oriented towards relationships (parent-child, specialization-generalization, inheritance-composition), but it can be organized around other discernment strategies.  The earlier in the rule set, the less specific the rule, with the later rules providing distinction in what would otherwise be a subtle difference.  It describes a process for classification.  A model might is the embodiment of a taxonomy.

Categorization

This is the process of labeling the whole of something in order to count or measure it.  The subject satisfies a degree of similarity, and lacks any disqualifying characteristic that we can call it the same.

Characterization

These are the individual features or traits of a thing.  This may include qualities of personality or behavior.  Or they may be physical properties.

To the problem at hand, to quote Uncle Bob's Clean Code:

The name of a variable, function, or class, should answer all the big
  questions. It should tell you why it exists, what it does, and how it
  is used. If a name requires a comment, then the name does not reveal
  its intent.

Martin, Robert C. (2008-08-01). Clean Code: A Handbook of Agile Software Craftsmanship (p. 18). Pearson Education (USA). Kindle Edition.

What we have before us is a mental map (pg 25 of Clean Code).  The solution specifies something that is probably a bit different from what it actually represents in the living domain.

To remedy this, we need to further characterize the things before applying a category to them.  What are the behaviors, relationships, or properties of the things? Do not describe it in terms of the database or design as it sits, as it is already contributing to the difficulty in clarity, but how they would describe themselves in terms of interactions, or the specific activities they perform?

This is what is clear:

Company: a business involved in the industry that participates at
times as a supplier and as a customer

Supplier: provides something to a customer; a vendor is synonymous; each supplier may or may not have an affiliation with another supplier

Supplier Model:  how a supplier is organized, affiliated, and
operates; examples include independent, authorized, franchised

Supplier Affiliation: explicit supplier relationship describing two suppliers who are organized, affiliated, or operate in cooperation with each other; each affiliation will have a supplier model describing the nature of the relationship

Customer: buyer of a good or service or a privilege from a supplier

Customer Model:   ????

Customer Affiliation:  ???

Purchase: a record of a sale between a supplier and a customer

Sellable Good: the resource or item distributed and sold by a supplier and purchased by a customer

Sellable Service: an activity performed by a supplier for a customer

Sellable Privilege: granting a legal opportunity to a customer to use something or perform an activity that is normally restricted by legal right of the supplier


问:
Controlling cookies with many tabs
I have a peculiar problem. My application has different levels of authentication. One specific level of user (super user) needs to be able to use the application as another user (subordinate user) that has lower privileges.

We decided that when the super user selects to be a subordinate user then another tab in the browser will be opened and will load the subordinate user's privileges and their respective cookie. The problem we have is: how can we get the reference for the new cookie in this new tab?

Also the super user will be able to open multiple tabs and each tab need to reference its own cookie.

答:
You could have each tab generate a cookie with a unique id in the name such as "mysiteCookie" + unique value. Keep the "mysiteCookie" base the same across all tabs.

That should be enough to keep each cookie separate. In order to read the correct one you could set up two javascript methods, one used for navigation that automatically appends it's unique id to the cookie base and adds it to the URL as a parameter, and another that fires on load to read that parameter and retrieve the cookie.

It's not exactly pretty but it would work.

Edit:

If you are using asp.net you might want to look into Server.Transfer() when navigating between pages. It allows you to get variables from the previous page. With that you can remove logged in user from cookies and just read it from prior page state.

Title: Controlling cookies with many tabs


问:
How can I shorten the amount of time it takes to change variables dependent on environment (QA/Dev/Prod)
I'm working on a Java Project, and I wrote a small plug-in to the existing project. I wrote it on my Mac(dev), QA is on Windows and Prod is on Unix.

In the code I make specific API calls to a different program. On my mac though I'm just reading in a file. In Dev it is using windows file path to execute an external programs CLI. Prod will be the same.

I'm aware of property files, should I use a property file for this to quickly switch environments.

At the moment it is just a lot of commenting/uncommenting to get everything up and running.

答: Best solution IMHO would be to completely avoid making any differences between those 3 environments in your Java program's code. So why don't you just provide a more or less simple command line program in your Mac environment (which is in fact a Unix environment, too) which takes exactly the same parameters as the external programs in the other 2 environments, and returns results in a compatible form? The path to this program should be configured by some kind of configuration file, outside of your Java source code.</p>


问:
Is the usage of internal scope blocks within a function bad style?
There are some (quite rare) cases where there is a risk of:

reusing a variable which is not intended to be reused (see example 1),

or using a variable instead of another, semantically close (see example 2).

Example 1:

```<code>var data = this.InitializeData();
if (this.IsConsistent(data, this.state))
{
    this.ETL.Process(data); // Alters original data in a way it couldn't be used any longer.
}

// ...

foreach (var flow in data.Flows)
{
    // This shouldn't happen: given that ETL possibly altered the contents of `data`, it is
    // not longer reliable to use `data.Flows`.
}
</code>```

Example 2:

```<code>var userSettingsFile = SettingsFiles.LoadForUser();
var appSettingsFile = SettingsFiles.LoadForApp();

if (someCondition)
{
    userSettingsFile.Destroy();
}

userSettingsFile.ParseAndApply(); // There is a mistake here: `userSettingsFile` was maybe
                                  // destroyed. It's `appSettingsFile` which should have
                                  // been used instead.
</code>```

This risk can be mitigated by introducing a scope:

Example 1:

```<code>// There is no `foreach`, `if` or anything like this before `{`.

{
    var data = this.InitializeData();
    if (this.IsConsistent(data, this.state))
    {
        this.ETL.Process(data);
    }
}

// ...

// A few lines later, we can't use `data.Flows`, because it doesn't exist in this scope.
</code>```

Example 2:

```<code>{
    var userSettingsFile = SettingsFiles.LoadForUser();

    if (someCondition)
    {
        userSettingsFile.Destroy();
    }
}

{
    var appSettingsFile = SettingsFiles.LoadForApp();

    // `userSettingsFile` is out of scope. There is no risk to use it instead of
    // `appSettingsFile`.
}
</code>```

Does it look wrong? Would you avoid such syntax? Is it difficult to understand by beginners?

答:
If your function is so long that you cannot recognize any unwanted side effects or illegal reuse of variables any more, then it is time to split it up in smaller functions - which makes an internal scope pointless.

To back this up by some personal experience: some years ago I inherited a C++ legacy project with ~150K lines of code, and it contained a few methods using exactly this technique. And guess what - all of those methods were too long. As we refactored most of that code, the methods became smaller and smaller, and I am pretty sure there are no remaining "internal scope" methods any more; they are simply not needed.


问:
MVC seems to create dependencies that just "don't feel right"
I might be misunderstanding MVC, so forgive me if that is the case.

This is my program structure (Java/Swing): I have a JTable (View) that is pointed to by a custom linked list (Model). When the user tries to add something to the JTable, the action listener (Controller) updates the linked list (Model) which updates the JTable (View).

Here's my issue: The linked list should be able to function independently of the JTable, but it doesn't. Let's say I decided to get rid of the user interface and just use the linked list for internal stuff within the program (The linked list has other properties and functions outside the scope of MVC). That should be able to work, because the linked list's FUNCTION is independent of the JTable's function, yet I would have to edit a lot of code to do so (or have a bunch of code that no longer does anything) because of MVC.

So am I misunderstanding MVC completely, just a little bit, or are the dependencies a price I have to pay?

NOTE: This is a simplified view of my project. In real life, there are other objects in the model and more than just a JTable in my interface. Also, the linked list has other thigns that get updates other than the number of objects.

答:
How I've addressed this issue is to have the data in base collection (a linked list in your case) as the real data model. Then create a TableModel instance that is a thin wrapper around the data model. Your view and controller don't need to change.

This way, if you don't need the UI anymore, you can still work directly with the linked list. Or if you come up with a different way to represent the same data, you could create a different TableModel to correspond with this new view, but still using the same backing data model.


问:
Is there a comparative study of the memory consumption of programming languages runtimes, correlated with expressiveness and production bug ratios?
There are many comparative studies and available online when it comes to the runtime performance of applications built using one language or another. Some driven by corporations, some academic, some just personal experiment reports.

We also get a decent share of comparative studies on side-effects of a programming language and its tooling, like:

build times,

likelihood of post-production bug detection,

expressive power,

etc...

However, I've recently been more and more bummed out by the memory consumption of my programs more than anything else. This might come from the fact that while Moore's Law is on our side for raw performance, we have come to realize that other bottlenecks matter more. That, and I don't tend to update my hardware every so often, and I have some "old" (read 2005-2006 3.6GHz Pentium 4 with 4GB of RAM) that nowadays are hard-pressed to be useable for large applications without requiring me to go through great trouble to squeeze every bit of juice out of them (choice of OS, UI, tweaking of services and daemons, choice of applications to use for a task or another...). Quite honestly, sometimes I fire up top or procexp and weep at the sight of the memory used by the most innocent programs.

I can address this by keeping to push in the direction listed above, and essentially trying to limit myself and the programs I use (I have a dear love for cli programs for that reason, I guess), but I also cannot help but to think that maybe we're doing it wrong.

Modern Tools for Modern Needs

Of course, higher-level languages are arguably better and justify their worth of dead weight. Some design choices were made for good (or supposedly well-intended) reasons at the time, in many toolchains. Shared libraries, memory models, pre-processors, type-systems, etc... But some might be more viable than others with our modern hardware, and I'd be curious to read a few serious studies on the matter.

So, my question is, is there a pendant to the Benchmarks Game and others that focus on a comparison of the languages' base runtime memory consumption?

And even further, are there some studies that cross-reference this with other parameters (similar to what this article did, for instance, for other criteria, also based on the Benchmarks Game)?

答:
I have found some partial information, so I will start to compile my findings in my own answer. Please don't let that stop you from contributing your own answers (or editing this one).

Existing Literature:

An Empirical Comparison of 7 Programming Languages - Prechelt (2000) [PDF]

A bit dated, but covers some of the material I'm interested in and does give a view of the runtime memory use and expressiveness. Results may greatly differ now, but it's an interesting start.

Speed, Size and Dependendability of Programming Languages - Marceau (2009) [blog]

Code Used, Time Used Shapes from the Benchmarks Game [u32, u32q, u64, u64q]

Though it doesn't cover runtime memory consumption, Marceau's work is more or less the kind of reference or empirical study I'd be willing to find for that critera, in terms of content and quality. A good example of what I'm after, just for different metrics. The second article is a follow-up found on the Benchmarks Game site and that was published shortly after (and which references) Marceau's work, with more recent screens and more languages, though still without runtime memory details. Each graph on these pages then leads to language-to-language comparison which do provide high-level memory info though.


问:
naming convention for different types of functions (use prefixes or suffixes?)
Does anyone have suggestions for naming conventions for different types of functions, particularly wrapper functions that need to connect to and disconnect from the database vs. wrapper functions that are passed a db link and don't need to connect and disconnect?

The project on which I am working has these types of functions (among other types):

wrapper functions that need to connect to the database, then call other functions, then disconnect

wrapper functions that are passed a db link and call other functions (these functions don't need to connect to the db, that has already been done)

Has anyone worked in a similar environment?  Did you follow any naming conventions to distinguish between these wrapper functions that need to connect vs. being passed a db link, such as using a particular prefix or suffix?

答:
If you are using an OO language that has polymorphism, it should already be apparent from the method signatures which method you need to call:</p>

```<code>bool SaveCustomer(Customer cust)
{
    var conn = new DatabaseConnection(connectionString);
    SaveCustomer(conn, cust);
}

bool SaveCustomer(DatabaseConnection conn, Customer cust)
{
    // Save the customer
}
</code>```

Body:
If you are using an OO language that has polymorphism, it should already be apparent from the method signatures which method you need to call:

bool SaveCustomer(Customer cust)
{
    var conn = new DatabaseConnection(connectionString);
    SaveCustomer(conn, cust);
}

bool SaveCustomer(DatabaseConnection conn, Customer cust)
{
    // Save the customer
}