问:
Does Agile (scrum) require one server environment?
Is it necessary/recommend/best practice/any other positive to use only one server environment to perform all development, unit testing and QA?

If so, is it then wise/part of Agile to then have only one staging environment before Live?

Considering that this could mean internationally distributed teams of developers and testers in different time zones is this wise?

This is something being implemented by our QA manager. The opinion put forward is that doing all the dev and testing on a single server is "Agile." The staging environment would be a second environment, and then live.

答:
I think teams can work in more agile fashion if they have multiple servers at appropriate levels..

First some assumptions: Two development teams: USA and Pakistan. QA is a separate team and uses nightly build. Development teams are highly productive and do frequent check-ins. They can use a Distributed Version Control e.g. git.

So a developer from Team USA will run unit test on his machine for areas effected by his latest check-in to Local Repository and will then push the changes to the Team Repository. There the complete unit testing suite along with automated functional tests* to be run on Product A. If everything is green then the code changes to be anatomically pushed to Check-Build Repository where integrated tests would run. If still green, then changes to be automatically pushed to Master Repository used for nightly build. That nightly build to be used by the QA next day.

All repositories to have their own application/data/build servers.

*If functional tests are long running then we can have two level of Team Repositories. One for short running tests (e.g. all unit tests, some functional tests) and second for long running functional tests.


问:
Enforcing a uniform Scrum approach to all teams within a department
Where I work we recently switched the Agile development using Scrum.  We went through the typical growing pains but have reached an approach that seems to work for now (whether it'll work in the long term is for another question!).

Obviously, the department management is happy the transition to Scrum is working.  But they have starting doing something that, to me, feels wrong.

Management will observe a team, see what works for them, and the prescribe it to the entire department.  Things like:

The definition of "Done"

Which story point values can be used for story pointing (eg, omitting 8 from the fib. sequence because 1, 2, 3, 5, 13, etc were the only ones used during a sprint they observed)

Telling teams they must calibrate their story point value of 1 to "updating a UI label," and limiting them to an upper bound of 20

(although not all our projects have clients and not all developers
have UI experience)

Telling teams to use story point estimates of 100 to mean "we'll split this story later"

Telling teams to use story point estimates of infinity to mean "this is an epic" or "we need more info"

I understand they're trying to be helpful, but shouldn't all the things above be Scrum-team specific?  That is to say, what works for one group of individuals on one project may not make sense to another group on another project.

I'm concerned we're drifting into a very prescriptive and stiff Agile approach.  Am I justified in thinking this, or am I overreacting?

Edit

Just to clarify... by "Management" and "Manager" I don't mean the Product Owner.  I mean any manager outside the Scrum Team, but within the Software Department.

答:
Ofcourse you're justified in thinking that. The very fact that you're talking about "enforcing Scrum" is a blaring alarm siren.

Scrum is first and foremost about self-organisation of the team; they get to choose how to do their work and how to organize themselves. Management only has a say in what work needs to be done.

The reason why teams should organize themselves is that they are always unique, due to the different natures of the individual team members (and the people they work with) and the due to the differences of the products they work on. A practice that works perfectly well for one team, can have adverse effects on another team. That's why within a certain scope (a sandbox metaphore is often used), they have to experiment, learn and find out what works best for them.

What you need is a very competent Scrum master (one per team), who can guide a team in this discovery, but at the same time can also work with management to obtain the freedom for the team to go on that discovery.

ContentLicense: CC BY-SA 3.0


问:
What is the advantage of using UI binder in GWT?
Mention the pros and cons of UIBinder in GWT.

I want to develop a big project. Is it flexible to use UIBinder for my project?

答:
The biggest advantage of GWT in the process creating DOM is UiBinders, also known as “Declarative Layout”.

The UiBinder is a framework designed to separate Functionality and View of User Interface.

The UiBinder framework allows developers to build gwt applications as HTML pages with GWT widgets configured throughout them.

The UiBinder framework makes easier collaboration with UI designers who are more comfortable with XML, HTML and CSS than Java source code

The UIBinder provides a declarative way of defining User Interface.

The UIBinder separates the programmic logic from UI.

The UIBinder is similar to what JSP is to Servlets.

Copied from tutorialspoint: GWT - Using UiBinder


问:
I have only two languages on my resume - how bad is this?
I have a question that can be best answered here, given the vast experience some of you guys have!

I am going to finish my bachelor's degree in CS and let's face it, I am just comfortable with C++ and Python. C++ - I have no experience to show for and I can't quote the C++ standard like some of the guys on SO do but yet I am comfortable with the language basics and the stuff that mostly matters. With Python, I have demonstrated work experience with a good company, so I can safely put that.

I have never touched C, though I have been meaning to do it now. So I cannot write C on my resume because I have not done it ever. Sure I can finish K & R and get a sense of the language in a month, but I don't feel like writing it cause that would be being unfaithful to myself.

So the big question is, are two languages on a a resume considered OK or that is usually a bad sign? Most resumes I have seen mention lots of languages and hence my question. Under the language section of my resume, I just mention: C++ and Python and that kinda looks empty!

What are your views on this and what do you feel about such a situation?

PS: I really don't want to write every single library or API I am familiar with. Or should I?

答: It would only probably hurt you with non-technical people who don't realize that learning languages is the trivial part of programming.</p>

ContentLicense: CC BY-SA 2.5


问:
Advantage of Solr over other DBs?
As far as I know, Apache Solr Lucene project is a web-app which is used for rich text searching.

I just wanted to know:

Why can't I use MySQL for that and just for rich text searching, why we use Solr?

When all the other things can be performed using any DB ?

答:
Generally Solr an open source enterprise search platform from the Apache Lucene project and also it has many advantages like,

Query language supports structured as well as textual search

Uses the Lucene library for full-text search

JSON, XML, PHP, Ruby, Python, XSLT, Velocity and custom Java binary output formats over HTTP

Distributed Search through Sharding - enables scaling content volume

A new auto-suggest component

solr 4 adds NoSQL features

Title: Advantage of Solr over other DBs?


问:
Is it worthwile to learn/use Play framework (for Scala or Java) if I don't use the MVC in it
I prefer Single Page Application to server side generated HTML.

I am sensible to the pitch of "high productivity" delivered by Play.

Now if I don't use the HTML generation part, is it still valuable?  Is it worthwile to learn it? For the controller (REST or other), business logic, persistence.

Does it help generating unit tests?

How do you use it?

Thank you

答:
I would yes, you still can use it for SPA.

Play! framework is a stateless framework and it is suitable to write REST API.    XML and JSON response, forms validation, Asynchronous HTTP are built in the framework.  Akka integration also!  I would say these features are convenient for SPA.

Build your frontend with anything you like (Angular.js, Ember.js, ClojureScript ..) and Your server side could be a neat API written in Play! framework.

Play! for Java Developers


问:
What does scannerless parsing have to do with the "Dangling Else Problem"?
I do not understand this sentence from the Wikipedia article on the Dangling Else problem:

[The Dangling Else problem] is a problem that often comes up in compiler construction, especially scannerless parsing.

Can someone explain to me how scannerless parsing techniques might exacerbate this problem?  It seems to me that the problem is with the grammar -- since it's ambiguous -- not with the choice of parsing technique.  What am I missing?

答:
My best guess is that the sentence in the Wikipedia article result from a misunderstanding of E. Visser work.

Grammars for scannerless parsers (i.e. grammars describing a language as set of sequences of characters instead as a set of sequences of tokens with the tokens described separately as strings of characters) tend to have lot of ambiguities. E. Visser paper Disambiguation Filters for Scannerless Generalized LR Parsers (*) proposes several mechanisms to solve ambiguities, one of which is useful for solving the dangling else problem.  But the paper do not state that the precise ambiguity named "dangling else problem" is related to scannerless parsers (nor even that the mechanism is especially useful for scannerless parsers).

The fact that it proposes a mechanism for solving it isn't an implicit statement as another ambiguity resolution mechanism (operator priority and precedence) seems also totally unrelated to the scannerless nature of the considered parsers (consider for instance that those ambiguities can't be present in regular grammars as they result from nesting, while those handled by a longest match rule can).

(*) Which is probably the paper serving as base of the Wikipedia article on scannerless parsers even if they reference another one, also by
 E. Visser, Scannerless Generalized-LR Parsing.


问:
Unit Test - an Enigma?
I am an objective-c/iOS apps developer and I was wondering if I perform Unit Tests on my code, how should I go about it?

What is unit test anyway? Ain't I testing a specific part of code while running the whole app itself?

What is its use?

I have read few articles, wikipedia etc. but I am not sure whether unit testing is a time consuming or a time saving process. I know the definition but I am in the dilemma about its purpose.

Plz guide a new bee here. :)
Have already gone through the following:

Unit testing best practices for a unit testing newbie

答:
What is unit test anyway?

A unit test is a piece of code that takes one unit (usually a method or free function, sometimes an entire class or module), isolates it from the rest of the application, runs it against a known environment, and verifies that it behaves as expected. A typical pattern is "set up, define inputs, run, assert outputs, tear down", where the "set up" and "tear down" steps create the known environment. For any unit that depends on other units, a technique called "mocking" is used, that is, the tested unit is put in a context where the dependencies aren't the real thing, but rather placeholders / stubs. For example, if you test a method that runs against a database class, you don't use the real database class, but a mockup class that ignores its input and returns a hard-coded data set containing what the real one should return.

