答:
The best way is to track what the next time is when you add to the array, then you sleep until that time.

So, when adding a new event to the array, you must decide if it is going to be triggered first, or later than the currently stored 'next event'. Then your loop simply sleeps (maybe periodically waking up every second or so to print an "I'm still running" diagnostic).

This will require a thread that wakes up to trigger the event must be synchronised with a mutex, so it can be prematurely woken up if a new event is added that is going to be fired sooner than the current next event. This thread then re-calculates the next time will be, sets the mutex and waits for either it to be triggered again or a timeout occurs where the timeout will be the right amount of time to wait for the next event's time.

Title: Infinite while loop CPU usage

Body: I'm coding an script in C, which is going to check constantly an array of events, the idea is to check if the Date and time of certain event is equal to de current time and trigger something, i'm doing this with a while(1){}, but this approach causes a high CPU usage, do you have any suggestion of how can i do this with a lower CPU usage ?</p>


问:
Manually scanning log files for exceptions/errors - is it a valid user story?
We've just deployed a new system for our users. The product owner asked us to check the log files every day in the next iteration for error messages and exceptions. We have written the following user story:

As a [web system] user I want that developers to check log files every day in the next iteration for errors so I don't have to file bug tickets for trivial bugs/get better service.

Is it a valid user story? If not, could it be rewritten to be a valid user story? How? (We had some debate about that with the product owner whether it is worth story points or not.)

答:
As it stands, I don't think it's a valid user story because of the indirect relationship between the user and the rest of the story -- "as a user I want the developers...."

It's also vague, hard if not impossible to estimate and test, and is a perpetual activity rather than a one-time series of tasks that can be completed.

Perhaps it could be written as a user story if there was a concrete goal. For example: the daily automated generation of an error log, or a feature that would allow users to easily flag errors without having to submit a full defect entry.

Edit:
Your update to the question does define this better as a task, but I still don't think it's a valid user story because again, it's hard to determine an acceptance test that demonstrates the business value for the user. What does "check the log files" entail, and to what level of detail? Also if there are errors in the log, might that imply that the user has had to file a bug ticket anyway, defeating the stated purpose of the task?

ContentLicense: CC BY-SA 3.0


