答:
What you are doing is not "encryption", per se; it's "hashing". The principal difference between the two is that encryption is easily reversible (with the correct key of course), while hashing is designed to be extremely difficult to reverse in any circumstance other than knowing the original message in the first place.

In theory, hashes simulate a "random oracle", a hypothetical homunculus with an eidetic memory and a way to generate perfectly unique, perfectly random numbers with no upper range limit. You'd give this little man a message, and one of two things would happen; either he's never seen the message before, in which case he generates a new random number and gives that to you as the digest, or he has seen that messsage before, and so he remembers and gives you the number he generated when he saw it the first time. In that theoretical model, there is zero relationship between a message and its digest, and with no single number ever appearing twice from the RNG there's no possibility for a collision.

Unfortunately, we don't have an ideal random oracle; the idea has practical impossibilities for a digital implementation, such as the ability of the oracle to efficiently store and efficiently recall every message ever hashed by anyone anywhere, and the ability of the clients to accept a number that could be hundreds or thousands of decimal digits in length. Instead, we have hash functions, which are irreversible (one-way) mathematical operations that work on the message itself, to create a deterministic transformation (same message => same hash) with no apparent relationship between the hash and the original message. As mentioned in the comments, there should also be no predictable change to the hash value produced by making systematic changes to the message; ideally, each bit of the digest would have a 50% chance to change, given a change to a single bit of the message.

There are many uses for a hash function; they're used for challenge verification (think login credentials like passwords) without the need for both parties to know the plain text secret, and they're used as checksums to verify that a message hasn't been tampered with or corrupted. They're also used in so-called "proof of work" scenarios; computational tasks that are difficult to complete but easy to verify.

If you were ever to find a way to efficiently reverse a SHA256 hash digest to produce a message (any message) that would result in that hash, it would be a proof by demonstration that in fact the hash is fundamentally broken. SHA256 is, in fact, believed secure, meaning there is no documented method, no matter how practical, to begin with a hash digest and produce a colliding message that requires less work than simply trying every possibility (which for SHA-256 is ideally 2^256 ~= 10^77 possibilities).

Title: Encryption Cannot Be Reversed?

Body:
I am under the impression that an encrypted string cannot be decrypted so the original value is lost forever.

However, if the following string always equals "dominic" (my name), then can't there be some logical way to reverse it; being as it's not random nor is it based on the date/time, but there is a logical method to it?

```<code>0WrtCkg6IdaV/l4hDaYq3seMIWMbW+X/g36fvt8uYkE=
</code>```

No matter what or how many times I encrypt "dominic" (string), it always equals as above.  So, shouldn't there be some way to decrypt a string like that?

Example of what I'm talking about:

```<code>public string EncryptPassword(string password)
{
    return Convert.ToBase64String(
        System.Security.Cryptography.SHA256.Create()
        .ComputeHash(Encoding.UTF8.GetBytes(password)));
}
</code>```


问:
substitute for static inheritance
I currently have a number of classes (~20) that all do the same thing (abstractly), namely, generate an instance of a particular class from an xml file.

The way that they use the content of the xml file varies quite a bit, and the data gets stored into different substructures (fields, groups, etc) that are shared across the classes, so I took all of the parsing and field information out of the files, and created a helper class (as is the final constructed type)

All of the above classes and methods are static, as they have no need to contain any state.

I then wanted to have all the classes derive from one common class so that I am not referencing a seemingly unrelated class constantly, only to discover that inheritance and static do not work together well.

What is the appropriate way of setting this up? Its bascially a large set of factory methods for a type that require no state.

Update: The control flow is currently as follows:

Pick one of ~20 factory methods

Read in an XML file (all tags, attributes are the same across the files, but the files are distict across the methods).

Convert the content in the XML files to a class that has some data structures as members (List<Field>, List<Group>, Dictionary<string,string> etc). These data structures use types that are nested in the helper.

Add these collections to the uninitialized object.

Return the object to caller.

Right now, the 20 factory methods are thier own static classes, and all return objects of the same type, as even though there might be some semantic difference between the "types" all of the memebers and functions are the same. The code that parses the XML file is in a helper, as this logic is common to all of the factory methods. Step 3 has to be different for all the methods, so that part is found in the static classes.

答:
I failed to understand why one might need 20 classes here. I think it takes one class with 20+ methods.

```<code>class XMLMaker {
  public OutputClassA ParseA(File input) { ... }
  public OutputClassB ParseB(File input) { ... }
  // etc, however many classes you need to create
  //
  // reusable helper methods for the public methods above
  protected XML.Node _ParseFoo(...) {...}
  protected string _ParseBar(...) {...}
  //
  // I can imagine you might want it, too:
  public OutputClass Parse(File input) {
    var file_kind = _DetectKind(input);
    if (file_kind == KIND_A) return ParseA(input);
    // etc
  }
}
</code>```

I can also imagine that you can spread ParseA, ParseB, etc into a manageable set of separate files by making XMLMaker a partial class.

XMLMaker does not need to store any state, so it can be instantiated once by a caching factory, or by a DI mechanism.

ContentLicense: CC BY-SA 3.0

Title: substitute for static inheritance

Body:
I failed to understand why one might need 20 classes here. I think it takes one class with 20+ methods.

class XMLMaker {
  public OutputClassA ParseA(File input) { ... }
  public OutputClassB ParseB(File input) { ... }
  // etc, however many classes you need to create
  //
  // reusable helper methods for the public methods above
  protected XML.Node _ParseFoo(...) {...}
  protected string _ParseBar(...) {...}
  //
  // I can imagine you might want it, too:
  public OutputClass Parse(File input) {
    var file_kind = _DetectKind(input);
    if (file_kind == KIND_A) return ParseA(input);
    // etc
  }
}

I can also imagine that you can spread ParseA, ParseB, etc into a manageable set of separate files by making XMLMaker a partial class.

XMLMaker does not need to store any state, so it can be instantiated once by a caching factory, or by a DI mechanism.


问:
How can I benchmark concurrent key-value stores?
I have some concurrent key-value store implementations that are implemented with hash tables and search trees that I would like to compare. I would like to benchmark them with a real world application where several threads stresses the key-value stores.

I already have some micro-benchmark that stresses the key-value stores by executing random operations on the key-value stores in parallel. What I'm interesting in now is applications that do some work that could be useful in the "real world" and where one or several key-value stores are important for scalability and speed. I would like to have a benchmark that is easy to set up and that could be run on many different system. I would prefer if it does not involve network communication etc.

An example of the kind of applications I'm looking for is the parallel PageRank algorithm. It is used as a benchmark of different key-value stores in the paper "Concurrent Tries with Efficient Non-Blocking Snapshots (PPoPP'12)".

The reasons why I'm not satisfied with "artificial" benchmarks that do X% inserts, Y% deletes and Z% lookups are:

It can be more convincing with a benchmark that also solves a real world problem. The risk with an "artificial" benchmarks is that they might not correspond to any real world situation.

Some usage scenarios that happen frequently in real world applications might not be covered by the artificial benchmark.

答:
Why not take your existing random KVP (key value pair) operation testing to the next level?

Presumably, your current set of tests includes a list of potential KVPs and then performing CRUD operations against whichever KVP was selected.  In effect, the list of KVPs drives the benchmarks against your system.  An Actor randomly selects the KVP and then picks a CRUD op.

The next logical stage is to create sets of operations which will "replace" your list of potential KVPs as the driver.  The sets of operations will reflect what you think a "real" workload will be.  In some cases, it will still be CRUD ops on KVPs.  In other cases, as you mentioned, it will have additional changes (aka "real work") and it's the aggregate of those operations that make the set.

Now your Actor will select from the list of sets instead of KVPs.  Bonus points if you make your Actor intelligent enough to pick relative workloads, so some percentage would be CRUD on KVP and some other percentage would be "real work."

This approach doesn't fully address your concerns with "artificial" benchmarks, but I don't know that any solution in the abstract can really resolve that issue.  In theory, you know the expected work load best so you can tailor those sets of operations accordingly.

The benefit of this approach is you can now state "The system can handle ### transactions of X% inserts, Y% deletes, Z% lookups and Q% 'real world' operations."  And you'll add a parenthetical remark explaining what "real world" means to you.


问:
Can compilers and interpreters have bugs, and what can we (as users) do to deal with them?
If a compiler's work is essentially translating source code into machine level code, can there be any glitch in a compiler, i.e. a faulty "translation?"

The same goes for an interpreter: can it fail to output the required content sometimes?

I have not heard of any bugs in compilers/interpreters, but do they exist?

答:
Not only bugs, but also deliberate malware.

The "login" trojan implemented by Brian Kernighan to the original Unix C compiler is the most well-known of these; the article http://cm.bell-labs.com/who/ken/trust.html has some background on this.


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答: John skeet got a job in Google as well, he has a good score on Stack Overflow.</p>

ContentLicense: CC BY-SA 2.5


问:
New to Programming/objective c
I've recently started to work on some iPhone apps, starting from a base where I had essentially no programming experience (I studied Maths & had very few programming modules)