Ain't I testing a specific part of code while running the whole app itself?

You are, but not in isolation - you are testing the entire application, and when something fails, you often know that it fails, but not where and why. Unit tests tell you that each individual part of your machinery works as specified; testing the whole thing, or larger parts of it, in concert (a.k.a. "Integration testing", "End-to-end testing", or "Simulation testing") is just as important at unit testing, but it serves a slightly different purpose and has a slightly different focus.

What is its use?

Unit testing has several uses:

Verification - unit tests should be written such that a passing unit test means that some aspect of the unit works as intended. If all aspects of the unit are covered by tests, you have 100% "coverage", and assuming that the tests accurately reflect the intended behavior, you can be confident that the unit as a whole works correctly.

Troubleshooting/Debugging - when things go wrong, you will either have a failing unit test somewhere, which will allow you to pinpoint the problem, or all the tests passes, but things are still going wrong. In the latter case, existing unit tests will help you rule out possible causes and find spec mismatches, and if it turns out that you don't have the kind of coverage you thought you had (e.g., you missed some edge case), you can add a unit test that reproduces the problem, then fix it and use the unit test to verify (see above) that the fix is correct.

Regression guards - every unit test you have guards against one possible regression, that is, a change in behavior that is caused as a side effect of another change. If you have good unit tests in place, and you make a change that breaks things elsewhere, your unit tests will tell you. Having complete test coverage will allow you to move faster and make more radical changes with higher confidence.

Documentation - since a unit test explicitly tests for one behavioral aspect of a unit, it can serve as a form of documentation: a unit test says "if I use this unit here in such a context and pass it these inputs here, it will produce those outputs". This is valuable information for other developers, and better yet, because it is code that gets validated on a regular basis, it is practically guaranteed to be up-to-date at all times, unlike more traditional forms of technical documentation.

Design - there is a whole development methodology (TDD, Test-Driven Design) built around the idea of using automated tests as an integral part of your design process. The mantra is "red, green, refactor": define the feature by writing a test (ideally, just one test) that captures the essence of your intended change; verify that it fails ("red"); change the code just enough to make the test pass ("green") without flipping any other tests to "red"; then refactor the codebase to remove duplication, redundancy and other code smells while still keeping all tests in "green". TDD forces you to work in a highly incremental way, it makes sure you always have near-perfect coverage, and it gets you to focus on one thing at a time. Particular challenges with TDD are that it takes some experience and vision to arrive at an elegant overall design with it (being religious about refactoring helps tons though), and that it doesn't work too well in a highly explorative context where you need to hack away at the code for a while before you even know what the problem is you're trying to solve.

I have read few articles, wikipedia etc. but I am not sure whether unit testing is a time consuming or a time saving process.

The jury is still out on this one, and rigid research in this area is hard if not impossible (how do you do double-blind studies about programming methodologies?) However, there seems to be quite some consensus that automated tests are an investment worth making for almost all projects; a single debugging session can easily eat up ten times the budget spent on writing unit tests, and an unnoticed design flaw can be many times more expensive even. Consider the alternatives:

Deploy untested code. This is sometimes a valid choice, e.g. when the code is low-impact (say, a screensaver), or when moving fast is more important than delivering code that works well - in other words, when the risk of deploying a bug is smaller than the risk of not deploying in time. Usually, this is not the case though.

Test manually. Manual labor is expensive, and it stays expensive every time you do it. As your codebase grows, so does the manual testing cost per deployment. To make matters worse, manual testing is repetitive work, something that humans are bad at - your testers will make mistakes, they'll raise false positives and miss bugs. Testing manually also takes a lot of time, which means your deployment procedure will take much longer - instead of a nightly build that runs ten thousand automated tests in a few hours, your testers go through a multi-day routine.

Formal proof. While it is theoretically possible to do formal proofs of correctness for any given computer program, even very trivial ones are too complicated to do it by hand. This means we need a computer program to do the proving for us, and such tools exist - unfortunately, them being computer programs, they require us to feed them the specifications in a formal language. If you want a complete proof of correctness, you need to give the prover program the entire specification in a formal language - but wait, isn't programming all about encoding requirements in a formal language? Yes it is. So what you really do in the end is write the program twice, in two radically different languages, and then automatically check that the two implementations are equivalent.

Rely on the compiler. Some programming languages have powerful type systems and compilers that can check them; in extreme cases, this rules out a large class of possible bugs, and you can leverage such a type system to give you quite some impressive guarantees about your code, for free. Still, you can't encode everything in a type system, so while a good type system can certainly remove the need for a whole truckload of trivial tests ("does this function fail when I pass it null instead of an integer? does it fail when I pass it a string? an object of type UserManager?"), but you will still have a lot of things to test for.

Title: Unit Test - an Enigma?


问:
Forcing logger/appender to output line logged at lower than its current level?
Consider the following scenario:

I am writing a Dispatcher Servlet that delegates processing to various handlers depending on the request URL; the handler objects having previously registered themselves for URL patterns, pretty much as Servlets register themselves in web.xml.

When a Handler registers or unregisters itself for a pattern, I want to log a line that includes the action and pattern; and also the current mappings, so that when a subsequent request processing logs a warning that a request was not processed I can go back in the logs and find out the mappings.

The question is how to ensure that lines logged by registerUrlPattern/unregisterUrlPattern actually appear in the log file:

It seems to me that these methods should log the mapping changes at INFO level, since it is additional INFO being logged. But the logger's level is WARN so that will not work. The logger get many other messages at INFO level so it is not possible to change its level to INFO in production, except for troubleshooting.

I could log it at WARN level, but qa/usability/customer does not like such warnings to appear.

I can think of the following alternatives:

Change the Logger's level to INFO when logging these lines, possibly by adding a forceInfo method in my Logger (which wraps a standard log4j type logger)

Use a different Logger for these methods and set its level to INFO

Log at warning level but change the language to indicate that it is not something to be worried about

答:
So, you need different treshold within the same class.
I think you use a different logger corresponding to a specific name.
You can thus set the log level to INFO for this specific Logger in DispatchServlet class.

For me, the benefits would be:

the possibility to specificly reduce the treshold to INFO as you required (the goal).

if one day you realize that your specific logs become too verbose and finally useless because the functionnality is 100% stable and doesn't cause any issue, you still can reduce the treshold by configuration and without impacting the rest of the logs. Logging in WARNING level or do something based on forcedLog would imply you to modify the sources for such a purpose.

The only CON I see is that it might be "surprising" but a correct documentation solves everything.

For example in your log4j.xml file, you could have:

```<code><!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <!-- general application log -->
    <appender name="MyLogFileAppender" class="org.apache.log4j.FileAppender">
        <param name="File" value="mylog.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{yyyy MM dd - HH:mm:ss,SSS} %-5p %t [%-40.40c] %x - %m%n"/>
        </layout>
    </appender>
    <logger name="DispatchServletSpecific">
        <level value="INFO" />
        <appender-ref ref="MyLogFileAppender" />
    </logger>
    <root>
         <level value="WARNING" />
         <appender-ref ref="MyLogFileAppender" />
    </root>
</log4j:configuration>
</code>```

And in the Java code you create a specific Logger

```<code>Logger specificLogger = Logger.getLogger("DispatchServletSpecific");
</code>```

This way the log treshold should be set to INFO while the rest of your app should be log only WARNING logs.
Hope it helps.

Body:
So, you need different treshold within the same class.
I think you use a different logger corresponding to a specific name.
You can thus set the log level to INFO for this specific Logger in DispatchServlet class.

For me, the benefits would be:

the possibility to specificly reduce the treshold to INFO as you required (the goal).

if one day you realize that your specific logs become too verbose and finally useless because the functionnality is 100% stable and doesn't cause any issue, you still can reduce the treshold by configuration and without impacting the rest of the logs. Logging in WARNING level or do something based on forcedLog would imply you to modify the sources for such a purpose.

The only CON I see is that it might be "surprising" but a correct documentation solves everything.

For example in your log4j.xml file, you could have:

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <!-- general application log -->
    <appender name="MyLogFileAppender" class="org.apache.log4j.FileAppender">
        <param name="File" value="mylog.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{yyyy MM dd - HH:mm:ss,SSS} %-5p %t [%-40.40c] %x - %m%n"/>
        </layout>
    </appender>
    <logger name="DispatchServletSpecific">
        <level value="INFO" />
        <appender-ref ref="MyLogFileAppender" />
    </logger>
    <root>
         <level value="WARNING" />
         <appender-ref ref="MyLogFileAppender" />
    </root>
</log4j:configuration>

And in the Java code you create a specific Logger

Logger specificLogger = Logger.getLogger("DispatchServletSpecific");

This way the log treshold should be set to INFO while the rest of your app should be log only WARNING logs.
Hope it helps.


问:
How do you get into the habit of using a repository (e.g. GitHub)?
Are there some best practices on the repository front, or some common newcomer-traps that I should avoid?

I have recently been reading about the benefits of repositories even for single-developer projects and, in addition, I am likely to start working with multiple other engineers in a short while but, how do I go from never having used a repository to setting one up - for multiple people, even!