问:
Protecting application against piracy
Can I somehow protect a source available (you can see the source, but you don't have rights to use it) application against piracy? Is it even theoretically possible?

Not all of the application has to be available, "security module" or how to call it can be closed source, no licensing issue here.

答:
As per comments:

If some or all of your sources have gone public - it's not the end of the world. Some companies operate on a semi-open software basis, where parts of the software are open, and some are proprietary.

Your main protection should be legal. Any software will be pirated, independent of the amount of protection on source code, if it is deemed worthwhile. It's copyright and patents that prevent other companies from using it. Private users may present more of a challenge, depending on the nature of the software you are making.

Title: Protecting application against piracy


问:
Where to put database table/column names?
I'm making a web app that will be querying an existing database. I'm thinking of putting the names of the tables and columns and such into a single static class, and then referencing that when constructing queries. I think this would help with maintainability since if in the future a column gets renamed for some reason, it just needs to be changed in one place.

Is this a good way to do this? Is there a better way?

答:
I'm thinking of putting the names of the tables and columns and such into a single static class...

Don't do this.

If you want to eliminate magic strings, please do yourself a favor and create one static class per table underneath a shared namespace.

A single static class to manage all table and column names would quickly turn into a big ball of mud.


答:
Can I somehow protect any application against piracy? Is it even theoretically possible?

No, and it's a complete waste of time and effort to even try.  When Microsoft's new OSes have cracked versions available before release day, and they put more R&D money into just that one feature than you'll ever see in your whole life, that should give you a bit of perspective.

Making the source available just makes it easier to copy, but either way, there's no way to keep a program you distribute a copy of to another person from being copied and distributed even further.  The basic problem is that the computer needs to read it in order to execute it, and if the computer can, so can someone who knows how computers work.

It's been called "the fundamental question of cryptography:" Alice wants to send a letter to Bob, without Charlie being able to read it even if he should get his hands on it.  The problem in this scenario is that Bob and Charlie are the same person.

So don't even worry about trying; it's a waste of time and money.  As Ordous said, your protection should be legal in nature, not technical.  And to add to that, the best protection against piracy is using human nature and basic capitalism to your advantage.  Generally speaking, people want to be good, and see themselves as good.  So if you follow fundamental market theory, and offer a good product at a price that is less than what they perceive its value to them to be, they will be willing to pay for it even if an illegal alternative exists.  Piracy is almost always a symptom of excessive pricing or poor attention to the needs of the customers.

Title: Protecting application against piracy

Body:
Can I somehow protect a source available (you can see the source, but you don't have rights to use it) application against piracy? Is it even theoretically possible?

Not all of the application has to be available, "security module" or how to call it can be closed source, no licensing issue here.


问:
Is there a name for the technique of converting method parameters into a unified form to simplify further processing?
When working with methods which accept a parameter in various forms (e.g. nil, a single string, a single string containing multiple data or an array of strings) I tend to unify them - splitting, sanitizing and putting them into an array because this simplifies further processing and removes the need for nil, type and size checks.

example (in Ruby):

```<code>params = Array(original_param).map { |a| a.split(/\s*,\s*/) }.flatten
params.each{|p| process(p)}
</code>```

However, I have no idea what I am doing, at least I have no idea if there is a name for what I am doing. Is there?

答:
The phrase you are looking for is tokenization, and as you noted, it's a very common process for sanitizing input parameters.

From the linked Wikipedia article:

Tokenization is the process of breaking a stream of text up into words, phrases, symbols, or other meaningful elements called tokens. The list of tokens becomes input for further processing such as parsing or text mining.


问:
How to measure (and improve) quality of bug-fixes?
I have the suspicion that many bug-fixes carried out by our developers sooner or later cause another bug, simply because the product is too complex.

I'd like to improve the quality of bug-fixes, i.e. make sure bug-fixes do not produce additional errors in the code. For that, I'd like to be able to measure how the quality changes as I apply various counter measures.

Is it a good idea to instruct bug-fixers to always look for the cause of their defect, and then evaluate the ratio of previous bug-fixes being such cause? I'm hesitant about this due to the obvious higher expenses and unwillingness of developers to blame themselves or fellow colleagues.

Is there a better approach?

答: How do you tell if the "new" bug is caused by a fix, or if it was there all along? The temptation is to say "I never saw this bug before that last patch, so the patch must have introduced the bug", but if that was unilaterally true, how did the original bug get into production code? Increasing the quality of fixes would essentially entail increasing the cost of fixes and delay their deployment, because this means dedicating more time to testing a fix before releasing the patch (something, in my experience, management doesn't want to dedicate a lot of time/money to). That also entails that the coders (or at least testers) actually be users of the system, too. In my situation, the team that works on patches has no idea whatsoever of the actual usage of the system they support, and it shows.</p>


答:
Ideally you will have as many useful unit tests as possible, testing every combination of inputs to each class.

Then when fixing a bug, check the unit test that should have caught it. Maybe there is an edge condition or combination of inputs not previously encountered (add a new unit test). Maybe an existing test erroneously passed (fix the test).

If a bug fix causes another unit test to fail, you now have a measurable result that tells you about the quality of the bug fix. Of course you could just have an application with too tight of coupling where code changes in one area affect code in another area when perhaps they should not.

If you combine this with a continuous integration system that will recompile your code and run tests on a regular basis, you will have very quick feedback on the quality of bug fixes and the frequency with which they break other code.

Title: How to measure (and improve) quality of bug-fixes?

Body:
I have the suspicion that many bug-fixes carried out by our developers sooner or later cause another bug, simply because the product is too complex.

I'd like to improve the quality of bug-fixes, i.e. make sure bug-fixes do not produce additional errors in the code. For that, I'd like to be able to measure how the quality changes as I apply various counter measures.

Is it a good idea to instruct bug-fixers to always look for the cause of their defect, and then evaluate the ratio of previous bug-fixes being such cause? I'm hesitant about this due to the obvious higher expenses and unwillingness of developers to blame themselves or fellow colleagues.

Is there a better approach?


问:
Wrap all external calls with flag to fight against recursion and double-entry?
Producing predictable output for each possible input is the responsibility of each module. For example (in C#):

```<code>class Logger
{
    public ITextWriter Writer { get; set; }

    private uint counter;

    /// <summary>
    /// Writes message in special format and returns the number of total messages written
    /// </summary>
    public uint Debug(string message)
    {
        if (message == null) throw new ArgumentNullException("message");

        if (Writer == null) throw new InvalidOperationException("Writer not set");

        Writer.Write(string.Format("{0:HHmmss}: [DEBUG] {1}", DateTime.Now, message));

        return ++counter;
    }
}
</code>```

Logger module is quite verbose, but it's output - exception, call to a depedency and returned value - is predictable and obvious for each argument and state.

But one possible use-case bothers me. What if Writer was set to some weird implementation which somehow calls the Logger.Debug method on that same object? First possible consequence is stackoverflow due to infinite recursion. Second - unpredictable output and possible bugs. It's obvious that such situation must be controlled somehow. If we want predictable output for our logger, it should control double-entries:

```<code>    // ...
    private bool enter;

    public uint Debug(string message)
    {
        if (message == null) throw new ArgumentNullException("message");

        if (Writer == null) throw new InvalidOperationException("Writer not set");

        if (enter) throw new InvalidOperationException("Double-entry");

        enter = true;

        Writer.Write(string.Format("{0:HHmmss}: [DEBUG] {1}", DateTime.Now, message));

        enter = false;

        return ++counter;
    }
    // ...
</code>```

And it seems that every external call (a call not to it's own components) must be wrapped with such flags. That looks crazy!

Is it how good code written? Or is it normal to beleive that your system has no circular calls? Am I missing something important? Please, advise.

UPDATE

It's even worse, guys:

```<code>    // ...

    private bool enter;

    public uint Debug(string message)
    {
        if (message == null) throw new ArgumentNullException("message");

        if (Writer == null) throw new InvalidOperationException("Writer not set");

        if (enter) throw new InvalidOperationException("Double-entry");

        try
        {
            enter = true;

            Writer.Write(string.Format("{0:HHmmss}: [DEBUG] {1}", DateTime.Now, message));
        }
        finally
        {
            enter = false;
        }

        return ++counter;
    }
    // ...
</code>```

I beleive that catching an exception is on duty of higher-level module (the one which created them all), so exceptions must follow their way. But the state after unsuccessfull call must remain correct. Exception is not the end of the world, and modules possibly can be re-used.

答:
If this is something you're really worried about, then it's clearly a cross-cutting concern, so it's one you could tackle with an Aspect-Oriented Programming approach.

For example, you could use Castle's DynamicProxy, and write an interceptor that keeps track of the entry variable and throws an exception if the same method is entered a second time. If you need more granular behaviour, like some methods being allowed to recurse or having a maximum number of allowed entries greater than one, you could control that with attributes. Obviously this approach will still only give you exceptions rather than design-time safety.

Generally, however, I'd say that this concern is outside what a module should take worry about. For example, let's say I have the following method:

```<code>public void CreateItem()
{
    _itemStorer.Create();
}
</code>```

Doesn't get much simpler than that. But what if when this is called, the stack is already almost full (not necessarily because of any recursion), and any calls into further methods will cause a stack overflow? Or what if the stack is half full, but _itemStorer puts enough items on it with Create to overflow it? Should this simple method take responsibility for knowing the stack usage of all of everything above and below it? Surely that way lies madness.

Or, an even simpler version, what if the day after you write this piece of code, somebody comes in and replaces all of the implementation of Create with throw new NotImplementedException()? Should you expect to be able to handle that too?

A module of code should take responsibility for itself, which means behaving and interacting with its dependencies in a safe and sane way. It should not be expected to take responsibility for its dependencies. Remember, if A takes B as a dependency, then B is being used to fulfill a need that A has, and it is B's responsibility to do that correctly.

Body:
If this is something you're really worried about, then it's clearly a cross-cutting concern, so it's one you could tackle with an Aspect-Oriented Programming approach.

For example, you could use Castle's DynamicProxy, and write an interceptor that keeps track of the entry variable and throws an exception if the same method is entered a second time. If you need more granular behaviour, like some methods being allowed to recurse or having a maximum number of allowed entries greater than one, you could control that with attributes. Obviously this approach will still only give you exceptions rather than design-time safety.

Generally, however, I'd say that this concern is outside what a module should take worry about. For example, let's say I have the following method:

public void CreateItem()
{
    _itemStorer.Create();
}

Doesn't get much simpler than that. But what if when this is called, the stack is already almost full (not necessarily because of any recursion), and any calls into further methods will cause a stack overflow? Or what if the stack is half full, but _itemStorer puts enough items on it with Create to overflow it? Should this simple method take responsibility for knowing the stack usage of all of everything above and below it? Surely that way lies madness.

Or, an even simpler version, what if the day after you write this piece of code, somebody comes in and replaces all of the implementation of Create with throw new NotImplementedException()? Should you expect to be able to handle that too?

A module of code should take responsibility for itself, which means behaving and interacting with its dependencies in a safe and sane way. It should not be expected to take responsibility for its dependencies. Remember, if A takes B as a dependency, then B is being used to fulfill a need that A has, and it is B's responsibility to do that correctly.


问:
How should I make progress further as a programmer?
I have just left my college after doing graduation in computer engineering,during my college life I tried to do some freelancing in local market.I succeeded in the last year and earned some small amounts based on joomla,wordpress and visual basic based job.I had some small projects on php,mysql also.
After finishing my undergrad life,I sat for an written test for post of python programmer and luckily I got the job and is working there(Its a small software firm do most of the  task in python).Day by day I have gained some experience with core python.

Meanwhile an USA based web service firm called me for the interview and after finishing three steps(oral+mini coding project+final oral)they selected me(i was wondered!).And I am going to join their with in few days.There I have to work in python(based on Django framework,I know only basic of this framework).

My problem is when I started to work with python simultaneously I worked in Odesk as a wordpress,joomla,drupal,php developer.
Now a days I am feeling that I am getting "Jack of all trades master of none".

My current situation is i am familiar with several popular web technologies but not an expert.I want to make myself skilled.
How should I organize myself to be a skilled web programmer?

答: Build something. The only way to gain more than a shallow knowledge of any programming language or framework is to build something substantial with it. You can never understand a framework or programming language until you've used it to do something big.

ContentLicense: CC BY-SA 2.5


问:
Logging instance information in Exceptions
During development on a large existing codebase I've started to capture variable values in my Exception logging. For example:

```<code>public int Foo(int a, int b)
{
   int returnInt;
   try{
      returnInt = bar(a) * b;
   }
   catch (Exception ex){
      ex.Message += "a: {0}, b: {1}", a, b;
      logger.log(ex);
   }

   return returnInt;
}
</code>```

While I'm not asking about this specific pseudocode I wondered if there were any valid reasons to not do this?

To me it would seem that logging instance variables in addition to the more general error message and stack trace is a positive thing. However I've never seen it done elsewhere.

答:
I take the "log anything and everything"* approach to logging because otherwise the one thing that you don't log will inevitably be the thing that you need to know when the exception occurs.

*of course as Bri points out I avoid logging passwords, (some) personal details, and payment details. Some personal information may be useful to log (name and email address) to help identify the person and potentially contact them about the error that occurred but there may be legal issues with this depending on your location.


答:
At Microsoft, the term I heard a lot for this was "Legoing" as in "I Legoed that crap spaghetti code down into a nice, maintainable bit of code".

I think this is very similar to what you're asking for, I just don't know how portable "to Lego" is outside of MSFT.  I'm not a big fan of "verbing a noun", but it seems to fit here.

Title: Is there a name for the technique of converting method parameters into a unified form to simplify further processing?

Body:
When working with methods which accept a parameter in various forms (e.g. nil, a single string, a single string containing multiple data or an array of strings) I tend to unify them - splitting, sanitizing and putting them into an array because this simplifies further processing and removes the need for nil, type and size checks.

example (in Ruby):

```<code>params = Array(original_param).map { |a| a.split(/\s*,\s*/) }.flatten
params.each{|p| process(p)}
</code>```

However, I have no idea what I am doing, at least I have no idea if there is a name for what I am doing. Is there?


问:
When, if ever, can code standards be ignored?
My company has decided to use stored procedures for everything dealing with the database (because they didn't know of any other way besides raw SQL), and as the saying goes "When in Rome..." so I try to follow.  Recently I had to add a hack fix that required grabbing a database value, and since it was a single value from a single table I wrote it as inline SQL (parameterized, of course) since there didn't seem to be a need for a stored procedure for one trivial line of code used in a single part of the application as a kludge.

Of course, I've now been told to fix it and only ever use Stored Procs for anything related to the database.  This feels just a bit too much like blindly following dogma instead of using common sense.  Don't get me wrong, I understand the purpose of having coding standards but I am also a proponent of ignoring standards when they don't make sense, not just blindly following them as though they were Gospel.

答:
RECAP ON OTHER ANSWERS

Here is a quick summary of what others have said here before.

Pro company policy:

Allows for tracking dependencies between database objects and overview how planned changes affect the schema;

DBA team is able to review and control application access rights;

DBA team is able to predict performance impact of changes;

Decouples database from application code;

Broken window theory... meaning that's the way how they organize their code, and breaking the consistency will makes the infrastructure harder to grasp for newcomers, which will make them respect and strive for quality less;

You get your paycheck to do what you were asked to do. This is a company policy and right now you are not in the authority to change it, so better live with it.

Contra company policy:

This company mindset is very rigid and dogmatic, and the policy makes developer's work unnecessarily cumbersome. Unfortunately, see last point in the Pros section;

As back2dos refers to it by saying "For every query made to the database, you have to look up the stored procedure", a sprocs-only policy often results in code duplication, because different developers have no idea which sprocs could be reused for their problem at hand;

Also, ironically the contrary to the previous case creates problems too, when some application owns a sproc, then another reuses it, then the first one updates it without the knowledge of who else started relying on it. DBAs track the dependencies not further than the walls of the DB server room, so don't expect them to give a damn what app relies on what outside of that. If the application teams don't track it between themselves that's their problem, the DBAs are covered.

THOSE 2 CENTS

Firstly, many answers here use the word standard. The practice of prohibiting direct queries and only allowing sprocs is not called a standard. It's a policy (see jzd's answer).

Secondly, specific to your problem: my main contra argument against such a restrictive policy of using stored procedures exclusively would be the SQL language itself, and not necessarily the centralized business-logic repository infrastructure it promotes (though that has it's counter-arguments too).

SQL is a rather rigid and non-composable language, with quite limited expressive power. This means that you will hit a dead-end very early with regards to code reusability. One of the reasons of this rigidity is that there are no means to pass first class functions in any way (like with OOP languages using polymorphism), which limits composability significantly. The closest you can get to that in expressive power is by writing dynamic SQL queries constructed using string concatenation. Not a neat thing. Dynamic queries defeat some of the points in the "pros" section, like the tracking dependencies between DB objects, and usually have worse performance, error prone, hard to debug, and increase the risk of SQL injection attacks. Unfortunately, with SQL you'll find that you can't get very far with extracting common reusable logic between sprocs without hitting the wall and being forced to resort to dynamically executed queries.

UPDATE: Another big limitation of stored procedures, besides the first class function thing, is the passing and returning of composite data types as arguments, whether it be lists, sets, records, or key-value pairs. This hurts composability badly too.

Finally, I don't necessarily agree with one of the pro points above, the "decoupling DB from application" by Jorge: The main principle which I feel applies here is to prefer primitive data structures with large set of common reusable and composable operations, rather than working with custom APIs. Sprocs are such custom APIs here, which stand in-between the user and the primitive relational data to query it using common composable data manipulation primitives (select, join, where, group by, etc). Now SQL itself is not the ideal choice to be the DSL for composable data manipulation primitives, due to the above mentioned rigidity, but with a more sensible language choice (like .NET Linq... or Lisp/Clojure!) you could run your logic against a simple List just the same way as against a DB ResultSet. Obviously, that makes it easily testable, which is a Good Thing. I say prefer your data-store to be dumb simple and primitive, such that it can be stubbed with plain CSVs. As you see, this model decouples DB from application too, only it draws the line at a lower level of abstraction.

WHAT TO DO NEXT?

It's a bit unrelated to the question, but I encourage you to take a look at Datomic, which has an interestingly novel approach to storing and querying data, in line with some of the above observations. (Obviously, I mean look at it strictly outside the work environment first... definitely do NOT go to the CTO's office the next day and say "Hey guys I rewrote some of your sprocs in Datomic and deployed it on this shiny prod server over there, it's really cool take a look!" They might not appreciate the otherwise completely understandable excitement ;)


答:
The most common terms for this are canonicalisation and normalisation. In mathematics, a normal form is a standard way of representing an object with multiple equivalent representations. For example, these two logical expressions are equal:

¬x ∨ ¬y ∨ ¬z

¬(x ∧ y ∧ z)

But the former is in disjunctive normal form while the latter is not.

In programming, we typically talk about canonicalisation only when there is a singular canonical representation, for example, on a file system (ignoring hard links), the canonical representation of the path referred to by ../bar might be /foo/bar. In other cases, where the choice of normal form is arbitrary, normalisation is the preferred term.

In the context of security, sanitisation refers to normalisation for the purposes of rendering malicious input harmless. This usually consists of enforcing language separation by escaping special characters or using type system features.


问:
Test Driven Development for Complex Games
I'm coding a game in my spare time, but I am mostly still a beginner when it comes to programming.  I'm sorry if this question is off topic or if it ends up not being helpful to anyone else, but hopefully it will be.

I've spent a lot of time reading books about the design of code, as well as different methodologies and approaches to coding.  In the course of this research I keep running into the concept of Test Driven Development.  The people who espouse this idea usually seem very passionate about it.  I do believe that it can help the speed and efficiency of writing software.  Time is a very precious resource so I would rather learn to do things the best way rather than muddle through without trying to expand my knowledge of the programming craft.

Anyway, possibly because I am a beginner, I cannot imagine how to apply test driven development to games.  I've found a couple of articles on the subject but they were not very helpful.  Most of the examples of unit tests that I have seen are very simple boilerplate examples, or examples from software that is not at all like a game.

In my own coding, I try to approach it with a similar mindset to test driven development, although I'm sure it does not actually qualify as TDD.  I write the minimum amount of code to try to implement whatever feature I am adding to the game, and then I immediately test the game to see if it works.  If things don't happen as I intended, I immediately make changes to get it closer to what I want.  If it is not working or broken, and if I cannot find the bugs by reading the code, I step through the methods in the debugger until I find the unexpected behavior, and then I remove it.  What I am trying to say is that I am constantly testing the game, pretty much after each and every incremental change.  Testing drives my development.  The "unit test" is in my head, because for example I know what the unit in my game is supposed to be doing, so I test to make sure that it is doing it, and if not, I try to fix it right away.

On to my actual question. How can one write unit tests for a complex game?  By complex, I mean with many emergent aspects of gameplay, such that the meat of the gameplay emerges from the interaction between the many different elements inside the game combined with the player's choices.  For example, a roguelike rpg with a procedural world.  What kind of unit tests would one write for a game like that?  How could one apply test driven development to such a game?

答:
It is hard to write unit tests for code that is non-deterministic. If you have code involving random numbers, you won't be able to write a unit test that asserts an expected result.

So, unit tests are more appropriate for the code that is deterministic. When I give a method these inputs, I expect these outputs. As an example: when a fighter with 15 strength uses his two-handed broadsword to successfully hit an undead ghoul with 10 armor, I expect 8 damage. The non-deterministic part (whether the hit was successful or not) can't necessarily be unit tested, but what happens after that can be. Even if the amount of damage is expected to be within some range, you can test for that.

If you're having a hard time finding code to write unit tests for, you need to refactor so that the deterministic logic is isolated in methods or classes. Roll the dice to first to determine success, then pass the relevant inputs (class, strength, armor, etc.) to a testable method.

To your comment about having the unit test in your head, the point of unit testing isn't just about freshly written code. It's also about having confidence that the code still works after making inevitable changes.


问:
Agile Story Pointing - Shared Resources
I'm running a team that takes care of 3 products that are distinct in language/product type so that 2 out of 6 developers I manage are only ever locked to coding on 2 of the products (thick client applications). The other 4, are the web developers and look after a very rich/complicated web application.

The process the team are used to doing is story pointing based entirely on complexity alone, but the web team and other 2 dev's point their own user stories for their products. So 4 dev's point their web stories, and the 2 point their other product stories. The team then total those up, and the velocity calculation is based on all 6 of those developers. Further to this, there are 3 QA's who bounce between being able to test either web and the other products, so don't strictly belong to the web developers alone, or the 2 other devs.

I'm really struggling to grasp that this is the 'Agile' way and what I want to do is split the two groups, lock 1 QA to the 2 thick client developers, and then lock 2 other QA to the web team. This way, I can get independent velocity and manage the time of both groups better.

Another problem I'm having is having no visibility of when a release is QA heavy or development heavy and light on QA. Thus having developers and/or QA running out of work. It's driving me a little crazy that I can't see any estimation of QA efforts along side development effort.

Can someone tell me where I'm going wrong in my thinking, or this teams process flawed? I just feel the 'Agile' scrum process here has such lack of clarity behind the individuals skills/time management.

答:
The core idea of Agile is that you can adapt quickly. Adapt your products quickly to changing requirements, but also adapt your processes to your unique situation.

Another core idea of Agile is that management shouldn't be laying down the law, but that the teams are quite capable of deciding for themselves what works and what doesn't. So, whatever you do, try to get the team to buy into it.

The fact that the web-dev stories have a different base for their story points from the thick-client stories indicates that the developers have already split themselves effectively into two teams.

There are several things that can be done to get more clarity:

For each story, estimate how much development effort and how much testing effort goes into it. This can be done by estimating twice, with different viewpoints, or by splitting the stories into tasks and estimating those. (Commonly, task estimation is done the traditional way in hours of effort. Tasks should be small enough that this can be done without too much uncertainty.)

When planning a sprint, this will give an idea not only if the planned stories fit within the velocity, but also if it can be done with the available resources (and their skill sets).

I would start to maintain different burndown charts and velocities for the web project and the thick-client projects. That way you see faster if a sub-team is under- or overcommitting for a sprint.

If you find there is a strong dis-balance in the planned workload for one particular skill set (for example, there is a boatload of work for the web developers, but less testing to be done), see if the others can help out. Possibilities are, for example, that the QA's/other devs help with unit testing, or that developers do some QA work (on code that they didn't write).

Ultimately, the team as a whole is responsible for delivering the complete set of stories they committed to and everyone should be prepared to do whatever is needed to realize that. Even if that means your job for the day is to fetch coffee for the others.

Title: Agile Story Pointing - Shared Resources


问:
Is it overkill to wrap a collection in a simple class only for the sake of better readability?
I have the following map:

```<code>Map<Double, List<SoundEvent>> soundEventCells = new HashMap<Double, List<SoundEvent>>();
</code>```

This HashMap maps double values (which are points in time) to the corresponding SoundEvent 'cell': each 'cell' can contain a number of SoundEvents. That's why it's implemented as a List<SoundEvent>, because that's exactly what it is.

For the sake of better readability of the code, I thought about implementing a very simple static inner class like so:

```<code>private static class SoundEventCell {
    private List<SoundEvent> soundEvents = new ArrayList<SoundEvent>();
    public void addEvent(SoundEvent event){
        soundEvents.add(event);
    }
    public int getSize(){
        return soundEvents.size();
    }
    public SoundEvent getEvent(int index){
        return soundEvents.get(index);
    }
    // .. remove() method unneeded
}
</code>```

And than the map declaration (and a lot of other code) would look better, for example:

```<code>Map<Double, SoundEventCell> soundEventCells = new HashMap<Double, SoundEventCell>();
</code>```

Is this overkill? Would you do this in your projects?

答:
Wrapping it limits your functionality to only those methods you decide to decide to write, basically increasing your code for no benefit.  At the very least, I would try the following:

```<code>private static class SoundEventCell : List<SoundEvent>
{
}
</code>```

You can still write the code from your example.

```<code>Map<Double, SoundEventCell> soundEventCells = new HashMap<Double, SoundEventCell>();
</code>```

That said, I've only ever done this when there is some functionality the list itself needs.  But I think your method would be overkill to this.  Unless you had a reason to want to limit access to most of List's methods.

Body:
Wrapping it limits your functionality to only those methods you decide to decide to write, basically increasing your code for no benefit.  At the very least, I would try the following:

private static class SoundEventCell : List<SoundEvent>
{
}

You can still write the code from your example.

Map<Double, SoundEventCell> soundEventCells = new HashMap<Double, SoundEventCell>();

That said, I've only ever done this when there is some functionality the list itself needs.  But I think your method would be overkill to this.  Unless you had a reason to want to limit access to most of List's methods.


问:
Are there any actual examples of profitable programmer's "worker's cooperatives"?
http://en.wikipedia.org/wiki/Worker_cooperative

I'm curious whether there are, anywhere in the world, worker's cooperatives that center on a technology business that involves either programming, IT, or some sort of IT or programming related consulting or services.

The wikipedia link above is an overview of the concept. The short form explanation is that a co-op is a worker-owned business. Also there is the notion that every worker owns shares in the business.

I am interested in knowing whether an example of a "programmer's/IT co-op" even exists.

Note: I am not talking about nor asking about a government-funded incubator nor any other socialized, state supported group. I also don't mean "co-working", which is renting an office with other self employed people doing their own thing.

I mean a going, profitable IT business operating in a competitive environment that is worker-owned and run.

答:
From Wikipedia:

A worker cooperative, therefore, has
  the characteristic that the majority
  of its workforce own shares, and the
  majority of shares are owned by the
  workforce

Google.com qualifies

Almost all Google's employees own voting shares.

Most of Google's shares are owned by the employees.

The management structure is shallow, with lots of autonomy for most employees (never mind the 20% time).

Profit sharing is performed through bonuses and stock options, and, overall, closely matches company performance

Employees are welcome and actively encouraged to migrate between teams, roles and positions within the company, taking on all any and all of the required work

Food, clothing, free time, family, etc... are all actively coordinated between employees

It may not be the most extreme example of a worker's cooperative, but it's a darn good one.


答:
Another solution might be to define your wrapper class with a single method which exposes the list:

```<code>private static class SoundEventCell
{
    private List<SoundEvent> events;

    public SoundEventCell(List<SoundEvent> events)
    {
        this.events = events;
    }

    public List<SoundEvent> getEvents()
    {
        return events;
    }
}
</code>```

This gives you your well-named class with minimal code, but still gives you encapsulation, allowing you to e.g. make the class immutable (by doing a defensive copy in the constructor and using Collections.unmodifiableList in the accessor).

(However, if these lists are indeed only being used in this class, I think you'd do better to replace your Map<Double, List<SoundEvent>> with a Multimap<Double, SoundEvent> (docs), as that often saves a lot of null-checking logic and errors.)

Title: Is it overkill to wrap a collection in a simple class only for the sake of better readability?

Body:
I have the following map:

```<code>Map<Double, List<SoundEvent>> soundEventCells = new HashMap<Double, List<SoundEvent>>();
</code>```

This HashMap maps double values (which are points in time) to the corresponding SoundEvent 'cell': each 'cell' can contain a number of SoundEvents. That's why it's implemented as a List<SoundEvent>, because that's exactly what it is.

For the sake of better readability of the code, I thought about implementing a very simple static inner class like so:

```<code>private static class SoundEventCell {
    private List<SoundEvent> soundEvents = new ArrayList<SoundEvent>();
    public void addEvent(SoundEvent event){
        soundEvents.add(event);
    }
    public int getSize(){
        return soundEvents.size();
    }
    public SoundEvent getEvent(int index){
        return soundEvents.get(index);
    }
    // .. remove() method unneeded
}
</code>```

And than the map declaration (and a lot of other code) would look better, for example:

```<code>Map<Double, SoundEventCell> soundEventCells = new HashMap<Double, SoundEventCell>();
</code>```

Is this overkill? Would you do this in your projects?

Body:
Another solution might be to define your wrapper class with a single method which exposes the list:

private static class SoundEventCell
{
    private List<SoundEvent> events;

    public SoundEventCell(List<SoundEvent> events)
    {
        this.events = events;
    }

    public List<SoundEvent> getEvents()
    {
        return events;
    }
}

This gives you your well-named class with minimal code, but still gives you encapsulation, allowing you to e.g. make the class immutable (by doing a defensive copy in the constructor and using Collections.unmodifiableList in the accessor).

(However, if these lists are indeed only being used in this class, I think you'd do better to replace your Map<Double, List<SoundEvent>> with a Multimap<Double, SoundEvent> (docs), as that often saves a lot of null-checking logic and errors.)


答:
It's not overkill at all.  Start with the operations you need, rather than starting with "I can use a HashMap".  Sometimes a HashMap is just what you need.

In your case I suspect it isn't.  What you probably want to do is something like this:

```<code>public class EventsByTime {
    public EventsByTime addEvent(double time, SoundEvent e);
    public List<SoundEvent> getEvents(double time);
    // ... more methods specific to your use ...
}
</code>```

You definitely don't want to have a bunch of code saying this:

```<code>List<SoundEvent> events = eventMap.get(time);
if (events == null) {
   events = new ArrayList<SoundEvent>();
   eventMap.put(time, events);
}
</code>```

Or maybe you could just use one of the Guava Multimap implementations.

Body:
It's not overkill at all.  Start with the operations you need, rather than starting with "I can use a HashMap".  Sometimes a HashMap is just what you need.

In your case I suspect it isn't.  What you probably want to do is something like this:

public class EventsByTime {
    public EventsByTime addEvent(double time, SoundEvent e);
    public List<SoundEvent> getEvents(double time);
    // ... more methods specific to your use ...
}

You definitely don't want to have a bunch of code saying this:

List<SoundEvent> events = eventMap.get(time);
if (events == null) {
   events = new ArrayList<SoundEvent>();
   eventMap.put(time, events);
}

Or maybe you could just use one of the Guava Multimap implementations.


问:
What are the standards for having nested resources in REST API
I am designing a REST API and figured I'll just look at how others are naming their resources and choosing the routes.

I look at Twitter's API and see that they have nested resources. For example:

```<code>https://dev.twitter.com/rest/reference/get/statuses/retweets_of_me
</code>```

The resource is called retweets_of_me but it's also nested under statuses.

Does this mean that there is a logical association between the two resources? I can pick whatever routes I want to use but arbitrarily nesting routes probably isn't good practice.

答:
Using random routes...bad design.

In regards to nesting, lets take a use case where you have a set of users and a set of books, and a certain user can have multiple books associated

It would then make sense to have:

  /users
 - get users, you can use query params for pagination, sorting and filtering

/books - get books

/users/{user_id}/books - get the books associated to a certain user, thus having a natural nesting, reflected by your data model as well

This was just a simple example, hoped in helped, for a better understanding I would suggest googleing for something like rest api desing best practices, go over multiple sources and try to adapt something that feels ok to you and also makes sense from the app requirements point of view


答:
Is it a good idea to instruct bug-fixers to always look for the cause of their defect

Well, it is a really, really bad idea to fix defects without knowing the root cause. The problem is: you cannot force your team to always make a root cause analysis by instructing them, they have to train this.

and then evaluate the ratio of previous bug-fixes being such cause?

Evaluating such a ratio won't improve the situation. Instead, I suggest you take every bug as an occasion to work with your teammates on how to make your code more bullet-proof. So discuss with your colleagues: why was this bug introduced in the first place, and what could be done to prevent such a bug next time:

is the code too convoluted / not self-documenting enough?

can the code be refactored to make it cleaner?

was the usual code review forgotten?

is there a missing test case (in your unit tests or your checklist for the manual tests?)

...


问:
Undefined behavior, in principle
Whether in C or C++, I think that this illegal program, whose behavior according to the C or C++ standard is undefined, is interesting:

```<code>#include <stdio.h>

int foo() {
    int a;
    const int b = a;
    a = 555;
    return b;
}

void bar() {
    int x = 123;
    int y = 456;
}

int main() {
    bar();
    const int n1 = foo();
    const int n2 = foo();
    const int n3 = foo();
    printf("%d %d %d\n", n1, n2, n3);
    return 0;
}
</code>```

Output on my machine (after compilation without optimization):

```<code>123 555 555
</code>```

I think that this illegal program is interesting because it illustrates stack mechanics, because the very reason one uses C or C++ (instead of, say, Java) is to program close to the hardware, close to stack mechanics and the like.

However, on StackOverflow, when a questioner's code inadvertently reads from uninitialized storage, the most heavily upvoted answers invariably quote the C or C++ (especially C++) standard to the effect that the behavior is undefined.  This is true, of course, as far as the standard goes—the behavior is indeed undefined—but it is curious that alternate answers that try, from a hardware or stack-mechanical perspective, to investigate why a specific undefined behavior (such as the output above) might have occurred, are rare and tend to be ignored.

I even remember one answer that suggested that undefined behavior could include reformatting my hard drive.  I didn't worry too much about that, though, before running the program above.

My question is this:  Why is it more important to teach readers merely that behavior is undefined in C or C++, than it is to understand the undefined behavior?  I mean, if the reader understood the undefined behavior, then would he not be the more likely to avoid it?

My education happens to be in electrical engineering, and I work as a building-construction engineer, and the last time I had a job as a programmer per se was 1994, so I am curious to understand the perspective of users with more conventional, more recent software-development backgrounds.

答:
Why is it more important to teach readers merely that behavior is undefined in C or C++, than it is to understand the undefined behavior?

Because the specific behavior may not be repeatable, even from run to run without rebuilding.

Chasing down exactly what happened may be a useful academic exercise for better understanding the quirks of your particular platform, but from a coding perspective the only relevant lesson is "don't do that".  An expression like a++ * a++ is a coding error, full stop.  That's really all anyone needs to know.

OwnerDisplayName: thb

Title: Undefined behavior, in principle


答:
Standards can be ignored in the following circumstances:

When you have talked to your fellow developers and obtained agreement or you have set in place a policy is intended to be enforced or you your business decides that not following standards is the correct business decision (for example millions of dollars might be on the line for a fix "now" regardless of whether it conflicts with standards).

This will apply to rules if;

they have been ignored and abused to the point where a large portion of the code doesn't follow them.

there are several competing sets of standards, and it is not clear which to apply.

the local standard go against the industry standard, e.g. a company say we use 9 spaces to indent (!)

But even in the above 3 examples the GOLDEN rule is, whenever possible, you speak to everyone concerned FIRST.  At the very least (e.g. 2am fix) you should discuss your decision as soon as feasible - and discuss it, not just send out information about what you did.  Be prepared for criticism and to make changes.

Title: When, if ever, can code standards be ignored?

Body:
My company has decided to use stored procedures for everything dealing with the database (because they didn't know of any other way besides raw SQL), and as the saying goes "When in Rome..." so I try to follow.  Recently I had to add a hack fix that required grabbing a database value, and since it was a single value from a single table I wrote it as inline SQL (parameterized, of course) since there didn't seem to be a need for a stored procedure for one trivial line of code used in a single part of the application as a kludge.

Of course, I've now been told to fix it and only ever use Stored Procs for anything related to the database.  This feels just a bit too much like blindly following dogma instead of using common sense.  Don't get me wrong, I understand the purpose of having coding standards but I am also a proponent of ignoring standards when they don't make sense, not just blindly following them as though they were Gospel.


问:
API design: Giving the signin endpoint a noun name
Nouns are good and verbs are bad.

HTTP codes + the endpoint /user/123 can signify user create, read, update and delete operations. But what should the signin and signout endpoint be called?

How can i avoid method-driven-naming my API?

答: Depending on how your signin process works, the noun the client is requesting when they sign in might be something like a ticket or a session.


问:
When to not use dynamic in C#
I'm making a class similar to the following:

```<code>public class KeyValue
{
    public readonly string key;
    public readonly object value;
}
</code>```

Value could be of any object type as a result of this design.

Alternatively, I could just use dynamic for value and it'll make my life easier, because it would mean no type-casting, and also because, as far as I understand, I could use value types without needing to box/unbox.

Is there any reason not to use dynamic and to use object instead? Because I can't think of any.

Note: I realize generics are much more suited for this, but it doesn't work for my needs. The above is really a simplification just for the purposes of this question.

答:
dynamic was primarily introduced as a way to allow C# to interop with languages such as Python, which is not statically typed.  If you are using it out of this context you are probably forgoing functionality.

As you said, in the limited context that you present, you are much better off using generics (the KeyValuePair class looks pretty much like what you are trying to create here).

Title: When to not use dynamic in C#


问:
Should I be writing feature or request specs?
I've been writing model specs for a while now and I'm gradually moving towards integration testing. Right now, I'm looking at the best way to test the output of my ActiveAdmin dashboard but I'm unsure which is the best type of spec for the job.

My dashboard contains two tables which summarise yesterday's and today's orders. Really, this is a simple case of asserting that the response contains certain content given some existing orders.

So far, the spec types I've looked at are:

controller: I'm not testing the controller (AA already does this).

view: I'm not testing a view file so this is not relevant.

feature: doesn't feel right because I'm not testing user interaction. However, having Capybara available is very useful because I'd like to use matchers such as has_content.

request: This seems like the most relevant because I'm testing the result of a single request rather than user interaction. However, RSpec Rails has removed Capybara support for this spec type.

In a "traditional" scenario I'd be able to test the individual components, i.e. view and controller, with their own spec types. But, in this scenario, I'm testing the output of a configurable plugin where I don't "own" the view-controller part of the stack.

My dilemma is: Is it acceptable to write feature specs which merely test rendered output without testing user interactions? Or should I be writing request specs and foregoing the convenience of Capybara's matchers? It seems a catch 22 but there must be a good reason for Capybara support being removed from request specs.

Relevant versions:

Rails 4.1.6

RSpec 3.1.0

RSpec Rails 3.1.0

Capybara 2.4.1

答:
Request specs have fallen very much out of favour, and for good reason.

Feature specs are likely the way to go for testing this type of functionality. There is user interaction - you're visiting or navigating to a page in your app.

However, if this is all just ActiveAdmin code, why are you testing it at all? Maybe one smoke test just to hit a URL and make sure it doesn't explode, but I wouldn't be going into the nitty-gritty of testing AA at all.

OwnerDisplayName: tristanm


问:
In layman's terms, what is left recursion?
According to one page on code.google.com, "left recursion" is defined as follows:

Left recursion just refers to any recursive nonterminal that, when it produces a sentential form containing itself, that new copy of itself appears on the left of the production rule.

Wikipedia offers two different definitions:

In terms of context-free grammar, a non-terminal r is left-recursive if the left-most symbol in any of r’s productions (‘alternatives’) either immediately (direct/immediate left-recursive) or through some other non-terminal definitions (indirect/hidden left-recursive) rewrites to r again.

"A grammar is left-recursive if we can find some non-terminal A which will eventually derive a sentential form with itself as the left-symbol."

I'm just barely starting out with language creation here, and I'm doing it in my spare time.  However when it comes down to selecting a language parser, whether left recursion is supported by this parser or that parser is an issue that immediately comes up front and center.  Looking up terms like "sentential form" only leads to further lists of jargon, but the distinction of "left" recursion almost has to be something very simple.  Translation please?

答:
I'll take a stab at putting it into layman's terms.

If you think in terms of the parse tree (not the AST, but the parser's visitation and expansion of the input), left recursion results in a tree that grows left and downwards. Right recursion is exactly the opposite.

As an example, a common grammar in a compiler is a list of items. Lets take a list of strings ("red", "green", "blue") and parse it. I could write the grammar a few ways. The following examples are directly left or right recursive, respectively:

```<code>arg_list:                           arg_list:
      STRING                              STRING
    | arg_list ',' STRING               | STRING ',' arg_list
</code>```

The trees for these parse:

```<code>         (arg_list)                       (arg_list)
          /      \                         /      \
      (arg_list)  BLUE                  RED     (arg_list)
       /       \                                 /      \
   (arg_list) GREEN                          GREEN    (arg_list)
    /                                                  /
 RED                                                BLUE
</code>```

Note how it grows in the direction of the recursion.

This isn't really a problem, it is ok to want to write a left recursive grammar...if your parser tool can handle it. Bottom up parsers handle it just fine. So can more modern LL parsers. The problem with recursive grammars isn't recursion, it is recursion without advancing the parser, or, recursing without consuming a token. If we always consume at least 1 token when we recurse, we eventually reach the end of the parse. Left recursion is defined as recursing without consuming, which is an infinite loop.

This limitation is purely an implementation detail of implementing a grammar with a naive top-down LL parser (recursive descent parser). If you want to stick with left recursive grammars, you can deal with it by rewriting the production to consume at least 1 token before recursing, so this ensures we never get stuck in non-productive loop. For any grammar rule that is left-recursive, we can rewrite it by adding an intermediate rule that flattens out the grammar to just one level of lookahead, consuming a token between the recursive productions. (NOTE: I'm not saying this is the only way or the preferred way to rewrite the grammar, just pointing out the generalized rule. IN this simple example, the best option is to use the right-recursive form). Since this approach is generalized, a parser generator can implement it without involving the programmer (theoretically). In practice, I believe ANTLR 4 now does just that.

For the grammar above, the LL implementation displaying left recursion would look like this. The parser would start with predicting a list...

```<code>bool match_list()
{
    if(lookahead-predicts-something-besides-comma) {
       match_STRING();
    } else if(lookahead-is-comma) {
       match_list();   // left-recursion, infinite loop/stack overflow
       match(',');
       match_STRING();
    } else {
       throw new ParseException();
    }
}
</code>```

In reality, what we are really dealing with is "naive implementation", ie. we initially predicated a given sentence, then recursively called the function for that prediction, and that function naively calls the same prediction again.

Bottom up parsers do not have the problem of recursive rules in either direction, because they don't reparse the beginning of a sentence, they work by putting the sentence back together.

Recursion in a grammar is only a problem if we produce from top down, ie. our parser works by "expanding" our predictions as we consume tokens. If instead of expanding, we collapse (productions are "reduced"), as in a LALR (Yacc/Bison) bottom up parser, then recursion of either side isn't a problem.

Body:
I'll take a stab at putting it into layman's terms.

If you think in terms of the parse tree (not the AST, but the parser's visitation and expansion of the input), left recursion results in a tree that grows left and downwards. Right recursion is exactly the opposite.

As an example, a common grammar in a compiler is a list of items. Lets take a list of strings ("red", "green", "blue") and parse it. I could write the grammar a few ways. The following examples are directly left or right recursive, respectively:

arg_list:                           arg_list:
      STRING                              STRING
    | arg_list ',' STRING               | STRING ',' arg_list

The trees for these parse:

         (arg_list)                       (arg_list)
          /      \                         /      \
      (arg_list)  BLUE                  RED     (arg_list)
       /       \                                 /      \
   (arg_list) GREEN                          GREEN    (arg_list)
    /                                                  /
 RED                                                BLUE

Note how it grows in the direction of the recursion.

This isn't really a problem, it is ok to want to write a left recursive grammar...if your parser tool can handle it. Bottom up parsers handle it just fine. So can more modern LL parsers. The problem with recursive grammars isn't recursion, it is recursion without advancing the parser, or, recursing without consuming a token. If we always consume at least 1 token when we recurse, we eventually reach the end of the parse. Left recursion is defined as recursing without consuming, which is an infinite loop.

This limitation is purely an implementation detail of implementing a grammar with a naive top-down LL parser (recursive descent parser). If you want to stick with left recursive grammars, you can deal with it by rewriting the production to consume at least 1 token before recursing, so this ensures we never get stuck in non-productive loop. For any grammar rule that is left-recursive, we can rewrite it by adding an intermediate rule that flattens out the grammar to just one level of lookahead, consuming a token between the recursive productions. (NOTE: I'm not saying this is the only way or the preferred way to rewrite the grammar, just pointing out the generalized rule. IN this simple example, the best option is to use the right-recursive form). Since this approach is generalized, a parser generator can implement it without involving the programmer (theoretically). In practice, I believe ANTLR 4 now does just that.

For the grammar above, the LL implementation displaying left recursion would look like this. The parser would start with predicting a list...

bool match_list()
{
    if(lookahead-predicts-something-besides-comma) {
       match_STRING();
    } else if(lookahead-is-comma) {
       match_list();   // left-recursion, infinite loop/stack overflow
       match(',');
       match_STRING();
    } else {
       throw new ParseException();
    }
}

In reality, what we are really dealing with is "naive implementation", ie. we initially predicated a given sentence, then recursively called the function for that prediction, and that function naively calls the same prediction again.

Bottom up parsers do not have the problem of recursive rules in either direction, because they don't reparse the beginning of a sentence, they work by putting the sentence back together.

Recursion in a grammar is only a problem if we produce from top down, ie. our parser works by "expanding" our predictions as we consume tokens. If instead of expanding, we collapse (productions are "reduced"), as in a LALR (Yacc/Bison) bottom up parser, then recursion of either side isn't a problem.


答:
The answer is that if dynamic types make your code better, produce a better outcome and make your life easier then of course you should use them. That's what they're for!

You should absolutely not concern yourself with boxing/unboxing, which is pretty efficient apart from imposing some load on the garbage collector. Look at the generated code for dynamic types and you'll see significantly higher overheads, but you shouldn't worry about those either.

The challenge in this game is to produce correct code that you and other people can understand and work with. Use generics if you can, dynamic if it works for you and raw objects if you have to. Then benchmark before you optimise. Or just move on.

Title: When to not use dynamic in C#

Body:
I'm making a class similar to the following:

```<code>public class KeyValue
{
    public readonly string key;
    public readonly object value;
}
</code>```

Value could be of any object type as a result of this design.

Alternatively, I could just use dynamic for value and it'll make my life easier, because it would mean no type-casting, and also because, as far as I understand, I could use value types without needing to box/unbox.

Is there any reason not to use dynamic and to use object instead? Because I can't think of any.

Note: I realize generics are much more suited for this, but it doesn't work for my needs. The above is really a simplification just for the purposes of this question.


答:
If you're using object as a variable type, and you're really sure that you need to, and you're really sure that generics won't do what you need, there is one and a half scenarios that I've encountered where you should not use dynamic:

You need to deploy to old machines. Dynamic is only available with .NET 4.0, so if you need to support machines that aren't guaranteed to have it... just use object.

And along similar lines, Xamarin (as of a few months ago when I was keeping track of it) did not yet have stable support for dynamics. This kinda falls in with #1 - essentially, if your target platform doesn't support them, then don't use them.

That's variables though. dynamic as a function parameter causes the function to be dynamically dispatched. This is usually what you want, but not always. Using object will use normal instance-only dispatch. Otherwise, the same guidelines apply.

Title: When to not use dynamic in C#


答:
If you can't think of a good reason TO use dynamic, then you are foregoing potential compile time checks for little to nothing in return.

I prefer generics over object, and prefer object over dynamic, unless I need to interact with a dynamic language ScriptEngine or a dynamic container like a web form where its reasonable to handle the potential runtime exceptions when I access a missing field. Generics will perform best; and with object, you are at least signifying your intentions are to store any sort of object in the same container.

Dynamic is not an actual type, and it isn't "object" so it should never be used to mean "any sort of object", it should actually be used when you know what the object's contract is (method/property signature's); it is a runtime dispatch vehicle for keeping the same, convenient syntax for a type-unsafe (or at least dynamically bound) activity. It's like saying:

"OK, I know the activity I'm doing is subject to runtime dispatch and
  runtime errors, so give me the syntactical sugar anyway"

When I see dynamic, I usually assume there is an imminent:

method call dispatch to a dynamically bound type (like an IronPython variable)

access to dynamic form data with property syntax in an MVC controller

Though another legit use for it is to use the dynamic dispatch capability to implement the Visitor Pattern, although traditional virtual methods are likely faster.

```<code>class FooVisitor {
     void Accept(Expression node) { ... }
     void Accept(Statement node) { ... }
}

foreach(dynamic node in ASTNodes) {
    visitor.Accept(obj);  // will be dispatched at runtime based on type of each obj
}
</code>```

Don't use it when:

Performance is number one priority.

Static type checking is desirable for more robust runtime

The types can be derived at compile time

A generic type will do

If used unnecessarily, dynamic can actually reduce the robustness of your code by changing C# to a dynamic scripting language.

Title: When to not use dynamic in C#

Body:
If you can't think of a good reason TO use dynamic, then you are foregoing potential compile time checks for little to nothing in return.

I prefer generics over object, and prefer object over dynamic, unless I need to interact with a dynamic language ScriptEngine or a dynamic container like a web form where its reasonable to handle the potential runtime exceptions when I access a missing field. Generics will perform best; and with object, you are at least signifying your intentions are to store any sort of object in the same container.

Dynamic is not an actual type, and it isn't "object" so it should never be used to mean "any sort of object", it should actually be used when you know what the object's contract is (method/property signature's); it is a runtime dispatch vehicle for keeping the same, convenient syntax for a type-unsafe (or at least dynamically bound) activity. It's like saying:

"OK, I know the activity I'm doing is subject to runtime dispatch and
  runtime errors, so give me the syntactical sugar anyway"

When I see dynamic, I usually assume there is an imminent:

method call dispatch to a dynamically bound type (like an IronPython variable)

access to dynamic form data with property syntax in an MVC controller

Though another legit use for it is to use the dynamic dispatch capability to implement the Visitor Pattern, although traditional virtual methods are likely faster.

class FooVisitor {
     void Accept(Expression node) { ... }
     void Accept(Statement node) { ... }
}

foreach(dynamic node in ASTNodes) {
    visitor.Accept(obj);  // will be dispatched at runtime based on type of each obj
}

Don't use it when:

Performance is number one priority.

Static type checking is desirable for more robust runtime

The types can be derived at compile time

A generic type will do

If used unnecessarily, dynamic can actually reduce the robustness of your code by changing C# to a dynamic scripting language.

ContentLicense: CC BY-SA 4.0


问:
How to enable non technical users to use GitHub
We're currently storing two Dynamic CRM solutions in Github and have triggers to automatically deploy these solutions once a change has been pushed to the master branch.

This works really well in the development world, but we'd now like to hand over the system to relatively non technical users who will make system changes via a GUI and will then need to upload files to GIT.

GitHub doesn't allow the manual uploading of files. Is there a easy way to upload files to GitHub without using Git?

Update: The GIT workflow can be difficult to understand especially if have not worked with source control before. Our users may be able to push changes, but the first time a merge is required, the workflow would fall over. Ideally I'm looking for something with an interface like a SharePoint document library, e.g. a very simple upload and replace control.

答:
To upload into a git repository, at some level you have to use git. But, you don't have to expose git directly to the users. You can write your own code that handles the git operations behind the scenes and presents a simpler system to the users.

See: https://libgit2.github.com/ for library that would let you make git calls.

Of course, that means you'd have to write the tools to provide the workflow for your users. I don't know of any system that already provides it.


问:
Java Desktop Application Requirement - Is sockets the preferred choice ?
I'm currently working on a requirement for a desktop application - using Java

If for some reason the GUI crashes, it shouldn't affect the background
  process. Once the GUI is restarted - the execution status along
  with the log messages should be given back to GUI.

Desktop application is built for both windows & ubuntu 12.04.

As per my knowledge in Java, this could be achieved using Sockets. Keeping GUI as client, and executing background code in a Server.( But again i'm still trying to understand how the server stays alive if the GUI crashes, - I mean if server is started from the GUI instance @ any point, and if the GUI crashes, the server is dead too, bcz it still belongs to the same JVM instance, right ? )

The question really comes down to - how to start a server(tcp) in a new process from the gui instance. Can someone throw some light on - how to implement this requirement?

答:
Your problem can be solved if you use RMI in java.

RMI is Remote Method Invocation.

In this what you can do is , you can create two applications.one for GUI and another Server(where your actual process(functions) is existed). GUI can communicate with server
via method calling with parameter pacing if necessary.But both application independent from each other. For your case this will work. Because if GUI(client) crash nothing happen to Server since it is independent from client execution. once you restart the client you can find the server and continue the works. But in case if server crashed then you have to restart both client and server. These application can be run in same JVM or separate JVMs . Anyway you have to use IP addresses to configure communication. I can give you small executable app(both apps client and server) if you want.

thanks.


问:
Would you allow your programmers to use Messenger and social networks like Facebook?
I had many bosses, each one had a different approach about allowing or not use of Windows Live Messenger, Facebook, and many other Internet sites.

Of course Internet is really needed to research about the best way to solve a specific task. Sometimes you could have a friend online, also a programmer, who knows better about something.

For some managers, internet access would slow down project progress, and on the other hand, allow people to interact and find out brand new solutions.

What would you do?

答: A solution such as www.workmeter.com could be of help, this allows the entreprise adopt a liberal policy while keeping programmers self conscious of their productivity. Allowing people handle and review their data enhances their time management self consciousness, they become aware about their online habits and tend to correct them (otherwise, as a monitoring solution, allows the manager to keep an eye on bad practices)</p>

OwnerDisplayName: Iago Tomàs


问:
What is the difference between if('' == $variable) and if($variable == '')
While using an 'if' statement to check whether a variable is an empty string or not we can write it in two ways i.e. if('' == $variable) and if($variable == ''). I want to know what is the impact of above in different cases?

Thanks in advance!!

答:
In a modern language, you should be writing your conditions of the form if($variable == "").  This makes the condition easier to read for natural English speakers.

In a legacy language, it sometimes was considered good practice to use the form if("" == $variable) as if you used the more natural form it was possible to create compilable and runnable code which was bugged if you accidentally missed one of the '=' symbols.

Now, most compilers, even for these older languages, will at least warn you if you accidentally miss the '=' symbol.

TL;DR; - use if($variable == "")


答:
This highly depends on the language used!

If == is implemented as a method in an object oriented language then the construct if ($variable == "") could lead to an exception because the object ($variable) might not be initialized or even null.

If you reverse the expression (if ("" == $variable)) then you can be sure that the object acted on ("" is always initialized and never null).

As an example in Java (where the method is called .equals()):

```<code>string.equals("")
</code>```

can cause a NullPointerException because the object string may be null.

```<code>"".equals(string)
</code>```

cannot lead to a NullPointerException as the object "" is never null.

If == is not a method of an object then it does not matter which order is used.

I think that many programmers with such a background use the expression if ("" == $variable) because they are more familiar with it.

Title: What is the difference between if('' == $variable) and if($variable == '')

Body:
While using an 'if' statement to check whether a variable is an empty string or not we can write it in two ways i.e. if('' == $variable) and if($variable == ''). I want to know what is the impact of above in different cases?

Thanks in advance!!

Body:
This highly depends on the language used!

If == is implemented as a method in an object oriented language then the construct if ($variable == "") could lead to an exception because the object ($variable) might not be initialized or even null.

If you reverse the expression (if ("" == $variable)) then you can be sure that the object acted on ("" is always initialized and never null).

As an example in Java (where the method is called .equals()):

string.equals("")

can cause a NullPointerException because the object string may be null.

"".equals(string)

cannot lead to a NullPointerException as the object "" is never null.

If == is not a method of an object then it does not matter which order is used.

I think that many programmers with such a background use the expression if ("" == $variable) because they are more familiar with it.


问:
Security in an iOS game?
I'm part of a team building an iOS game which has multiplayer elements.

A concern right now is how to make the game more secure, from user manipulation. I know there's a lot of multiplayer games out there, and so there must be techniques they use to make their games more secure.

An example of a scenario is if the saved game is being stored on the local device. Is there some method we can use - perhaps encryption or something else, that can stop the user from being able to just generate their own saves?

Or when making a call to a method, similar to 'createItem:', they could add something to their game that they shouldn't be able to. I'm wondering how other iOS games prevent such activity?

答:
You will need to have code on the server that detects attempts at tampering and deals with them.

So don't calculate whether that gun hit something on the client, don't calculate how much damage that sword did on the client, don't even calculate whether your user sees something on the client. Do ALL of that on the server, the client is only for displaying data and generating input.

Also don't let the client tell the server "I moved 5 meters forward". No, let the client tell the server "move forward for 2 seconds" and then the server calculates how far that is, or if it's even possible (prevents speed hacks and people walking through solid obstacles).

That's just a few things you should do, I'm sure you can think of a lot more yourself based on what your game is going to do.

Title: Security in an iOS game?


问:
Given a number X, how do I find from an array of numbers, a unique combination that adds up to X and has the lowest sum of squares?
Given the number 15 and the array [1, 2, 3, 4, 5, 6]

Possible combinations (sum=15) would be:

[1, 2, 3, 4, 5]

[2, 3, 4, 6]

[1, 3, 5, 6]

[4, 5, 6]

Their respective sum of squares would be:

55, 65, 71 and 77

Any number in the array can only be used once in any of the number combinations (no repeating numbers). The solution would be the number combination with the smallest sum of squares (i.e. 55)

What could be an efficient logic to solve this problem?

So far, I've tried this:

Nested for loops:

```<code>for (j=0; j<arrLength; j++){
    sum = 0;
    for (i=j; i<arrLength; i++){
        sum+=arrNumbers[i];
        if (sum >= 15) {break;}
    }
}
if (sum == 15) {
    for(j=j; j<=i; j++){
    printf("%d ", arrNumbers[j]);
}
</code>```

However, that doesn't always give the correct results because it only checks number combinations in succession (e.g. [1, 2, 3], [2, 3, 4], [3, 4, 5])

After that, I tried this:

```<code>for (j=0; j<arrLength; j++){
    sum = 0;
    for (k=j; k<arrLength; k++){
        if (sum == 15) {break;}
        sum=arrNumbers[j];
        for (i=k+1; i<arrLength; i++){
            sum+=arrNumbers[i];
            if (sum >= 15) {break;}
        }
    }
    if (sum >= 15) {break;}
}
if(sum==15){
    //print number combinations here
}
</code>```

That didn't work either as I learnt later that it isn't quite different from the first solution and my logic is flawed.

What I'm having trouble with is trying to think of a logic that iterates through all the numbers in the array (regardless of order) to find combinations that add up to the number 15.

For instance, my code can find these combinations if they are in sequential order [1, 2, 3, 4, 5] or [4, 5, 6] but it can't find something like [1, 3, 5, 6].

答:
One possible approach is to generate all combinations (or subsets) of the array (google for "generate combinations c" or "generate subsets c" and you will find plenty of examples).

Then you add up the elements of each combination, check if the sum is equal to 15, and if that's true, keep the combination for the "lowest sum of squares" test.

The drawback of this approach is that if you try to process bigger arrays, it becomes very slow. For an array of size n, there are 2^n possible combinations. For n=6, this is ok, for n=100, you will have to wait forever.

So if you are after a more efficient algorithm, I suggest you try a recursive approach. The subsets of a set of elements a1,...a_n can be divided into the ones containing a_n and those not containing a_n. Thus the subsets with a specific sum s are formed by

the subsets of a1,...a_(n-1) summing up to s

the subsets of a1,...a_(n-1) summing up to s - a_n, combined with the element a_n

This recursive process can be stopped when s becomes 0 or negative, or the total sum of the remaining a1,...a_k elements becomes less than s, or when s is greater 0, but the smallest element a_1 is greater than s.

I would expect this recursive approach to be much faster for bigger arrays.


问:
Is there a chart for helping me decide between open-source licenses?
The Open Source Initiative lists 9 different licenses in their list of "License that are popular and widely used or with strong communities".

I want to license my project as open-source. Unfortunately, I do not speak legalese. Is there some chart I could consult that will help me make the right choice, or at least point me in the right direction? For example a table summarizing the differences between the licenses, or perhaps a flow-graph using my requirements to guide me into the correct license for me?

I also intend to meet a lawyer, but any information to start with will help.

答:
There's a simplified explanation for many licenses available on NRecursions (there are more licenses on the blog. Listed a few below).

Copyleft license: You can use, modify and distribute the license
under the same or equivalent license, but you should also share the
source code.

Berkely Software Distribution license (BSD): You can combine the
software with your proprietary software and release it under a
proprietary license, but you have to retain the BSD license text and
notices. This license may also have one or two more clauses about
using the author's name or advertising.

Gnu Public License (GPL): You can use, modify and distribute the
software for free or for a fee, but you have to also distribute the
source code with it, and if the software is combined with other
software, that software will also have to be released as GPL, unless
it is not an aggregate (it does not interact with the GPL software)

Lesser Gnu Public License (LGPL): Same as GPL, but you're allowed to
link your proprietary software with LGPL software and release it
under your terms. But there are some conditions under which you can
do so.

Affero Gnu Public License (AGPL): Same as GPL, but it additionally
says that your software is considered as having been distributed, if
someone else is able to use it (like if you keep it on a server and
they can run it from the server).

Massachusetts Institute of Technology license (MIT): You are allowed
to use, modify and distribute copies of the software as long as you
allow the same rights to the person to whom you distribute the
software

Apache License: If you follow the Apache license, you're allowed to
use, modify and distribute copies of the software, and you can add
your own copyright statement to the changes you make. You can also
provide additional or different license terms and conditions for use,
reproduction or distribution of your modifications.

Mozilla Public License (MPL): You can use, modify, distribute and
sell the software, provided you also give the recipient the source
code. You can also sub-license the modified work, provided you don't
restrict the recipients rights to the source code.


问:
What kinds of non-source artifacts are vital to your development process?
The "classic" development artifacts are requirements documents and design specifications. But the development process includes many other non-source code artifacts: bug tracking databases, emails, wikis.

What kinds of non-source code artifacts do you think are most vital to your development process? And how do you keep these documents up to date?

Also, are there any artifacts that you don't necessarily find useful, but have to use because it's required by the contractor or management?

答:
(UI Mockup) Wireframe and Compositions

Required by contract. In order to qualify, the company needs to hire user-experience (UX), human-computer interaction (HCI), and graphic designers who can furnish those artifacts, and signed off by the DBA, in the first milestone.


问:
How to responsibly handle license mistakes?
Say I push to a public repository an original file that I cover under a specific license. I later (or even immediately) find out that this license is incompatible with other licenses in the project. (Say one is the GNU GPL and the other is something incompatible with it.) I would like to know how I should responsibly and professionally handle mistakes like these.

If this mistake simply means that this particular project snapshot is technically against license for other people to build, then I imagine the responsible thing to do is push a new version of the file to add a second, compatible license or altogether replace the first license with a compatible one.

On the other hand, if it's against license to be distributing this snapshot even in source form (and having them in the repository history is, technically, "distributing"), I imagine I should additionally attempt (or ask the repository owner, when it's not me) to clear that particular commit from history.

Which of the above is closer to the truth? And are the implications/actions that I'm describing in each case correct?

答:
If you have files with incompatible licenses in your project, then it is a license violation. This means that you do not have the right to distribute the project in that state.

The responsible actions to take when such a license violation is detected depend on who owns the copyright to the various parts.

The easiest fix, which should always be possible, is to remove the files (or library) that cause the license violation.

If you are the sole copyright holder of the files that cause the violation, you could change the license on those files to a license that is compatible with the other licenses.

If you are not the copyright holder, or there are multiple copyright holder, you will need to get explicit agreement from all of them to change a license.

You are probably not required to rewrite history on the archive, but if you provide downloads outside of the repository (for example, binaries for various platforms), you should ensure that the version with license violations is no longer available.


答:
Source code edit history

(especially if linked to use case and bug tracker)

Title: What kinds of non-source artifacts are vital to your development process?

Body:
The "classic" development artifacts are requirements documents and design specifications. But the development process includes many other non-source code artifacts: bug tracking databases, emails, wikis.

What kinds of non-source code artifacts do you think are most vital to your development process? And how do you keep these documents up to date?

Also, are there any artifacts that you don't necessarily find useful, but have to use because it's required by the contractor or management?


答:
What could be an efficient logic to solve this problem?

There aren't any. Even the first part of your question, "Given a number X, find a subset that sums to it", is NP-Complete. If you could find an efficient algorithm to solve this problem, you'd be in line for a Nobel prize.

Title: Given a number X, how do I find from an array of numbers, a unique combination that adds up to X and has the lowest sum of squares?

Body:
Given the number 15 and the array [1, 2, 3, 4, 5, 6]

Possible combinations (sum=15) would be:

[1, 2, 3, 4, 5]

[2, 3, 4, 6]

[1, 3, 5, 6]

[4, 5, 6]

Their respective sum of squares would be:

55, 65, 71 and 77

Any number in the array can only be used once in any of the number combinations (no repeating numbers). The solution would be the number combination with the smallest sum of squares (i.e. 55)

What could be an efficient logic to solve this problem?

So far, I've tried this:

Nested for loops:

```<code>for (j=0; j<arrLength; j++){
    sum = 0;
    for (i=j; i<arrLength; i++){
        sum+=arrNumbers[i];
        if (sum >= 15) {break;}
    }
}
if (sum == 15) {
    for(j=j; j<=i; j++){
    printf("%d ", arrNumbers[j]);
}
</code>```

However, that doesn't always give the correct results because it only checks number combinations in succession (e.g. [1, 2, 3], [2, 3, 4], [3, 4, 5])

After that, I tried this:

```<code>for (j=0; j<arrLength; j++){
    sum = 0;
    for (k=j; k<arrLength; k++){
        if (sum == 15) {break;}
        sum=arrNumbers[j];
        for (i=k+1; i<arrLength; i++){
            sum+=arrNumbers[i];
            if (sum >= 15) {break;}
        }
    }
    if (sum >= 15) {break;}
}
if(sum==15){
    //print number combinations here
}
</code>```

That didn't work either as I learnt later that it isn't quite different from the first solution and my logic is flawed.

What I'm having trouble with is trying to think of a logic that iterates through all the numbers in the array (regardless of order) to find combinations that add up to the number 15.

For instance, my code can find these combinations if they are in sequential order [1, 2, 3, 4, 5] or [4, 5, 6] but it can't find something like [1, 3, 5, 6].


问:
Why do IoC containers provide public Resolve method(s)?
In my opinion it just inverses the inversion and could make new users (including myself) make incorrect assumptions about using IoC containers.

It can be used for the Service Locator (anti-)pattern of course, but it doesn't sound like a strong reason to me (can be a separate class in the end of the day).

There probably will be at least one call to get the root object to start the program, but it could be named and designed (signature and contract) accordingly to avoid calling it for more than one reason.

I am more interested in single-point of entry "classic" apps rather than server-side web apps.

答:
DI containers are tools and tools can be used in many ways, which may be correct or incorrect. An axe is designed to chop wood, but it can also chop the neighbor's tree cause its leaves are falling on axe owner's lawn. The axe doesn't know how it's being used. But it still needs to cut.

Same goes for DI containers. Their creators don't know all the possible scenarios of how their tool will be used. It's easier for them to tell you how to use it properly, rather than prevent you from doing the things deemed as incorrect uses of the tool.  Resolve is the feature that does the cutting, in this case. If you choose to misuse it, it's your choice.


答:
Even if service locator pattern is an anti pattern it sometimes useful. Say you are using event sourcing where you can have multiple event handlers for an event. Say

```<code>IHandleEvent<T>
</code>```

Multiple classes can handle the same event. When the user logs in you are tasked with instantiating all classes that implement. Also you have a large number of events in your system and T is not known until runtime.

```<code>IHandleEvent<UserLoggedIn>
</code>```

In this case you can ask your ioc container for all implementations of the interface.
Alternatively you can duplicate lots of the functionality in an ioc container. Obviously the first approach is easiest to implement.

Sometimes advanced scenarios of the tools are useful.

Title: Why do IoC containers provide public Resolve method(s)?

Body:
In my opinion it just inverses the inversion and could make new users (including myself) make incorrect assumptions about using IoC containers.

It can be used for the Service Locator (anti-)pattern of course, but it doesn't sound like a strong reason to me (can be a separate class in the end of the day).

There probably will be at least one call to get the root object to start the program, but it could be named and designed (signature and contract) accordingly to avoid calling it for more than one reason.

I am more interested in single-point of entry "classic" apps rather than server-side web apps.

Body:
Even if service locator pattern is an anti pattern it sometimes useful. Say you are using event sourcing where you can have multiple event handlers for an event. Say

IHandleEvent<T>

Multiple classes can handle the same event. When the user logs in you are tasked with instantiating all classes that implement. Also you have a large number of events in your system and T is not known until runtime.

IHandleEvent<UserLoggedIn>

In this case you can ask your ioc container for all implementations of the interface.
Alternatively you can duplicate lots of the functionality in an ioc container. Obviously the first approach is easiest to implement.

Sometimes advanced scenarios of the tools are useful.