问:
PHP Framework for RESTful Web Service
I have been going round in circles with this question for days - which is the best PHP framework to use to create a RESTful Web service?

I've trawled the web for info and have come across three main factors that are important:

must have REST architecture built into the framework

must be a stable application

must be full featured

It may be that what I want does not exists, but I wanted to check with the community to see of I had missed something.

Currently the three contenders are:

CodeIgniter

Is a very stable framework with a large community and plenty of features and 'extensions'. Issue is that it's not RESTful. I have found a RESTful controller but there are a few things that I don't like about it. Mainly that it does not seem to correctly use the HTTP methods as per the RESTful architecture definition.  I think this stems from restrictions in the CodeIgniter core though.

Yii

Again, seems like a large community and is stable with plenty of features, but not RESTful.

Laravel

A framework that is RESTful straight out of the box, and it has a good amount of features. The issue is that this is a relatively new framework so lacks stability.

Other frameworks I've considered:

Zend - from what I've read, avoid unless writing Enterprise software.

Recess - RESTful, but seems very inactive and under used.

UPDATE:

In the end I went for Laravel. Can't recommend it enough! I had a RESTful API up and running in a week and also a simple web client. Amazing framework.

答:
Zend Framework is the obvious choice, it's the more well designed, mature and stable of the frameworks you list, and perfectly suitable for RESTful applications. That said and although I've build numerous apps with it and not just "Enterprise" applications, it's notoriously hard to get the hang of and it might just not be your cup of tea. There was a significant effort to simplify it recently, but had I not been an early adopter I'd probably stay far away from it.

CodeIgniter, a framework I've used extensively, isn't really a good choice. As you've already noticed it doesn't offer a RESTful architecture out of the box, and you are quite right in assuming that the design of the core makes any custom RESTful design a bit tedious (the lack of a HTTP Request class comes to mind). It's not impossible, far from it, but CodeIgniter's main attraction, its ease of use, becomes a lot less attractive when you have to write tons of custom code to do relatively simple things that most other frameworks support out of the box.

Which brings us to Laravel, the newest addition to the endless list of PHP frameworks. I must admit I haven't used it extensively, but from what I've seen so far stability is not an issue. It's a bit idiomatic, but it does provide REST out of the box and Eloquent, its ORM, is awesome. I went with Laravel from my latest application, that has some RESTful components, moving on from my usual Zend Framework + Doctrine combo, but this is my first non throwaway application with the framework and I'm still not 100% comfortable with it.

If you feel Zend Framework is too much for you, Laravel certainly seems like a worthy contender. If you don't want to invest in a relatively new project then there's another option that you missed in your research, Symfony. It sits somewhere between Zend Framework and CodeIgniter when it comes to learning curve, and it's as stable as it gets. The FOSRestBundle offers a simple but complete REST API basis for Symfony, and it might just be exactly what you are looking for.

At the end of the day, it's completely up to you and it's not a decision you can take lightly. Its framework imposes architectural choices that you'll have to live with for as long as you are using it, and for comparably mature frameworks more often than not it boils down to personal preference.

Good luck ;)

Title: PHP Framework for RESTful Web Service


问:
How does one handle sensitive data when using Github and Heroku?
I am not yet accustomed with the way Git works (And wonder if someone besides Linus is ;)).

If you use Heroku to host you application, you need to have your code checked in a Git repo. If you work on an open-source project, you are more likely going to share this repo on Github or other Git hosts.

Some things should not be checked in the public repo; database passwords, API keys, certificates, etc...
But these things still need to be part of the Git repo since you use it to push your code to Heroku.

How to work with this use case?

Note: I know that Heroku or PHPFog can use server variables to circumvent this problem. My question is more about how to "hide" parts of the code.

答:
You should not be hiding parts of the code.  The security of your system should not rely upon the secrecy of the code; that's known as "security through obscurity", which is frowned upon by security experts because it works very poorly.

Instead, passwords, crypto keys, etc. should be kept separate from the code.  Store them in a separate configuration file or configuration value which is read by the code.  You don't need to store them in git.

Important: Never hardcode cryptographic keys, passwords, or other secrets in your source code!  That is very bad practice.

See also:

How do open source projects handle secure artifacts?

Password in file .php

Standards for encrypting passwords in configuration files?

Open Source and how it works for secure projects?

How to protect ftp account information in the source code of a program

Is it a secure way to declare DB parameters in htaccess rather than in a PHP file?

Plug: IT Security.SE is a great place to ask questions about security!

ContentLicense: CC BY-SA 3.0


问:
Why is the minimum value of ints, doubles, etc 1 farther from zero than the positive value?
I know it has something to do with 2's complement and adding 1, but I don't really get how you can encode one more number with the same amount of bits when it comes to negative numbers. </p>

答:
Think about it in these terms. Take a 2-bit number with a preceding sign:

```<code>000 = 0
001 = 1
010 = 2
011 = 3
</code>```

Now let's have some negatives:

```<code>111 = -1
110 = -2
101 = -3
</code>```

Wait, we also have

```<code>100 ...
</code>```

It has to be negative, because the sign-bit is 1. So, logically, it must be -4.