Background: I am an electronics engineer before anything else, and while application programming has been part of that, it's never been something I've done a lot of - it has mainly been snippets of C for embedded systems where I was the only person working on it.

答: Both GitHub and Bitbucket come with excellent tutorials on using their products with all major development environments on Windows, Mac and Linux. My best advice is to toy with a first repository, With a small HelloWorld solution to get your bearings.</p>


答:
Welcome to one of scrum's worst nightmare. You have encountered one of the reasons scrum fails to deliver the great stuff everybody has in mind when adopting it.

Unfortunately scrum is not compatible with upper management that tend to centralize and create management processes across the organisation and the teams. In order to be successful the upper management has to change their mindset and focus on what they need from the teams. They should not focus on how the teams work. The only time they should get involved, is if a team is not performing to figure out the reason.

I believe that you have to sit down with the management and talk about their requirements and what they want the teams to deliver. That can be a global requirement to all teams. It could be estimates that they understand, duration, etc. Those things should not dictate the teams processes. It is important that you separate the management expectations from the way you run scrum. Each team has to find their own pace and their own way of driving the projects, that will make them successful, productive, and deliver what the management needs. If for instance you have an estimate of 15 story points, the team should be able to calculate those points into man days (or hours) based on the average team velocity. But it will be unique to the team.

Title: Enforcing a uniform Scrum approach to all teams within a department

Body:
Where I work we recently switched the Agile development using Scrum.  We went through the typical growing pains but have reached an approach that seems to work for now (whether it'll work in the long term is for another question!).

Obviously, the department management is happy the transition to Scrum is working.  But they have starting doing something that, to me, feels wrong.

Management will observe a team, see what works for them, and the prescribe it to the entire department.  Things like:

The definition of "Done"

Which story point values can be used for story pointing (eg, omitting 8 from the fib. sequence because 1, 2, 3, 5, 13, etc were the only ones used during a sprint they observed)

Telling teams they must calibrate their story point value of 1 to "updating a UI label," and limiting them to an upper bound of 20

(although not all our projects have clients and not all developers
have UI experience)

Telling teams to use story point estimates of 100 to mean "we'll split this story later"

Telling teams to use story point estimates of infinity to mean "this is an epic" or "we need more info"

I understand they're trying to be helpful, but shouldn't all the things above be Scrum-team specific?  That is to say, what works for one group of individuals on one project may not make sense to another group on another project.

I'm concerned we're drifting into a very prescriptive and stiff Agile approach.  Am I justified in thinking this, or am I overreacting?

Edit

Just to clarify... by "Management" and "Manager" I don't mean the Product Owner.  I mean any manager outside the Scrum Team, but within the Software Department.


问:
Should I split a Python class with many methods into multiple classes?
I have a class that will end up having more than ~30 methods. They all make sense to be part of the same class because they require access to the same data.

However, does it make any sense to split up a large class into several smaller abstract classes (by functionality, type, use, etc.) and have the main class extend (i.e. multiple inheritance) from all the smaller classes?

答:
Just because things need data access doesn't means they belong in the same class. They belong in the same class if they share responsibility for protecting invariants, or are a naturally cohesive group of things that consumers will want to pass around wholesale.

A more likely scenario is that you have multiple classes that all contain the data (or data provider) passed in via constructor (or otherwise dependency inverted).

OwnerDisplayName: Jace Browning


问:
REST API concepts
I have three questions about REST API design that I'm hoping someone can shed some light on. I've searched relentlessly for many hours but haven't found answers to my questions anywhere (maybe I just don't know what to search for?).

Question 1

My first question has to do with actions/RPC. I've been developing a REST API for a while and I'm used to thinking of things in terms of collections and resources. However, I've come across a couple cases where the paradigm doesn't seem to apply and I'm wondering if there is a way to reconcile this with the REST paradigm.

Specifically, I have a case where modifying a resource causes an email to be generated. However, at a later point the user can specifically indicate that they want to resend the email that was sent earlier. When resending the email no resource is modified. No state is changed. It's simply an action that needs to occur. The action is tied to the specific resource type.

Is it appropriate to mix some sort of action call with a resource URI (e.g. /collection/123?action=resendEmail)? Would it be better to specify the action and pass the resource id to it (e.g. /collection/resendEmail?id=123)? Is this the wrong way to be going about it? Traditionally (at least with HTTP) the action being performed is the request method (GET, POST, PUT, DELETE), but those don't really allow for custom actions with a resource.

Question 2

I use the querystring portion of the URL to filter the set of resources returned when querying a collection (e.g. /collection?someField=someval). Within my API controller I then determine what kind of comparison it is going to do with that field and value. I've found this really doesn't work. I need a way to allow the API user to specify the type of comparison they want to perform.

The best idea I've come up with so far is to allow the API user to specify it as an appendage to the field name (e.g. /collection?someField:gte=someval - to indicate that it should return resources where someField is greater than or equal to (>=) whatever someval is. Is this a good idea? A bad idea? If so, why? Is there a better way to allow the user to specify the type of comparison to perform with the given field and value?

Question 3

I often see URI's that look something like /person/123/dogs to get the persons dogs. I generally have avoided something like that because in the end I figure that by creating a URI like that you are actually just accessing a dogs collection filtered by a specific person ID. It would be equivalent to /dogs?person=123. Is there ever really a good reason for a REST URI to be more than two levels deep (/collection/resource_id)?

答:
Question 1: Is it appropriate to mix some sort of action call with a resource URI [or] would it be better to specify the action and pass the resource id to it?

Good question. In this case I'd advise you use the latter approach, namely specify the action and pass a resource ID to it. This way, when your resource is first modified, it in turn calls the /sendEmail action (side note: no need to call it "resend") as a separate RESTful request (which you can later call again and again, independently of the resource being modified).

Question 2: regarding using a comparison operator like so: /collection?someField:gte=someval

Whilst this is technically ok, it is probably a bad idea. One of the key principles of REST is readability. I'd suggest you simply pass the comparison operator as another parameter, for example: /collection?someField=someval&operator=gte and of course design your API so that it caters for a default case (in the event that the operator parameter is left out of the URI).

Question 3: Is there ever really a good reason for a REST URI to be more than two levels deep?

Yup; for abstraction. I've seen a couple REST APIs that utilise layers of abstraction through multiple URI levels, for example: /vehicles/cars/123 or /vehicles/bikes/123 which in turn allows you to work with useful information pertaining to both /vehicles and /vehicles/bikes collections. Having said that, I'm not a big fan of this approach; you'll seldom need to do this in practise, and chances are you could redesign the API to use just 2 levels.

And yes, as the comments above suggest, in future it would be best to split up your questions into separate posts ;)

Title: REST API concepts


答:
About getting how to start using a repository just signup on Github and create a repo. If you are having problems creating a repo you can try gitextensions. A very easy-to-use GUI for creating and managing repositories. That should take care of you having problems start to use Github. It has support for other online repo-storage websites also.

To get into the habit of using repo just make a folder containing code on your computer a repo and then start doing commits(quite easy via Gitextensions) and pushing them. Try to change things online on your repo and sync between the 2. It should become easy to grasp how it works.

That's for individual work. That's as far as my experience goes.

You can try reading this article. Helped me get started on using git. I don't use command-line much for git but it explains it all.

Title: How do you get into the habit of using a repository (e.g. GitHub)?

Body:
Are there some best practices on the repository front, or some common newcomer-traps that I should avoid?

I have recently been reading about the benefits of repositories even for single-developer projects and, in addition, I am likely to start working with multiple other engineers in a short while but, how do I go from never having used a repository to setting one up - for multiple people, even!

Background: I am an electronics engineer before anything else, and while application programming has been part of that, it's never been something I've done a lot of - it has mainly been snippets of C for embedded systems where I was the only person working on it.


答: Most graduates don't have much language experience, just the one or two their degree focuses on. And most I have met struggle with those few as well.</p>

Title: I have only two languages on my resume - how bad is this?

Body:
I have a question that can be best answered here, given the vast experience some of you guys have!

I am going to finish my bachelor's degree in CS and let's face it, I am just comfortable with C++ and Python. C++ - I have no experience to show for and I can't quote the C++ standard like some of the guys on SO do but yet I am comfortable with the language basics and the stuff that mostly matters. With Python, I have demonstrated work experience with a good company, so I can safely put that.

I have never touched C, though I have been meaning to do it now. So I cannot write C on my resume because I have not done it ever. Sure I can finish K & R and get a sense of the language in a month, but I don't feel like writing it cause that would be being unfaithful to myself.

So the big question is, are two languages on a a resume considered OK or that is usually a bad sign? Most resumes I have seen mention lots of languages and hence my question. Under the language section of my resume, I just mention: C++ and Python and that kinda looks empty!

What are your views on this and what do you feel about such a situation?

PS: I really don't want to write every single library or API I am familiar with. Or should I?


问:
Would a simple attribution satisfy the BSD license's requirements for reuse or do I need to copy the whole copyright notice?
Would something like This program uses code written by Nathan2055 satisfy the requirements for the BSD license, or do I need to copy out the whole notice? I know it asks that the notice is kept intact, but if I'm only using one file of code it's a waste to have to copy the entire license into the main copyright file.