I worked my way through Beginning Mac Programming: Develop with Objective-C and Cocoa and found it useful, while it gave me the feeling that I needed to quickly address my lack of a real foundation in programming.

For the forseeable future my work will involve developing iPhone apps - I want to have a real grasp of objective-c before things get more pressurised in the coming months.

Is my best bet to study c first of all, before worrying about the finer points of objective-c?

If so has anyone had any experience teaching themselves through an online resource? It would be great if someone could recommend a website with which to self-teach c.

Sorry if this covers some old ground but nothing in the similar questions quite answered my question.

Any help is greatly appreciated :)

答:
I myself do come from a similar background, after completing my Btech(BE) in Mechanical it took some time and research for me to get into Programing world (Computers).

I think read Objective C than C, because there is a difference in the way you would think in C and in objective c and From My opinion if you understand Obective C, it would be easier for you to go thru C language concepts.

Apart from that: There is a constant need of Learning and you may need to connect those dots. Be a part of a Group where you can discuss any thing (StackExchange for e.g.)

Do lot of Google / Stack Exchange / Stack Overflow for any curious question. There is lot of content available online.

Understand the concept of Memory in an Operating System. Ram VS Hard Disk Memory. Understand how a source code (in any language in general) is converted to an Executable. Don't go into the details, but get a feel of whats happening inside the box.

Understand Objective C first, give importance to the concepts then to syntax. But Yeah be familiar with one language syntax also. Then move Cocoa framework, using which you would be able to do iphone /ipad apps. For that you have Apple Programing Guide, which covers all of it in details and in depth.

Understand and read about Data Structures, understand what it is and why do we need it, try to use your knowledge in objective c and practice data structures. Eg. try to create a linked list using objective c. Try to write your own implementation of NSMutableArray and NSArray.

Later read about algorithms and understand the concepts there.

Try to solve puzzles (use programing if required).Be good with Logic and thank your Brain for always being there for you!!!

Title: New to Programming/objective c


问:
NodeJS: Freeze dependences before testing and deployment? Check in node_modules?
Suppose you have a NodeJS application.
A release could consists of multiple steps:

Automated and/or manual tests

Deployment

(if something goes wrong) Rollback to the last stable version

There are some  desirable requirements regarding the application's dependencies:

When you have done your testing, you want to deploy exactly the version that you tested with, including all dependencies.

The same goes for rollbacks: You want to restore not only your own code, but all external dependencies, too.

My question is about best practices to meet this goals.

What is the recommended way to create a snapshot of all dependencies of your NodeJS application?

Here are three options that I can think of:

In this article, the author recommends to put the node_modules directory under source control. (Not for all modules, but only for modules that will be deployed.)

One alternative, which the same article describes as an anti-pattern, is to use explicit version locking. His argument seems reasonable: When you lock, for example, Express to a certain version, you still cannot control that one of its dependences hasn't introduced a subtile bug, later.

Just don't care and always use the most recent version of all external modules.

My thoughts so far (but I don't have much experience with NodeJS yet):

3) seems to be too reckless.

I tend to 1), but I'm not sure where to put the node_modules. When you just check it along with your normal code, I fear that workflows like npm link to your local modules will no longer work. Additionally, there is always the problem of annoying merge conflicts.

答:
You can use npm shrinkwrap to implement option #2 and lock all of the child dependencies. From the doc:

This command locks down the versions of a package's dependencies so
  that you can control exactly which versions of each dependency will be
  used when your package is installed. The "package.json" file is still
  required if you want to use "npm install".


问:
Scrum: How much can the Product Owner shake up the Product Backlog?
For the last 3 sprints or so, I've observed our Product Owner suddenly shoving new stories -- stories not previously in the Product Backlog -- at the top of the Product Backlog.

Because of this, the existing items in the backlog never get worked on.  New stories continuously take over the helm and make into our Sprint Backlog.

My question is - how much can the Product Owner really shake up the Product Backlog?  Is it really fair game to ignore what's already in the backlog and keep on shoving new stories at the top?

I've tried to argue that this is hogwash, but I often hear counter-arguments such as "adapting to frequently changing business needs," "we're moving so fast - we're super agile" and I don't know what to say to those arguments, although I feel it is not how Scrum was meant to be.

EDIT:
I understand that the product owner owns the product backlog.  What I am observing at my team though, is that the PO constantly puts new items at the top of the backlog, ignoring the existing backlog items completely.

For instance, say we're building a car and PO creates 10 stories to make it happen.  We decide to take on 3 stories in our sprint backlog - thus 7 stories still remain in the product backlog.  Everything is good so far.

At the next sprint planning, however, the PO now claims that we need to build a baseball bat and creates 5 stories around that - which are then placed at the top of our backlog (i.e. highest priority); nevermind those car stories we already had in the backlog.

答:
Great answers here and I do agree that it is the PO's job to do that as he/she has to determine the best possible ROI for the product.  He/she would be doing the wrong thing by building less valuable PBI's.

However there are some fundamental rules.

The PO cannot change the current sprint by moving items in and out at whim.

When the PO adds a new item,  the team has needs to estimate it and the PO needs to respect that estimate

The PO is then responsible for managing time, budget and scope (the magic triangle).  i.e. if they add new items they have to come up with more budget or remove an equivalent lower valued item.

The PO is accountable to make sure the items have enough detail in them that the team can pick 1up in sprint planning.  It should have enough information that the team can ask minor clarification questions.   This is often a dysfunction in many teams where a long time is spent discussing what the requirement is, instead of minor clarifications.

The PO in grooming sessions should consult with the team and heed their advise on any potential challenges with new requirements, impacts or dependencies.  This should help him/her order or make better decisions.

Is it the teams accountability and responsibility of defining what gets built or that of how it should get built?  The bottom line is its not the teams decision or risk to take and the team should focus on delivery of quality items regardless of what they are.

Finally,  use retrospectives to thrash out any concerns you may have


答:
Of course, because compilers are software.

In 2005, I had a piece of code fail in a highly critical piece of software I had written for a large company.   Since it cost the company literally millions of dollars to rectify, they of course launched a big-ass investigation.

Thankfully (from my perspective), the issue turned out to be a compiler issue in Delphi.   In the try finally block, the return value of a function was destroyed, and resulted in absolutely random results back to the caller.   This was documented, and acknowledged by Borland.

.NET was well known to have literally hundreds of different memory leaks, particularly in its early implementations.

I would contend that there is no such thing as bugless software.   Compilers are no exception.   They are, though, tested more thoroughly than most business software, and are consumed by smart, critical, contentious people, so their track record has actually, on the whole, been pretty good.

Title: Can compilers and interpreters have bugs, and what can we (as users) do to deal with them?

Body:
If a compiler's work is essentially translating source code into machine level code, can there be any glitch in a compiler, i.e. a faulty "translation?"

The same goes for an interpreter: can it fail to output the required content sometimes?

I have not heard of any bugs in compilers/interpreters, but do they exist?


答:
Of course, compilers are just programms and their authors are idiots too :). Even language specification can have a bug. Example: c# + foreach + lambda.

Or in Python, bug in interpreter: Compiling evil ast crashes interpreter.

Well, if you want to look on bugs in compiler/interpeter -> look at php. There is a famous bug with integer overflow. First fix started from if (size > INT_MAX) return NULL;. Continuation of the story.


问:
Backend devs put down by user stories
I planned to slice in backend development into to the user stories vertically.
But a backend guy on our team started to complain that this makes their work invisible.

My answer was that

at the sprint planning and review meetings we discuss backend tasks
in front of stakeholders so it makes it visible, and

maintaining a high quality during the project will result a slower
startin pace than other teams, but we will have a stable velocity
during the project. And velocity is highly visible to stakeholders.

He still insist having stories like:
"As a developer
I need to have a domain layer
so I can encapsulate business logic."

How can I solve the issue before it pollutes the team?

The root of the issue is that our management systematically consider backend work as invisible and call backed devs miners, or other pejorative terms.

答:
There are a few things wrong with the situation described, the obvious problem being the lack of respect given to the back-end developers.  As this question is tagged agile I am going to push back on other answers suggesting this is only a social problem.  There are several bad smells and possible anti-patterns in your story, none of which have to do with ignorant management or even how you slice the stories.

The fact that a group of individuals on the team feel slighted for not getting glory from work completed smacks of several possible problems.

There should not be people who only do back-end development.  A common Agile approach is to have cross-functional teams made up of generalizing specialists who practice shared code ownership.  Individuals should not be focused exclusively on back-end or front-end development, though they will certainly better more experienced or better at some things than others.

Architecture doesn't earn value.  From a user's perspective -- the only perspective that really matters -- it does not matter if you have layers or domain languages or even if the solution is programmed.  The only thing that matter is whether you created value for the users.  The proposed "story" from the back-end developer is a nonsense requirement -- it is a summary of design decisions that, from the perspective of a user/customer do nothing to achieve the functionality desired.  In other words, any given user story might be achieved by any number of different architecture designs.  It's possible that a user story might be completed with no modification to the back-end at all.  This does not make it an invalid story.