(Edit: As WorldEngineer rightly points out, not all numbering systems work this way -- but the ones you're asking about do.)

Body:
Think about it in these terms. Take a 2-bit number with a preceding sign:

000 = 0
001 = 1
010 = 2
011 = 3

Now let's have some negatives:

111 = -1
110 = -2
101 = -3

Wait, we also have

100 ...

It has to be negative, because the sign-bit is 1. So, logically, it must be -4.

(Edit: As WorldEngineer rightly points out, not all numbering systems work this way -- but the ones you're asking about do.)


问:
How to organize MVVM files in solution
I'm fairly new to the MVVM concept but like a lot of the flexibility it gives me so far.  However, I'm struggling to find a good way to manage my code.  I have several classes that are just sitting in a folder in my solution such as xxxView.cs, xxxViewModel.cs, yyyView.cs, yyyViewModel.cs, zzzView.cs, zzzViewModel.cs you get the idea.  It has started to crowd my solution, making it harder to find the files I'm looking for.  Is there some standard way to organize these files?  Do I create a View and ViewModel folder to separate and clean up the solution or have people found a better way?

答:
If you don't want separate projects, at least separate the different parts with project folders and namespaces.

I use a different pattern.  I keep related view, viewmodel, and model in the same assembly, separated by namespace.  Each new relationship creates a new assembly.

Title: How to organize MVVM files in solution


问:
Past If statements Arrays, loops... Now what?
I gave up on programming a little over a year ago when I kept hitting this wall. I am revisiting the subject because I want to create basic Android application. But I feel that my limited knowledge will not suffice.

Here is my problem.

I have read a few books and watched video tutorials on C#/Java, followed examples, then finished the book. In the end they always seem to leave me dumbfounded as to what to do next.

What a mean is they teach you from your basic "hello world" application all the way up to if's and arrays then seemingly expect you to know how to go out into the world of coding and create anything.

Am I missing something here? I know these are the building blocks of all programs but books that I read never really show me what to do next.

The easy answer I suppose would be to 'start coding', but where? I read "Head First Java" for example; up to the part were they tell you take everything you have learned and create a dog racing game....

"try not to cheat and look at the source code provided, you should be able to do this by now" _ that's not an exact quote but basically that's what I was told.......

Half an hour ago they were just explaining how to do arrays, then without any theory I am meant to create a working game?

The reason I ask this is because I fear that this is all I am supposed to know to at least start coding, yet it feels like I have been given a small toolbox and been told to build a skyscraper.

Thank you for any advice

答:
I would suggest finding open source projects and turning those into personal sandboxes.  Modify existing behaviors, add new behaviors and delete some too.  Play around, implement your own ideas and "what if I tried this".

I'm not advocating you convert someone elses open source project and claim it your own.

I am saying look at other working projects as a means of teaching yourself how to get to the next steps.   There's lots of sites available with opensource code to download.  Here's a few that come to mind:
CodePlex
CodeProject


问:
What's the difference between WTFPL, CC0, and public domain?
What's the difference between WTFPL, CC0, and public domain? Are they essentially the same thing?</p>

答:
The public domain is a bit hard to define formally, as it varies per jurisdiction and there are even jurisdictions that don't recognize a creator's right to dedicate her works to the public domain. This is exactly the problem CC0 is designed to solve:

CC0 helps solve this problem by giving creators a way to waive all their copyright and related rights in their works to the fullest extent allowed by law. CC0 is a universal instrument that is not adapted to the laws of any particular legal jurisdiction, similar to many open source software licenses. And while no tool, not even CC0, can guarantee a complete relinquishment of all copyright and database rights in every jurisdiction, we believe it provides the best and most complete alternative for contributing a work to the public domain given the many complex and diverse copyright and database systems around the world.

CC0 is a license that is equivalent to dedicating your works to the public domain, but it also takes care of the various legal issues and ambiguities of the public domain by simply being a license. The same, more or less, holds true for WFTPL, it's an extremely permissive license you can apply to your works and not worry about the nuances of the public domain.


答:
What is the difference between CC0 and the Public Domain Mark ("PDM")?

CC0 and PDM differ in important respects and have distinct purposes.
CC0 is intended for use only by authors or holders of copyright and
related or neighboring rights (including sui generis database rights),
in connection with works that are still subject to those rights in one
or more jurisdictions. PDM, on the other hand, can be used by anyone,
and is intended for use with works that are already free of known
copyright restrictions throughout the world. The tools also differ in
terms of their effect when applied to a work. CC0 is legally operative
in the sense that when it is applied, it changes the copyright status
of the work, effectively relinquishing all copyright and related or
neighboring rights worldwide. PDM is not legally operative in any
respect – it is intended to function as a label, marking a work that
is already free of known copyright restrictions.

http://creativecommons.org/about/cc0

Unlike Public Domain, the WTFPL is actually a license, and confers rights to the user of the software as such, whereas Public Domain doesn't confer any rights, but is merely an acknowledgement that no rights are asserted.  That's why a license is always preferable to Public Domain; a license explicitly gives permission.

Body: What's the difference between WTFPL, CC0, and public domain? Are they essentially the same thing?</p>


问:
Functional or non-functional requirement?
I'm wondering about functional or non-functional requirements. I have found lot of different definitions for those terms and I can't assign some of my requirement to proper category.

I'm wondering about requirements that aren't connected with some action or have some additional conditions, for example:

On the list of selected devices, device can be repeated.

Database must contain at least 100 items

Currency of some value must be in USD dollar.

Device must have a name and power consumption value in Watts.

are those requirements functional or non-functional ?

答:
Functional or non-functional? I would say neither. Most, if not all of the listed examples look like business rules to me (specifying process-related constraints and decision rules which system processes must follow). </p>

<p>They're something a lot of engineers forget about or aren't aware of, as business rules are typically collected as part of business analysis (and often embedded in functional requirements specs rather than externally referenced). </p>

Body:
Functional or non-functional? I would say neither. Most, if not all of the listed examples look like business rules to me (specifying process-related constraints and decision rules which system processes must follow).

They're something a lot of engineers forget about or aren't aware of, as business rules are typically collected as part of business analysis (and often embedded in functional requirements specs rather than externally referenced).


问:
Programmer Ethics: Can I fork a project from one code host to another?
Say I find this great snippet of code on Bitbucket. I really, really like it but there's a small bug I want to fix. On the other hand, I have all of my code on GitHub.

Is it ok to start a new repo on Github and refer to the original by a comment or on the wiki?

答:
Check the license. Different open source license have different requirements about what kind of changes must be contributed back to the origin.

While there are a lot of cases where an author picks a license out of ignorance, most of the time, the license that author picks reflects the author's ethical position.

Most open source license are written in a manner that is technology-agnostic, forking to a different code host or DVCS would not be considered distinct than forking to the same code host and DVCS. It is a feature of many open source license which allows forkers to use whatever technology they see fit for their own purpose as long as the requirements of the license is fulfilled.

Forking to a different technology does add a layer of difficulty for contributing back, so that should be part of your consideration whether it's worth it to fork to another technology. These technical difficulties are now lessened since there are now very stable and high quality bridging between Mercurial and Git.


问:
Why do we use story points instead of man days when estimating user stories?
In agile methodologies (e.g. SCRUM), the complexity/effort needed for user stories are measured in Story points. Story points are used to calculate how many user stories a team can take in an iteration.

What is the advantage of introducing an abstract concept (story points), where we can just use a concrete measurement, like estimated man-days? We can also calculate velocity, estimate coverage of an iteration, etc. using estimated man-days.

In contrast, story points are harder to use (because the concept is abstract), and also harder to explain to stakeholders. What advantage does it offer?

答:
As already mentioned, story points are a relative measure of complexity. One can use power of 2 series (1,2,4,8,16...) or a Fibonacci scale (1,2,3,5,8,13,20...) for estimation. As espoused developers are quite adept at saying something like this:

Feature A is almost twice as hard as Feature B

But it's really difficult to say 'how long' will this feature take for implementation. You let that be balanced by velocity. So if something was estimated as a 5 but turned out to be a 13, a slower velocity would normalize that for the iteration (or you could re-estimate).

Now, there is another alternative, it's called 'ideal days' (some what similar to man-days but I'm not sure if that's what you meant) and I know of quite a few teams who prefer that. Ideal days are to be interpreted as:

If that's all what I do after coming to office and take only the necessary breaks, have no interruptions and will have everything I need to 'implement the story' i.e. no peripheral activities like meetings, responding to mails etc.,

Mike Cohn, one of the many well know agile evangelists provides the following comparison between story points and ideal days

Story Points

Helps drive cross-functional behavior i.e. teams estimate stories w.r.t. total implementation complexity all the way from UI to DB and back.

SP estimates don't decay i.e. a few months from now a 5 point story is still likely to be 5 points, but an ideal day estimate may change depending on the acquired development skill/speed of that particular programmer

SP are a pure measure of size i.e. they only and only reflect size w.r.t. complexity. Period. No duration etc., thrown it. That's the job of velocity. But not so with ideal days. In fact with ideal days there is a tendency to muddle it with calendar days. Keeping it abstract as SPs fights the temptation to compare with reality. Just a measure of size. No nonsense.

Is typically faster than ideal days. It may be tricky for the first couple of stories, but once you get the hang of it, it's faster.

Different developers can have a different take on their ideal day estimate for completing a story. I could do the same in 3 and you could in 5. SPs are more or less uniform across the board. They level the playing field so to speak.

Ideal Days

Easier to explain outside the team; for obvious reasons :)

Easier to estimate at first as mentioned above. But once you get the hang of SPs it comes naturally

Now, which one to choose is up to the team. However, as most answers here and my personal experience, I prefer story points. Ideal days don't really have that much of a benefit over SPs (and Mike Cohn also advocates SP along with many other agile evangelists).


问:
What are the key differences between software engineers and programmers?
What are the key differences between software engineers and programmers?</p>

答:
Software engineers are people who work at companies that call the people who write software for them "software engineers."

Programmers are people who work at companies that call the people who write software for them "programmers."

There are also developers, or software developers.  They are people who work at companies that call the people who write software for them "developers" or "software developers," respectively.

ContentLicense: CC BY-SA 2.5


问:
Why store a function inside a python dictionary?
I'm a python beginner, and I just learned a technique involving dictionaries and functions. The syntax is easy and it seems like a trivial thing, but my python senses are tingling. Something tells me this is a deep and very pythonic concept and I'm not quite grasping its importance. Can someone put a name to this technique and explain how/why it's useful?

The technique is when you have a python dictionary and a function that you intend to use on it.  You insert an extra element into the dict, whose value is the name of the function. When you're ready to call the function you issue the call indirectly by referring to the dict element, not the function by name.

The example I'm working from is from Learn Python the Hard Way, 2nd Ed. (This is the version available when you sign up through Udemy.com; sadly the live free HTML version is currently Ed 3, and no longer includes this example).

To paraphrase:

```<code># make a dictionary of US states and major cities
cities = {'San Diego':'CA', 'New York':'NY', 'Detroit':'MI'}

# define a function to use on such a dictionary
def find_city (map, city):
    # does something, returns some value
    if city in map:
        return map[city]
    else:
        return "Not found"

# then add a final dict element that refers to the function
cities['_found'] = find_city
</code>```

Then the following expressions are equivalent. You can call the function directly, or by referencing the dict element whose value is the function.

```<code>>>> find_city (cities, 'New York')
NY

>>> cities['_found'](cities, 'New York')
NY
</code>```

Can someone explain what language feature this is, and maybe where it comes to play in "real" programming? This toy exercise was enough to teach me the syntax, but didn't take me all the way there.

答:
There are 2 techniques that leap to my mind which you may be referring to, neither of which are Pythonic in that they are more broad than one language.

1.  The technique of information hiding/encapsulation and cohesion (they usually go hand in hand so I'm lumping them together).

You have an object which has data, and you attaching a method (behavior) which is highly cohesive with the data.  Should you need to change the function, extend the functionality or make any other changes the callers will not need to change (assuming no additional data needs to be passed in).

2. Dispatch tables

Not the classic case, because there is only one entry with a function.  However, dispatch tables are used to organize different behaviors by a key such that they can looked up and called dynamically.  I'm not sure if your thinking of this since your not referring to the function in a dynamic way, but none the less you still gain effective late binding (the "indirect" call).

Tradeoffs

One thing to note is what your doing will work fine with a known namespace of keys.  However, you run the risk of collision between the data and the functions with an unknown namespace of keys.


答:
Note that Python class is really just a syntax sugar for dictionary. When you do:

```<code>class Foo(object):
    def find_city(self, city):
        ...
</code>```

when you call

```<code>f = Foo()
f.find_city('bar')
</code>```

is really just the same as:

```<code>getattr(f, 'find_city')('bar')
</code>```

which, after name resolution, is just the same as:

```<code>f.__class__.__dict__['find_city'](f, 'bar')
</code>```

One useful technique is for mapping user input to callbacks. For example:

```<code>def cb1(...):
    ...
funcs = {
    'cb1': cb1,
    ...
}
while True:
    input = raw_input()
    funcs[input]()
</code>```

This can alternatively be written in class:

```<code>class Funcs(object):
    def cb1(self, a):
        ...
funcs = Funcs()
while True:
    input = raw_input()
    getattr(funcs, input)()
</code>```

whichever callback syntax is better depends on the particular application and programmer's taste. The former is more functional style, the latter is more object oriented. The former might feel more natural if you need to modify the entries in the function dictionary dynamically (perhaps based on user input); the latter might feel more natural if you have a set of different presets mapping that can be chosen dynamically.

Title: Why store a function inside a python dictionary?

Body:
I'm a python beginner, and I just learned a technique involving dictionaries and functions. The syntax is easy and it seems like a trivial thing, but my python senses are tingling. Something tells me this is a deep and very pythonic concept and I'm not quite grasping its importance. Can someone put a name to this technique and explain how/why it's useful?

The technique is when you have a python dictionary and a function that you intend to use on it.  You insert an extra element into the dict, whose value is the name of the function. When you're ready to call the function you issue the call indirectly by referring to the dict element, not the function by name.

The example I'm working from is from Learn Python the Hard Way, 2nd Ed. (This is the version available when you sign up through Udemy.com; sadly the live free HTML version is currently Ed 3, and no longer includes this example).

To paraphrase:

```<code># make a dictionary of US states and major cities
cities = {'San Diego':'CA', 'New York':'NY', 'Detroit':'MI'}

# define a function to use on such a dictionary
def find_city (map, city):
    # does something, returns some value
    if city in map:
        return map[city]
    else:
        return "Not found"

# then add a final dict element that refers to the function
cities['_found'] = find_city
</code>```

Then the following expressions are equivalent. You can call the function directly, or by referencing the dict element whose value is the function.

```<code>>>> find_city (cities, 'New York')
NY

>>> cities['_found'](cities, 'New York')
NY
</code>```

Can someone explain what language feature this is, and maybe where it comes to play in "real" programming? This toy exercise was enough to teach me the syntax, but didn't take me all the way there.

Body:
Note that Python class is really just a syntax sugar for dictionary. When you do:

class Foo(object):
    def find_city(self, city):
        ...

when you call

f = Foo()
f.find_city('bar')

is really just the same as:

getattr(f, 'find_city')('bar')

which, after name resolution, is just the same as:

f.__class__.__dict__['find_city'](f, 'bar')

One useful technique is for mapping user input to callbacks. For example:

def cb1(...):
    ...
funcs = {
    'cb1': cb1,
    ...
}
while True:
    input = raw_input()
    funcs[input]()

This can alternatively be written in class:

class Funcs(object):
    def cb1(self, a):
        ...
funcs = Funcs()
while True:
    input = raw_input()
    getattr(funcs, input)()

whichever callback syntax is better depends on the particular application and programmer's taste. The former is more functional style, the latter is more object oriented. The former might feel more natural if you need to modify the entries in the function dictionary dynamically (perhaps based on user input); the latter might feel more natural if you have a set of different presets mapping that can be chosen dynamically.


问:
php - auto populate the model member variable from database table
I am stuck with a very old large website which I need to do some modifications. I can't use or integrate a new MVC framework due to current site is outdated with some custom coding done long time ago.

I am writing custom reflection class for the user table in the database, but I find it easy to work on the model creating when the parameter passed or primary key and populated the member variables , then use them in the code. for example

```<code>$user= new User($user_id);
</code>```

and then if I need the age I can use

```<code>if($user->age > 18)
</code>```

To do this you might say it's easy just create a constructor method and do a select and assign them to the member variables .. however tricky part is

I want to

Even the database table design is changed I want them to be reflected in the coding without altering the code, ie. if we add a new field to the database table I want it to be called using  $user->new_field; without touching the code. (I know Yii can do this but I can't use Yii as I have to write all functionality of the website if I have to move to a framework)

if possible assign them to the member variables with the data type i.e Strings, Int etc reading them from the database

How to build a model base on above (actually constructor method)?

答:
Suggestion:

Focus on writing decent classes for data access.  The time you will spend putting a few select, insert, update, and delete queries in class definitions will likely pale in comparison to the amount of time you will spend automating it, not to mention the bugs you will likely introduce.

Using schema to generate classes at runtime is possible, but why?  Schema and code are locked together like hand and glove -- one cannot change without the other.


问:
Relationship between user story, feature, and epic?
As someone who's still new to agile, I'm not sure I completely understand the relationship or difference between user story, feature, and epic.

According to this question, a feature is a collection of stories.  One of the answers suggests that a feature is actually an epic. So are features and epics considered the same thing, that is basically a collection of related user stories?

Our project manager insists that there's a hierarchical structure:

Epic -> Features -> User stories

And that basically all user stories must fall within this structure.  Therefore all user stories must fall under an umbrella feature and all features must fall under an epic.

To me, that sounds awkward.  Can someone please clarify how user stories, features, and epics are related?  Or is there an article that clearly outlines the differences?

答:
They are very generic term actually. There is many way to interpret them, varying in the literature and how people see them. Take everything I say with a huge grain of salt.

Usually, an Epic comprise a very global and not very well defined functionality in your software. It is very broad. It will usually be broken down into smaller user story or feature when you try to make sense of it and making them fit in an agile iteration. Example :

Epic

Allow the customer to manage its own account via the Web

Feature and User Story are more specific functionality, that you can easily test with acceptance tests. It is often recommended that they be granular enough to fit in a single iteration.

Features usually tend to describe what your software do :

Feature

Editing the customer information via the web portal

User stories tend to express what the user want to do :

User story

As bank clerk,

I want to be able to modify the customer information

so that I can keep it up to date.

I don't think there is really a hierarchy between the two, but you can have one if you want or if it fit how you work. A user story can be a specific justification for a feature, or a specific way to do it. Or it can be the other way around. A feature can be a way to realize a user story. Or they can denote the same thing. You can use both : User stories to define what bring business value and feature to describe constraint of the software.

User story: as a customer, I want to pay with the most popular credits cards

Feature support the GOV-TAX-02 XML API of the government.

There is also the question of scenario, which are usually a way a Feature/User story will be executed. They usually map cleanly to a specific acceptance test. For example

Scenario : Withdrawing money

Given I have 2000$ in my bank account

When I withdraw 100$

Then I receive 100$ in cash

And my balance is 1900$

That is how we define those terms where I work. Those definitions are far from a mathematical definition or a standardized term. Its like the difference between a right wing politician or a left wing politician. It depend where you live. In Canada, what is considered right wing may be considered left-wing in the United State. It's very variable.

Seriously, I wouldn't worry too much about it. The important is that everyone on the team agree on a definition so you can understand each other. Some method like scrum tend to define them more formally, but pick what work for you and leave the rest. After all, isn't agile about Individuals and interactions over processes and tools and Working software over comprehensive documentation?

ContentLicense: CC BY-SA 4.0


答:
Epic

A very large user story that is eventually broken down into smaller stories.

User story

A very high-level definition of a requirement, containing just enough information so that the developers can produce a reasonable estimate of the effort required to implement it.

http://www.telerik.com/agile-project-management-tools/agile-resources/vocabulary.aspx
 (archived link)

Feature

A distinguishing characteristic or capability of a software application or library (e.g., performance, portability, or functionality).

http://en.wikipedia.org/wiki/Software_feature

Title: Relationship between user story, feature, and epic?

Body:
As someone who's still new to agile, I'm not sure I completely understand the relationship or difference between user story, feature, and epic.

According to this question, a feature is a collection of stories.  One of the answers suggests that a feature is actually an epic. So are features and epics considered the same thing, that is basically a collection of related user stories?

Our project manager insists that there's a hierarchical structure:

Epic -> Features -> User stories

And that basically all user stories must fall within this structure.  Therefore all user stories must fall under an umbrella feature and all features must fall under an epic.

To me, that sounds awkward.  Can someone please clarify how user stories, features, and epics are related?  Or is there an article that clearly outlines the differences?


问:
Round Table - Minimum Cost Algorithm
Problem Link - http://www.iarcs.org.in/zco2013/index.php/problems/ROUNDTABLE

It's dinner time in Castle Camelot, and the fearsome Knights of the Round Table are clamouring for dessert. You, the chef, are in a soup. There are N knights, including King Arthur, each with a different preference for dessert, but you cannot afford to make desserts for all of them.

You are given the cost of manufacturing each Knight's preferred dessert-since it is a round table, the list starts with the cost of King Arthur's dessert, and goes counter-clockwise.

You decide to pick the cheapest desserts to make, such that for every pair of adjacent Knights, at least one gets his dessert. This will ensure that the Knights do not protest.
  What is the minimum cost of tonight's dinner, given this condition?

I used the Dynamic Programming approach, considering the smallest of i-1 & i-2, & came up with the following code -

```<code>#include<cstdio>
#include<algorithm>
using namespace std;

int main() {
int n,i,j,c,f;
scanf("%d",&n);
int k[n],m[n][2];
for(i=0;i<n;++i) scanf("%d",&k[i]);
m[0][0]=k[0]; m[0][1]=0;
m[1][0]=k[1]; m[1][1]=1;
for(i=2;i<n;++i) {
                 c=1000;
                 for(j=i-2;j<i;++j) {
                                    if(m[j][0]<c) { c=m[j][0]; f=m[j][1];}
                 }
                 m[i][0]=c+k[i]; m[i][1]=f;
}
if(m[n-2][0]<m[n-1][0] && m[n-2][1]==0) printf("%d\n",m[n-2][0]);
else printf("%d\n",m[n-1][0]);
}
</code>```

I used the second dimension of the m array to store from which knight the given sequence started (1st or 2nd). I had to do this because of the case when m[n-2]<m[n-1] but the sequence started from knight 2, since that would create two adjacent knights without dessert. The problem arises because of the table's round shape.

Now an anomaly arises when I consider the case - 2 1 1 2 1 2. The program gives an answer 5 when the answer should be 4, by picking the 1st, 3rd & 5th knight. At this point, I started to doubt my initial algorithm (approach) itself!

Where did I go wrong?

答:
So I've looked at your code, and I have to be honest, it will take me quite a bit longer to get into your frame of mind and code then I'm willing to put in. But I can suggest an alternative way of dividing the sub problems that I think will be easier to understand and write.

Define a 4x(n+1) array. At index i,j the j index corresponds to the sub-problem of the first n knights. The last spot is the first one repeated again. The 4 array locations correspond to 4 different cases, corresponding to whether or not the very first knight got his dessert, and whether the jth knight got his dessert.

The base case is easy to do because we have restricted whether or not the first knight gets dessert. So it's even more trivial than usual. To solve the current case in terms of previous cases is fairly straightforward: the cases where the first knight does or doesn't get dessert are completely separate. For each case, the value for the case where the current knight gets dessert is the min of the previous entries, plus the current cost of dessert. The case where he doesn't is the sum of the previous solution where the last knight did get dessert, plus the current cost of dessert.

To wrap up the algorithm: out of the 4 rows, only 2 are relevant, because only 2 correspond to cases where the beginning and end (which is the beginning repeated) are consistent. Take the smallest out of these two.

Title: Round Table - Minimum Cost Algorithm


答: Because there are not two classes of numbers in the integer range, but three: negative numbers, zero, and positive numbers. Zero has to take up a slot (would be rather impractical not to be able to represent zero...), so either the positive or the negative class has to give up a slot. The fact that it's usually the positive range that has to make that sacrifice is to a certain extent arbitrary, but on the level of bit manipulations there are some things that this decision makes more convenient.</p>

Title: Why is the minimum value of ints, doubles, etc 1 farther from zero than the positive value?

Body: I know it has something to do with 2's complement and adding 1, but I don't really get how you can encode one more number with the same amount of bits when it comes to negative numbers. </p>


问:
Why is the cyclomatic complexity equal to two for a simple Hello World?
I would have two questions related to cyclomatic complexity:

Can I use this metric for a whole app? I guess I cannot, as it would be incredibly large number, considering functions calling functions etc. Is it just for module/method/unit?

In Visual Studio, for starting app with just calling the Main method, the cyclomatic complexity value is 2. Why? There is just one possible way if I run the program - it ends.

答:
The cyclomatic complexity of the most basic console application is 2 for a simple reason: aside the Main() method, there is also a constructor. It's like writing:

```<code>public class Program
{
    public Program()
    {
    }

    public static void Main()
    {
    }
}
</code>```

The first path is to create a new instance of the Program class. This path is taken by default to launch the application.

The second path is to call the static method Program.Main(). This path can be taken if the application is used as an ordinary library by another application.

Note that this applies to any non-static class having a static method. For example:

```<code>public class Hello
{
    // Even if the constructor was omitted, it will still be added by the compiler.
    public static void SayHello()
    {
    }
}
</code>```

will have a cyclomatic complexity of 2 as well.

Also note that if you really want to have an application with a cyclomatic complexity of 1, you simply declare Program class as static, as in the following piece of code. I have no idea why the default template in Visual Studio forgets to add both public and static keywords.

```<code>public static class Program // ← See, we replaced a non-static class by a static one
{
    static void Main(string[] args)
    {
    }
}
</code>```

As for your first question, you don't use cyclomatic complexity as the sole factor. Maintainability index, with its quite tricky formula, is a better metric, but even maintainability index is not something you can fully trust and rely on to say that a piece of code is "good" or "bad".

It's not disturbing to have a cyclomatic complexity of a few thousands for a small project, and it doesn't make too much sense to use it for class, assembly or project scope; what would be much more disturbing is to obtain a high cyclomatic complexity for a specific method.

Body:
The cyclomatic complexity of the most basic console application is 2 for a simple reason: aside the Main() method, there is also a constructor. It's like writing:

public class Program
{
    public Program()
    {
    }

    public static void Main()
    {
    }
}

The first path is to create a new instance of the Program class. This path is taken by default to launch the application.

The second path is to call the static method Program.Main(). This path can be taken if the application is used as an ordinary library by another application.

Note that this applies to any non-static class having a static method. For example:

public class Hello
{
    // Even if the constructor was omitted, it will still be added by the compiler.
    public static void SayHello()
    {
    }
}

will have a cyclomatic complexity of 2 as well.

Also note that if you really want to have an application with a cyclomatic complexity of 1, you simply declare Program class as static, as in the following piece of code. I have no idea why the default template in Visual Studio forgets to add both public and static keywords.

public static class Program // ← See, we replaced a non-static class by a static one
{
    static void Main(string[] args)
    {
    }
}

As for your first question, you don't use cyclomatic complexity as the sole factor. Maintainability index, with its quite tricky formula, is a better metric, but even maintainability index is not something you can fully trust and rely on to say that a piece of code is "good" or "bad".

It's not disturbing to have a cyclomatic complexity of a few thousands for a small project, and it doesn't make too much sense to use it for class, assembly or project scope; what would be much more disturbing is to obtain a high cyclomatic complexity for a specific method.


问:
Creating huge decision tree
I'm to write an event correlator. A fundamental part of the system will be a decision tree that recognizes the origin of the fault basing on recorded states and log files.

Often many accidents will differ with minor details and many decisions taken will be made basing on fuzzy, incomplete or unreliable data, but most of these decisions can be written down as binary logic functions.

Thing is, there will be a lot of them. I expect at least 100 nodes in the decision tree, and I may underestimate the value by an order of magnitude. And on top of that,  as new, unexpected patterns emerge, unforseen failures happen leaving new traces, or with extension of the system new failure modes become viable, the decision tree will have to be maintained.

(and it won't always be a pure tree structure - some faults of the same effect have two or more modes of appearance, some of these branching off into different modes, e.g. event A means failure X, event B means: check event C. If C is true, it's also failure X, but if not, it's failure Y. Although I can always normalize it into X1 and X2, which are technically identical but different from the tree point of view.) Also, the tree will be often fairly deeply nested so I'm afraid a simple series of nested if() will quickly slip out of control.

Now my question is, how to store / write / build that tree so that it could be compilable into something the machine can digest, but still maintainable for the developers?

Note this is for an embedded system, so heavyweight solutions like JBoss don't really fit unless they appear only on the compiler side, and the final system runs a compiled ruleset in something much more machine friendly.

(the system is written in C++, it also makes extensive use of JSON, and will run on an ARM9 CPU if that's of any help.)

答:
I am no C++ developer, but I think the rule declarations DSL can be implemented purely in C++.

First, there is a request object, containing all input parameters (e.g. as a map). This object can also cache an already checked conditions, rule check trace, and possibly some intermediate data.

```<code>class Request {
public:
    template<T> Value<T> get(Parameter<T>); // Returns the given parameter value.
    /* Returns a 3-state status for the given condition:
       - not checked yet
       - condition succeed
       - condition failed */
    ConditionCheckStatus getCheckStatus(Condition);
    void setCheckStatus(Condition, bool); // Caches the condition check status.
}
</code>```

Such object should be constructed once per request and should be passed to a topmost rule.

A conditions can be expressed using a Condition class subclasses. The Condition checks whether it's already evaluated. If not - then evaluates itself and caches the evaluation check status. To build a complex conditions it is good to override &, | and ! operators:

```<code>class Condition {
public:
    inline bool check(Request &request) {
        switch (request->getCheckStatus(this)) {
        case COND_SUCCESS:
            return true;
        case COND_FAILURE:
            return false;
        }
        bool result = this->checkCondition(request);
        request.setCheckStatus(this, result);
        return result;
    }
    inline Condition &operator & (Condition &other) {return *new AndCondition(*this, other)}
    inline Condition &operator | (Condition &other) {return *new OrCondition(*this, other)}
    inline Condition &operator ! () {return *new NotCondition(*this)}
protected:
    virtual bool checkCondition(Request &) = 0;
}
</code>```

A concrete conditions can be declared as global constants and may be combined with logical operators to build a more complex ones.

The Parameter template can be used to access a Request parameters in a type-safe manner. A concrete parameters can be declared as global constants. Parameters can also override operators to construct Conditions like this:

```<code>// Declare a "counter" input parameter.
const Parameter<int> Counter;

// Construct a "more than once" condition.
const Condition &MoreThanOnce = Counter > 1;
</code>```

A ruleset can be declared using Rule objects (also declared as global constants).

```<code>const Rule FailIfMoreThanOnce(
    MoreThanOnce, /* The condition */
    Failure,      /* The rule invoked if condition succeed */
    OtherRule     /* The rule invoked if condition failed */);

// ... Other rule definitions

const Rule TopRule(SomeCondition1 | SomeCondition2, SomeRule1, SomeRule2);
</code>```

A decision tree evaluation would look like this:

```<code>Request request;
// Fill the request.
bool result = TopRule.check(request);
// Handle the result.
</code>```

Note that all Parameters, Conditions and Rules are stateless. The only mutable object is Request, which is constructed once per request and collects the evaluated data.

The rules, parameters and conditions may have a meaningful names, can be constructed using operators. There is almost none syntax overhead for their declaration. The even shorter declarations can be done using macros.

Title: Creating huge decision tree

Body:
I am no C++ developer, but I think the rule declarations DSL can be implemented purely in C++.

First, there is a request object, containing all input parameters (e.g. as a map). This object can also cache an already checked conditions, rule check trace, and possibly some intermediate data.

class Request {
public:
    template<T> Value<T> get(Parameter<T>); // Returns the given parameter value.
    /* Returns a 3-state status for the given condition:
       - not checked yet
       - condition succeed
       - condition failed */
    ConditionCheckStatus getCheckStatus(Condition);
    void setCheckStatus(Condition, bool); // Caches the condition check status.
}

Such object should be constructed once per request and should be passed to a topmost rule.

A conditions can be expressed using a Condition class subclasses. The Condition checks whether it's already evaluated. If not - then evaluates itself and caches the evaluation check status. To build a complex conditions it is good to override &, | and ! operators:

class Condition {
public:
    inline bool check(Request &request) {
        switch (request->getCheckStatus(this)) {
        case COND_SUCCESS:
            return true;
        case COND_FAILURE:
            return false;
        }
        bool result = this->checkCondition(request);
        request.setCheckStatus(this, result);
        return result;
    }
    inline Condition &operator & (Condition &other) {return *new AndCondition(*this, other)}
    inline Condition &operator | (Condition &other) {return *new OrCondition(*this, other)}
    inline Condition &operator ! () {return *new NotCondition(*this)}
protected:
    virtual bool checkCondition(Request &) = 0;
}

A concrete conditions can be declared as global constants and may be combined with logical operators to build a more complex ones.

The Parameter template can be used to access a Request parameters in a type-safe manner. A concrete parameters can be declared as global constants. Parameters can also override operators to construct Conditions like this:

// Declare a "counter" input parameter.
const Parameter<int> Counter;

// Construct a "more than once" condition.
const Condition &MoreThanOnce = Counter > 1;

A ruleset can be declared using Rule objects (also declared as global constants).

const Rule FailIfMoreThanOnce(
    MoreThanOnce, /* The condition */
    Failure,      /* The rule invoked if condition succeed */
    OtherRule     /* The rule invoked if condition failed */);

// ... Other rule definitions

const Rule TopRule(SomeCondition1 | SomeCondition2, SomeRule1, SomeRule2);

A decision tree evaluation would look like this:

Request request;
// Fill the request.
bool result = TopRule.check(request);
// Handle the result.

Note that all Parameters, Conditions and Rules are stateless. The only mutable object is Request, which is constructed once per request and collects the evaluated data.

The rules, parameters and conditions may have a meaningful names, can be constructed using operators. There is almost none syntax overhead for their declaration. The even shorter declarations can be done using macros.


答:
There are BASICALLY three ways to represent signed integers in binary: 2's complement, 1's complement, and sign-magnitude.  (Biquinary went the way of the Dodo Bird a long time ago.)

1's complement and sign-magnitude have two zero values, +0 and -0, each with a unique representation.  2's complement only has one zero value, and one representation.

Now, a field of N bits can encode 2^N values.  Subtract one in 2's complement, and you have 2^N-1 = 2^(N-1) + 2^(N-1) + 1.  Since the representation for zero is all zero bits, and a + sign is zero, there will be one more possible nonzero representation with the sign bit set to 1.

This is a very long-winded way of saying 2's complement represents values in the range -(2^(N-1)) .. +(2^(N-1) - 1).

1's complement actually has an advantage over 2's complement if you are doing integer digital signal processing computations.  1's complement operations inherently truncate toward zero.  2's complement truncates toward -infinity.  I learned this one the HARD way...


问:
Where can I find statistics on worldwide developers and software companies?
I try to find an answer of a very difficult question. The question is:

How many developers and how many software companies are there in the world?

For example if I check the Statistic Austria page I can see that in Austria there are 8383 companies with 35522 employees defined as "Computer programming, consultancy and related activities" and another 4102 companies with 15171 employees defined as "Information service activities".

This statistic is good, but it is only for Austria. Is there a similar for Europe, USA, Worldwide?

答: In Mexico there is 538,292, IT Professionals according to INEGI (statics of Mexico) in his "Boletín de Política Informática No. 5, 2002" here is the file. The paper shows the jobs and some other info hope it helps. Maybe you can made a sum of all the others. And get the total of programers in all the world.</p>


问:
Is this "anti-pattern" and should I stop using it or is this clever design?
I've basically stared to do the following when creating a REST service:

HTML is requested

service returns the desired web page but without the requested "resource", eg. data

web page contains JavaScript that issues AJAX request to the same service (different content-type)

service then returns the actual data (JSON) and the page displays it

On one side it seems inefficient (2 requests) but then were I used this, "performance is of no concern", meaning low traffic internal app and the web sites are simple and load fast.

The reason I ended up with this is that the web page can then be almost pure Html + JavaScript and almost no server-side stuff is required, especially no loops, to create tables and stuff like that (which I think is very ugly compared to things like slickgrid), e.g. separation of data and view.

Now before I get to using this, is this a good idea or should I just stop doing it?

答: as @Jan Hudec said, your approach can definitely not be called REST. Though the part where the client requests for a resource could be. It is better if the client handles the presentation part, like backbone does. It communicates with the REST server for the resources and displays them using views.


问:
How and why to decide between naming methods with "get" and "find" prefixes
I always have trouble figuring out if I should name a certain method starting with getSomething versus findSomething.

The problem resides in creating helpers for poorly designed APIs. This usually occurs when getting data from an object, which requires the object as a parameter. Here is a simple example:

public String getRevision(Item item) {
    service.load(item, "revision");
    // there is usually more work to do before getting the data..
    try {
        return item.get_revision();
    }
    catch(NotLoadedException exception) {
        log.error("Property named 'property_name' was not loaded", exception);
    }
    return null;
}
```

How and why to decide between naming this method as getRevision() or findRevision()?

答:
Find implies not having the result, like when executing a database query with some parameters that may change between calls. Get, on the other hand, implies the results are known to the method beforehand or won't change once known, that there are no parameters to the call.

So, I'd use for example Customer findCustomerById(long customerId) and Customer getCustomer()


问:
Should I still use Debug.Assert today?
I recently came across some newly written code that was interspersed with lots of Debug.Assert (C#).

Should we still use this widely despite the usage of TDD, BDD and Unit Testing in general?

答:
I consider asserts and unit tests to be two different tools in my toolbox. Some things are better suited to one, and some are better suited to the other.

As an example, these days I mostly make use of asserts to validate parameters for non-public methods.

Title: Should I still use Debug.Assert today?


答:
I don't see any reason why you shouldn't use Assert. By doing so you've already acknowledged a need for guards, like preconditions & invariants, and are making a move towards Design by Contract. Assert is only one way of achieving this...

```<code>// Precondition using Asert
void SomeMethod(Foo someParameter)
{
    Debug.Assert(someParameter != null)
}

// Precondition using If-Then-Throw
void SomeMethod(Foo someParameter)
{
    if (someParameter == null)
        throw new ArgumentNullException("someParameter");
}

// Precondition using Code Contracts
void SomeMethod(Foo someParameter)
{
    Contract.Requires(someParameter != null);
}

// Precondition using some custom library
void SomeMethod(Foo someParameter)
{
    Require.ArgumentNotNull(() => someParameter);
}
</code>```

All are ways of achieving the same thing: robustness in code. It just comes down to choosing an option, of which Assert is a valid choice.

Note that I have not mentioned unit tests at all so far, as they accomplish something very different. A unit test formally proves the robustness of the code by exercising a guard:

```<code>[Test]
void SomeMethod_WhenGivenNull_ThrowsArgumentNullException()
{
    delegate call = () => someObject.SomeMethod(null);

    Assert.That(call).Throws<ArgumentNullException>();
}
</code>```

This is an entirely different kind of assert...

**Note that in some frameworks it's actually quite difficult to unit test for an assertion failure, as an assertion failure can bring down the entire runtime, so one of the other options might be preferred...*

Title: Should I still use Debug.Assert today?

Body:
I recently came across some newly written code that was interspersed with lots of Debug.Assert (C#).

Should we still use this widely despite the usage of TDD, BDD and Unit Testing in general?

Body:
I don't see any reason why you shouldn't use Assert. By doing so you've already acknowledged a need for guards, like preconditions & invariants, and are making a move towards Design by Contract. Assert is only one way of achieving this...

// Precondition using Asert
void SomeMethod(Foo someParameter)
{
    Debug.Assert(someParameter != null)
}

// Precondition using If-Then-Throw
void SomeMethod(Foo someParameter)
{
    if (someParameter == null)
        throw new ArgumentNullException("someParameter");
}

// Precondition using Code Contracts
void SomeMethod(Foo someParameter)
{
    Contract.Requires(someParameter != null);
}

// Precondition using some custom library
void SomeMethod(Foo someParameter)
{
    Require.ArgumentNotNull(() => someParameter);
}

All are ways of achieving the same thing: robustness in code. It just comes down to choosing an option, of which Assert is a valid choice.

Note that I have not mentioned unit tests at all so far, as they accomplish something very different. A unit test formally proves the robustness of the code by exercising a guard:

[Test]
void SomeMethod_WhenGivenNull_ThrowsArgumentNullException()
{
    delegate call = () => someObject.SomeMethod(null);

    Assert.That(call).Throws<ArgumentNullException>();
}

This is an entirely different kind of assert...

**Note that in some frameworks it's actually quite difficult to unit test for an assertion failure, as an assertion failure can bring down the entire runtime, so one of the other options might be preferred...*


问:
Most flexible UI Framework for Windows endpoint?
I am tasked with designing and implementing a flexible UI solution for deployment across a series of "kiosk"-ed Windows endpoints. There is some debate about what is the considered to be the best technology solution for the actual UI itself. The requirements are:

Must be hardware accelerated

Must play WMV video (for licensing reasons)

Must be skinnable/themeable.

Must support off-screen rendering.

答:
WPF handles all of those.

It is fully HW accelerated. It plays WMV through MediaElement class. It was designed with themability from the begining, not unlike many bolt-on solutions found in WinForms libraries. And it allows rendering of visuals into a bitmap through RenderTargetBitmap, which I assume you mean by "off-screen rendering".


问:
How to organize projects in Redmine?
I deployed a Redmine installation yesterday and today I try to fill it with some relevant data. One issue I came across is the organization of projects itself. While I took a look at how Redmine itself uses parts of the software, they unfortunately  have only one project set up and I haven’t seen any other examples. I know that this is heavily tied to your workflow, but seeing / reading about some examples would guide me to the right path.

We are two guys (a designer & developer, both of us do also other stuff like marketing or paperwork) and we have more than 20 projects that I want to map to Redmine. Less than a handful of projects are active at the same time and they aren’t specifically related. However, we want to see how much time we spent on all projects and also see the overall project situation, i.e. should we start another project or add this or that to the current one or won’t this be doable for such a small team?

At the moment I tend to have one of these setups:

A company project and all of our real projects organized as subprojects.

Separate Redmine projects for each of our projects, and eventually subprojects for broader functionality if needed (sync support for app xyz).

The problems I see with the first approach is that the projects aren’t necessarily related to each other. They may share a common framework which is a project for itself, but otherwise they are really separate things. All of them are software projects, so they share common metaphors like Trackers, though. I haven’t seen a way to separate versions. The roadmap would be an overview of the current work situation, but it could get pretty confusing. My biggest fear is that we will have endless drop down lists with unrelated things like versions from other projects.

The second approach seems to be saner, but my biggest fear is that we won’t have the general overview. We would have to look at all other roadmaps to plan the current one, we wouldn’t see just one calendar with things to do in all projects.

I think the core of the problem is that we have very limited human resources that have to be shared across a lot of projects, but they mustn’t overlap. Any ideas how this can be mapped to Redmine?

答:
The second approach seems to the way to go. I missed that one can view all issues on all projects and then use the sidebar to show an overall calendar & Gantt chart.

The only thing I’ll have to check is if some of the charts plugins support cross-projects statistics, too. Most plugins look like they are awfully outdated.

It’s overwhelming how flexible Redmine (or most other related software) is at the beginning, but it’s also good to know that it can grow with your requirements.

Title: How to organize projects in Redmine?


问:
Architecture(structure)-oriented vs. feature-oriented project structure
The project, I have involved, has an architecture-oriented project's file/folder structure:

```<code>Root
|____ Node1
    |____ Event Handlers
    |         |___ <all event handlers of project>
    |____ Events
    |         |___ <all events of project>
    |____ Request Handlers
    |         |___ <all request handlers of project>
    |____ Requests
    |         |___ <all requests of project>
    |____ ...
</code>```

It is a clear from the architectural point of view of system (has been proposed by development team).

It is a feature-oriented structure has been proposed by designer team:

```<code>Root
|____ Feature #1
    |____ Event Handlers
    |         |___ <all event handlers of Feature #1>
    |____ Events
    |         |___ <all events of Feature #1>
    |____ Request Handlers
    |         |___ <all request handlers of Feature #1>
    |____ Requests
    |         |___ <all requests of Feature #1>
    |____ ...
</code>```

This variant is closer to designers and it describes clearly a feature to be implemented.

Our teams have started a holy war: what is the best approach. Could somebody help us and explain cons and pros of the first and second ones. Maybe there is a third one that is more useful and beneficial for both of us.

Thank you.

答:
I don't understand the terminology you're using, but will try to answer anyway, since both structures seem to be the wrong approach.

Unless you've only got a handful of features, you need to group them into categories - and that doesn't appear to be catered for in either design (unless that's what Node1 is intended as, but the "all X of project" suggests otherwise, and makes me wonder WTF it is - is there a Node2?)

I might consider something like this:

```<code>Root
|____ Event Handlers
|   |____ Category A
|   |    |___ Feature #1 EHs
|   |    |___ Feature #2 EHs
|   |    |___ Feature #3 EHs
|   |
|   |____ Category B
|   |    |___ Feature #4 EHs
|   |    |___ Feature #5 EHs
|   |
|
|____ Events
|   |____ Category A
|   |    |___ Feature #1 Events
|   |    |___ Feature #2 Events
|   |    |___ Feature #3 Events
|   |
|   |____ Category B
|   |    |___ Feature #4 Events
|   |    |___ Feature #5 Events
|   |
|
</code>```

Or this:

```<code>Root
|____ Category A
|   |____ Event Handlers
|   |    |___ Feature #1 EHs
|   |    |___ Feature #2 EHs
|   |    |___ Feature #3 EHs
|   |
|   |____ Events
|        |___ Feature #1 Events
|        |___ Feature #2 Events
|        |___ Feature #3 Events
|
|____ Category B
|   |____ Event Handlers
|   |    |___ Feature #4 EHs
|   |    |___ Feature #5 EHs
|   |
|   |____ Events
|        |___ Feature #4 Events
|        |___ Feature #5 Events
</code>```

But they're both making assumptions which may be completely off - if you can update your question with more details I may change my mind. :)

Body:
I don't understand the terminology you're using, but will try to answer anyway, since both structures seem to be the wrong approach.

Unless you've only got a handful of features, you need to group them into categories - and that doesn't appear to be catered for in either design (unless that's what Node1 is intended as, but the "all X of project" suggests otherwise, and makes me wonder WTF it is - is there a Node2?)

I might consider something like this:

Root
|____ Event Handlers
|   |____ Category A
|   |    |___ Feature #1 EHs
|   |    |___ Feature #2 EHs
|   |    |___ Feature #3 EHs
|   |
|   |____ Category B
|   |    |___ Feature #4 EHs
|   |    |___ Feature #5 EHs
|   |
|
|____ Events
|   |____ Category A
|   |    |___ Feature #1 Events
|   |    |___ Feature #2 Events
|   |    |___ Feature #3 Events
|   |
|   |____ Category B
|   |    |___ Feature #4 Events
|   |    |___ Feature #5 Events
|   |
|

Or this:

Root
|____ Category A
|   |____ Event Handlers
|   |    |___ Feature #1 EHs
|   |    |___ Feature #2 EHs
|   |    |___ Feature #3 EHs
|   |
|   |____ Events
|        |___ Feature #1 Events
|        |___ Feature #2 Events
|        |___ Feature #3 Events
|
|____ Category B
|   |____ Event Handlers
|   |    |___ Feature #4 EHs
|   |    |___ Feature #5 EHs
|   |
|   |____ Events
|        |___ Feature #4 Events
|        |___ Feature #5 Events

But they're both making assumptions which may be completely off - if you can update your question with more details I may change my mind. :)


答:
I view Debug.Assert as premature optimization nowadays. Unless you really need the performance, suppressing the Assert in release mode can hide bugs for longer.

As MattDavey points out code contracts can be a superior, providing static checking instead of dynamic checking, and if not available I'd prefer Trace.Assert or a plain old if(x) throw SomeException;

Title: Should I still use Debug.Assert today?


问:
Open Source Cloud Computing
Recently I realized that the most popular social platforms on the net are in the hand of just a few companies, Google, Twitter, Facebook, to name just a few. Taking into account the world changing power of these frameworks I am looking for a non-profit, democratic alternatives to these sites. (Mozilla is a non-profit project, however it could not thrive without the backing of Google.)

In my imagination, the ideal approach (see explanation below) would be a distributed approach as used in file sharing programs or tools like seti@home. Every user willing to take part in the project would have to install software on his or her computer to act as a node in the network that would make up a social space similar to Google+, Facebook or Twitter but with a non-commercial approach. This approach could also be used for a "democratic" cloud to store data.

Is anyone aware of projects that go in this direction?

I call it "ideal approach" for a couple of reasons. No need for big server farms or hardware maintaining costs. Invulnerability against most hack attack because it's distributed and there is no central node. Just some I could think of right now.

答:
I think there are a lot of problems building a truely distributed social network. Problems will be Privacy, Spam and Manipulation.
Diaspora is cool, but i think a better one is friendica.

Another cool open source Cloud computing Sofware is ownCLoud which replaces dropbox and other services.

Title: Open Source Cloud Computing


答:
I would go with the second approach.

In my company we are two guys as well, and also use Redmine. We have a separate Redmine project for each project, and Redmine subproject when it has to be. We also have one or two Redmine projects for server/applications management (using the wiki project for documentation).

So, our solution is your second approach and we work confortable, but we dont have 20 projects...

There are a lot of 3rd party plugins, may be you can find some plugins for a general overview that you are confortable with.

Title: How to organize projects in Redmine?

Body:
I deployed a Redmine installation yesterday and today I try to fill it with some relevant data. One issue I came across is the organization of projects itself. While I took a look at how Redmine itself uses parts of the software, they unfortunately  have only one project set up and I haven’t seen any other examples. I know that this is heavily tied to your workflow, but seeing / reading about some examples would guide me to the right path.

We are two guys (a designer & developer, both of us do also other stuff like marketing or paperwork) and we have more than 20 projects that I want to map to Redmine. Less than a handful of projects are active at the same time and they aren’t specifically related. However, we want to see how much time we spent on all projects and also see the overall project situation, i.e. should we start another project or add this or that to the current one or won’t this be doable for such a small team?

At the moment I tend to have one of these setups:

A company project and all of our real projects organized as subprojects.

Separate Redmine projects for each of our projects, and eventually subprojects for broader functionality if needed (sync support for app xyz).

The problems I see with the first approach is that the projects aren’t necessarily related to each other. They may share a common framework which is a project for itself, but otherwise they are really separate things. All of them are software projects, so they share common metaphors like Trackers, though. I haven’t seen a way to separate versions. The roadmap would be an overview of the current work situation, but it could get pretty confusing. My biggest fear is that we will have endless drop down lists with unrelated things like versions from other projects.

The second approach seems to be saner, but my biggest fear is that we won’t have the general overview. We would have to look at all other roadmaps to plan the current one, we wouldn’t see just one calendar with things to do in all projects.

I think the core of the problem is that we have very limited human resources that have to be shared across a lot of projects, but they mustn’t overlap. Any ideas how this can be mapped to Redmine?


问:
Can I ask the job interviewer to show me their code before joining the company?

Possible Duplicate:

  Asking for a code sample of the company at an interview

Last year I changed jobs twice.. In the interviews with the companies, everything was so ideal and perfect. Latest frameworks, design patterns, distributed systems, scalable and enterprise systems, etc.. But in both cases something was not as expected..

First day after joining the company, you open the solution and find legacy code in a 10 year old technology, tightly coupled layers, design patterns incorrectly applied..

So, my questions are.. Has this ever happened to you? Is that often?
The interviewer makes sure I'm the proper developer for the company, how can I make sure this project/company is the proper one for me?
Can I ask them to show me the code???

答:
You can always ask, but it is highly improbable they will show you.

You can try asking them to write a quick coding test so that you can evaluate, but I doubt that will fly either.

The closest that I have to figuring out how to detect this situation in advance is to ask about their coding standards.

Ask for a copy of the their coding standard.

Ask if they adhere to it.

Ask what they don't like about it.

The aim of these questions is to raise any red flags and let you know the depth of what you may be getting into before you get into it.  I know it does not directly answer your question, but I do hope it helps somewhat.


答:
Absolutely.

In my opinion, any candidate requesting an overview of the code base goes up a notch in my review.  Regrettably, few ask.

Part of the challenge with this request is that they may not have scheduled time for it during the initial interviews. You may have to come back at a later point in time, or they may be able to extend out the length of the interview session to give you an overview.

I would start by asking about general architecture questions.

What technologies are the using?

What amount of time are they spending on defects vs. new development?

What's the trickiest part of their code base, and why?

How long does it generally take to make changes?

All of those questions can give you very telling answers regarding the state of the code base.

If / when they are able to provide you a walk-through, consider asking about and looking at the following.

How is the code organized?

Who owns what areas and how are problems resolved (note that the names won't be meaningful to you, but the answer can be telling.

Ask to see the more "interesting" parts of the code.  The interviewer will likely choose from some areas they have written, and that should give you some insight into the layout and structuring.

Ask to see their common library and what routines they provide within their framework.

The key is to show genuine technical interest in their code base and how things are laid out.  Every application has its warts and ugly code.  Every application has faced time crunches and less-than-optimal code had to be put in place.  Every application carries technical debt.  Look to see that the fundamentals are in place, such as encapsulation between layers of the application.

Title: Can I ask the job interviewer to show me their code before joining the company?

Body:
Possible Duplicate:

  Asking for a code sample of the company at an interview

Last year I changed jobs twice.. In the interviews with the companies, everything was so ideal and perfect. Latest frameworks, design patterns, distributed systems, scalable and enterprise systems, etc.. But in both cases something was not as expected..

First day after joining the company, you open the solution and find legacy code in a 10 year old technology, tightly coupled layers, design patterns incorrectly applied..

So, my questions are.. Has this ever happened to you? Is that often?
The interviewer makes sure I'm the proper developer for the company, how can I make sure this project/company is the proper one for me?
Can I ask them to show me the code???


问:
Git & project backups
I've been using SVN for sometime and have been making an awkward, but soon to be rewarding transition over to git.

Theres quite a few side / small projects that I'm working on which 90% will never see the light of day. As well - I also have my weekly school assignments / projects, and finally client projects that I have on the go.

I've been rolling the idea or question of how or what the best way would be to back up my projects.

The solutions I've sought out so far:

github which offers an outstanding service - I'm ok with my work being open source, however It's the school work and client work I might not want the public to be open to. github, of course has a payment plan - but let's face it, im a poor colleage student doing what I can to at least put KD on the table!

Theres the USB thumbstick that I can take around with me, work off of or back up, but that requires it to be around constently.

Theres Dropbox, but thats a little overkill since it already is a form of a version control system, as well - I have quite a few things on the go - putting everything within dropbox would eat a lot of space

Finally, theres a private server. I have a mac mini setup as a media server and I was thinking that I could backup to that.

Anyways - what are your guys thoughts, how do you handle backing up projects, not only for version control but for the everyday backups.

答: If you want a more github like experiance but on a private server you could setup Gitlab, which is a open souce github clone. </p>

Title: Git & project backups


问:
Maintenance wise, is `else while` without intervening braces considered safe?
Is else while without intervening braces considered "safe" maintenance wise?

Writing if-else code without braces like below...

```<code>if (blah)
    foo();
else
    bar();
</code>```

...carries a risk because the lack of braces make it very easy to change the meaning of the code inadvertently.

However, is below also risky?

```<code>if (blah)
{
    ...
}
else while (!bloop())
{
    bar();
}
</code>```

Or is else while without intervening braces considered "safe"?

答:
Modern IDEs can easily be configured to reformat (including removing or adding unnecessary braces) and/or reindent the code on saving a file. Thus your example would automatically look like for instance

```<code>if (blah) {
  blub();
} else
  while (!bloop()) {
    bar();
  }
</code>```

The indentation always makes the nesting easily visible, even without unneccesary braces. So, if you manage to enforce such IDE settings, I see no risk.

Personally, I find code that omits the braces and linebreaks much more readable since it avoids clutter:

```<code>if (blah) blub();
else while (!bloop()) bar();
</code>```

But of course, many developers are very happy to argue about such things forever and a day.

Body:
Modern IDEs can easily be configured to reformat (including removing or adding unnecessary braces) and/or reindent the code on saving a file. Thus your example would automatically look like for instance

if (blah) {
  blub();
} else
  while (!bloop()) {
    bar();
  }

The indentation always makes the nesting easily visible, even without unneccesary braces. So, if you manage to enforce such IDE settings, I see no risk.

Personally, I find code that omits the braces and linebreaks much more readable since it avoids clutter:

if (blah) blub();
else while (!bloop()) bar();

But of course, many developers are very happy to argue about such things forever and a day.


答:
It may be an anti-pattern, but I think it's also the future of web applications. Rather than mucking about with JavaScript, however, you should be using a templating library at the least. A better solution is a client-side MVC framework like AngularJS (which I happen to be using now).

For some more references, here's a popular blog post comparing several frameworks, and here's a site that implements the same program using multiple frameworks.

Also: Jan Hudec's comments about search-engine interaction and screen readers are valid. If you're working on an eCommerce site (where pagerank matters), then you probably don't want to use client-side frameworks. But for internal apps, these aren't usually concerns.

Title: Is this "anti-pattern" and should I stop using it or is this clever design?

Body:
I've basically stared to do the following when creating a REST service:

HTML is requested

service returns the desired web page but without the requested "resource", eg. data

web page contains JavaScript that issues AJAX request to the same service (different content-type)

service then returns the actual data (JSON) and the page displays it

On one side it seems inefficient (2 requests) but then were I used this, "performance is of no concern", meaning low traffic internal app and the web sites are simple and load fast.

The reason I ended up with this is that the web page can then be almost pure Html + JavaScript and almost no server-side stuff is required, especially no loops, to create tables and stuff like that (which I think is very ugly compared to things like slickgrid), e.g. separation of data and view.

Now before I get to using this, is this a good idea or should I just stop doing it?


问:
Stack and heap - dynamic allocation question
Sources usually mention that dynamically created variables are allocated on the heap, while functions' variables on the stack. Also the ones on the stack cease to exist automatically when e.g. the function which contains the variable exits. If I understand correctly, data fields of class are on the heap.
I do not understand, what is meant by 'dynamic'? As I see it, when the code is running, anything being created is created dynamically on the fly, be it function variables or objects with variables inside them. I would be glad for simple explanation. Thanks</p>

答:
Dynamic pretty much means the number of bytes is not known until runtime:

```<code> void f(int a) {
    int *array=new int[a];
    ...
 }
 int main() {
   f(10);
   f(22);
 }
</code>```

Having both f(10) and f(22) supported(without separate instances of f) means that the memory block size changes on the runtime.

Body:
Dynamic pretty much means the number of bytes is not known until runtime:

 void f(int a) {
    int *array=new int[a];
    ...
 }
 int main() {
   f(10);
   f(22);
 }

Having both f(10) and f(22) supported(without separate instances of f) means that the memory block size changes on the runtime.


答: I agree that "dynamic" is a poor choice of words, but we're stuck with it now.  It basically means the memory allocation is done explicitly by the programmer, using something like new or malloc, instead of automatically by the programming language, as in a function's local variables.

Title: Stack and heap - dynamic allocation question

Body:
Sources usually mention that dynamically created variables are allocated on the heap, while functions' variables on the stack. Also the ones on the stack cease to exist automatically when e.g. the function which contains the variable exits. If I understand correctly, data fields of class are on the heap.
I do not understand, what is meant by 'dynamic'? As I see it, when the code is running, anything being created is created dynamically on the fly, be it function variables or objects with variables inside them. I would be glad for simple explanation. Thanks</p>


问:
Is a Unique ID column needed in a many-to-many (junction) table?
Getting a few projects started with EF, but I had some questions about join tables and keys etc. Lets say I have a table of applications and a table of permissions. Applications have many permissions and each permission can belong to many applications (many-to-many).

Now, the Application and Permission tables are easy:

```<code>Applications
--------------
PK  ApplicationID
    Name

Permissions
--------------
PK  PermissionID
    Name
</code>```

But what's the BEST way to do the join table? I have these two options:

```<code>ApplicationPermissions
-----------------------
PK  ApplicationPermissionID
CU  ApplicationID
CU  PermissionID
</code>```

OR

```<code>ApplicationPermissions
-----------------------
CPK ApplicationID
CPK PermissionID

PK = Primary Key
CPK = Composite Primary Key
CU = Composite Unique Index
</code>```

Have you ever been burned doing it one way over the other? is it strictly preference? It has occurred to me that a lot of the "differences" will be abstracted away by my repository pattern (for example, i would almost never create an entire permission object and add it to an application, but do it by ID or unique name or something), but I guess I'm looking for horror stories, one way or the other.

答:
Over the years I got into the habit of giving each table "TableName" an auto generated primary key "TableNameID", without any exceptions, not even for junction tables. I can say I never regretted it, because it makes a lot of things easier when creating generic code which does something for "all tables" or "some tables", or for "a lot of rows of several different tables".

For example, if someone asks you to store some rows of different tables (or references to those) in a file or in memory, for example, for logging purposes, it is very handy when you know beforehand that you just need to store exactly one table name & exactly one integer ID, and you don't have to deal with any "special cases".

Another thing, when you start with combined PKs, you will probably some times later run into the need for combined foreign keys (since you may come to a point where you want to add a FK ref to your ApplicationPermissions table). Then the next requirement may be to have this FK to be unique in conjunction with other attributes or foreign keys - which will result in increased complexity overall. Nothing which is not possible to handle for most modern DB systems, of course, but a uniform solution makes life for programmers often a lot easier.

And finally, a statement like SELECT ... FROM TABLE WHERE TableNameID IN (id1,id2,...) does work well with a single column as primary key, but I have never seen an SQL dialect so far which lets you do this with combined keys. If you know beforehand that you will never need a query like this, fine, but don't be surprised if tomorrow you get a requirement which will be solved most easily with this kind of SQL.

Of course, when you expect your ApplicationPermissions table to hold several hundred millions of rows, then you should consider to avoid something like a ApplicationPermissionsID.


答:
You should think of the stack as an optimization, an implementation detail.  Unfortunately, the abstraction that is memory management tends to be leaky.  Some languages leak it a lot (I'm looking at you C) and some leak it...less (i.e. Java).

When you need memory, by default, you can imagine that it all goes in the heap.  It's possible, under any set of circumstances, to use heap memory to solve all problems.  Allocations to the heap can be of a size unknown until right when you need it, and can live for an indeterminate amount of time.  Allowing those qualities comes at a cost though.  Different languages manage it differently, but the point remains that time and effort is spent by the language, in some way, to both allocate, deallocate, and potentially defragment memory in the heap.

Not all memory that's needed needs that level of flexibility.  There are a number of very common contexts in computer programming in which the memory needed is of a size known at compile time and with a scope that contains certain well defined properties.  When you call a method you know that the information in memory that represents the parameter list, the return value, and the local variables is of a fixed size, and you know that all new allocations of memory will leave scope before any memory stored at the time it was allocated.  This follows the exact implementation of the data structure known as a Stack.

A stack, as a general data structure, is where the last in is the first out.  You push items onto it, and then pop items off of item.  The item poped is the item most recently pushed on (that's still in the structure).  So we assume that there's a stack that holds onto memory.  When we start execution of a new method we know that the memory we allocate for that method (all methods need memory for their arguments, return value, and local variables).  If we push all of that memory onto the stack it will need to be pushed off of the stack before any items "above" it in the stack can be pushed off.  This is okay.  We know that the memory of the method that called "us" won't need to be freed until after we finish, and we know that any methods we call will have their memory both allocated and freed before we need to be freed.

Managing this type of memory is much easier than managing heap memory.  It's very quick and easy to add new memory to the stack, and very easy to take it off.  The "stack" is really just a long contiguous block of memory with at pointer to the "end" of the stack.  Allocating new memory is as simple as increasing the stack pointer and telling someone which addresses they are allowed to access, and deallocating is as simple as decreasing the stack pointer by a fixed value.  Adding/subtracting a fixed value to a pointer is very fast and easy for a computer.

So the entire purpose of the stack is not to allow additional functionality; in fact using the stack is more restrictive than using the heap, and most complex programs tend to have at least some situations in which the restrictions of stack memory are prohibitive, so you'll still need a heap.  Stack memory simply allows much quicker allocation and deallocation of a certain uses of memory that meet the restrictions of a stack.


答:
```<code>table Person
   Id int identity(1,1) not null primary key
   ...other fields go here...
table Address
   Id int identity(1,1) not null primary key
   ...other fields go here...
table PersonAddress
   Id int identity(1,1) not null primary key
   PersonId int not null
   AddressId int not null
</code>```

Remember to create an index and foreign key on both PersonId and AddressId.

No matter what others think are "better" or "you should", this is the simplest and easiest way to allow the database to function properly.

Title: Is a Unique ID column needed in a many-to-many (junction) table?

Body:
Getting a few projects started with EF, but I had some questions about join tables and keys etc. Lets say I have a table of applications and a table of permissions. Applications have many permissions and each permission can belong to many applications (many-to-many).

Now, the Application and Permission tables are easy:

```<code>Applications
--------------
PK  ApplicationID
    Name

Permissions
--------------
PK  PermissionID
    Name
</code>```

But what's the BEST way to do the join table? I have these two options:

```<code>ApplicationPermissions
-----------------------
PK  ApplicationPermissionID
CU  ApplicationID
CU  PermissionID
</code>```

OR

```<code>ApplicationPermissions
-----------------------
CPK ApplicationID
CPK PermissionID

PK = Primary Key
CPK = Composite Primary Key
CU = Composite Unique Index
</code>```

Have you ever been burned doing it one way over the other? is it strictly preference? It has occurred to me that a lot of the "differences" will be abstracted away by my repository pattern (for example, i would almost never create an entire permission object and add it to an application, but do it by ID or unique name or something), but I guess I'm looking for horror stories, one way or the other.

Body:
table Person
   Id int identity(1,1) not null primary key
   ...other fields go here...
table Address
   Id int identity(1,1) not null primary key
   ...other fields go here...
table PersonAddress
   Id int identity(1,1) not null primary key
   PersonId int not null
   AddressId int not null

Remember to create an index and foreign key on both PersonId and AddressId.

No matter what others think are "better" or "you should", this is the simplest and easiest way to allow the database to function properly.


答:
In most contexts, "dynamic" refers to memory that the programmer explicitly allocates, as opposed to the memory that is allocated as the normal part of entering a function (reserving space for parameters, local variables, etc.).

Let's take the following C function as an example:

```<code>void foo(int x, int y)
{
  int z;
  char *str = NULL;
  ...
  str = malloc(sizeof *str * y);
  ...
  free(str);
}
</code>```

When we enter the function, space is automatically reserved on the stack for x, y, z, and the str pointer (remember stack elements are allocated in last-in, first-out order).  Moreover, the amount of space to reserve for each object is fixed at compile time (based on the sizes of the respective types).  If you look at the stack frame, it will look something like this (assume int and char * are all the same size):
```
+--------+
|        | <-- y           STACK BOTTOM
+--------+
|        | <-- x
+--------+
|        | <-- z
+--------+
|        | <--str          STACK TOP
+--------+<br>
```

When we exit the function, all the elements between "STACK BOTTOM" and "STACK TOP" will be popped (deallocated).

I do not control memory allocation at this level; this is all done automatically for me when I enter and leave the function.  However, within the function I want to allocate some memory for str to point to.  Moreover, the amount of memory I want to allocate isn't fixed, but is determined at runtime from the value of the y parameter.  The malloc call reserves some memory from the heap (an area of memory distinct from the stack, which is managed differently as well) and assigns the address of that memory to str.  That memory stays allocated until I explicitly release it with a call to free; if I don't do so before the function exits, the str variable gets deallocated (meaning I lose my reference to that dynamically-allocated block), but the memory it points to does not (this is known as a memory leak; once I lose my reference to the dynamic block, I can't free it).

Java behaves ever so slightly differently:

```<code>public void foo(int x, int y)
{
  int z;
  String str = new String(); // don't need to specify a length as with malloc
  ...
}
</code>```

Similar to C, Java will reserve space on the stack for each of x, y, z, and a str pointer (yes, Java uses pointers under the hood, it just doesn't expose pointer operations to the programmer).  Similar to C, the new operator reserves memory for the String object on the heap at runtime.  Unlike C, Java monitors objects on the heap to see if they are being referenced by anyone (such as the str variable).  Once the Java function exits, all references to the dynamic memory cease to exist, and an automatic garbage collector will eventually deallocate that memory, so I don't have to explicitly free it (in fact, Java doesn't provide an equivalent to the free function).

Body:
In most contexts, "dynamic" refers to memory that the programmer explicitly allocates, as opposed to the memory that is allocated as the normal part of entering a function (reserving space for parameters, local variables, etc.).

Let's take the following C function as an example:

void foo(int x, int y)
{
  int z;
  char *str = NULL;
  ...
  str = malloc(sizeof *str * y);
  ...
  free(str);
}

When we enter the function, space is automatically reserved on the stack for x, y, z, and the str pointer (remember stack elements are allocated in last-in, first-out order).  Moreover, the amount of space to reserve for each object is fixed at compile time (based on the sizes of the respective types).  If you look at the stack frame, it will look something like this (assume int and char * are all the same size):

+--------+
|        | <-- y           STACK BOTTOM
+--------+
|        | <-- x
+--------+
|        | <-- z
+--------+
|        | <--str          STACK TOP
+--------+

When we exit the function, all the elements between "STACK BOTTOM" and "STACK TOP" will be popped (deallocated).

I do not control memory allocation at this level; this is all done automatically for me when I enter and leave the function.  However, within the function I want to allocate some memory for str to point to.  Moreover, the amount of memory I want to allocate isn't fixed, but is determined at runtime from the value of the y parameter.  The malloc call reserves some memory from the heap (an area of memory distinct from the stack, which is managed differently as well) and assigns the address of that memory to str.  That memory stays allocated until I explicitly release it with a call to free; if I don't do so before the function exits, the str variable gets deallocated (meaning I lose my reference to that dynamically-allocated block), but the memory it points to does not (this is known as a memory leak; once I lose my reference to the dynamic block, I can't free it).

Java behaves ever so slightly differently:

public void foo(int x, int y)
{
  int z;
  String str = new String(); // don't need to specify a length as with malloc
  ...
}

Similar to C, Java will reserve space on the stack for each of x, y, z, and a str pointer (yes, Java uses pointers under the hood, it just doesn't expose pointer operations to the programmer).  Similar to C, the new operator reserves memory for the String object on the heap at runtime.  Unlike C, Java monitors objects on the heap to see if they are being referenced by anyone (such as the str variable).  Once the Java function exits, all references to the dynamic memory cease to exist, and an automatic garbage collector will eventually deallocate that memory, so I don't have to explicitly free it (in fact, Java doesn't provide an equivalent to the free function).


答:
While Mike's answer is good, here are the reasons I would add a separate ID field or not.

Consider using a separate ID field for the junction/join table if it contains fields other than the ID.  This tends to note that it is a first class entity.

Consider using a separate ID field if APIs or any existing logic tend to use single fields for retrieving/editing entities.  That can help other people follow your code in the context of a larger project.

Don't use it if there is no specific benefit (KISS).  EF knows how to handle this type of table and a composite unique constraint can sometimes be missed when other people are trying to understand this type of relationship.  Also, when normalizing I try to use the smallest key possible that uniquely defines the tuple.  In your second example, you effectively have 2 separate candidate primary keys.


问:
statistics for checking imported data?
I'm working on a data migration of several hundred nodes from a Drupal 6 to a Drupal 7 site. I've got the data exported to the new site and I want to check it. Harkening back to my statistics classes, I recall that there is some way to figure out a random number of nodes to check to give me some percentage of confidence that the whole process was correct. Can anyone enlighten me as to this practical application of statistics? For any given number of units, how big must the sample be to have a given confidence interval?</p>

答: Computers are really good at doing repetitive tasks and comparisons, it wouldn't take long to write a small app that verifies all the data, and unless the amount of data you transferred was huge it could be done overnight or over the weekend and get 100% certainty. Stats rely on getting a true random sample of the entire population, and failing to get a valid set makes that confidence worthless and both humans and computers are really bad at true random.  If something does come up its a lot better to be 100% certain than 95%.</p>

Title: statistics for checking imported data?