答: You would probably have to say something to the effect of "This program uses code written by Nathan2055, which is licensed under the BSD license" and provide a link to the version of the license. However, to be safe, you're probably better off just putting the entire license in there. You don't want to get into any legal trouble over the exclusion of a simple text document.</p>

OwnerDisplayName: jepugs


答:
It is understandable to be a little confused about how to properly use REST based on all the ways I have seen large companies design their REST APIs.

You are correct in that REST is a Resource Collection system. It stands for Representational State Transfer. Not a great definition if you ask me. But the main concepts are the 4 HTTP VERBs and being stateless.

The important piece to note is that you only have 4 VERBS with REST. These are GET, POST, PUT and DELETE. Your resend example would be adding a new Verb to REST. This should be a red flag.

Question 1

It is important to realize that the caller of your REST API should not have to know that performing a PUT on your collection would result in an e-mail being generated. That smells of a leak to me. What they could know is that performing a PUT could result in extra tasks which they could query later. They would know this by performing a GET on the recently created resource. That GET would return the resource and all of the Task resource id's associated with it. You can then later query those tasks to determine their status and even submit a new Task.

You have a few options.

REST - Task resource based approach

Create a tasks resource in which you can submit specific tasks into your system to perform actions. You can then GET the task based on the ID it returned to determine it's status.

Or you can mix in a SOAP over HTTP Web Service in order to add some RPC to your architecture.

querying for all tasks for a specific resource

GET http://server/api/myCollection/123/tasks

```<code>{ "tasks" :
    [ { "22333" : "http://server/api/tasks/223333" } ]
}
</code>```

task resource example

PUT http://server/api/tasks

```<code>{
    "type" : "send-email" ,
    "parameters" :
    {
         "collection-type" : "foo" ,
         "collection-id" : "123"
    }
}
</code>```

==> returns id of task

223334

GET http://server/api/tasks/223334

```<code>{
    "status" : "complete" ,
    "date" : "whenever"
}
</code>```

REST- Using POST to trigger actions

You can always POST additional data to a resource. In my opinion this would violate the spirit of REST but it would still be compliant.

You can do a POST similar to this:

POST http://server/api/collection/123

    { "action" : "send-email" }

You will be updating the resource 123 from collection with additional data. That additional data is essentially a action telling the backend to send an email for that resource.

The issue I have with this is that a GET on the resource will return this updated data. However, this would solve your requirements and still be RESTful.

SOAP - Web Service that accepts resources obtained from REST

Create a new WebService in which you can send e-mails based on the previous resource ID from the REST API. I won't go into detail about SOAP here as the original question is about REST and these two concepts/technologies should not be compared as it's Apples and Oranges.

Question 2

You also have a few options here:

It appears many larger companies that publish REST API's expose a search collection that is really just a way to pass in query parameters to return resources.

GET http://server/api/search?q="type = myCollection & someField >= someval"

Which would return a collection of fully qualified REST resources such as:

```<code>{
    "results" :
       { [
             "location" : "http://server/api/myCollection/1",
             "location" : "http://server/api/myCollection/9",
             "location" : "http://server/api/myCollection/56"
         ]
       }
}
</code>```

Or you can allow something like MVEL as a query parameter.

Question 3

I prefer the sub-levels than having to go back up and query the other resource with a query parameter. I do not believe there is any rule one way or another. You can implement both ways and allow the caller to decide which is more appropriate based on how they first entered into the system.

Notes

I disagree about the readability comments from others. Despite what some might think REST is still not for human consumption. It is for machine consumption. If I want to see my Tweets I use Twitters regular website. I do not perform a REST GET with their API. If I want to programmatically do something with my tweets then I use their REST API. Yes APIs should be understandable, but your gte isn't that bad, it's just not intuitive.

The other main thing with REST is that you should be able to start at any give point in your API and navigate to all other associated resources WITHOUT know the exact URL of the other resources ahead of time. The results of the GET VERB in REST should return the full REST URL of the resources it references. So instead of a query returning the ID of a Person object, it would return the Fully Qualified URL such as http://server/api/people/13. Then you can always programmatically navigate the results even if the URL changed.

Response to comment

In the real world there are in fact things that need to happen that don't Create, Read, Update or Delete (CRUD) a resource.

Additional actions can be taken on resources. Typical relational databases support the concept of Stored Procedures. These are additional commands that can be executed on a set of data. REST does not inherently have that concept. And there is no reason it should. These types of actions are perfect for RPC or SOAP Web Services.

This is the general problem I see with REST APIs. Developers don't like the conceptual limitations that surround REST so they adapt it to do whatever they would like. That breaks it from being a RESTful service though. Essentially those URL's become GET calls on pseudo-REST-like servlets.

You have a few options:

Create a task resource

Support POSTing additional data to the resource to perform an action.

Add the additional commands through a SOAP Web Service.

If you used a query parameter which HTTP VERB would you use to resend the email?

GET - Does this resend the email AND return the resource's data? What if a system cached that URL and treated it like the unique URL for that resource. Every time they hit the URL it would resend an email.

POST - You didn't actually send any new data to the resource, just an additional query parameter.

Based on all the given requirements, doing a POST on the resource with an action field as POST data will solve the problem.

Title: REST API concepts

Body:
I have three questions about REST API design that I'm hoping someone can shed some light on. I've searched relentlessly for many hours but haven't found answers to my questions anywhere (maybe I just don't know what to search for?).

Question 1

My first question has to do with actions/RPC. I've been developing a REST API for a while and I'm used to thinking of things in terms of collections and resources. However, I've come across a couple cases where the paradigm doesn't seem to apply and I'm wondering if there is a way to reconcile this with the REST paradigm.

Specifically, I have a case where modifying a resource causes an email to be generated. However, at a later point the user can specifically indicate that they want to resend the email that was sent earlier. When resending the email no resource is modified. No state is changed. It's simply an action that needs to occur. The action is tied to the specific resource type.

Is it appropriate to mix some sort of action call with a resource URI (e.g. /collection/123?action=resendEmail)? Would it be better to specify the action and pass the resource id to it (e.g. /collection/resendEmail?id=123)? Is this the wrong way to be going about it? Traditionally (at least with HTTP) the action being performed is the request method (GET, POST, PUT, DELETE), but those don't really allow for custom actions with a resource.

Question 2

I use the querystring portion of the URL to filter the set of resources returned when querying a collection (e.g. /collection?someField=someval). Within my API controller I then determine what kind of comparison it is going to do with that field and value. I've found this really doesn't work. I need a way to allow the API user to specify the type of comparison they want to perform.

The best idea I've come up with so far is to allow the API user to specify it as an appendage to the field name (e.g. /collection?someField:gte=someval - to indicate that it should return resources where someField is greater than or equal to (>=) whatever someval is. Is this a good idea? A bad idea? If so, why? Is there a better way to allow the user to specify the type of comparison to perform with the given field and value?

Question 3

I often see URI's that look something like /person/123/dogs to get the persons dogs. I generally have avoided something like that because in the end I figure that by creating a URI like that you are actually just accessing a dogs collection filtered by a specific person ID. It would be equivalent to /dogs?person=123. Is there ever really a good reason for a REST URI to be more than two levels deep (/collection/resource_id)?

Body:
It is understandable to be a little confused about how to properly use REST based on all the ways I have seen large companies design their REST APIs.

You are correct in that REST is a Resource Collection system. It stands for Representational State Transfer. Not a great definition if you ask me. But the main concepts are the 4 HTTP VERBs and being stateless.

The important piece to note is that you only have 4 VERBS with REST. These are GET, POST, PUT and DELETE. Your resend example would be adding a new Verb to REST. This should be a red flag.

Question 1

It is important to realize that the caller of your REST API should not have to know that performing a PUT on your collection would result in an e-mail being generated. That smells of a leak to me. What they could know is that performing a PUT could result in extra tasks which they could query later. They would know this by performing a GET on the recently created resource. That GET would return the resource and all of the Task resource id's associated with it. You can then later query those tasks to determine their status and even submit a new Task.

You have a few options.

REST - Task resource based approach

Create a tasks resource in which you can submit specific tasks into your system to perform actions. You can then GET the task based on the ID it returned to determine it's status.

Or you can mix in a SOAP over HTTP Web Service in order to add some RPC to your architecture.

querying for all tasks for a specific resource

GET http://server/api/myCollection/123/tasks

{ "tasks" :
    [ { "22333" : "http://server/api/tasks/223333" } ]
}

task resource example

PUT http://server/api/tasks

{
    "type" : "send-email" ,
    "parameters" :
    {
         "collection-type" : "foo" ,
         "collection-id" : "123"
    }
}

==> returns id of task

223334

GET http://server/api/tasks/223334

{
    "status" : "complete" ,
    "date" : "whenever"
}

REST- Using POST to trigger actions

You can always POST additional data to a resource. In my opinion this would violate the spirit of REST but it would still be compliant.

You can do a POST similar to this:

POST http://server/api/collection/123

    { "action" : "send-email" }

You will be updating the resource 123 from collection with additional data. That additional data is essentially a action telling the backend to send an email for that resource.

The issue I have with this is that a GET on the resource will return this updated data. However, this would solve your requirements and still be RESTful.