Thinking systemically is still critical.  While architecture may not earn value it is still critical to success.  The back-end developer has some valid concerns.  You should be thinking about how you will build the system.  You should be writing those decisions down.  The whole system is important even though only the front-end features are the things that will get all the glory.

My recommendation is to treat architecture as a first class citizen -- but do it the right way.  Perform a quality attributes workshop with stakeholders.  Involve key stakeholders in architecture reviews, or at least summarize essential design decisions at important milestones.  Draw the architecture on big paper and make it visible so the entire team can see it.

Require that everyone develop everywhere in the system (front-end and back-end), pair program if you need to so this can happen effectively.  Continue to create user-focused user stories.  But also identify key quality attribute scenarios that show why the system is designed the way it is and drives decision making regarding "back-end" design.  Elevate the architecture design so that it is not invisible anymore.

Title: Backend devs put down by user stories


答:
No

the real answer: spend a few months earning a five digit Stack Overflow reputation, and you'll be getting job offers in the $100K+ range without an interview.

There is no reason why a high reputation (or "score") on any site will get you a job at all. I have pointed this out before, you are more likely to get a job by maintaining open source projects, writing proficiently, leaving good impressions, and making personal connections within the community.

Are these people good programers? Undoubtedly yes! Does that mean they are a good fit for your team? Absolutely not. Calling these people "superstars" may be completely correct, but that doesn't make them perfect. 1

What determines if you are a good fit? Interviews and connections. You can't replace meeting people face to face with a number.

Having a high reputation can't hurt, but it isn't a magic bullet.

1: In no way do I mean to imply these people are bad programmers, I mean to emphasize the inability to instantly and wholly judge someone based on a number.

Title: Will high reputation in Stack Overflow help to get a good job?

Body:
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?


答:
Compiler is a program that reads a program written in one language (the source language) and translates it into an another equivalent program in another language (the target language), mostly machine language.

There are different phases of compiler through which your source language code is scanned line by line. There is a symbol table which keeps the track of all Keywords which are scanned for in source language code.

Phase 1 : Lexical Analyzer - reads all the character in source program and forms the
          logical separation of tokens (int, char, float, if-else,for,while etc.)

Phase 2 : Syntax Analyzer  - analyze the structure of stream of tokens. Hierarchical
          parsing of expressions which includes postfix/prefix etc.
          (a=b+c*d)

Phase 3 : Semantic Analyzer - Type checking of tokens (integer to real, float etc.) and
          many things like operator precedence etc..

Phase 4 : Intermediate Code Generator -
          a=b+c*d-e(temp1=c*d, temp2=temp1+b, temp3=temp2-e)

Phase 5 : Code Optimization - Various Analysis (control flow, data flow, transformations)

          which eleminates : Redundancy code, Constants propogation, Partial dead code,
          common subexpression, Loop invariant code

Phase 6 : Code Generation - Generation of target code (Mostly Assembly Language) putting
          values in Registers

All these phases are nothing but well written programs and there could be N number of flaws in that..


问:
Sprint item takes longer then expected to be completed. What should we do?
What should we do if a item in scrum takes longer then expected? i am asking this because i have been noticing items that developers is struggling to complete as it is much tougher then initially thought.

In such situation should we

remove the item from sprint back to product catalog so that we can
meet the sprint timeline?

move to easier sprint item and leave problematic sprint till the end of timeline

justify at sprint review why the item cant be completed at current
sprint to stakeholders?

How can we avoid such situation in future? Is it due to lack of upfront planning or we did not make an effort to break down the sprint item into smaller item?

答:
With "item", I suppose you mean "task".

Planning optimism in software is as old as software itself. The good thing about scrum is that you are facing it soon and create visibility of it: this is why the teams velocity is based on past data and not future estimates.

To complete a story, you also have to complete the tasks that turn out much harder than anticipated. No excuse to postpone them. (This is why the Definition Of Done is so important). If that means that the team is failing a story, then too bad, you will have something to talk about on your next retrospective. Velocity will go down (become more realistic) and the team will learn to make better estimates, or leave more safety margin for unforeseen tasks. The product owner will get a more realistic view on his release planning.


问:
Shelving code in Team Foundation Server (TFS)
I'm pretty new at using TFS and I'd like to know how you or your team use the "shelve" function of tfs.

We have the following guidelines in using TFS:
- perform a "Get Latest" before you check in and try to build/compile
- do not check in code that does not compile
- at the end of the day, if your work is not complete/partially done, you should "shelve" your pending changes

The first two make sense but I don't really get the last one. I asked my mgr and he said that its so he knows that you actually did some work for that day, which does kind of makes sense but still, I'm wondering what other teams use the "shelve" function for?

答:
in our environment,

A Developer first get latest version of the SLN within TFS before making any changes.

modify code or/add a feature & shelve changes as many times as needed during the day.

Perform unit testing

when unit testing is done for the changes/or added features by the end of the day, Dev
creates a final shelf set by unchecking "preserve pending changes locally" checkbox

Dev send an email to Team lead about the  final shelf

Team lead will review code and if approved will apply the Dev shelf and send a reply
email to DEV to test the changes in the Test environment.
if code is not approved, Dev will unshelve changes and make more modification go   back to step4

Dev runs test cases in test Environment and if everything is according to
the desired results, then Dev notify the user coordinator or Business analyst for Project as ready for UAT.

at this point Dev will see his/her changes in TFS

and cycle begin again from Step 1.

it is good practice for the developer to shelve the changes at the end of the day as a backup.
it is also a good practice for developer to get latest SLN changes several times during the day.

communication is important between developers to avoid working on the same module and overwrite each other code.


问:
Aggregation vs Composition
I understand what composition is in OOP, but I am not able to get a clear idea of what Aggregation is. Can someone explain?</p>

答:
Composition is an Association

Aggregation is an Association

Composition is a strong Association (If the life of contained object totally depends on the container object, it is called strong association)