SOAP - Web Service that accepts resources obtained from REST

Create a new WebService in which you can send e-mails based on the previous resource ID from the REST API. I won't go into detail about SOAP here as the original question is about REST and these two concepts/technologies should not be compared as it's Apples and Oranges.

Question 2

You also have a few options here:

It appears many larger companies that publish REST API's expose a search collection that is really just a way to pass in query parameters to return resources.

GET http://server/api/search?q="type = myCollection & someField >= someval"

Which would return a collection of fully qualified REST resources such as:

{
    "results" :
       { [
             "location" : "http://server/api/myCollection/1",
             "location" : "http://server/api/myCollection/9",
             "location" : "http://server/api/myCollection/56"
         ]
       }
}

Or you can allow something like MVEL as a query parameter.

Question 3

I prefer the sub-levels than having to go back up and query the other resource with a query parameter. I do not believe there is any rule one way or another. You can implement both ways and allow the caller to decide which is more appropriate based on how they first entered into the system.

Notes

I disagree about the readability comments from others. Despite what some might think REST is still not for human consumption. It is for machine consumption. If I want to see my Tweets I use Twitters regular website. I do not perform a REST GET with their API. If I want to programmatically do something with my tweets then I use their REST API. Yes APIs should be understandable, but your gte isn't that bad, it's just not intuitive.

The other main thing with REST is that you should be able to start at any give point in your API and navigate to all other associated resources WITHOUT know the exact URL of the other resources ahead of time. The results of the GET VERB in REST should return the full REST URL of the resources it references. So instead of a query returning the ID of a Person object, it would return the Fully Qualified URL such as http://server/api/people/13. Then you can always programmatically navigate the results even if the URL changed.

Response to comment

In the real world there are in fact things that need to happen that don't Create, Read, Update or Delete (CRUD) a resource.

Additional actions can be taken on resources. Typical relational databases support the concept of Stored Procedures. These are additional commands that can be executed on a set of data. REST does not inherently have that concept. And there is no reason it should. These types of actions are perfect for RPC or SOAP Web Services.

This is the general problem I see with REST APIs. Developers don't like the conceptual limitations that surround REST so they adapt it to do whatever they would like. That breaks it from being a RESTful service though. Essentially those URL's become GET calls on pseudo-REST-like servlets.

You have a few options:

Create a task resource

Support POSTing additional data to the resource to perform an action.

Add the additional commands through a SOAP Web Service.

If you used a query parameter which HTTP VERB would you use to resend the email?

GET - Does this resend the email AND return the resource's data? What if a system cached that URL and treated it like the unique URL for that resource. Every time they hit the URL it would resend an email.

POST - You didn't actually send any new data to the resource, just an additional query parameter.

Based on all the given requirements, doing a POST on the resource with an action field as POST data will solve the problem.


问:
How to write unit tests for utility programs
I am working on a C# console application that loads the data from a third party and bulk inserts into tables. Basically the code consists of a static method with logging statements. In these scenarios, how does one write the unit test cases?

Example code

```<code>void Main(string[] args)
{
    // for loop here to read config from XML file

    // initialize third party library
    ReportLib objLib = new ReportLib();

    DataTable dt = objLib.Refresh("test");

    //call SQL bulk copy
    DBHelper.BulkCopy(dt, dictmappings, destTblName);//dbhelper is static class

}
</code>```

答:
Also, remember that a unit test is a unit test. Not an integration test. Don't fall into a familiar pit an try to test the entire workings of your commandline tool.

Test fragments of your utility. If that seems impossible because you only have a small class, decide to skip unittesting because the utility is trivial, or split up your program into seperate modulesthat are testable.


答:
Is it appropriate to mix some sort of action call with a resource URI (e.g. /collection/123?action=resendEmail)? Would it be better to specify the action and pass the resource id to it (e.g. /collection/resendEmail?id=123)? Is this the wrong way to be going about it? Traditionally (at least with HTTP) the action being performed is the request method (GET, POST, PUT, DELETE), but those don't really allow for custom actions with a resource.

I'd rather model that in a different way, with a collection of resources representing the emails that are to be sent; the sending will be processed by the internals of the service in due course, at which point the corresponding resource will be removed. (Or the user could DELETE the resource early, causing a canceling of the request to do the send.)

Whatever you do, don't put verbs in the resource name! That's the noun (and the query part is the set of adjectives). Nouning verbs weirds REST!

I use the querystring portion of the URL to filter the set of resources returned when querying a collection (e.g. /collection?someField=someval). Within my API controller I then determine what kind of comparison it is going to do with that field and value. I've found this really doesn't work. I need a way to allow the API user to specify the type of comparison they want to perform.

The best idea I've come up with so far is to allow the API user to specify it as an appendage to the field name (e.g. /collection?someField:gte=someval - to indicate that it should return resources where someField is greater than or equal to (>=) whatever someval is. Is this a good idea? A bad idea? If so, why? Is there a better way to allow the user to specify the type of comparison to perform with the given field and value?

I'd rather specify a general filter clause and have that as an optional query parameter on any request to fetch the contents of the collection. The client can then specify exactly how to restrict the set returned, in whatever way you desire. I'd also worry a bit about the discoverability of the filter/query language; the richer you make it, the harder it is for arbitrary clients to discover. An alternative approach which, at least theoretically, deals with that discoverability issue is to allow making restriction sub-resources of the collection, which clients obtain by POSTing a document describing the restriction to the collection resource. It's still a slight abuse, but at least it's one you can clearly make discoverable!

This sort of discoverability is one of the things that I find least strong with REST.

I often see URI's that look something like /person/123/dogs to get the persons dogs. I generally have avoided something like that because in the end I figure that by creating a URI like that you are actually just accessing a dogs collection filtered by a specific person ID. It would be equivalent to /dogs?person=123. Is there ever really a good reason for a REST URI to be more than two levels deep (/collection/resource_id)?

When the nested collection is truly a sub-feature of the outer collection's member entities, it is reasonable to structure them as a sub-resource. By “sub-feature” I mean something like UML composition relation, where destroying the outer resource naturally means destroying the inner collection.

Other types of collection can be modeled as an HTTP redirect; thus /person/123/dogs can indeed be responded to by doing a 307 that redirects to /dogs?person=123. In this case, the collection isn't actually UML composition, but rather UML aggregation. The difference matters; it is significant!

Title: REST API concepts


答:
Most of the times, my utilities are simple 20-lines scripts that I use daily/weekly/monthly, and do one thing. If you execute the utility, it'll be immediately obvious that the script is not working.

You don't need unit tests for such utilities.

Title: How to write unit tests for utility programs

Body:
I am working on a C# console application that loads the data from a third party and bulk inserts into tables. Basically the code consists of a static method with logging statements. In these scenarios, how does one write the unit test cases?

Example code

```<code>void Main(string[] args)
{
    // for loop here to read config from XML file

    // initialize third party library
    ReportLib objLib = new ReportLib();

    DataTable dt = objLib.Refresh("test");

    //call SQL bulk copy
    DBHelper.BulkCopy(dt, dictmappings, destTblName);//dbhelper is static class

}
</code>```


问:
How are GPL-compatible licenses like MIT usable in GPL programs without being subject to the copyleft provision?
I'm currently examining the possibilities and implications of linking against a GPL library for an application in a commercial context.

From what I've understood of the GPL, as long as the application is used internally there is no obligation to release its code (even if a copy is moved to a controlled subsidiary).

What I don't understand is the following point from the FAQ :

If a library is released under the GPL (not the LGPL), does that mean that any software which uses it has to be under the GPL or a GPL-compatible license?
Yes, because the software as it is actually run includes the library.

If I take a look at the GPL-compatible licenses, some of them (like the boost one) don't seem to impose the release of the code. Using it would create a situation where you could be compliant with the GPL licence without having to respect its obligation of making your code public (which doesn't seem very credible).