Aggregation is a weak Association (If the life of contained object doesn't depends on the container object, it is called weak association)

Example:

```<code>class Contained {
    public void disp() {
        System.out.println("disp() of Contained A");
    }
}

public class Container {
    private Contained c;

    //Composition
    Container() {
        c = new Contained();
    }

    //Association
    public Contained getC() {
        return c;
    }

    public void setC(Contained c) {
        this.c = c;
    }

    public static void main(String[] args) {
        Container container = new Container();
        Contained contained = new Contained();
        container.setC(contained);
    }
}
</code>```

Title: Aggregation vs Composition

Body:
Composition is an Association

Aggregation is an Association

Composition is a strong Association (If the life of contained object totally depends on the container object, it is called strong association)

Aggregation is a weak Association (If the life of contained object doesn't depends on the container object, it is called weak association)

Example:

class Contained {
    public void disp() {
        System.out.println("disp() of Contained A");
    }
}

public class Container {
    private Contained c;

    //Composition
    Container() {
        c = new Contained();
    }

    //Association
    public Contained getC() {
        return c;
    }

    public void setC(Contained c) {
        this.c = c;
    }

    public static void main(String[] args) {
        Container container = new Container();
        Contained contained = new Contained();
        container.setC(contained);
    }
}


答:
I have a 5 digit SO reputation, and my salary is barely half of what you mention.

Obviously a good SO reputation doesn't guarantee anything, but even though most recruiters don't even know what SO is, surely it's worth mentioning it in one's CV. It's substantial, after all, unlike all kinds of official-looking certifications from two-day courses etc.

On the other hand: while Joel has a point, your activity on Q/A sites isn't really supposed to define your salary in any way. It may be a proof of some proficiency and enthusiasm, but the recruiting company is interested in what you're going to do for them if they recruit you, not in your abilities to answer programming questions. So by all means, consider SO reputation as a part of your professional credibility, but don't expect it to be something huge.


问:
External id for every relational table
Should I add an external id for every table?

For example if I have these tables :

```<code>Customer
=======================================
Id       Name      Gender
---------------------------------------
1        John      M
2        Doe       M
---------------------------------------

CustomerPurchase
==========================================================================
Id       ExternalId      CustomerId            TotalQty
--------------------------------------------------------------------------
1        PO0313-0001     1                     10
--------------------------------------------------------------------------
</code>```

In that example, I understand that ExternalId is required in CustomerPurchase table (for printing, etc).

But I don't see any reason why Customer table should need one as well.

FYI, the reason I asked this because a friend of mine said that SAP uses ExternalIds in their tables.

Should I use ExternalId in every table?

Am I missing any ExternalId's other usage besides for user's eye friendlier identification?

Thanks!

答:
In layman's words:

Use surrogate primary keys as primary keys when:

There are no natural or business keys

Natural or business keys are bad ( change often )

The value of natural or business key is not known at the time of inserting record

Multicolumn natural keys ( usually several FK ) exceed three columns, which makes joins too verbose.

If a natural key exists that doesn't fall into the conditions listed above, for the sake of God, use it, especially if the key is an ISO standard or is issued by some respected institution, like country codes, airport or airline IATA codes, MAC addresses, car plaque numbers, IMDB movie codes, radio station call signs, etc. That would allow you to interoperate easier.

Above conditions mean surrogate keys will have to be used in many tables. But not all.

Title: External id for every relational table


答:
What should we do if a item in scrum takes longer then expected?

Assuming that by item you mean story, at the end of the sprint you typically put it back in the product backlog (and likely plan it for the next iteration). The team scores zero points for it in the current iteration.

Another alternative, if the story is big enough, is to slice it vertically. For example, the story "product catalog search", can possibly be split in "search by category" and "full text search", but not in "search form" and "search results".

How can we avoid such situation in future?

There is no easy direct answer to this. In scrum you do sprint retrospectives every iteration, where you typically discuss these kinds of things with the team. There are many different possibilities:

The team, or some team members, has a bad week

Your team pipelines work items horizontally (e.g. backend->frontend->QA)

The stories are too big by mistake

The team "gold plates" the stories by adding extra work which is not strictly necessary for the completion of the story.

The stories are very big in nature, you need longer sprints (unlikely)

The team estimates stories imprecisely (incoherently)

The project has a lot of tech debt/rotten code base and your velocity is too low

You are not measuring and estimating your sprint capacity correctly (or at all).

etc. etc.

Title: Sprint item takes longer then expected to be completed. What should we do?

Body:
What should we do if a item in scrum takes longer then expected? i am asking this because i have been noticing items that developers is struggling to complete as it is much tougher then initially thought.

In such situation should we

remove the item from sprint back to product catalog so that we can
meet the sprint timeline?

move to easier sprint item and leave problematic sprint till the end of timeline

justify at sprint review why the item cant be completed at current
sprint to stakeholders?

How can we avoid such situation in future? Is it due to lack of upfront planning or we did not make an effort to break down the sprint item into smaller item?


答:
What we usually do in our company when a task starts to take longer than expected is dividing it into smaller tasks.

That way we don't put all the blame on the developer for being too slow, but we also acknowledge that the task was designed incorrectly.

Another thing could be to assign the task to another member of your Development Team to avoid your late developer digging himself into a hole. And if the task is really critical some XP could be the solution.


问:
Creating a new file format: Write code or documentation first?
When creating a new file format for an application, you can write the code or the documentation first.

When writing the documentation first, you have a better idea of what you should implement.

However, you might need to change a lot of the documentation you have written afterwards when writing the code, because you may discover certain things aren't very efficient to implement that way.

So: When creating a new file format, what should you write first: The code or the documentation?

答: The documentation that should come first is the one that specifies what the format must accomplish. If the user should be able to specify text size, color, links, and have them reproduced, all of this information needs to come first. This is distinct from documenting how it was implemented. As you said, this kind of technical doc is hard to write completely in advance, since you cannot foresee all consequences of decisions you make early on. My experience is that it is best to interleave both tasks and finish the technical documentation simultaneously with the reference implementation and test suite.


答:
This is really a question of development process and development methodology. Any approach can be equally valid, but some may work better in your organization than others.

I'm a fan of agile processes, and I'm not a big fan of comprehensive documentation. Documentation has a tendency to cost more to write than the benefit you get from people reading it (which they tend not to do), and it has a tendency to become outdated quicker than it can be written.

Instead I would write executable specifications using specification by example. Various tools support this, e.g. FIT or Cucumber. Then you start by writing a little bit of specification, and then write just enough code to satisfythis specification. Then a little more specification, etc.

In the end, you get a living documentation, that can be verified to always reflect what the system actually does.

Title: Creating a new file format: Write code or documentation first?

Body:
When creating a new file format for an application, you can write the code or the documentation first.

When writing the documentation first, you have a better idea of what you should implement.

However, you might need to change a lot of the documentation you have written afterwards when writing the code, because you may discover certain things aren't very efficient to implement that way.

So: When creating a new file format, what should you write first: The code or the documentation?


答: If I was to hire, I would rather see how the person performs in the interview.</p>


答:
I have been using shelving the same way I use stashing in Git. I need to put my current work aside in order to fix something else first. Once this fix has been made, I can resume where I was.

This fix could be a critical bug fix (I say 'could be', because I have never actually had to, but it would be a valid reason). Rather, I have mostly done this because I identified a refactoring that should be made. I would never work on both the refactoring, and the new feature on the same time, and check them in in the same changeset. I would always first implement the refactoring, check that in, and then work on the feature/functionality, and then check that in.

In regards to a lot of the other answers about using shelves as a backup measure, I wouldn't bother. In the 20+ years I have owned computers, I have only experience a hard disk crash once, and that was because I pulled it out of the computer while it was still turned on (and I still managed to salvage the data by replacing the print board). So if this unlikely event really should happen, how much work would you have to recreate? If it is a significant amount, then I would say that your change-sets are too large.

So even though there is nothing wrong with creating a shelve for backup purposes, I just wouldn't bother.

Title: Shelving code in Team Foundation Server (TFS)

Body:
I'm pretty new at using TFS and I'd like to know how you or your team use the "shelve" function of tfs.

We have the following guidelines in using TFS:
- perform a "Get Latest" before you check in and try to build/compile
- do not check in code that does not compile
- at the end of the day, if your work is not complete/partially done, you should "shelve" your pending changes

The first two make sense but I don't really get the last one. I asked my mgr and he said that its so he knows that you actually did some work for that day, which does kind of makes sense but still, I'm wondering what other teams use the "shelve" function for?


答:
You are confusing documentation with specification.

Specification is the process (usually collaborative) through which the definition of what the format should do and how a hypothetical application should handle it, render it, or parse it.

It's a design process like the one W3C does when creating the HTML or CSS specifications way before browsers implement it.

Or course the product of this process can be understood as "documentation", but it's not the documentation of an application.

If you are creating a new file format, discuss and design the specification.

Then code the application that uses that file format ( or have others code it ).

But to create a new file format you don't have to write a single line of code. The specification may never be implemented, yet it exists as an specification.

Obviously when an specification does get implemented, it is revised and extended with the feedback of implementers.


问:
How to properly conduct a feature development meeting?
I am a Product Manager, under me I have about 10 developers, UX designers and marketers. Marketers research about the demands of features, UX designers providing UI mockups, and develkopers write code.

Now, we want to do our feature development monthly meeting (sprint) in a more structured manner ( previously, feature priority is decided in a somewhat adhoc manner, we want to change this). The goals of the meeting are

To set the priority ( urgent, important, normal, not important) of each feature

To make sure that everyone knows what to do for this coming milestone after the meeting is over.

But given that we have 10 people on the team and usually, we have more than 50 features to discussed, I afraid that the whole meeting will drag on for a long time. Also, for the second step, I would need to allow time for everyone to check their schedule, as not everyone is fully available to work on the features ( some would need to fix bugs, provide technical supports etc), so if I ask them to do this in the meeting, then there will be some lull time and disrupt the flow of the meeting.

Is there any well-established meeting procedure that is fitting to my situation above?

答:
I would advise you to split up your team of 10 and make two or three teams out of them.

Think divide-and-conquer. Meetings with 10 people tend not to be optimally productive, but work better with maybe 3-5 people.

The development meetings (as you call them) might not need all people, and are probably not the right way to make sure everybody knows what to do for the next milestone. Those development meetings should be where the decision on what to do is taken, after a long discussion.

After the meetings with each team is done, you should have (for each team) a list of tasks that should be done within the sprint. Maybe it's better to just share those. You can even make a whiteboard or kanban board that everybody can see.

Thinking about this, however, it seems to me that the basic problem you are having is with the organizational structure, with how to structure a team of 10, and not necessarily with Scrum or sprints.


问:
Optimize Reading of Multiple files
I have a unique problem which I'm hoping someone can assist with.

I have One big text file, our Production file. The data in the file is delimited in the following format

```<code>Reference|Cost Centre|Analytics Base Value|....
UMBY_2288|023437|2883484|...
NOT_REAL|1343534|283434|...
</code>```

The average size of this file is about 30MB. with about 120000 rows.

and then I have about 20 Regional files.
these files are similar to the Current big file in structure. except that they are smaller. average size 50000 rows.

Now I have to loop through each line in the big Prod file. For each Reference code, I have to search through each of the 'Regional' files to see which ones contain that specific reference code. and then copying some of the data from that line into a report. There is no way of predetermining what files to look into. And each reference can be in multiple Regional files..

As you can imagine, looping through each row in each file, multiple times is a very time consuming process. Due to memory constraints, I can't load the files into memory.

Does anyone have any smart ideas on how I can do this? I don't need code samples. just pointers on ways I could solve this problem.

I'm developing the tool in C#.

答:
Those loads seem quite small for memory, so there could be a bug in your application.  It doesn't sound like you're using much on what is probably a multi-gigabyte system.

But.. there is a solution to your problem, it's called a 'relational database' and this kind of load is very small fry for many of them.  For the kind of load you're looking at it sounds like SQL Express is probably what you want.

You can load in all your regional files into tables and build indexes to handle the references much more efficiently than you do presently.

Title: Optimize Reading of Multiple files


答:
The solution is to read each file once, storing the date in memory. Keep an associative array or similar data structure where the key is the reference number. Then, as you process the master file, looking up each reference should take just microseconds.

If the data is too big to fit in memory, you can create a temporary sqlite database.

Title: Optimize Reading of Multiple files

Body:
I have a unique problem which I'm hoping someone can assist with.

I have One big text file, our Production file. The data in the file is delimited in the following format

```<code>Reference|Cost Centre|Analytics Base Value|....
UMBY_2288|023437|2883484|...
NOT_REAL|1343534|283434|...
</code>```

The average size of this file is about 30MB. with about 120000 rows.

and then I have about 20 Regional files.
these files are similar to the Current big file in structure. except that they are smaller. average size 50000 rows.

Now I have to loop through each line in the big Prod file. For each Reference code, I have to search through each of the 'Regional' files to see which ones contain that specific reference code. and then copying some of the data from that line into a report. There is no way of predetermining what files to look into. And each reference can be in multiple Regional files..

As you can imagine, looping through each row in each file, multiple times is a very time consuming process. Due to memory constraints, I can't load the files into memory.

Does anyone have any smart ideas on how I can do this? I don't need code samples. just pointers on ways I could solve this problem.

I'm developing the tool in C#.


答:
You say you won't finish it, but that's not bad, that's just data.

"Meet the sprint timeline" isn't a goal. Your goal is to complete user stories. The timeline is just a tool to help you measure and learn how much work you can do in a sprint.

If you are certain you can't finish the work in the sprint, one solution is to move it to the bottom of the priority list and work on the other stories in the sprint first. Then, with the time remaining you can begin to work on it. Re-estimate the work going into the next sprint and finish it then.

Make sure in your retrospective that you discuss what went wrong so you can improve your estimates in the future.


答:
It sounds like the PO is just doing their job. It is their job to know the needs of the customer, and to balance those with the needs of the business. They are the ones that decide what the company will ultimately sell. If they switch from automobiles to baseball bats, presumably that's because they've decided bats are more important. If they are more important, why do you want to continue to build an automobile?

If the team is bothered by this, talk to the PO and tell them your concerns. Again, they are just doing their job, but they should know the effect this churn has on the development team. It's hard to focus on a product when you're constantly switching products back and forth.

Title: Scrum: How much can the Product Owner shake up the Product Backlog?

Body:
For the last 3 sprints or so, I've observed our Product Owner suddenly shoving new stories -- stories not previously in the Product Backlog -- at the top of the Product Backlog.

Because of this, the existing items in the backlog never get worked on.  New stories continuously take over the helm and make into our Sprint Backlog.

My question is - how much can the Product Owner really shake up the Product Backlog?  Is it really fair game to ignore what's already in the backlog and keep on shoving new stories at the top?

I've tried to argue that this is hogwash, but I often hear counter-arguments such as "adapting to frequently changing business needs," "we're moving so fast - we're super agile" and I don't know what to say to those arguments, although I feel it is not how Scrum was meant to be.

EDIT:
I understand that the product owner owns the product backlog.  What I am observing at my team though, is that the PO constantly puts new items at the top of the backlog, ignoring the existing backlog items completely.

For instance, say we're building a car and PO creates 10 stories to make it happen.  We decide to take on 3 stories in our sprint backlog - thus 7 stories still remain in the product backlog.  Everything is good so far.

At the next sprint planning, however, the PO now claims that we need to build a baseball bat and creates 5 stories around that - which are then placed at the top of our backlog (i.e. highest priority); nevermind those car stories we already had in the backlog.


问:
What does "branching is free" mean in Git?
What does "branching is free" mean in Git?

I hear this a lot whenever Git is mentioned in comparison to other version control systems.

I haven't had the opportunity (?) to deal with others (SVN, etc.), so how is branching "expensive" in others?

答:
The claim that "branching is free in git" is a simplification of facts because it isn't "free" per se. Looking under the hood a more correct claim would be to say that branching is redonkulously cheap instead, because branches are basically references to commits. I define "cheapness" here as the less overhead the cheaper.

Lets dig in to why Git is so "cheap" by examining what kinds of overhead it has:

How are branches implemented in git?

The git repository, .git mostly consists of directories with files that contain metadata that git uses. Whenever you create a branch in git, with e.g. git branch {name_of_branch}, a few things happen:

A reference is created to the local branch at: .git/refs/heads/{name_of_branch}

A history log is created for the local branch at: .git/logs/refs/heads/{name_of_branch}

That's basically it, a couple of text files are created. If you open the reference as a textfile the contents will be the id-sha of the commit the branch is pointing at. Note that branching does not require you to make any commits as they're another kind of object. Both branches and commits are "first-class citizens" in git and one way is to think about the branch-to-commit relationship as an aggregation rather than a composition. If you remove a branch, the commits will still exist as "dangling". If you accidentally removed a branch you can always try to find the commit with git-lost-found or git-fsck --lost-found and create a branch on the sha-id you find left hanging (and as long as git hasn't done any garbage collection yet).

So how does git keep track of which branch you're working on? The answer is with the .git/HEAD file, that looks sort of like this if you're on the master branch.

ref: refs/heads/master

Switching branches simply changes the reference in the .git/HEAD file, and then proceeds to change the contents of your workspace with the ones defined in the commit.

How does this compare in other version control systems?

In Subversion, branches are virtual directories in the repository. So the easiest way to branch is to do it remotely, with a one-liner svn copy {trunk-url} {branch-url} -m "Branched it!". What SVN will do is the following:

Copy the source directory, e.g. trunk, to to a target directory,

Commit the changes to finalize the copy action.

You will want to do this action remotely on the server, because making that copy locally is a linear-time operation, with files being copied and symlinked. This is a very slow operation, whereas doing it on the server is a constant time operation. Note that even when performing the branch on the sever, subversion requires a commit when branching while git does not, which is a key difference. That is one kind of overhead that makes SVN marginally less cheap than Git.

The command for switching branches in SVN, i.e. svn switch, is really the svn update in disguise. Thanks to the virtual directory concept the command is a bit more flexible in svn than in git. Sub directories in your workspace can be switched out to mirror another repository url. The closest thing would be to use git-submodule but using that is semantically quite different from branching. Unfortunately this is also a design decision that makes switching a bit slower in SVN than in Git as it has to check every workspace directory which remote-url it is mirroring. In my experience, Git is quicker to switch branches than SVN.

SVN's branching comes with a cost as it copies files and always need to be made publicly available. In git, as explained above, branches are "just references" and can be kept in your local repository and be published to your discretion. In my experience however SVN is still remarkably cheaper and more performant than e.g. ClearCase.

It's only a bummer that SVN is not decentralized. You can have multiple repositories as mirrored to some source repo but synching differing changes multiple SVN-repositories is not possible as SVN does not have uniquely identifiers for commits (git has hashed identifiers that are based on the contents of the commit). The reason why I personally started using git over SVN though is because initiating a repository is remarkably easier and cheaper in git. Conceptually in terms of software configuration management, each divergent copy of a project (clone, fork, workspace or whatever) is a "branch", and given this terminology creating a new copy in SVN is not as cheap as Git, where the latter has branches "built-in".

As another example, in Mercurial, branching started out a bit different as a DVCS and creating/destroying named branches required seperate commits. Mercurial developers implemented later in development bookmarks to mimic git's same branching model though heads are called tips and branches are bookmarks instead in mercurial terminology.


问:
Should a software company have a dedicated team for research and/or utility libraries?
I work in a company that does web applications for various banks and some smaller e-shops
We employ about 20 developers and have 4-5 projects in development at any one time.
Our development teams don't interact much and a lot of the same problems are done in varied ways(good to bad).

I was wondering if it would be a good idea for a company to have a team of programmers that do research on current frameworks and continually improve a common library of functions and a common framework to build current and future projects much faster and more efficiently.

How large should a team like this be?

Also should it have permanent members that train others or should it rotate people?

Update: I was thinking about a common project that people can work on for fun that might spark some interest. It seems that when people have job pressures the solutions they come up with are not the best.

答:
I'm a little late to the game but I felt like no one was addressing this:

Your individual teams that are solving different problems in different ways would definitely benefit from shared functionality, and there are a variety of ways to get that in a way that doesn't devote a single team to developing it, but I've seen a lot of places that do.

In most cases I see this referred to as a "core" of your product line, and sometimes there is a team in charge of maintaining it, led by (as Amir suggested) an architect. This is typically how you'd be able to find ways to leverage or create a framework that follows the tightest standards you set in your organization but provide only the most bare functionalities that may or may not need to be extended into the full-fledged applications that your individual product teams offer. This allows you to have the benefit of "dogfooding" your core code by implementing it in every individual place that you use it, and then also branch out to different products that may have completely different implementations. This allows all your teams to contribute to the core libraries but not bog it down with functionality that only they need.


答: Maybe Joel's implicitly offering a job to anyone with a 5-digit reputation? On a more serious note, some employers do follow sites like this, and also open source projects and mailing lists. I was contacted by a firm about a job opportunity a few years ago based on a recommendation from someone I worked on an open source project with. Having a reputation for being knowledgeable and helpful surely has to count for something.</p>


问:
What do you call an application that is not specifically tied to a DB structure
I'm wondering what you call an applications that are not hard coded around any database structure?

Let me give a small example:

I have one application where the views, the controllers and the  model are tailored to the information and fields in the model, and thus the database.

I have a second (theoretical) application where the views and controllers are completely generic; I could change the fields in my database and make some minor adjustments to model classes and the application still works for editing/adding information.

I wouldn't try to create an application on either of these principles, but I'm wondering what you would label them as.

答:
IMHO it's not really the application that is not tied to a DB structure but its architecture.

In that case, we'll speak about Clean Architecture.

As Uncle Bob says:

a good architecture allows you to defer critical decisions like the
  UI, frameworks, database, etc

Have a look at this pretty interesting article as well, where it tells why:

Architecture is About Intent, not Frameworks


问:
substitute for static inheritance
I currently have a number of classes (~20) that all do the same thing (abstractly), namely, generate an instance of a particular class from an xml file.

The way that they use the content of the xml file varies quite a bit, and the data gets stored into different substructures (fields, groups, etc) that are shared across the classes, so I took all of the parsing and field information out of the files, and created a helper class (as is the final constructed type)

All of the above classes and methods are static, as they have no need to contain any state.

I then wanted to have all the classes derive from one common class so that I am not referencing a seemingly unrelated class constantly, only to discover that inheritance and static do not work together well.

What is the appropriate way of setting this up? Its bascially a large set of factory methods for a type that require no state.

Update: The control flow is currently as follows:

Pick one of ~20 factory methods

Read in an XML file (all tags, attributes are the same across the files, but the files are distict across the methods).

Convert the content in the XML files to a class that has some data structures as members (List<Field>, List<Group>, Dictionary<string,string> etc). These data structures use types that are nested in the helper.

Add these collections to the uninitialized object.

Return the object to caller.

Right now, the 20 factory methods are thier own static classes, and all return objects of the same type, as even though there might be some semantic difference between the "types" all of the memebers and functions are the same. The code that parses the XML file is in a helper, as this logic is common to all of the factory methods. Step 3 has to be different for all the methods, so that part is found in the static classes.

答:
I then wanted to have all the classes derive from one common class so that I am not referencing a seemingly unrelated class constantly

That is your mental error here - you seem to believe that "inheritance" is somehow better for reuse than using a separate helper class. In fact, in most cases the opposite is the case, and since all of your classes are static, you won't get any benefits from inheritance, even if you could use that here.  Your example shows exactly the kind of thinking which leads into typical wrong use of inheritance. Better give your helper class a better name so it does not seem to be so "unrelated".

Title: substitute for static inheritance


答:
If a task takes longer than expected, this should be brought up in the retrospective and discussed.  Was there some piece missed in the early analysis?  Was this something that hadn't been done often already by the team?  There are lots of possible reasons why something may take longer than initially estimated.

The team should try to get the task done as best as possible and then in the retrospective discuss strategies about this in the future.  If the team is fairly new to using Scrum then it may be part of working out the team's initial velocity.  Some teams may think they can do 20 points and some teams may do 60 points, the point is how consistently can the same number of points be done each sprint.

This will happen in the future as any time the team has new tasks it hasn't done before there will be some time taken to work out the kinks of making estimates.  This is part of the learning process that shouldn't really be that surprising.


问:
Writing unit test only for applications that requires them
Bit of a rant, but bear with me.

People call me purist. I do not code in any way other than TDD. When I try to push TDD as a company policy, the following conversation:

company owner: "we'll do TDD when the project warrants it"

me: "if you can't do TDD on even small/simple projects, you won't suddenly know how to do it for big projects. Also if a project is small/simple. the so-called cost of unit test should be negligible".

company owner: "all the devs here know how to do TDD, they'll do it when required".

That last sentence struck me as complete B(each) S(and).

My argument is if a dev "choose to do TDD when he's told it's required". He's doing it wrong and he has no clue about unit test/TDD. Unit testing is like my left hand and my code is like my right hand. Yeah sure I can just use my right hand. It'll just do things wonky and slower.

Do I have my head too far up my @$$? I just have a hard time believing a dev who does TDD fluently would prefer not to do it. (For a whole application)

Edit- I'm not talking about whether TDD/Unit testing is/if/how/when required and its benefit. It's a dead horse. I'm talking about now that I do it day in and day out, I feel uncomfortable NOT doing it. I just want to know if it is a healthy mentality.

答:
No, I suspect the issue here is that the company owner doesn't really understand that one of the core points of TDD is that you have to do it from the beginning of a project or else it'll likely never happen, at least that has been my experience where whenever it is tried to be adopted mid-project it falls apart quite quickly.  As a methodology, I can appreciate TDD and if a place used it, I'd probably acclimatize to it.  However, I'm not sure many places can see the full value of doing things in that manner and thus it is like trying to educate the owner that falls short as he doesn't quite get it would be my interpretation here.

There is nothing wrong with preferring a style and seeking out companies that use a specific methodology, as long as you understand how limiting your pool of potential employers would be in this case.


问:
What is the most inspiring speech from a developer you ever watched?
Please put a direct link to it.

Required:

Still available online (please put a direct link to it)

Must be a speech from a current or former developer

Speaker's popularity doesn't matter

Target audience should be other developers

It is not required that the topic is programming (the task). I'm more looking for subject generally developing here within P.SE rather than SO.

Explain why it was inspiring

(please, native english speaker, edit my question)

答: "The Joys of the Craft" by Frederick P. Brooks Jr in "The Mythical Man Month". Doesn't quite fit your requirement of being a speech - but for me it is still the one essay that perfectly captures the soul of programming.</p>


问:
What are the downsides of implementing a singleton with Java's enum?
Traditionally, a singleton is usually implemented as

```<code>public class Foo1
{
    private static final Foo1 INSTANCE = new Foo1();

    public static Foo1 getInstance(){ return INSTANCE; }

    private Foo1(){}

    public void doo(){ ... }
}
</code>```

With Java's enum, we can implement a singleton as

```<code>public enum Foo2
{
    INSTANCE;

    public void doo(){ ... }
}
</code>```

As awesome as the 2nd version is, are there any downsides to it?

(I gave it some thoughts and I'll answer my own question; hopefully you have better answers)

答:
An enum instance is dependant on the class loader. ie if you have a second class loader that does not have the first class loader as a parent loading the same enum class you can get multiple instances in memory.

Code Sample

Create the following enum, and put its .class file into a jar by itself. ( of course the jar will have the correct package/folder structure )

```<code>package mad;
public enum Side {
  RIGHT, LEFT;
}
</code>```

Now run this test, making sure that there is no copies of the above enum on the class path:

```<code>@Test
public void testEnums() throws Exception
{
    final ClassLoader root = MadTest.class.getClassLoader();

    final File jar = new File("path to jar"); // Edit path
    assertTrue(jar.exists());
    assertTrue(jar.isFile());

    final URL[] urls = new URL[] { jar.toURI().toURL() };
    final ClassLoader cl1 = new URLClassLoader(urls, root);
    final ClassLoader cl2 = new URLClassLoader(urls, root);

    final Class<?> sideClass1 = cl1.loadClass("mad.Side");
    final Class<?> sideClass2 = cl2.loadClass("mad.Side");

    assertNotSame(sideClass1, sideClass2);

    assertTrue(sideClass1.isEnum());
    assertTrue(sideClass2.isEnum());
    final Field f1 = sideClass1.getField("RIGHT");
    final Field f2 = sideClass2.getField("RIGHT");
    assertTrue(f1.isEnumConstant());
    assertTrue(f2.isEnumConstant());

    final Object right1 = f1.get(null);
    final Object right2 = f2.get(null);
    assertNotSame(right1, right2);
}
</code>```

And we now have two objects representing the "same" enum value.

I agree that this is a rare and contrived corner case, and almost always an enum can be used for a java singleton. I do it myself. But the question asked about potential downsides and this note of caution is worth knowing about.

Body:
An enum instance is dependant on the class loader. ie if you have a second class loader that does not have the first class loader as a parent loading the same enum class you can get multiple instances in memory.

Code Sample

Create the following enum, and put its .class file into a jar by itself. ( of course the jar will have the correct package/folder structure )

package mad;
public enum Side {
  RIGHT, LEFT;
}

Now run this test, making sure that there is no copies of the above enum on the class path:

@Test
public void testEnums() throws Exception
{
    final ClassLoader root = MadTest.class.getClassLoader();

    final File jar = new File("path to jar"); // Edit path
    assertTrue(jar.exists());
    assertTrue(jar.isFile());

    final URL[] urls = new URL[] { jar.toURI().toURL() };
    final ClassLoader cl1 = new URLClassLoader(urls, root);
    final ClassLoader cl2 = new URLClassLoader(urls, root);

    final Class<?> sideClass1 = cl1.loadClass("mad.Side");
    final Class<?> sideClass2 = cl2.loadClass("mad.Side");

    assertNotSame(sideClass1, sideClass2);

    assertTrue(sideClass1.isEnum());
    assertTrue(sideClass2.isEnum());
    final Field f1 = sideClass1.getField("RIGHT");
    final Field f2 = sideClass2.getField("RIGHT");
    assertTrue(f1.isEnumConstant());
    assertTrue(f2.isEnumConstant());

    final Object right1 = f1.get(null);
    final Object right2 = f2.get(null);
    assertNotSame(right1, right2);
}

And we now have two objects representing the "same" enum value.

I agree that this is a rare and contrived corner case, and almost always an enum can be used for a java singleton. I do it myself. But the question asked about potential downsides and this note of caution is worth knowing about.


问:
Is there value denoting a key as "Primary"?
Question: Is there value in denoting a key as "Primary"?

This question is not about the definition of a primary key. It is not about the fact primary's aren't nullable. It is not about implementations such as MySQL which automatically perform clustered index voodoo behind the scenes on primary keys.

NOTE: The question is not about the benefits of auto-number-ID surrogates over natural keys.

Suppose a table has 3 candidate keys. All non-nullable. All immutable. I find no value denoting a key as "secondary" or "tertiary". I don't find the concept of precedence useful when dealing with multiple keys. I find the same logic against "secondary" and "tertiary" flags applies to the "primary" flag.

I even feel the word "candidate" is not useful for a key. It implies the candidate is not as important as the key that won the primary election. I don't feel precedence has any place in describing keys. The attributes of the key itself (unique, non-nullable, etc) should be sufficient.

Would the relational model be missing anything if we did not have the "primary" attribute to describe 1 of a table's keys?

答:
As a matter of general principle, I summarily add an "autonumber" field to every table I create in a relational database, give it a sensible name, and mark it as the Primary Key.  Doing this eliminates all sorts of intricacies, like the "candidate, "secondary" and "tertiary" concepts.

Primary keys are well-understood to have certain characteristics: they are unique, and not nullable, among other things.  Marking a key a Primary Key makes it very clear to other developers what its purpose is, and what it can be effectively used for.

Mostly, it is guaranteed to be a stable, unique identifier for each record, making it possible for the key to participate in joins with foreign tables.  I think I'd pull my hair out if I routinely had to deal with tables containing composite, tertiary, secondary keys, and had to figure out each time how to get a unique identifier so that I could join it in a query.


答:
A "Primary" index is the one that uniquely and canonically identifies a record.  If a table were employees, we might have keys on their name, ssn, and hire date, but it would be the employee id that canonically identifies them, and would be the table's primary key.

Without a primary index, you don't have a formal designator of the proper way for another table to refer to a record in your table. So, to extend my example above, you might have payroll indexed by ssn and evaluations indexed by hire date, requiring the actual employee table to be referenced if you wanted to query evaluations against payroll.

Title: Is there value denoting a key as "Primary"?

Body:
Question: Is there value in denoting a key as "Primary"?

This question is not about the definition of a primary key. It is not about the fact primary's aren't nullable. It is not about implementations such as MySQL which automatically perform clustered index voodoo behind the scenes on primary keys.

NOTE: The question is not about the benefits of auto-number-ID surrogates over natural keys.

Suppose a table has 3 candidate keys. All non-nullable. All immutable. I find no value denoting a key as "secondary" or "tertiary". I don't find the concept of precedence useful when dealing with multiple keys. I find the same logic against "secondary" and "tertiary" flags applies to the "primary" flag.

I even feel the word "candidate" is not useful for a key. It implies the candidate is not as important as the key that won the primary election. I don't feel precedence has any place in describing keys. The attributes of the key itself (unique, non-nullable, etc) should be sufficient.

Would the relational model be missing anything if we did not have the "primary" attribute to describe 1 of a table's keys?


问:
What does the term Virtualization encompass?
I have seen on a number of resumes the term "virtualization."  While every resume is unique, what does the broader term or skill of "virtualization" mean or imply?

I feel that the ability to install virtual machines is not the only thing that this means.  I have installed VMs and in my experience it was mostly following instructions.

Is there something else to it that I'm missing, like actually programming virtual machines? Is there an implied IT expertise on the issue, or relevant programming knowledge?

答:
Optimizing the configuration of virtual machines is likely part of what you are missing.  How does one know how much RAM, disk space, CPU cycles to give to each of the VMs and how to monitor the health of these machines as some projects may ramp up and what was initially a good hardware configuration may no longer stay that way.

Failovers and load balancing would be a couple of other components that can be related to setting up virtual machines as they may be used in development and test environments where there isn't the need for beefy hardware and some of the bigger servers could act as 3 or 4 servers in some cases.

Wikipedia notes hardware and desktop virtualization where the latter may be something to consider in some companies as if someone doesn't require a powerful desktop, then a virtual machine could be made off an existing machine that could be shared amongst people without high requirements.


答:
It's not too hard to imagine projects that don't gain any benefit from test driven development.

After all, if the code will never be updated, is so simple it almost can't be written incorrectly, and has so little variation edge cases just can't happen, then writing tests won't help at all.

Of course, what's hard to imagine is a professional software development shop that does this sort of thing day in and day out, and manages to stay In business.

It shouldn't be the size of a project that determines the choice of TDD or not.  It should be the complexity of the code and the possibility of re-use.

Title: Writing unit test only for applications that requires them

Body:
Bit of a rant, but bear with me.

People call me purist. I do not code in any way other than TDD. When I try to push TDD as a company policy, the following conversation:

company owner: "we'll do TDD when the project warrants it"

me: "if you can't do TDD on even small/simple projects, you won't suddenly know how to do it for big projects. Also if a project is small/simple. the so-called cost of unit test should be negligible".

company owner: "all the devs here know how to do TDD, they'll do it when required".

That last sentence struck me as complete B(each) S(and).

My argument is if a dev "choose to do TDD when he's told it's required". He's doing it wrong and he has no clue about unit test/TDD. Unit testing is like my left hand and my code is like my right hand. Yeah sure I can just use my right hand. It'll just do things wonky and slower.

Do I have my head too far up my @$$? I just have a hard time believing a dev who does TDD fluently would prefer not to do it. (For a whole application)

Edit- I'm not talking about whether TDD/Unit testing is/if/how/when required and its benefit. It's a dead horse. I'm talking about now that I do it day in and day out, I feel uncomfortable NOT doing it. I just want to know if it is a healthy mentality.


答:
Sometimes, people put buzzwords on their resume in the hopes that it will get them noticed. For me virtualization goes beyond just creating a virtual machine and running linux or windows on it.

Virtualization encompasses things like selecting hardware and configuring nodes (including failover) for the virtual environment. Deciding whether to use raw storage so that you can take advantage of a SAN solution that handles de-duplication or using virtual hard drives for portability. Creating a management portal and potentially a self-service portal for authorized users to automatically deploy virtual machines based off library templates.

In addition to server virtualization there is also desktop virtualization. This concept involves creating a farm of virtual hosts running desktop clients or a terminal solution and replacing desktop machines with thin clients. These clients typically cost less than $500 and don't have to be upgraded because the horsepower is all in the server.

Finally, there is app virtualization, where applications are stored in bundles. When a user needs to run the application, the bundle is deployed to the client machine and runs in an isolated environment.

If someone puts "Virtualization" on his resume, I'd expect him to be able to talk about one or more of these topics.

Title: What does the term Virtualization encompass?

Body:
I have seen on a number of resumes the term "virtualization."  While every resume is unique, what does the broader term or skill of "virtualization" mean or imply?

I feel that the ability to install virtual machines is not the only thing that this means.  I have installed VMs and in my experience it was mostly following instructions.

Is there something else to it that I'm missing, like actually programming virtual machines? Is there an implied IT expertise on the issue, or relevant programming knowledge?


问:
calling test methods within other test methods
To test a method that returns a clone of the object it is called on, i need to re-run the test suite on the newly created object if i am to ensure that full functionality is retained, i found my instinct was to clone the object then call all other test methods in sequence i order to reduce code duplication. However that approach now smells to me and i can't pinpoint why. Is there a better way to test this kind of functionality?</p>

答:
Such testing might be cleaner with code contracts.  The test methods you are talking about should be invariants (must hold true before and after all public method calls) on your object, rather than unit tests.  Your clone function would have preconditions and postconditions (the postcondition would require that the object be equal to the object it cloned, and possibly that its reference was not equal).

In some cases, your code could be statically tested for compliance with such invariants.


答:
company owner: "all the devs here know how to do TDD, they'll do it when required".

It is pretty obvious that the company owner is running out of arguments and tries end up the discussion.

But honestly, as long as the company owner is not also the lead developer, you are talking to the wrong person. TDD is something you have to convince your dev colleagues of, and if they are willing to adopt it, then the company owner most probably won't resist. If your boss is a good one, he will listen to what the whole team says, and you have just one voice among many. Accept that if you want to be a good team-worker.


答:
A common perception of TDD (or any practice which includes writing an extensive number of automated test code alongside the "real" code) is that it adds to the cost of a project: the time to write the unit test code and the time it takes to maintain unit test code. After all, there's more code, right? It can't come for free, can it? As such, TDD is thought of as overhead. Sure, it provides some value, but it's expensive.

To management, costs need to be justified. Not every widget requires the highest possible construction standards, and likewise not every project should need TDD, right? At some point, a project might become sensitive enough to justify TDD, and at that point it's worth the cost.

As a developer comfortable with TDD, you see that TDD done well doesn't necessarily add to the cost of the project, but may actually reduce the cost, especially in the long run. You're convinced of this, but it's a hard sell to other developers who are comfortable with their own process. It's an even harder sell to management.

Your best bet is to show (other developers, management) that the benefits of TDD outweigh the costs. That takes time. It may never happen. But you will not get anywhere trying to "push TDD as a company policy" without proving its value first.


答: A database needs a way to uniquely identify every record in every table. It needs only one way even if several possibilities exist. But that is used for indexing the table and for making sure action queries correctly affect only the record(s) you want them to affect. Because it needs to know which to use, you should define one of the possible keys as the primary. It doesn't mean the others are less important or that they are not also unique and non-nullable. The others can and should be uniquely indexed and they can also participate in joins to related tables if need be. But one and only one thing must be what the database uses to uniquely identify the record because this key will get added to all indexes (At least in SQL Server). This should be the least mutable of the candidate keys in general. Updating primary keys (espcially of they are also the FKs in related tables) can be an expensive task. It also makes the relationships to other tables easier to define consistently. If you have ever had the displeasure of working with a database where there was no consistent key to use for joins  you would understnd how imporatnt this type of consistency is. </p>


答:
ExternalId seems to be nothing more than a function that provides the current SAP login.

When describing a record of activities, including identification of who performed the activity is normal.  It is expected.  Deciding which ID to use is a different matter.

Are you interested in recording the external user name as determined by the underlying system, or are you interested in providing the username as far as the logical application domain is concerned?

Conceivably, the purchasing company will have more than one authorized buyer.  Likely, this is a common scenario.  This is probably a clear case where including identification of the actor in this action record is important.

In this case, the user ID in question is not a logical internal user ID.  Instead, it is an external, physical system provided user id.  While utilizing the external system user id as a means of convenience for authentication is great, I would be reluctant to recommend using it as basis of internal identification for authorization questions.  Instead, harmonize or translate external user ids to logical internal, application local user ids.

Recording external user ids is great because it provides an opportunity to audit system access and usage patterns.  However, there is a conflict.  Is a logical user that logs in from a Windows machine different from a user who logs in from a UNIX machine even when it actually the same person or service?  What if the schema/database is ported/hosted/replicated to a different system, which uses different database access control and uses a different database username scheme?  Instead of adding another mapping of external user id's to internal logical user id, you may have to transform past data too.

By segregating external user ids to a user table, you can choose to associate different system logins with the same or different logical users.  By also preventing the bleeding of external system user id's into logical application data you provide some protection to the data in the event that future implementations provide different authentication schemes.

The third reason to isolate external usernames from internal logical domain usernames is in the case of impersonation or delegation.  Sometimes a user is authorized and expected to perform actions on behalf of others, where the action should normally be viewed as being performed by delegator, but perhaps with some leading step indicating that delegation occurred and who assumed the subsequent identity (and other session pertinent information).

```<code>User
|UserId(PK)    |PersonaId    |AuthExternSAP    |GoogleOAuth2    |
|1             |1            |PO0313-0001      |                |
|2             |1            |                 |345345324       |

Customer
|CustomerId(PK)    |UserId    |
|1                 |1         |

CustomerPurchase
|CustomerPurchaseId (PK)    |CustomerId    |TotalQty    |SellableResourceId    |
|1                          |1             |10          |1                     |
</code>```

Title: External id for every relational table

Body:
Should I add an external id for every table?

For example if I have these tables :

```<code>Customer
=======================================
Id       Name      Gender
---------------------------------------
1        John      M
2        Doe       M
---------------------------------------

CustomerPurchase
==========================================================================
Id       ExternalId      CustomerId            TotalQty
--------------------------------------------------------------------------
1        PO0313-0001     1                     10
--------------------------------------------------------------------------
</code>```

In that example, I understand that ExternalId is required in CustomerPurchase table (for printing, etc).

But I don't see any reason why Customer table should need one as well.

FYI, the reason I asked this because a friend of mine said that SAP uses ExternalIds in their tables.

Should I use ExternalId in every table?

Am I missing any ExternalId's other usage besides for user's eye friendlier identification?

Thanks!

Body:
ExternalId seems to be nothing more than a function that provides the current SAP login.

When describing a record of activities, including identification of who performed the activity is normal.  It is expected.  Deciding which ID to use is a different matter.

Are you interested in recording the external user name as determined by the underlying system, or are you interested in providing the username as far as the logical application domain is concerned?

Conceivably, the purchasing company will have more than one authorized buyer.  Likely, this is a common scenario.  This is probably a clear case where including identification of the actor in this action record is important.

In this case, the user ID in question is not a logical internal user ID.  Instead, it is an external, physical system provided user id.  While utilizing the external system user id as a means of convenience for authentication is great, I would be reluctant to recommend using it as basis of internal identification for authorization questions.  Instead, harmonize or translate external user ids to logical internal, application local user ids.

Recording external user ids is great because it provides an opportunity to audit system access and usage patterns.  However, there is a conflict.  Is a logical user that logs in from a Windows machine different from a user who logs in from a UNIX machine even when it actually the same person or service?  What if the schema/database is ported/hosted/replicated to a different system, which uses different database access control and uses a different database username scheme?  Instead of adding another mapping of external user id's to internal logical user id, you may have to transform past data too.

By segregating external user ids to a user table, you can choose to associate different system logins with the same or different logical users.  By also preventing the bleeding of external system user id's into logical application data you provide some protection to the data in the event that future implementations provide different authentication schemes.

The third reason to isolate external usernames from internal logical domain usernames is in the case of impersonation or delegation.  Sometimes a user is authorized and expected to perform actions on behalf of others, where the action should normally be viewed as being performed by delegator, but perhaps with some leading step indicating that delegation occurred and who assumed the subsequent identity (and other session pertinent information).

User
|UserId(PK)    |PersonaId    |AuthExternSAP    |GoogleOAuth2    |
|1             |1            |PO0313-0001      |                |
|2             |1            |                 |345345324       |

Customer
|CustomerId(PK)    |UserId    |
|1                 |1         |

CustomerPurchase
|CustomerPurchaseId (PK)    |CustomerId    |TotalQty    |SellableResourceId    |
|1                          |1             |10          |1                     |


问:
Getting started with object detection - Image segmentation algorithm
Just getting started on a hobby object-detection project. My aim is to understand the underlying algorithms and to this end the overall accuracy of the results is (currently) more important than actual run-time.

I'm starting with trying to find a good image segmentation algorithm that provide a good jump-off point for the object detection phase. The target images would be "real-world" scenes.

I found two techniques which mirrored my thoughts on how to go about this:

Graph-based Image Segmentation:
http://www.cs.cornell.edu/~dph/papers/seg-ijcv.pdf

Contour and Texture Analysis for Image Segmentation:
http://www.eng.utah.edu/~bresee/compvision/files/MalikBLS.pdf

The first one was really intuitive to understand and seems simple enough to implement, while the second was closer to my initial thoughts on how to go about this (combine color/intensity and texture information to find regions). But it's an order of magnitude more complex (at least for me).

My question is - are there any other algorithms I should be looking at, that provide the kind of results that these two, specific papers have arrived at? Are there updated versions of these techniques already floating around?

Like I mentioned earlier, the goal is relative accuracy of image segmentation (with an eventual aim to achieve a degree of accuracy of object detection) over runtime, with the algorithm being able to segment an image into "naturally" or perceptually important components, as these two algorithms do (each to varying extents).

I found these two papers after a couple of days of refining my search terms and learning new ones relevant to the exact kind of techniques I was looking for. I have just about reached the end of my personal Google creativity, which is why I am finally here!

I do not know if this is a better fit for cstheory.stackexchange (or even cs.stackexchange). I looked, but cstheory seems more appropriate for intricate algorithmic discussions than a broad question like this. Also, I couldn't find any relevant tags there either! But please do move if appropriate.

答:
Sounds like a fun project. I wonder if your "Google" strategy for refining terms included checking Google Scholar for papers that cite your two sources? For example, the first paper is cited by 1949 other articles, and the second one is cited by 717. Exploring the most highly-cited articles within those two lists should lead you to related and relevant approaches.

Good luck!


问:
Javascript and web application data
I am pretty new to Web Application programming and so to OOP Javascript and the new Client-Server interactions.
I am encountering some trouble wondering about how much AJAX I should use or how much data I have to save "locally" .
Explainig it better: at the moment , to manage the data that I obtain from AJAX request , I push them in Data Structure like Array's and then I handle them helping myself rendering html through template.
Now, was I wondering : is all this necessary? Do I really need to store all this data in Data Structures or I can make AJAX call for every action users do on my application?
I apologize for the explanation but it's a difficult concept for me to explain in English.
Thanks in advance

答:
The correct answer is: "It depends".

See it all depends on your need what actually you want. If the requirement of data is huge then it is better to make just one ajax call and store the data in client side and can do further processing. This will slow cut down the extra time which will may be required in huge ajax requests. But in case you require small chunks of data, then making separate ajax requests for each data has no harm.

It's enough to make it feel like that the data is always present, you just have to figure out how to show or process so it will feasible with user point of view.

Title: Javascript and web application data