(NB : there are components in Adobe Photoshop licensed under boost and I don't think the code is available on demand)

The most reasonable explication would be that I'm missing something... Could you please tell me where I made a mistake ?

答:
How are GPL-compatible licenses like MIT usable in GPL programs without being subject to the copyleft provision?

Short answer: They're not.  They'll become subject to the copyleft.

Long answer:

The Wikipedia article on license compatibility has a good section on GPL compatibility:

Many of the most common free software licenses, such as the original MIT/X license, ... are "GPL-compatible". That is, their code can be combined with a program under the GPL without conflict (the new combination would have the GPL applied to the whole).

[emphasis added]

And more explicitly from the FSF FAQ on GPL compatibility:

It means that the other license and the GNU GPL are compatible; you can combine code released under the other license with code released under the GNU GPL in one larger program.

And just for edification, here's the FSF's comments on various licenses

FSF's comment on the boost license

This is a lax, permissive non-copyleft free software license, compatible with the GNU GPL.

Which means that anything licensed under Boost is easily subsumed by the GPL.

Where it gets tricky

Let's say we have project Foo licensed under Boost, and project Bar licensed under GPL and which wants to use Foo.

Bar+Foo is allowed since the licenses are compatible, and the release of Bar+Foo must be GPL as Bar is GPL.  Foo, by itself and without Bar or Bar+Foo, is still available under the Boost license.  Said another way, Bar+Foo has no license impact upon Foo itself.

The resulting license of the project combination is a forward acting event for the combination only.  It is not a retroactive event.

So if someone else wants to take Foo and do something else with it, they are still free to do so without the copyleft provision of the GPL.  However, if they take Bar+Foo, delete Bar and only use +Foo then they are still bound by the terms of the GPL since Bar+Foo was GPL'd.

Your other question:

From what I've understood of the GPL, as long as the application is used internally there is no obligation to release its code (even if a copy is moved to a controlled subsidiary).

This is directly answered by the FSF GPL FAQ on source distribution

The GPL does not require you to release your modified version, or any part of it. You are free to make modifications and use them privately, without ever releasing them. This applies to organizations (including companies), too; an organization can make a modified version and use it internally without ever releasing it outside the organization.

Wholly owned subsidiaries are considered part of the parent organization, so you would legally be in the clear.  FSF would point out that you are violating the spirit of Free Software though.


答: Add a couple lines at the end of the script that verify the data made it into the tables. If they did not, then throw an exception or log the error. KISS is definitely the way to go with this sort of thing. If this script becomes part of a larger system, you can always refactor out this simple catch code into an integration test.</p>


问:
How do you name your private variables in C#?
What is the best practice, most commonly accepted naming conventions for private variables in C#?

private int myInteger;

private int MyInteger;

private int mMyInteger;

private int _myInteger;

private int _MyInteger;

Mysterious other option

Which do you use and why?  (My company is fairly new to C# and I would like to pick the most "industry accepted" method to try and get into our coding standard.)

答:
The MSDN class design guidlines http://msdn.microsoft.com/en-us/library/ta31s3bc.aspx recommends option 1 - myInteger.

I have always used this style. I have a personal dislike for the _ character.


问:
Do these specific tables need surrogate keys?

Background

I have this tables

```<code>+-------------------------+  +------------------------+
|Airport                  |  |Country                 |
|-------------------------|  |------------------------|
|airport_code string (PK) |  |country_code string (PK)|
|address string           |  |name string             |
|name  string             |  +------------------------+
+-------------------------+

+-------------------------+
|Currency                 |
|-------------------------|
|currency_code string (PK)|
|name string              |
+-------------------------+
</code>```

airport_code is the IATA (International Air Transport Association ) airport code, you can see them in your luggage tags when you travel by plane.

country_code is the ISO 3166-1 A3 standard country code, you can see them in the olympics.

currency_code is the IS0 417 standard 3-chars currency code, you can see them in international currency exchange display boards.

Questions

Are these natural PKs good enough ?

Is using world respected standards, which are accepted by whole industries good enough for PKs ?

Do this tables need surrogates no matter what ?

答:
If you take the "I use surrogate keys all the time" approach, you get to bypass this type of concern. That may not be a good thing because it's important to give your data some thought, but it certainly saves a lot of time, engergy and effort. If anyone were to adopt an acception to this rule, the listed examples certainly qualify because it takes an a near "act of congress" to make the change.

Ad hoc queries of a database with these natural keys is certainly helpful. Creating views that do the same thing by including the lookup tables can work just as well. Modern databases do a much better job with this type of stuff to the point where it probably doesn't matter.

There are some cases specific to the US, where standards were drastically changed: Postal code expanded from 5 - 9 digits, State abbreviations to a consistent 2 letters and get rid of the period (Remember when Illinois was Ill.?), and most of the world got to deal with Y2K. If you have a real-time app with data spread all over the world containing billions of records, cascading updates are not the best idea, but shouldn't we all work in places that face such challenges? With that dataset, you could test it for yourself and come up with a more diffinitive answer.


答:
I'm a relative newbie to version control; I've used mostly SVN, a little Mercurial, and even less Git, for only a few years now. That said, I think the following is probably good advice:

Make small commits often.

When you commit changes, commit only related items together to keep things coherent. This helps later on when you're looking back through commit messages -- if you're looking for a particular change and it's one of many, unrelated things done in a commit, you might miss it. It's also helpful if you need to roll something back since you won't be rolling back unrelated changes that were committed at the same time.

If you're going to do something that you think will mess things up, do it in a branch and merge it in later after you get it working.

Write a nice overview of what was done in each change for your commit messages. If you need more information than that, you'll probably end up looking at the code anyway.

Link related changes together by mentioning some overarching task you're working on. This will help paint a story across commits when you look back at things later on. An example would be: "Refactoring Feature Alpha: Changed X, Y, and Z"

You might find the Hg Init Tutorial of interest; it has information on setting things up for multiple people and general usage advice.

Recently I've been reading through the (Ruby on) Rails Tutorial, and they take you through everything you'll do while working on a RoR project, including using Git; you might like to read/follow along for a few chapters of this to see how use of version control integrates with the rest of the development process, in more of a live setting.


答:
For question 2, a different alternative can be more flexible: consider each search a resource that the user builds before using.

lets say you have a "searches" container, there you do a POST /api/searches/ with the query specification on the content.  it could be a JSON, XML, or even an SQL document, whatever is easier for you.  If the query parses correctly, a new search is created as a new resource with its own URI, let's say /api/searches/q123/

Then, the client can simply GET /api/searches/q123/ to retrieve the query results.

Finally, you can either ask the client to delete the query, or purge it after closing the session.

Title: REST API concepts


问:
When and for what purposes should the const keyword be used in C for variables?
While getting my code reviewed here the issue of using the const keyword came up. I understand that it is used for implementing read-only behaviour on variables.

I am confused about what are the various situations when it can be useful.

Should it be used for the sake of clarity in function prototypes?

Should it be used as a security measure during code development?

Should it be used in the scope of various functions for declaring run-time constants?

Should it be used at all?

These question are just examples of the confusion that I am facing. The general confusion is

When should be the const keyword used in C programming?

What are the various types of benefits that can be gained by using this keyword in C?

Are there any cons of using const keyword?

It has been pointed that this question may be too broad due to all these questions in the detail of my question. I just wanted to clarify that these questions are just to clarify the confusion regarding the main question.

When and for what purposes should the const keyword be used in C for variables?

It can also be rephrased as

The proper use of const keyword in C` with the pros and cons of the same.

答:
Generally in any programming language its recommended to use const or the equivalent modifier since

It can clarify to the caller that what they passed in is not going to change

Potential speed improvements since the compiler knows for certain it can omit certain things that are only relevant if the parameter can change

Protection from yourself accidentally changing the value


问:
Suggested Web Application Framework and Database for Enterprise, “Big-Data” App?
I have a web application that I have been developing for a small group within my company over the past few years, using Pipeline Pilot (plus jQuery and Python scripting) for web development and back-end computation, and Oracle 10g for my RDBMS. Users upload experimental genomic data, which is parsed into a database, and made available for querying, transformation, and reporting.

Experimental data sets are large and have many layers of metadata.  A given experimental data record might have a foreign key relationship with a table that describes this data point's assay. Assays can cover multiple genes, which can have multiple transcript, which can have multiple mutations, which can affect multiple signaling pathways, etc.  Users need to approach this data from any point in those layers in the metadata. Since all data sets for a given data type can run over a billion rows, this results in some large, dynamic queries that are hard to predict.

New data sets are added on a weekly basis (~1GB per set).  Experimental data is never updated, but the associated metadata can be updated weekly for a few records and yearly for most others.  For every data set insert the system sees, there will be between 10 and 100 selects run against it and associated data.  It is okay for updates and inserts to run slow, so long as queries run quick and are as up-to-date as possible.

The application continues to grow in size and scope and is already starting to run slower than I like.  I am worried that we have about outgrown Pipeline Pilot, and perhaps Oracle (as the sole database). Would a NoSQL database or an OLAP system be appropriate here? What web application frameworks work well with systems like this? I'd like the solution to be something scalable, portable and supportable X-years down the road.

Here is the current state of the application:

Web Server/Data Processing: Pipeline Pilot on Windows Server + IIS

Database: Oracle 10g, ~1TB of data, ~180 tables with several billion-plus row tables

Network Storage: Isilon, ~50TB of low-priority raw data

答:
Not sure if you finalized on a solution, but my two cents for those who stumble on this question:
There are two parts (1) Database (2) Web App framework.

On Database, Did you explore Hadoop? Following specs of your environment makes Hadoop an attractive platform for data processing.

~1TB of data,  ~50TB of low-priority raw data

several billion-plus row tables

New data sets are added on a weekly basis (~1GB per set)

Experimental data is never updated, but the associated metadata can be updated weekly/yearly

Insert to Select ratio is 10 to 100 times

all data sets for a given data type can run over a billion rows

Following specs are of concern though:

large, dynamic queries that are hard to predict.

(okay for updates and inserts to run slow,) so long as queries run quick

Hadoop is insanely scalable, but Hadoop performs the best with batch processing. For online queries YMMV. Unless you try out it will be hard to predict if you will be better of or worse. You have to experiment with Hive, Cloudera Impala etc. This Article has some introductory overview on Impala. It also mentions some other options.

If Hive/Impala are not giving you right performance, there are variations you can explore based on your environment

Since Disk space is comparably cheap, generate a lot more "summarized intermediate" tables, that could speed up queries.

Pre join meta data, if that can reduce number of joins in the queries

Use some hybrid approach of Oracle + Hadoop (but with increased overall complexity).


问:
Enforcing a uniform Scrum approach to all teams within a department
Where I work we recently switched the Agile development using Scrum.  We went through the typical growing pains but have reached an approach that seems to work for now (whether it'll work in the long term is for another question!).

Obviously, the department management is happy the transition to Scrum is working.  But they have starting doing something that, to me, feels wrong.

Management will observe a team, see what works for them, and the prescribe it to the entire department.  Things like:

The definition of "Done"

Which story point values can be used for story pointing (eg, omitting 8 from the fib. sequence because 1, 2, 3, 5, 13, etc were the only ones used during a sprint they observed)

Telling teams they must calibrate their story point value of 1 to "updating a UI label," and limiting them to an upper bound of 20

(although not all our projects have clients and not all developers
have UI experience)

Telling teams to use story point estimates of 100 to mean "we'll split this story later"

Telling teams to use story point estimates of infinity to mean "this is an epic" or "we need more info"

I understand they're trying to be helpful, but shouldn't all the things above be Scrum-team specific?  That is to say, what works for one group of individuals on one project may not make sense to another group on another project.

I'm concerned we're drifting into a very prescriptive and stiff Agile approach.  Am I justified in thinking this, or am I overreacting?

Edit

Just to clarify... by "Management" and "Manager" I don't mean the Product Owner.  I mean any manager outside the Scrum Team, but within the Software Department.

答:
As a company, balancing your resources should be a competitive advantage. Otherwise, just create a bunch of individual software companies that lose this type of leverage. An organization with multiple teams and projects has to be concerned with turn-over and team balancing. I don't think it is a good idea for every unique team combination to rewrite the book on how they are going to do scrum.

Anytime you're trying to aggregate things to measure something, consistency is important, i.e. don't compare apples and oranges. Management should focus on these higher-level needs, but make sure they don't get too involved in the details of how teams operate. Try to apply their suggestions, but be prepared to defend why it one team may be the exception. Anyone who just doesn't personally like a particular way of doing things needs put on their adult pants and deal with it.

There has to be some flexibility, so you can get the job done. There should be consistency when needed. If team membership gets changed, everyone shouldn't feel like it's their first day on the job.

Maybe your teams never change, but you should give that choice a chance by having some consistency.


问:
I have only two languages on my resume - how bad is this?
I have a question that can be best answered here, given the vast experience some of you guys have!

I am going to finish my bachelor's degree in CS and let's face it, I am just comfortable with C++ and Python. C++ - I have no experience to show for and I can't quote the C++ standard like some of the guys on SO do but yet I am comfortable with the language basics and the stuff that mostly matters. With Python, I have demonstrated work experience with a good company, so I can safely put that.

I have never touched C, though I have been meaning to do it now. So I cannot write C on my resume because I have not done it ever. Sure I can finish K & R and get a sense of the language in a month, but I don't feel like writing it cause that would be being unfaithful to myself.

So the big question is, are two languages on a a resume considered OK or that is usually a bad sign? Most resumes I have seen mention lots of languages and hence my question. Under the language section of my resume, I just mention: C++ and Python and that kinda looks empty!

What are your views on this and what do you feel about such a situation?

PS: I really don't want to write every single library or API I am familiar with. Or should I?

答:
I would focus your resume on your demonstrated work experience - show that you've completed projects.  That is worth so much more than what classes you took.  Truth be told, unless a CS graduate has actually completed a real project - and I'm not talking school work, I'm talking something they've worked on for months or years that was actually used by real people to solve real problems - they probably dont have enough experience to claim they 'know' any language.  Since you have actual work experience with Python for a company, you're probably a step ahead of a lot of people already.

Also yes, definately include API's and frameworks you've worked with.  Also dont forget SQL, if you've worked with databases.


问:
Moving from PHP to ASP.NET
I have been working for a long time with PHP, and tried to be as good as possible on it (good coding practices, knowing how every request is handled from the start to the end, etc.), but now, for job reasons I have to start learning ASP.NET and C#.

I've read and tried to understand it's foundations, as ASP.NET is always working with a given Framework called .NET, but there are so many versions, and different approaches like MVC or WebForms, etc.

I've made some tests, and I see that parts of the code get compiled, others not —don't know why—, and that a lot of shit is generated in the final HTML output.

I have the feeling of losing control over my WebApp, so my question is: Where can I start to understand how that works? Any tutorial, book, etc is welcome (as up-to-date as possible).

Is it possible to keep having control of the code with that Microsoft software, so the final output is clean, lightweight and high performance JS and HTML code?

For the C# part, I think this it is the easiest one, I'm just looking for a good book to read... I guess version 5.0. Am I right?

答:
Classic ASP existed before the .Net framework and thus is a separate technology that often used a Scripting variation is something to note just in case someone wants to know what is ASP .

While there is the story of classic ASP, early versions of the .Net framework, there is something to be said for what job reasons do you have to learn ASP.Net, which is different than classic ASP, and C#.  There is also VB.Net that can be used in ASP.NEt so ASP.Net as a platform does support more than one language.

Rather than worry over "losing control", I'd suggest you learn about the merits of different approaches as ASP.Net MVC is quite different from WebForms though both have their advantages and disadvantages.  For new development, MVC is probably a better selection though if you are going to be supporting existing applications then you may have to learn WebForms and these are rather different.

Understanding how it all works would likely take you a long time and in that time new versions would be born as there is something to be said for ASP.Net 1.0, 1.1, 2.0, and 4.0 on the web side of things never mind the versions of C# that also get enumerated in their own way.

Depending on how you want to define "clean, lightweight and high performance JS and HTML code" there are tons of ways you can build this.  In one of my previous jobs, a co-worker often used primitives so that he didn't use the built-in ASP.Net controls at all and stuck with hand-coded JavaScript and HTML for the most part that worked within his architecture.  Others may prefer to use the built-in controls that have their trade-offs.

Last but not least, don't forget that C# can also be used within WinForms, WCF services and a bunch of other platforms beyond the web.  I'd probably suggest going through MSDN's tutorials as a starting point.

Title: Moving from PHP to ASP.NET


问:
Is there a canonical source supporting "all-surrogates"?

Background

The "all-PK-must-be-surrogates" approach is not present in Codd's Relational Model or any SQL Standard (ANSI, ISO or other).

Canonical books seems to elude this restrictions too.

Oracle's own data dictionary scheme uses natural keys in some tables and surrogate keys in other tables. I mention this because these people must know a thing or two about RDBMS design.

PPDM (Professional Petroleum Data Management Association) recommend the same canonical books do:

Use surrogate keys as primary keys when:

There are no natural or business keys

Natural or business keys are bad ( change often )

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

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

Also I have not found canonical source that says natural keys need to be immutable. All I find is that they need to be very estable, i.e need to be changed only in very rare ocassions, if ever.

I mention PPDM because these people must know a thing or two about RDBMS design too.

The origins of the "all-surrogates" approach seems to come from recommendations from some ORM frameworks.

It's true that the approach allows for rapid database modeling by not having to do much business analysis, but at the expense of maintainability and readability of the SQL code. Much prevision is made for something that may or may not happen in the future ( the natural PK changed so we will have to use the RDBMS cascade update funtionality ) at the expense of day-to-day task like having to join more tables in every query and having to write code for importing data between databases, an otherwise very strightfoward procedure (due to the need to avoid PK colisions and having to create stage/equivalence tables beforehand ).

Other argument is that indexes based on integers are faster, but that has to be supported with benchmarks. Obviously, long, varying varchars are not good for PK. But indexes based on short, fix-length varchar are almost as fast as integers.

The questions

- Is there any canonical source that supports the "all-PK-must-be-surrogates" approach ?

- Has Codd's relational model been superceded by a newer relational model ?

答:
Primary and Foreign Keys do not have to be readable.  Their purpose is to maintain the internal relational structure of the database, not to be read by a human.

Naturally, if there is an appropriate natural key that will never change (I claim these are as rare as hen's teeth or four-leaf clovers, but...), you can use that, and some customers will make that one of their requirements.

But why add the additional complexity to a database system, for little appreciable benefit?  Primary Surrogate keys are system-generated, guaranteed to be unique, guaranteed to never change, and are the same data type for all tables.  They will have the same reliable behavior under all circumstances.

If you're looking for a canonical resource that supports this practice, you won't find one.  There are just as many designers on the other side of the aisle that will viciously defend their use of natural, composite keys with clustered indexes as primary keys, and all of the canonical resources say that it is the designer's choice.

See Also

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


问:
Interfaces, Adapters, exposing business objects via WCF design
I know there have been countless discussions about this but I think this question is slightly different and may perhaps prompt a heated discussion (lets keep it friendly).

The scene:

I am developing a system as a means for me to learn various concepts and I came across a predicament which my brain is conflicting with. That is whether to keep my interfaces in a separate class library or should they live side by side my business objects.

I want to expose certain objects via WCF, however refuse to expose them in its entirety. I am sure most will agree exposing properties such as IDs and other properties is not good practice but also I don't want to have my business objects decorated with attributes.

The question:

Essentially, I'll be having a separate interface for each of my objects that will essentially be exposed to the outside world (could end up being quite a few) so does it make sense to create a separate class library for interfaces? This also brings up the question of whether adapters should live in a separate class library too as ideally I want a mechanism from transferring from one object to the other and vice versa?

答:
Reasons to use a separate interface library:

The interfaces rarely change.

There are third party (outside company) consumers of those interfaces, and they don't need the implementation library.

To reduce dependencies in interface consumers: they only have dependencies on the types used within the interfaces, so they may require less assembly references.

Reasons to put the interfaces in the same library as the implementation:

You only have to distribute one library.

You can hide the implementation completely -- the implementation classes, and supporting types, can be internal. The interfaces are public, if you need them to be public. In some cases, you can make the WCF interfaces internal as well.

Because there is only one library, the interfaces and implementation class versions are always in sync.


问:
The 10 minutes technical interview
I must do a quick assessment of dozens of fresh students very quickly. I have 30 minutes meeting with each of them (in two or three days). I want to use most of the time to discuss non technical aspects. So I plan to use 10 minutes for technical questions. The same questions for all of them.

They are all hired already (they are students), what I need to know is the average level in order to prepare a training.

Ideally, the difficulty must be progressive in order to set a level for each. Level I will average, and I'll do an average on each question too.

If you had only 10 minutes and 10 questions to ask to a candidate, what would be your top 10 ?

答:
Surely you are going about this the wrong way.  Identify the groupings that you want to place each student into

e.g.

```<code>No previous programming experience
Familiar with procedural constructs like variables, loops, branching
familiar with basic object orientated constructs like classes, interfaces, events, inheritance
familiar with using Generics/Templates
familiar with creating Generics/Templates
</code>```

and so on. When you have identified the suitable groupings which will depend on the course material, working out what questions to ask will be trivial.

Title: The 10 minutes technical interview

Body:
Surely you are going about this the wrong way.  Identify the groupings that you want to place each student into

e.g.

No previous programming experience
Familiar with procedural constructs like variables, loops, branching
familiar with basic object orientated constructs like classes, interfaces, events, inheritance
familiar with using Generics/Templates
familiar with creating Generics/Templates

and so on. When you have identified the suitable groupings which will depend on the course material, working out what questions to ask will be trivial.


问:
Should a surrogate key ever be exposed to a user?
Often in a table that has no natural key, it is still useful for users to be able to have a uniquely generated identifier.  If the table has a surrogate primary key (and in such a case you would certainly expect it to) should that key be exposed to the user or should another field be used for that purpose?

One reason not to expose the surrogate key is that now you can't do operations that preserve the relationship between records, but change the key values, such as certain kinds of deletion/re-insertion, many methods of copying data from one database to another, etc.

The main advantage of exposing the surrogate key is the simplicity of using a field you have anyway.

Under what circumstances is it better to directly expose the surrogate key to users?

答:
You should only expose a surrogate key if it's a properly generated GUID/UUID*. Exposing sequential surrogate keys is number 4 on the OWASP Top 10 security issues.

* In practice, it's best to assume that it wasn't properly generated for these purposes unless you know that it was created by a cryptographically secure random or pseudo-random number generator.


问:
Best way for a technical manager to stay up to date on technology
My manager asked for a list of technical blogs he should follow to stay current on technology.  His problem is he keeps hearing terms that he hasn't heard of (i.e. NoSql, sharding, agure, sevice bus, etc.) and he would prefer to at least have a fighting chance of knowing something about them without having to be reactive and looking them up.  Also I think he wants to have a big picture of all the emerging technologies and where they fit in together instead of just learning about each thing in isolation.

He asked about blogs but I'm thinking print magazines may also help.

What should I answer him?

答:
You can tell him at least get a news feed or just go to the followings sites.
This will at least should help him to get a bird's eye view about the technology or software related things that he may need to learn more about.
by the way you are a great employee that you are even coming online and posting questions for him to be able to help him and for that you deserve a raise :)

https://news.ycombinator.com/

http://www.gartner.com/newsroom/archive/

http://www.codinghorror.com/blog/

http://www.reddit.com/r/programming

http://mashable.com/apps-software/

http://www.drdobbs.com/

http://www.infoworld.com/news

http://slashdot.org/

OwnerDisplayName: JoelFan


问:
How to design a calculator from scratch
A basic calculator can perform a wide variety of operations. How does the claculator 'get' the concept of adding two numbers in the same way a human does? I dont think people that make claculators store every possible result of every possible addition on the chip before shipping it. Soemhow the chip needs to 'learn' how to add.

I mean if I were to start with a blank slate(chip) and 'teach' the chip to perform calculations(additions), how do i go about it? Do i need to learn artificial nural networks first?

答:
Work in binary: 0, 1, 10, 11, 100, 101...

Know your math: 0+0=00, 0+1=01, 1+0=01, 1+1=10

Know your logic: or, and, not, xor...

Find that the low bit is a XOR and the high bit is a AND.

Expand the principle of one bit to 8, 16, 32, 64 bits

Build it with logic gates.

If you want to know more, see my answer to How is fundamental mathematics efficiently evaluated by programming languages?

Title: How to design a calculator from scratch


答:
Ten questions:

Show a for loop that sums the values of an array. Ask then what the piece of code does. [Can they read a basic loop?]

Ask them to write a for loop that prints out the numbers 1 through 10, separated by commas. [In addition to "can they do this?" you can judge how repetitive their code is.]

Show a piece of code with two references, a and b, pointing to two different objects with an integer field x set to, say, 7 and 5. Then reassign: a = b;, b.z = 9;, and then ask for the value of a.z. [Do they understand references?]

Show two nested for loops (using indexes i and j), accumulating values from some expression. In the innermost loop, have two computations: double x = Math.pow(2.0, i) and double y = x * j. Ask them to make the code more efficient. [Do they know about simple loop dependence?]

Ask them what is wrong in code sample A. (See below.) [Can they think logically?]

Ask them what is wrong in code sample B. (See below.) [Also on logical thinking.]

Ask them to invert this condition: (s != null && s.Length != 0) without using !. [Do they know DeMorgan's Law?]

Show a piece of code similar to the old Lint advertisements in magazines: Ask them to find the bug. For example, overloading equals instead of overriding it. [Are they good language lawyers? These kind of questions mostly test for experience: have you seen this one before?]

Can they describe how to perform a binary search through a sorted array?

Can they describe how a sorting method might be implemented?

These may seem "too short," but I believe for assessing students you might find the ten minutes is pretty tight. You really do want to see them do some coding. (It sounds like you'll do FizzBuzz, based on one comment.)

If you can assume a stronger student, then you will also want to ask some of the classics, such as recursion, reversing a linked-list, and maybe an advanced wild card like explaining an XOR-list, or what intuitions they might have for why sorting a set of numbers makes it easier to compress than unsorted.

Code Sample A:

```<code>if (m != null)
    a = m;
else
    a = null;
</code>```

Code Sample B:

```<code>if (x != 0 || x != 1) {
    ...
}
</code>```

Title: The 10 minutes technical interview

Body:
I must do a quick assessment of dozens of fresh students very quickly. I have 30 minutes meeting with each of them (in two or three days). I want to use most of the time to discuss non technical aspects. So I plan to use 10 minutes for technical questions. The same questions for all of them.

They are all hired already (they are students), what I need to know is the average level in order to prepare a training.

Ideally, the difficulty must be progressive in order to set a level for each. Level I will average, and I'll do an average on each question too.

If you had only 10 minutes and 10 questions to ask to a candidate, what would be your top 10 ?

Body:
Ten questions:

Show a for loop that sums the values of an array. Ask then what the piece of code does. [Can they read a basic loop?]

Ask them to write a for loop that prints out the numbers 1 through 10, separated by commas. [In addition to "can they do this?" you can judge how repetitive their code is.]

Show a piece of code with two references, a and b, pointing to two different objects with an integer field x set to, say, 7 and 5. Then reassign: a = b;, b.z = 9;, and then ask for the value of a.z. [Do they understand references?]

Show two nested for loops (using indexes i and j), accumulating values from some expression. In the innermost loop, have two computations: double x = Math.pow(2.0, i) and double y = x * j. Ask them to make the code more efficient. [Do they know about simple loop dependence?]

Ask them what is wrong in code sample A. (See below.) [Can they think logically?]

Ask them what is wrong in code sample B. (See below.) [Also on logical thinking.]

Ask them to invert this condition: (s != null && s.Length != 0) without using !. [Do they know DeMorgan's Law?]

Show a piece of code similar to the old Lint advertisements in magazines: Ask them to find the bug. For example, overloading equals instead of overriding it. [Are they good language lawyers? These kind of questions mostly test for experience: have you seen this one before?]

Can they describe how to perform a binary search through a sorted array?

Can they describe how a sorting method might be implemented?

These may seem "too short," but I believe for assessing students you might find the ten minutes is pretty tight. You really do want to see them do some coding. (It sounds like you'll do FizzBuzz, based on one comment.)

If you can assume a stronger student, then you will also want to ask some of the classics, such as recursion, reversing a linked-list, and maybe an advanced wild card like explaining an XOR-list, or what intuitions they might have for why sorting a set of numbers makes it easier to compress than unsorted.

Code Sample A:

if (m != null)
    a = m;
else
    a = null;

Code Sample B:

if (x != 0 || x != 1) {
    ...
}