问:
Handing Off A Unity Project
I have someone who wants me to develop a game for them. I do not intend to continue developing the game after its first release (he wants me to develop it for commercial use). To make the project easy, I was thinking of using the Unity game engine. I am going to say right now, I am a kid heading into college, he wants to pay me, but I don't want to be paid, and this is for his own personal business endeavor, I am afraid if I hand off this project to a more established professional, even if I use source control, he will disregard it, throw it away, and the part I am most afraid of tell him I did a cruddy or lazy job (because I used Unity). What are your opinions on this situation, and the use of Unity in this way?</p>

答:
With the exception of people sunk in the real programmer syndrome, no one is going to disregard you for using Unity. Unity is a framework, like many others, that helps you make software. Saying that using 3rd frameworks and libraries is being lazy is like saying that driving(or using public transport) to work instead of walking is being lazy. While that might be true, you need to do it if you want to get there in time and stay long enough to actually do something before you need to get back. The time you save by not walking is used for being productive - which makes it a nice analogy for using frameworks and libraries.

As for doing a "cruddy" job - that's expectable. Like you said - you are "a kid heading into college" - no one expect you to do a top quality job. After you graduate, when you look back at that project, if you won't be able to think that this is a crappy project created by an idiot programmer I would say your college wasn't doing a very good job(assuming you are learning computer science or software engineering).

The only people that will hate you(not laugh - hate!) for doing a bad job are the ones tasked with maintaining it. But while you should try and be considerate toward the people who'll have to deal with your code in the future(high chances it'll be future you), this should not stop you from coding, because it's hard to improve without working on actual projects and making actual mistakes that'll come back to bite you and by doing so teach you the best lessons you can possibly learn. Your (non) employer might suffer from this if they ever want to continue the work on that game, but you shouldn't feel bad about that because you gave them that game for free.

Which leads us to the next topic - why are you giving them that game for free? Yes, you said they want to pay you and you are the one who want to work for free, and while there might be some drawbacks for getting paid(like being as obliged to the project's deadlines and quality), it still doesn't explain what you gain from working for free.

Now, I'm not saying you shouldn't make this game for free - I'm saying you shouldn't make this game for free for them. You are the one doing all the work - you don't need them to make that game. Even if you want to make that game for your portfolio, or for experience, or just for fun, that still doesn't explain why you should hand that project to someone else that'll make money out of it without you seeing a dime. Why shouldn't you keep the copyrights to that project, and be able to license and distribute it as you please?

Title: Handing Off A Unity Project


问:
w3c library license: does it prevent the inclusion in/distribution with paid software?
From W3C Software Notice and License:

Permission to copy, modify, and distribute this software and its documentation, with or without modification, for any purpose and without fee or royalty is hereby granted

My app depends on the xml-apis 1.4.01 library that in turn includes W3C software and I need to distribute it along with my non-free app. I am not explicitly charging for the included xml-apis/W3C components. Does the stated license statement exclude such a paid distribution?

Don't answer if you are not aware of the GPL linking exception.

答:
Speaking as a layman, not a lawyer, the answer is that it doesn't forbid that.  The key phrase is "for any purpose".  This is plain, simple legal english.

Also ... consider the context.  Why would the W3C forbid use of their code in commercial software?  It is not in their remit to push the "libre source" philosophy.  It would be counter-productive to their goals as an organization .... which is the interoperability of web software, irrespective of how it was written or made available to users.

However if (hypothetically) you were to charge customers for the W3C material, you would (IMO) be stepping outside of the rights granted by the license.  It grants you the right to copy, modify, distribute etc, without fee or royalty ...

Note: I'm not a lawyer.  If you have doubts about this, consult a professional; i.e. a lawyer who understands copyright law ... in the jurisdictions that apply to you.

(Or you could just email the W3C and ask them if you are permitted to do what you want to do.)

ContentLicense: CC BY-SA 3.0


问:
Is it good practice to declare and set properties in abstract classes?
I am using PHP and designing some abstract classes.

I can declare properties with constant values within my abstract class and access/overwrite them from any class which extends this without re declaring them within any of the extending classes.

A benefit to this is less repetitive typing but the downside that overtime the original structure/layout of these abstract properties is forgotten and could be left at there default static values or even forgotten(not used) completely.

How is this handled in professional environments? I assume this has been thought out before and is either favored or isn't?

I am trying to adhere to good OOP principles/rules such as SOLID, DRY and KISS but I haven't seen this specific issue talked about in these. (perhaps I missed it when researching?)

答:
If you keep your inheritance shallow (the opposite of lasagna) then there is nothing philosophically wrong with putting properties in an abstract class. The language, after all, allows it. Keeping your inheritance shallow will ensure those properties aren't forgotten.

The only thing about this you might want to seriously consider though is making those properties protected. Inheriting classes can always loosen the visibility, but otherwise if at some point you need to make a public property into a protected one you are out of luck.

When designing an abstract class, you may want to ask yourself:

Are there a lot of properties?

How many classes will inherit this? 3? 15? 100?

Am I declaring any abstract methods (such as leftovers from partial interface implementations)?

Does this abstraction tie together two or more otherwise unrelated classes?

If not many classes will inherit from it or it creates a relationship where there would otherwise be none then chances are you can do what you're trying to do with traits.

An example would be Model vs ActiveRecord; "form vs feature".

ActiveRecord can provide scaffolding/partial implementation for a CRUD interface (like a $table property, a static::load($id) method, etc).

Model might have built-in helper functions or an abstract validate() method, and can't instantiate on its own.

Not all Models are ActiveRecords, and vice versa.

ActiveRecord would be best as a trait, as it applies horizontally throughout the application. Models on the other hand have a definite hierarchy and would work best as an abstract.


问:
How could your company's learning/development department best serve you?
I'll preface my question with a disclaimer - I am not an engineer, I'm just someone who works with them full-time, in a learning and development capacity.

Given that, one of the comments I get regularly from the engineers I'm tasked with developing is that they feel that they're having solutions (both technical and non-technical) for development "pushed" at them vs. anyone from my field consulting with them to determine what they really need.

So my question is - if you could give your company a list of the top 3-5 things they could do - in a classroom, or elsewhere - to develop meaningful skills that would help you be a better engineer, a better employee, and one more likely to STAY with the company for the long haul, what would make the cut and why?

Thanks in advance for your responses.

答:
Encourage lunchtime presentations of technology related to what your company does or new technology by and for employees.  Provide lunch.  Reward the speakers with some sort of token.

Encourage lunchtime book discussion groups going through a particular technological book with lunch provided.

Sponsor employees at industry conferences, but make sure that they are the very best that you can provide.

Do not force employees to go to internal or external training that is below their level.  Ideally let team leads pick appropriate training for employees, and absolutely don't let training companies or support guys just sell you something.  I have gone to courses many times that were a waste of my company's money.

ContentLicense: CC BY-SA 2.5


问:
Do you rotate agile team members?
I've got long standing developers in my sprint team. They know the domain, they've been with the company 5+ years and as a team we have a pretty good burn down rate.

There are other sprint teams, some with equally knowledgeable developers and others with newer developers who are trying to get up to speed.

My manager is worried that all our eggs are in one basket and wants to rotate out one or two knowledgeable developers in exchange for the some new guys. I can see their point but can also see the problems that go with that - I'm sure there are others but these are just a few off the top of my head.

New developer will have a much lower work rate

New developer will bring down the work rate of at least one experienced person as they constantly ask questions.

New developer leaves the team at the end to join another team - hopefully he'll remember what he did with us.

New developer leaves the company - wow we wasted a whole bunch of time.

I might like to add that the organisation is struggling with agile. It was a traditional waterfall development company and still thinks in big releases and items that are "expected" to be in the release.

If you've been in a similar situation to this I'd love to know you experiences - does rotating out the team members work? Would pair programming or other methods be a better route to take?

答:
One possibility:
If you are concerned about loss of productivity by rotating a team member, your manager has the correct approach, and will most likely be seriously concerned (if he's any good), but not saying so.

As companies grow, they become less concerned about immediate productivity and more concerned about continuity and predictability. Issues such as business continuity, key person dependency and technical vitality come into play - the same people working closely together for many years, with no one coming or going almost always ends badly, think the red buss... or more commonly, BBoM (Big Bucket of Money) inflicting multiple casulties on the team.

High throughput at all costs is critical to survival of startups but there is a cost in both technical and non-technical debt. Consistant, repeatable, predicitible processes is more critical to established companies than pure speed. (Think tortoise and hare)

Long term, low turn over, siloed teams are a very real problem for management of larger companies. Are you transtioning from a small company to a big company - or more subtly. from a 'big small' company to a 'small big' company?

If this really is the situation, you need to decide if you really want to be seen to be resisting the changes.

Title: Do you rotate agile team members?


问:
Do objects maintain identity under all non-cloning conditions in PHP?
PHP 5.5

I'm doing a bunch of passing around of objects with the assumption that they will all maintain their identities - that any changes made to their states from inside other objects' methods will continue to hold true afterwards. Am I assuming correctly?

I will give my basic structure here.

```<code>class builder {
  protected $foo_ids = array(); // set in construct
  protected $foo_collection;
  protected $bar_ids = array(); // set in construct
  protected $bar_collection;
  protected function initFoos() {
    $this->foo_collection = new FooCollection();
    foreach($this->food_ids as $id) {
      $this->foo_collection->addFoo(new foo($id));
    }
  }
  protected function initBars() {
    // same idea as initFoos
  }
  protected function wireFoosAndBars(fooCollection $foos, barCollection $bars) {
    // arguments are passed in using $this->foo_collection and $this->bar_collection
    foreach($foos as $foo_obj) { // (foo_collection implements IteratorAggregate)
      $bar_ids = $foo_obj->getAssociatedBarIds();
      if(!empty($bar_ids) ) {
        $bar_collection = new barCollection(); // sub-collection to be a component of each foo
        foreach($bar_ids as $bar_id) {
          $bar_collection->addBar(new bar($bar_id));
        }
        $foo_obj->addBarCollection($bar_collection);
        // now each foo_obj has a collection of bar objects, each of which is also in the main collection. Are they the same objects?
      }
    }
  }

}
</code>```

What has me worried is that foreach supposedly works on a copy of its arrays. I want all the $foo and $bar objects to maintain their identities no matter which $collection object they become of a part of. Does that make sense?

EDIT: My understanding is that using the clone keyword is the only way to really copy an object in PHP 5+. Using the assignment operator basically just creates another reference to the same object. I'm hoping that return values and foreach also work that way.

答:
No, they are not the same bars, since you are calling new. Also I don't see $bars being used anywhere in wireFoosAndBars.

Use the exact "associated" instances from $bars when constructing the new collection and they will be the same objects.

You are correct in that clone is the only way to make a copy of an object. Modifying an object's properties, no matter how indirectly, whether the property is an array or not, will always modify the property in that object.

You don't need to use references for objects, it's superfluous.

$foo = new Foo();
$foo->x = [];
function doSomething($object) {
    $object2 = $object;
    $object2->x[0] = 'hello';
}
doSomething($foo);
var_dump($foo->x); // array(0=>'hello')


答:
"New developer leaves the company - wow we wasted a whole bunch of time."

There are a classical response to this: why if you don't invest time in the training of this developer and he decides to stay at the company?

In my opinion is a good idea that developers rotate between teams, normally this gives developers a better understanding of the company as a whole and creates a lot of learn opportunities for newer developers.

Off course the velocity of the teams change, because the velocity of a team is defined by his developers, normally a change in the team always decrease the velocity of the team. But you are investing in the training of this new developers and in the future of the company, this velocity decrease are the cost of the investment, you can't have the benefits without the cost, and every intelligent manager understand this simple fact if you talk to him in a language he can understand.

Title: Do you rotate agile team members?

Body:
I've got long standing developers in my sprint team. They know the domain, they've been with the company 5+ years and as a team we have a pretty good burn down rate.

There are other sprint teams, some with equally knowledgeable developers and others with newer developers who are trying to get up to speed.

My manager is worried that all our eggs are in one basket and wants to rotate out one or two knowledgeable developers in exchange for the some new guys. I can see their point but can also see the problems that go with that - I'm sure there are others but these are just a few off the top of my head.

New developer will have a much lower work rate

New developer will bring down the work rate of at least one experienced person as they constantly ask questions.

New developer leaves the team at the end to join another team - hopefully he'll remember what he did with us.

New developer leaves the company - wow we wasted a whole bunch of time.

I might like to add that the organisation is struggling with agile. It was a traditional waterfall development company and still thinks in big releases and items that are "expected" to be in the release.

If you've been in a similar situation to this I'd love to know you experiences - does rotating out the team members work? Would pair programming or other methods be a better route to take?


答:
does rotating out the team members work?

Define "work".

Rotating team members sometimes spreads (good or bad) culture to the different sprint teams. Sometimes it can build teamwork between teams because people get to build friendships that didn't exist before.

Does it spread domain knowledge? slowly. Like months slowly.

Does it slow down sprint teams? Almost always. It depends on how different the teams are in work, culture and organization.

Does it often frustrate people and lower morale, especially for the reasons you bring up - your team being expected to maintain velocity despite this added overhead? Absolutely. This depends of course on the personalities of the people involved, the skill of your leads/management, and piles of other factors. Oh and let's not get into how well disengaged employees pick up knowledge specific to your domain...

Personally, I don't think it is ever worth it. The spread of domain knowledge is too slow, the risks are too high, and domain knowledge isn't nearly as valuable to me as it is to most managers.

If you want to foster good personal relations between teams, then you need to foster good personal relations between people. In my experience, stressing people out with change (shifting social landscapes of their team) and boss orders is not setting them up for success in that regard.

Title: Do you rotate agile team members?


问:
Can this code be made more concise?
I came across some code recently where in many, many places, expression evaluations were being assigned to different arrays one index at a time. A psuedo-code example:

```<code>array[0] = item1[0] + item2[0];
array[1] = item1[1] + item2[1];
array[2] = item1[2] + item2[2];
</code>```

or

```<code>array[0] /= variable;
array[1] /= variable;
array[2] /= variable;
</code>```

My instinct would be to first create a function for iterating through an array and assigning an evaluation using a single for loop. Then secondly, just call that function with arguments for the array, a number defining how many indices to loop through and the items to be evaluated.

Obviously, one obstacle to that method is the fact that the
expressions being evaluated are arbitrary - they can be additions,
subtractions, divisions, multiplications.

And for another, the expression operands can be either variables or arrays, and of
course in statically typed languages, the types could be varied.

Also, the number of operands may be varied.

Is it possible to make this code more concise taking into account all possible cases, and what would the solution be called in technical terms?

答:
Yes of course it is :)

You are quite correct in that creating a loop already simplifies things, so let me address your more detailed concerns about it:

Arbitrary expressions: while the expressions themselves may be arbitrary, they may still be representable as a function. When you are thinking in a more functional programming mindset, then you will realize, that all you're really doing is mapping a function over the array elements.

Type difference: This is the reason, why we have polymorphism. When abstractly mapping over an array of type T with a function that returns Ts, you don't have to mind the type difference really.

Number of operands: This is captured by the first point above. As we only care about mapping a function over this array, we do not care about the number of that function's arguments.

So in general, my suggestion on how to simplify this would be to take a closer look at functional programming principles, in particular, higher-level functions (i.e. functions, which take another function as a parameter).

Note that FP may be the most direct and easiest way for simplifying it, but even if you are not working in a FP language (which is most likely anyways), its ideas are portable to most languages. You may however have invest more into supporting structures/classes, which may make the simplification look rather involved overall. But keep in mind, that high-level concepts like mapping a function over some elements are extremely reusable, hence, it may well be worth it to make a small investment up front.

Title: Can this code be made more concise?


问:
Dynamic query in MySQL
I'm doing a J2EE web application with Struts2, MyBatis and a MySQL database, so what I want is to allow the user to be free to choose different parameters to perform a select to a table in the database.

For example, I have a Table called SALES, so I want that user to be able to select different parameters according to what he needs. Maybe, he wants to filter by dates and the employee name, and then he wants to filter just by customer and so on.

Should I show all the necessary data to filter on the client side with Javascript, or can I do a query to several tables after the user chooses the parameters? if that is possible, how should I write the query with parameters that could be present or not?

答:
If your table contains small amount of data (and will always contain small amount) then of course you can filter in JavaScript. This is true, for example, if you always select from DB only one "page" of data (LIMIT 10,20). But in real application you want to LIMIT and FILTER the same time as user wants to see filtered results but only 10 of them at once. He doesn't want to load 10 results and then filter it to 3. So you will almost always use the server side filtering.

If you using Mybatis read about Dynamic SQL and The SQL Builder Class. You can read filter parameters from HTTP request and set values of variables to test by Mybatis Dynaimc SQL if method. Of course you first need to write that xml with if for any filter condition.

For example if you want to filter SALES by amount (>100) and name (contains "Goo") then you can pass from JS your filter options like this:

```<code>{
    "filterBy" : [
        { field: "amount", op: "gt" }
        { field: "name", op: "contains" }
    ]
}
</code>```

In Java code you can read this JSON to Map (with Jackson for example) and assign values to variables for MyBatis Dynamic SQL expression.

I can't explain more as I am not expert of Mybatis.

Title: Dynamic query in MySQL

Body:
If your table contains small amount of data (and will always contain small amount) then of course you can filter in JavaScript. This is true, for example, if you always select from DB only one "page" of data (LIMIT 10,20). But in real application you want to LIMIT and FILTER the same time as user wants to see filtered results but only 10 of them at once. He doesn't want to load 10 results and then filter it to 3. So you will almost always use the server side filtering.

If you using Mybatis read about Dynamic SQL and The SQL Builder Class. You can read filter parameters from HTTP request and set values of variables to test by Mybatis Dynaimc SQL if method. Of course you first need to write that xml with if for any filter condition.

For example if you want to filter SALES by amount (>100) and name (contains "Goo") then you can pass from JS your filter options like this:

{
    "filterBy" : [
        { field: "amount", op: "gt" }
        { field: "name", op: "contains" }
    ]
}

In Java code you can read this JSON to Map (with Jackson for example) and assign values to variables for MyBatis Dynamic SQL expression.

I can't explain more as I am not expert of Mybatis.


问:
How to allow innovation in an Agile Methodology
It is one thing to say that agile methodologies are good in settings where requirements are poorly understood, or that significant novelty is involved.  But should it be applied where outright innovation is required?  If yes, how?

If what you are contemplating is unknown in the industry, or even thought to be impossible, it may be difficult to conceive of the user stories and related tasks.  For example, would it have benefitted Albert Einstein (or a hypothetical employer he reports to) to have devised the theory of general relativity by breaking it down into epics, sprints, and tasks?  If the answer is "yes," then what special accomodations should have been incorporated to help an agile approach work best with Einstein's way of achieving revolutionary insight?

To give a specific software example, imagine the year is 2008 and you would like to use WCF to provide COMET or "long-polling" type capabilities.  All your research of "prior work" turns up nothing, and you even read an MSDN blogger say it isn't possible.

Again, what adjustments or "flavor" could be brought into the user stories and tasks to accomodate the inventiveness (or audacity?) of this endeaver?  Or would it indeed be better to conclude the effort is so innovative (in 2008), it is best left as an undirected think-tank exercise?

The innovator who is operating under two-week sprints certainly does not want to be shot-down every time he abandons a dead-end task and starts working on a newly discovered task that was not envisioned when the sprint was defined.  Likewise, when the sprint ends and no working code or working approaches are delivered, the innovator should not be shot down by management.  There needs to be a way to label the effort as "success" even in these circumstances.  In perhaps one or three more sprints of this kind of "dead end" pursuits, the innovator might finally hit on something that works.

How does agile allow management know that each sprint was "ok" despite the innovative set-backs?  How is this managed so that the burn-down chart does not look preposterous?

答:
Back to Agile Manifesto:

Individuals and interactions over processes and tools

Working software over comprehensive documentation

Customer collaboration over contract negotiation

Responding to change over following a plan

Nothing in these values forbid innovation. Actually, innovation has a better nest with Agile than with Waterfall.

Nevertheless, it may happen that usual implementations of Agile put some constraints on a software project that limit innovation, such as deadlines (the timeframe of a sprint is a deadline) or cost. But this is not an issue with Agile, it is an issue with current work organizations.


答:
The title question, where innovation refers to smaller-scale creative advancements in a team that is already doing well in Agile.

The best answer is summarized in this article about "Gold Card Days".

Summary (paraphrased, and with my own interpretations which may not reflect the author's intentions):

Developers can identify interesting (intellectually stimulating) stretch-goals that are work-related that they would like to work on.

These stretch goals, after being approved by the team (including the product owner), becomes "gold cards".

The team is encouraged to take out a day to work on these "gold cards".

Usually this happens to be on Fridays, so it becomes the "Gold Card Day".

With respect to Scrum, Gold Cards are scheduled and tracked just like any other backlog items; the team will need to demonstrate their results.

There are some other points (not in that article) in relation to applying "gold cards":

Do not let a single team member take all the fun. Every team member should be encouraged to spend some creative time by taking a "gold card day" once a while.

Along the same line, try to make a "gold card" a team effort (as opposed to a solo task), and exploit that task as a socializing (team-building) moment.

The substantial question, where innovation refers to research (months to years of gruesome work) which have a real risk of not finding any useful solution.

This earlier question, Which extreme-programming techniques are appropriate to use in a research environment? covers much of the ground of this question.

(Disclaimer: I wrote one of the answers for that question, though not the selected one.)

The summary is that software research work can be fast-paced; it requires its participants to prioritize based on new information (by absorbing discovered/learned ideas and synthesizing new ones). It gives the appearance of being "slow" only because it is "slow to show the fruits of success, and only if it was successful."

This question on Project Management Beta - What are the pros and cons of incorporating a project manager into a research team? - also covers the same grounds.

In spirit, yes.

As pointed out in mouviciel's answer, the spirit of software research is in line with the spirit of the Agile Manifesto. What I will argue next is whether high-risk research can be fit into Agile as a organization or management methodology ("Agile in practice").

In practice, you have to answer a few questions.
This list is not exhaustive...

We have to track back a little bit about how Agile Methodology comes into existence.

Agile Methodology is usually used when there is a sponsor of the project. Furthermore, the sponsor's willingness to fund the project is limited; it expects to see some software of usable (potentially shippable) quality being delivered on a regular basis after funding the project for some time.

The kind of research work in this question refers to "potentially non-solvable endeavors". In other words, the very nature of this type of work involves a risk that it can ultimately fail, despite all of the intentions and diligence of the people involved.

This is not a ScrumButt-style checklist.

This is more of a preflight checklist that predicts whether one is better off "Que Sera, Sera"

1. Transparency up-front. Is the sponsor of the project being told the truth about the riskiness nature of the project?

2. Willingness of the sponsor. Is the sponsor aware of the risk and willing to continue the funding?

The sponsor needs to have a risk acceptance that is higher than the typical business projects, or the typical Software / IT / Agile projects. Not every sponsor fits this criteria. If it doesn't fit, it would be good for a professional to back out from the project.

3. Transparency throughout the project. Is the sponsor being informed of the true status of the project regularly?

This is to thwart attempts to hide setbacks or looming failures in the project by misusing the time lapse between status updates.

4. Active participation of the sponsor. Is the sponsor interested in knowing the nitty-gritty details, the ups and downs, the promises and the limitations of each attempt?

The issue with software research is that there can be many false leads - both false positives (believing an approach would work but it ended up not successful), and false negatives (claiming something isn't possible, only to be disproved by someone else).

Agile projects allows the team (including the sponsors and stakeholders) to take calculated risks. "Calculated" means that the risk-takers are fully-informed. If the sponsor is not willing to learn the nitty-gritty details of the project, then the sponsor will not have complete information to calculate (judge) the risk on their own.

Even if a sponsor is willing to take the financial risk, if it is unwilling to also partake the decision-making risks (and accepts consequences to its own choices) then the sponsor is also unfit for such high-risk research projects.

5. Can the research team show (demonstrate) their progress in the form of running software, as opposed to presentation slides?

This question is appropriate for research projects where the end-result is expected to be running software. Presentation slides could be useful for explaining CS theories, but it could also be misused to hide setbacks in the software implementation (or the complete lack of). A software demo is intended to thwart such misuses.

6. Can the research team deliver a partially valuable software product, even if the sponsor decides to stop funding at any time in the project?

This question is only relevant on a case-by-case basis. Some research projects are incremental; they may have multiple milestones and deliverables. It requires a research team to prioritize their approaches to favor "lowest hanging fruits first", or the "least cost approach to demonstrate viability".

Some research projects are not incremental: to deliver a single, very specific technological breakthrough. It is a hit or miss. For this type of projects, the only incremental outcomes are the research work and prototyping, and maybe the academic publications. These "non-consumable" incremental deliverables are nonetheless valuable to some types of sponsors - namely, universities, research funding agencies, and big-name corporations hoping to build up academic goodwill.

However, research projects having such characteristics might also favor the "Cowboy coding" approach, as discussed further below. These are aptly termed "hacks", and they do occur in academia.

Because of the time-scale of most academic research, academic-style research funding is usually provided with a commitment of one or more years; medical research funding (academic and commercial) may be committed for even longer periods. On the other hand, typical commercially-funded research may be terminated without notice, or have their resources (manpower) being completely reassigned to other projects.

7. How does the research team measure on the scale of silo vs. cross-functional?

Some types of research team are highly-siloed. Often, this happens in "multi-disciplinary" projects - exactly one member from each discipline is involved. As a result, no one member can take over another member's task, not even very small ones, because their knowledge and skills do not overlap. The difficulty would also extend to communications and task definitions.

Extremely-siloed teams will still benefit from some Scrum rituals such as a daily stand-up meeting, but aside from the "ritual" there may not be much interaction going on. It would take a highly socializing agile coach to get the team into talking and building trust.

8. If an agile coach is present, does the coach prescribe short iteration cycles, time boxing, and providing time estimates?

Each of these agile practices pose difficulties for certain types of research projects. Nevertheless, it was reported that some expertly-skilled research groups were able to apply these practices in advanced research. Since there is no detail about how agile coaching occurs within these expert teams, we may not be able to know how each of these difficulties could be overcome.

9. Does the research team unanimously vote for adopting Solo development style over any other methodology?

Edited: an earlier version uses the phrase "cowboy coding", which alludes to the lack of professionalism. However, there is a difference between solo development and cowboy coding, and the circumstances in this checklist item may make solo development a legitimate choice.

This question shows that there are programmers who prefer to own a large chunk of development. If the research team is mainly comprised of this type of programmers, given that the team members' skill set are irreplaceable (referring to the previous point of skill silo), then the team members may have to be granted what they wish for, in exchange for their skills and labor.

The main difference between solo development and cowboy coding is that in solo  development, one can adopt the practices listed in The Joel Test: 12 Steps to Better Code, such as the use of version control, build automation, and fixing bugs before adding new features.

Some circumstances will favor each member carrying out solo development, whereas some circumstances will favor cowboy coding.

Cowboy coding is favored if the end-goal is to "make a point", by showing that something is technologically possible. There is no requirements for delivery - nor quality - aside from a good presentation on the next DEF CON ®.

Final question. If the circumstances do not allow an Agile team to carry out groundbreaking research, then how do they make use of innovative technology?

Business as usual. Let other companies (or academics, individuals or teams of hackers, startups, etc.) tackle the hard problem first, and then buy/license the technology from them. The software industry has been running on these principles for many decades.

The emphasis on showing early working prototypes in Agile methodology compels a team to look for existing solutions first, which is a good thing because it may save the team from some redundant work.

Title: How to allow innovation in an Agile Methodology

Body:
It is one thing to say that agile methodologies are good in settings where requirements are poorly understood, or that significant novelty is involved.  But should it be applied where outright innovation is required?  If yes, how?

If what you are contemplating is unknown in the industry, or even thought to be impossible, it may be difficult to conceive of the user stories and related tasks.  For example, would it have benefitted Albert Einstein (or a hypothetical employer he reports to) to have devised the theory of general relativity by breaking it down into epics, sprints, and tasks?  If the answer is "yes," then what special accomodations should have been incorporated to help an agile approach work best with Einstein's way of achieving revolutionary insight?

To give a specific software example, imagine the year is 2008 and you would like to use WCF to provide COMET or "long-polling" type capabilities.  All your research of "prior work" turns up nothing, and you even read an MSDN blogger say it isn't possible.

Again, what adjustments or "flavor" could be brought into the user stories and tasks to accomodate the inventiveness (or audacity?) of this endeaver?  Or would it indeed be better to conclude the effort is so innovative (in 2008), it is best left as an undirected think-tank exercise?

The innovator who is operating under two-week sprints certainly does not want to be shot-down every time he abandons a dead-end task and starts working on a newly discovered task that was not envisioned when the sprint was defined.  Likewise, when the sprint ends and no working code or working approaches are delivered, the innovator should not be shot down by management.  There needs to be a way to label the effort as "success" even in these circumstances.  In perhaps one or three more sprints of this kind of "dead end" pursuits, the innovator might finally hit on something that works.

How does agile allow management know that each sprint was "ok" despite the innovative set-backs?  How is this managed so that the burn-down chart does not look preposterous?


答:
In addition to what 'Frank' wrote, you build something like strategy , an abstract Operator class that its constructor takes two arguments and has a method of myCalc which returns the value.
Then have for each arithmetic or mathematical operation and derived class.
Using generics you can even have it get different Types as parameters.

Then at your code you write it like this:
array[i] = calc(value1,value2,new plus())

where calc is simply return Op.calc(value1,value2)

Title: Can this code be made more concise?

Body:
I came across some code recently where in many, many places, expression evaluations were being assigned to different arrays one index at a time. A psuedo-code example:

```<code>array[0] = item1[0] + item2[0];
array[1] = item1[1] + item2[1];
array[2] = item1[2] + item2[2];
</code>```

or

```<code>array[0] /= variable;
array[1] /= variable;
array[2] /= variable;
</code>```

My instinct would be to first create a function for iterating through an array and assigning an evaluation using a single for loop. Then secondly, just call that function with arguments for the array, a number defining how many indices to loop through and the items to be evaluated.

Obviously, one obstacle to that method is the fact that the
expressions being evaluated are arbitrary - they can be additions,
subtractions, divisions, multiplications.

And for another, the expression operands can be either variables or arrays, and of
course in statically typed languages, the types could be varied.

Also, the number of operands may be varied.

Is it possible to make this code more concise taking into account all possible cases, and what would the solution be called in technical terms?


问:
Is there a correlation between the scale of the project and the strictness of the language?
Explaining the difference between strictness of languages and paradigms to a colleague of mine, I ended up asserting that:

Tolerant languages, such as dynamic and interpreted languages, are used best for prototypes and small projects or medium-size web applications. When choosing elegant dynamic languages such as Python or JavaScript with Node.js, the benefits are:

Fast development,

Reduced boilerplate code,

Ability to attract young, creative programmers who flee “corporate languages”  like Java.

Statically typed/compiled languages are best for applications which require higher strictness such as business-critical apps or apps for medium to large-size apps.

Well-known paradigms and patterns developed for decades,

Ease of static checking,

Ability to find many professional developers with decades of experience.

Strict languages such as Haskell, Ada or techniques such as Code contracts in C# are better for systems which favor safety over flexibility (even if Haskell can be extremely flexible), such as life critical systems and systems which are expected to be extremely stable. The benefits are:

Ability to catch as many bugs as possible at compile time,

Ease of static checking,

Ease of formal proofs.

However, by looking at the languages and technologies used for large-scale projects by large corporations, it seems that my assertion is wrong. For example, Python is successfully used for large systems such as YouTube or other Google applications which require an important amount of strictness.

Is there still a correlation between the scale of the project and the strictness of the language/paradigm which should be used?

Is there a third factor that I've forgotten to take in account?

Where am I wrong?

答:
There are two kind of errors to check for: type errors (concatenate an integer + list of floats) and business logic errors (transfer money to a bank account, check if the source account have money).

The "dynamic" part of a dynamic programming language is just the place where type checking takes place. In a "dynamically typed" programming language, type checking is done while executing each statement, while in a "statically typed language" type checking is done at compilation time. And you can write an interpreter for a static programming language (like emscriptem does), and you can also write an static compiler for a dynamic programming language (like gcc-python or shed-skin does).

In a dynamic programming language like Python and Javascript you need to write unit tests not only for the program business logic but also to check if your program does not have any syntax or type errors. For example, if you add "+" an integer to a list of floats (which does not makes sense and will issue an error), in a dynamic language the error will be raised at runtime while trying to execute the statement. In a static programming language like C++, Haskell and Java, this kind of type error will be caught by the compiler.

A small codebase in a dynamically checked programming language is easier to look for type errors because is easier to have a 100% coverage of source code. That's it, you execute the code by hand a few times with different values and you're done. Having a 100% coverage of source code gives you a fair hint that your program may not have type errors.

With a large codebase in a dynamically checked programming language it is harder to test every statement with every possible type combination, specially if you are careless and write a function that may return a string, list or custom object depending on its arguments.

In a statically checked programming language the compiler will catch most of the type errors at compile time. I say most because a division by zero error, or an array out of bounds error are also type errors.

More often than not the real discussion is not about programming languages but about the people using those languages. And this is true because, for example, assembly language is as powerful as any other programming language, yet we're writing code on JavaScript. Why? Because we're humans. First, we all make mistakes and its easier and less error prone to use a dedicated tool specialized for a specific task. Second, there is a resources constraint. Our time is limited, and writing webpages on assembly would take ages to finish.


答:
I don't think it does. Agile is about eating chocolate elephants - taking a large task and breaking it down into manageable chunks that can not only be delivered, but are delivered regularly.

Research type projects do not fit into this - not unless your project can be broken down into small chunks that can be demonstrated every fortnight (or longer - nowhere does Agile say 2 weeks is the time your sprint has to take, best agile project I ever worked on had 6 week sprints)

I wouldn't try it though. I'd take the bits of agile tools that you think would work for you, and ignore those that don't. Too many people think Agile means "you must do everything the scrum tutorial says you must do and no discretion is allowed ever", that approach is very un-agile.


问:
Wrapping function in closures to make testable functions
In my nodejs project, I have functions like this for socketio.

```<code>socket.on('draw', function (data) {
    socket.broadcast.to(socket.room).emit('draw', data);
    addEvent(socket, ["draw", data]);
});
</code>```

I'd like to rewrite them to something like this:

```<code>function onDraw(socket, config) {
    return function (data) {
        socket.broadcast.to(socket.room).emit('draw', data);
        addEvent(socket, ["draw", data]);
    }
}

socket.on('draw', onDraw(socket, config));
</code>```

The idea is that by placing all of my functions in simple closures like this, I can put them in different modules and it will make it easier to test by passing mockup objects to the function that construct the callback.

I was wondering if it was overkill or if there is a better way to make my code testable?

答:
IMHO it is not overkill, that is just the Javascript (or functional) form of the command pattern, used in conjunction with dependency injection.

The classic OO equivalent for achieving the same, is to construct a command class, pass socket and config through the constructor, store them in some member variables, and add a member function like Draw(data) using that member variables. That would result in much more boilerplate code - whilst your example is very concise compared to the OO version.


问:
GPL+FE license also applies to fonts used for the UI of a software?
The GPL font exception allows the font to be embedded within a digital "document" file without requiring the "document" itself to also be shared with GPL.

Now I wonder, what is considered a "document"? If the GPL+FE font is embedded in a software to render a user interface, the software can be released with a non-GPL license?

答:
In my view the definitions would be those used by the relevant copyright law. The law is quite careful about definitions of things, and if you had a font embedded in a work that fitted the definition of "program" then the law regarding "program" would be what would apply. Trying to call a "program" a "document" would not help.

As always, if you make no money out of it and harm no-one then just do your best, acknowledge the work of others and don't worry too much. If you distribute something with GPL in the mix you will probably have to distribute your source code and if you don't, prepare for some unpleasant questions as to why not.

if you make money out of your product or services and/or if you may cause damage to someone or compete with someone who does, then you must take competent legal advice. That won't protect you, but it will warn you about the risks and possibly help to mitigate them. You are at risk, even if you don't realise it, and the more money you make the bigger the risk.


答:
According to the FSF's page Various Licenses and Comments about Them:

W3C Software Notice and License

This is a free software license and is GPL compatible.

Futhermore, the W3C license is OSI approved.

As an open source software license, it cannot impose restrictions on field of endeavor, which includes permission to sell the software. This does not guarantee that a license can be redistributed combined with proprietary software, but in this particular case (though I'm not a lawyer), I see nothing to indicate that the W3C license would forbid that.

Title: w3c library license: does it prevent the inclusion in/distribution with paid software?

Body:
From W3C Software Notice and License:

Permission to copy, modify, and distribute this software and its documentation, with or without modification, for any purpose and without fee or royalty is hereby granted

My app depends on the xml-apis 1.4.01 library that in turn includes W3C software and I need to distribute it along with my non-free app. I am not explicitly charging for the included xml-apis/W3C components. Does the stated license statement exclude such a paid distribution?

Don't answer if you are not aware of the GPL linking exception.


问:
Coding style - define fields separate or not
Some use this convention:

```<code>private String event;
public getEvent() { return this.event; }
public setEvent(String value) { this.event = value; }

private int id;
... same as above ...
</code>```

In some projects they define all the fields first, all static fields after (or before), all public/private variables, then the setters, getters, other methods.

Which do you use and why?

答: I usually keep the private variable with the getter/setter, so the relevant code is all in the same place.  </p>


问:
How should one implement the dependency-injection for a geocoding client that aggregates different coordinate provider implementations?
I am new to DI and I would like to know how DI might be used to help resolve this problem.

If I have an ILatLongLocation which implements a Latitude and Longitude, then given two of these I can produce a Distance using a variety of algorithms, but I can also reasonably pick one of these as the "best" algorithm at design-time without losing any sleep.

However, since users will rarely input physical coordinates, I may need to instead compare by zip codes or something similar.

Now, in order to resolve zip codes to coordinates, I could apply a naive algorithm that uses string concatenation, etc to do a rough guess as to the physical coordinates, I could pick a random set of coordinates, etc. But in all likelihood, I will need to resolve the zip codes by using some sort of database mapping zip codes to coordinates.

So being new to DI, I would like to know if the following is a reasonable application of DI and/or if I am overthinking it.

ILocatable has ILatLongLocation

ILocatableProvider<T> : ILocatable has a T RawLocatable and can return an ILatLongLocation.

IZipCodeLocatableProvider : ILocatableProvider<string> has a string RawLocatable and returns an ILatLongLocation.

NaiveZipCodeLocatableProvider is an implementation that just uses patterns in zip codes that are well-known to provide a best-effort guess as to the coordinates.

DbZipCodeLocatableProvider is an implementation that uses a database (maybe through a DbContext or somehow else) to return the coordinates.

Now DbZipCodeLocatableProvider itself must depend on some sort of repository or context or connection or something to access a database (unless it is literally hard-coded)... so then this means I need to have a DbContext or something similar... here is where I get lost.

Am I thinking about this the right way? Is this a legitimate scenario for dependency injection? And how do I discriminate between, say different connection strings vs different strategies altogether for resolving zip codes to coordinates?

Edit: ...and don't forget about WebServiceZipCodeLocatableProvider ... there's another (realistic) option.

答:
I would only implement the dependency-injection for a geocoding client that aggregates different coordinate provider implementations if you either

have more than one provider (i.e. location based on ip-adress instead of zip code)

or do Test-driven_development.

For me your design looks over-complicated.

I have implemented something similar for android using Test-driven_development and all i needed was

a LatLongLocationCalculationService that can process ILatLongLocation (i.e. calculates distance between to locations)

a ZipCodeLatLongAdapter that lets Zip-codes appear as ILatLongLocation.

An implementation detail for the ZipCodeLatLongAdapter is that it looks up the location of a zip-code from the database.


问:
Model Driven Architecture Approach in programming / modelling
I know the basics of the model driven architecture: it is all about model the system which I want to create and create the core code afterwards. I used CORBA a while ago. First thing that I needed to do was to create an abstract interface (some kind of model of the system I want to build) and generate core code later.

But I have a different question: is model driven architecture a broad approach or not? I mean, let's say, that I have the language (modelling language) in which I want to model EXISTING system (opposite to the system I want to CREATE), and then analyze the model of the created system and different facts about that modeled abstraction.

In this case, can the process I described above be considered the model driven architecture approach? I mean, I have the model, but this is the model of the existing system, not the system to be created.

答:
I donot think that your model-driven-analysing approach is helpful until you want to remplement the old system.

The benefit about model-driven-design is that you create a model and the basic code is generated from it if you have the apropriate codegenerators.

For example the hybris-shop-system is implemented this way:

you create a modell (an xml-file) and database-schema, java-database-access-code and gui for shop-maintenance is generated from that model.

example:

If you add a new attribute "lastOrderDate" to the model-file, you get the generated java/gui code from it.

you can reverse-engeneer a model from your existing database-modell but it is quite likely that the corresponding generated code for businessmodell/databaseaccess/gui will not compatible with it.


问:
Is it safe to rely on static analysis to "reproduce" concurrency bugs reliably?
I've inherited some Java code which I suspect harbours some concurrency bugs when synchronizing between a thread that queries data and an IO event that updates the same data. I'm trialling a static analysis tool called ThreadSafe which indeed detects various concurrency issues (i.e. field accessed from asynchronously invoked method without synchronization and Inconsistent synchronization of accesses to a collection).

After discovering how difficult it is to reproduce data races reliably by writing unit tests, I wondered if it's advisable to depend on ThreadSafe to "reproduce" the bugs reliably?
What I'm asking is, is it safe to depend on the static analysis tool to tell me when I've fixed the bugs? (Of course, to fix the bugs I will need to understand each one in context).

答:
Answering your first question:

http://www.contemplateltd.com/threadsafe/faq#non-checkers

"What kinds of concurrency defects does ThreadSafe not look for?

We do not yet include support for all of java.util.concurrent. Specifically, ThreadSafe does not check for misuse of the advanced synchronization facilities provided by java.util.concurrent, for example the java.util.concurrent.atomic package. Nor does it currently include any checkers for mistakes that may occur when writing parallel programs using the Fork-Join framework.

Finding bugs in intricate lock-free algorithms requires analysis technology that does not scale well. Such algorithms should be left to specialized concurrency experts. ThreadSafe can be configured to find defects in applications that use libraries containing such algorithms.

Which analyses we include in new releases of ThreadSafe is dictated both by what is possible using analysis technology that is mature enough for integration into a usable product, and by the features and concurrency defects that we see often in ‘average’ Java programs.

If you have a Java concurrency problem that is not currently covered by ThreadSafe, Contemplate’s Java concurrency specialists may be able to help by adding custom configuration to ThreadSafe and/or by use of advanced analysis technology that is not yet mature enough for integration into ThreadSafe."


答:
In my experience, a determined, well-meaning, but clueless developer can wrap enough obfuscation around a concurrency bug that the analysis tool will miss it.

If the tool thinks there's a bug, assume it's right until you prove otherwise.  That's the value of the tool.  If the tool doesn't find any bugs, your best bet is to pretend the tool doesn't exist.

If you want reliable concurrent code (in any language), your goals should include:

The critical sections should be tiny and simple so they are trivial to understand.

The critical sections should be completely isolated from other code at the source level.

A function/method/subroutine involved in concurrent code should do one thing only. If it manipulates a synchronization primitive (lock, semaphore, etc.) it should NOT fiddle with any of the shared resources and it should NOT contain loops or conditional code. Move the "real work" to a separate function. This supports item 1.

If you have any kind of lock, a developer should be able to read the code and determine exactly what resource(s) that lock protects in 30 seconds or less. If it's not obvious to you, it won't be obvious to the next guy. And it probably wasn't clear to the fellow who wrote the code. So it's probably broken.

The visibility of the resource you're protecting should be no greater than the visibility of the synchronization primitive that protects it. Neither component should be visible to the larger body of code.

Etc.  The rest of the list is really just a variety of ways of restating items 1 and 2.

If your code is designed and organized right, you should be able to look at a tiny fraction of the code to understand and trust the concurrency.  When you reach that goal, then feed the code to the static analysis tool and see if it agrees.

And give the code to a few other non-guru developers for review.  Ask them to explain how the concurrency works and why it's correct.  If they can't explain it, it's still too complex.

Title: Is it safe to rely on static analysis to "reproduce" concurrency bugs reliably?

Body:
I've inherited some Java code which I suspect harbours some concurrency bugs when synchronizing between a thread that queries data and an IO event that updates the same data. I'm trialling a static analysis tool called ThreadSafe which indeed detects various concurrency issues (i.e. field accessed from asynchronously invoked method without synchronization and Inconsistent synchronization of accesses to a collection).

After discovering how difficult it is to reproduce data races reliably by writing unit tests, I wondered if it's advisable to depend on ThreadSafe to "reproduce" the bugs reliably?
What I'm asking is, is it safe to depend on the static analysis tool to tell me when I've fixed the bugs? (Of course, to fix the bugs I will need to understand each one in context).


问:
Structuring a storage system for a game
I am working on a multiplayer game, where a player has many storages to store items in.

Storage

Storage is the system that allows the user to deposit items, and take them back. Example of storage types:

Inventory: Same as WoW inventory, you can add items, drop items, move items from slot to slot.

Bank: Bank is what you can call, a super-inventory, which has around 300 items limit per tab Bank can have maximum of 10 tabs which will store items. total items allowed in the bank is 3000 (10 tabs multiplied by 300 items per tab). How ever, in the bank, all items are stackable.

Equipment: Equipment is the same as Inventory, just with sorted slots, i.e Helm, Body, Legs and there are total of 8 slots.

Chests and other: Same as Bank just without tabs.

An item in-game

Each item has it's own item id. Only certain items can be stackable, unless the storage type is Bank or chest.

I have created a system which will make it easier for me to manage storages, and there's the abstract class, that each storage type class will extend it:

```<code>public abstract class PlayerItemStorage {

    private int size;

    /**
     * The items
     */
    private PlayerItem[] items;

    /**
     * Sometimes, by default, the storage items are id + 1, due to
     * the client's interfaces. No exact explanation on it, but the only
     * feature that doesn't do that is equipment and possible BoB
     */
    private boolean increasedItem = true;

    public PlayerItemStorage(int storageSize) {
        this.items = new PlayerItem[storageSize];
        this.size = storageSize;
    }

    public PlayerItemStorage(PlayerItem[] items) {
        this.items  = items;
        this.size = items.length;
    }

    /**
     * Resets the storage
     */
    public void resetStorage() {
        this.items = new PlayerItem[this.size];
    }

    /**
     * Gets the item list
     * @return PlayerItem list
     */
    public PlayerItem[] getItems() {
        return this.items;
    }

    /**
     * Counts how many items there are with the same id.
     * @param id Item id
     * @return count
     */
    public int count(int id) {
        int count = 0;
        for (PlayerItem item : this.items) {
            if (this.getId(item) == id) {
                count++;
            }
        }
        return count;
    }

    /**
     * Counts how many items there are in the inventory
     * not including amount, just the item objects themself.
     * @return amount
     */
    public int countItems() {
        int count = 0;
        for (PlayerItem item : this.items) {
            if (this.getId(item) > 0 && item.getAmount() > 0) {
                count++;
            }
        }
        return count;
    }

    /**
     * Gets the length of the storage
     * @return
     */
    public int getLength() {
        return this.items.length;
    }

    /**
     * Checks how many free slots the storage has
     * @return
     */
    public int freeSlots() {
        int slots = 0;
        for (PlayerItem item : this.items) {
            if (this.getId(item) <= 0) {
                slots++;
            }
        }
        return slots;
    }

    /**
     * Finds an item id in the earliest slot.
     * @param id Item ID
     * @return Slot id
     */
    public int find(int id) {
        for (int i = 0; i < this.items.length; i++) {
            PlayerItem item = this.items[i];
            if ( this.getId(item) == id && item.getAmount() > 0) {
                return i;
            }
        }
        return -1;
    }

    /**
     * Gets the earliest free slot
     * @return slot id
     */
    public int getFreeSlot() {
        for (int i = 0; i < this.items.length; i++) {
            if (this.getId(i) <= 0) {
                return i;
            }
        }
        return -1;
    }

    /**
     * Checks if item is existing in the given slot, with the given amount and
     * item id.
     * @param id Item ID
     * @param amount Item Amount
     * @param slot Slot id
     * @return boolean
     */
    public boolean containsInSlot(int id, int amount, int slot) {
        int found = 0;
        if (this.items[slot].getAlpha() == id) {
            for (int i = 0; i < this.items.length; i++) {
                PlayerItem item = this.items[i];
                if (this.getId(item) == id) {
                    if (item.getAmount() >= amount) {
                        return true;
                    } else {
                        found++;
                    }
                }
            }
            if (found >= amount) {
                return true;
            }
            return false;
        }
        return false;
    }

    /**
     * Checks if item exists in the storage
     */
    public boolean contains(int id) {
        for (PlayerItem item : this.items) {
            if (this.getId(item) == id) {
                return true;
            }
        }
        return false;
    }

    /**
     * {@link #increasedItem}
     * @param i Index
     * @return real item id
     */
    private int getId(int i) {
        if (this.increasedItem) {
            return this.items[i].getAlpha();
        }
        return this.items[i].getId();
    }

    /**
     * {@link #increasedItem}
     * @param item PlayerItem object
     * @return real item id
     */
    private int getId(PlayerItem item) {
        if (this.increasedItem) {
            return item.getAlpha();
        }
        return item.getId();
    }

    public abstract boolean add(int id, int amount);
    public abstract boolean remove(int id, int amount, int fromSlot);
}
</code>```

I also have a container class which is in charge to control all storages:

```<code>/**
 * Container class for all storages of a player
 * @author Ben
 */
public class PlayerStorageContainer {

    /**
     * Player object (Client extends Player extends Entity)
     */
    public Player player;

    /**
     * boolCatach: If enabled, when removing/adding item to ALL of the storages,
     * it will check if the action returned false, if yes it will stop right away and
     * return false.
     */
    private boolean boolCatch;

    /**
     * All of the storages the player will contain
     */
    private Map<String, PlayerItemStorage> storages =
            new HashMap<String, PlayerItemStorage>();

    public PlayerStorageContainer(Player p) {
        this.player = p;
        this.initializePlayerStorages();
    }

    /**
     * Initializes the existing storage for player.
     */
    private void initializePlayerStorages() {
        this.storages.put("inventory", new Inventory(this.player));
    }

    /**
     * Gets the required PlayerItemStorage implementation
     * @param name Name of the implementing object
     * @return The object that extends PlayerItemStorage
     */
    public PlayerItemStorage getStorage(String name) {
        return this.storages.get(name);
    }

    /**
     * Removes an item from ALL storages
     * @param id        The Item ID
     * @param amount    The amount of the item
     * @return Returns a boolean if action was successful without any falses in the
     * middle of the execution, will return always true if {!boolCatch}
     */
    public boolean remove(int id, int amount) {
        for (PlayerItemStorage storage : this.storages.values()) {
            if (!storage.remove(id, amount) && this.boolCatch) {
                return false;
            }
        }
        return true;
    }

    /**
     * Adds an item to ALL storages
     * @param id        The Item ID
     * @param amount    The amount of the item
     * @return Returns a boolean if action was successful without any falses in the
     * middle of the execution, will return always true if {!boolCatch}
     */
    public boolean add(int id, int amount) {
        for (PlayerItemStorage storage : this.storages.values()) {
            if (!storage.add(id, amount) && this.boolCatch) {
                return false;
            }
        }
        return true;
    }

    /**
     * Resets all storages
     */
    public void reset() {
        for (PlayerItemStorage storage : this.storages.values()) {
            storage.resetStorage();
        }
    }

    /**
     * Toogles {@link PlayerItemContainer#boolCatch} for errors
     * @param b
     */
    public void setErrorCatch(boolean b) {
        this.boolCatch = b;
    }
}
</code>```

The problem

This system works fine for inventory, and equipment - however, this will be a problem and cause some big algorithm code duplicating for the bank type.

Since bank type storage can have multiple tabs up to 10, we will either need to create class named Tab and make it implement PlayerItemStorage, and put the same algorithm over the two classes (Bank and Tab) or have one method in Bank, and then have a variable named "focusedTab" which will hold the selected tab id, and make the add method accept 3 arguements (itemId, amount, tabId).

But making it accept 3 arguments will make a problem, I'll have to either ignore the abstract method add, and make own method for it, or create 2 abstract adds method, one with 2 parameters, one with 3 which I find too messy.

Did I design this whole thing incorrectly that I am having these problems?
How can I design a proper structure for this whole storage feature so it works with all kind of storages I can think of?

If you cannot understand the problem, you might find my code review thread helpful

Background about how the server handles items

When the client clicks on any item, in any game interface that supports item storage, it sends the slot id the player clicked on, due to security reasons. The server uses the slot id as the index of the PlayerItem[] array to get the information about the item.

答:
I think you've confused having an interface for your program to call to add/remove items for a particular player and being able to manage all individual cases.  The interface to the rest of your program should remain simple.  By simple I mean it should be single-purpose and the only methods public will be those that will be called.

As I understand it, it is PlayerItemStorage that handles the logic about fitting and physical layout of those items.  This sort of complication should remain within PlayerItemStorage.  For the callers of PlayerItemStorage, they should only care about what items are present, if an item has been removed or added.  When this happens, through a PlayerItemStorageChangeHandler interface, any instance in your program that wants to know about this event can register.  Your PlayerStorageContainer would use this as a means to get this information and act consequently.

Any validation about whether or not they can fit it in storage should be entirely managed by PlayerItemStorage.  Notice that I said that whether or not an item has been removed or added should be handled by PlayerItemStorage.  Do not be tempted to put the logic in PlayerStorageContainer since it should not know whether or not it is possible.

Granted, I still think adding and removing items from PlayerStorageContainer should be possible, however you should allow the possibility of failure.  Anything that you would want to happen as a consequence of adding it to PlayerItemStorage should be put in the same place as your PlayerItemStorageChangeHandler listener for new adds/removes (again, avoiding to duplicate your code).  Also, I presume that the main interface to be called when a player adds/removes items to his storage should be PlayerItemStorage and not PlayerStorageContainer for most operations, however I suppose if you say wanted to add a gift item to a player's storage, it would be preferable not to care which storage it is (just throw it anywhere where there's room).

Once you've established this relationship, you'll see that a bank concept with tabs is nothing more than a collection of PlayerItemStorage.  I would therefore create a special type of PlayerItemStorage called PlayerBankItemStorage.  It would override the same operations called by PlayerStorageContainer, but it could also maintain open tab state.  Try to keep the logic simple though.  You should forward most calls to PlayerItemStorage.    PlayerBankItemStorage would listen to PlayerItemStorageChangeHandler and then throw the event itself (if it should handle events at least, otherwise adding a new listener should simply forward to each individual PlayerItemStorage.

The key thing to remember is to avoid duplicating logic.  Keep class roles clear in your mind, and you'll find that it is easier to delegate tasks to your classes and keep logic in one place only.

Title: Structuring a storage system for a game


答:
This is the classical use case for favor composition over inheritance. If some properties belong closely together, than put them in a class of their own. Then you only need one property that references that class instead of having repeated properties all over the place. You then can get rid of the complete class hierachy.

Also mind that abstract classes are about abstracting behavior. If a getter is the behavior of your class, than it might be ok to have an abstract class with a getter (same applies for setter). But it mostly makes no sense from a behavioral perspective to have the getter and setter for the same property in the same base class, since that just leaves no room for behavioral abstractions.

Title: Is it good practice to declare and set properties in abstract classes?

Body:
I am using PHP and designing some abstract classes.

I can declare properties with constant values within my abstract class and access/overwrite them from any class which extends this without re declaring them within any of the extending classes.

A benefit to this is less repetitive typing but the downside that overtime the original structure/layout of these abstract properties is forgotten and could be left at there default static values or even forgotten(not used) completely.

How is this handled in professional environments? I assume this has been thought out before and is either favored or isn't?

I am trying to adhere to good OOP principles/rules such as SOLID, DRY and KISS but I haven't seen this specific issue talked about in these. (perhaps I missed it when researching?)


问:
Scalable Job Handler
We have a job table that triggers a notification when a new job gets inserted.
Clients that can handle such jobs may subscribe to those notifications.
When a client receives a notification, he can "lock" the job, so no other client will try to process it. We have also take care of errors and if a job takes to long to process.

Problem: A client can only handle X jobs at the same time.
On heavy load, all clients are busy handling their jobs. And new jobs may not get handled right away. If the client is no longer busy, he may query the table to find jobs that have not been processed yet. But if all clients stay busy for a long time (they finish jobs but new jobs arrive at the same time), those old jobs will never be processed.

Idea: After a client has processed Y jobs, he ignores all new jobs, and queries the table for the old ones. But I am not really comfortable with that idea.

Any ideas by you? If you need more information don't hesitate to ask for them.

答:
If I understand your question correctly, I think the following approach should work:

If a client ignores a notification once, because of its load, it ignores all following notifications too (even if the load decreases). From then on, it relies only on querying the database for old requests. Once all old requests are handled, it will start accepting notifications again.

Title: Scalable Job Handler


答:
This is the problem closely related to the job scheduling. But there are two issues you have to consider:

1) Your clients are free to choose any job they want. They know when new jobs arrive and can pick any one they want. If you really want to control what they do you should really limit what they can know and reserve for processing.

2) Before really delving deeper into the details and implementations of how all the scheduling and querying should work, you should first answer the next questions:

What do I want from my system's scheduling - determinism, fairness or efficiency of use?

Do I want my jobs to be handled the sooner the better?

Or I want to handle new jobs before old?

Or old before new?

Or there is some other property of jobs(estimated duration,
tag) that should determine their scheduling?

Can I preemptively stop(pause, abort) the job to handle a new
one(not your case, but nonetheless)?

And other similar questions...

As I understand for now you want:

To handle the new jobs as soon as possible, but never allow the old jobs to be unprocessed.

The simplest solution is FIFO-like processing with one job producer, but multiple job handlers.

I can suggest you something like:

```<code>// Job - the data needed to process the job
public interface IJob {...}

// Client - client that handles the jobs - IJobScheduler can suggest JobClient to
// requery for a new job if needed.
public interface IJobClient
{
    void SuggestQueryForNextJob();
}

// Each JobClient has its own JobQuery(IJobScheduler knows what to show to each of it).
// JobClient can query the next job or notify about the current one.
public interface IJobQueue
{
   bool TryQueryNextJob(ref IJob nextJob);
   void NotifyAboutJob(JobCompletionState jobCompState)
}

// Your main server, that allows JobConsumers to register themselves for job handling
public interface IJobScheduler
{
    IJobQueue RegisterConsumer(IJobConsumer consumer);
}
</code>```

This scheme will concentrate all the scheduling on your JobProducer's side, actually  allowing for nearly any possible scheduling mode.

It will demand its fair share of proxies and other stuff, but will greatly simplify your JobClients.

Title: Scalable Job Handler

Body:
We have a job table that triggers a notification when a new job gets inserted.
Clients that can handle such jobs may subscribe to those notifications.
When a client receives a notification, he can "lock" the job, so no other client will try to process it. We have also take care of errors and if a job takes to long to process.

Problem: A client can only handle X jobs at the same time.
On heavy load, all clients are busy handling their jobs. And new jobs may not get handled right away. If the client is no longer busy, he may query the table to find jobs that have not been processed yet. But if all clients stay busy for a long time (they finish jobs but new jobs arrive at the same time), those old jobs will never be processed.

Idea: After a client has processed Y jobs, he ignores all new jobs, and queries the table for the old ones. But I am not really comfortable with that idea.

Any ideas by you? If you need more information don't hesitate to ask for them.

Body:
This is the problem closely related to the job scheduling. But there are two issues you have to consider:

1) Your clients are free to choose any job they want. They know when new jobs arrive and can pick any one they want. If you really want to control what they do you should really limit what they can know and reserve for processing.

2) Before really delving deeper into the details and implementations of how all the scheduling and querying should work, you should first answer the next questions:

What do I want from my system's scheduling - determinism, fairness or efficiency of use?

Do I want my jobs to be handled the sooner the better?

Or I want to handle new jobs before old?

Or old before new?

Or there is some other property of jobs(estimated duration,
tag) that should determine their scheduling?

Can I preemptively stop(pause, abort) the job to handle a new
one(not your case, but nonetheless)?

And other similar questions...

As I understand for now you want:

To handle the new jobs as soon as possible, but never allow the old jobs to be unprocessed.

The simplest solution is FIFO-like processing with one job producer, but multiple job handlers.

I can suggest you something like:

// Job - the data needed to process the job
public interface IJob {...}

// Client - client that handles the jobs - IJobScheduler can suggest JobClient to
// requery for a new job if needed.
public interface IJobClient
{
    void SuggestQueryForNextJob();
}

// Each JobClient has its own JobQuery(IJobScheduler knows what to show to each of it).
// JobClient can query the next job or notify about the current one.
public interface IJobQueue
{
   bool TryQueryNextJob(ref IJob nextJob);
   void NotifyAboutJob(JobCompletionState jobCompState)
}

// Your main server, that allows JobConsumers to register themselves for job handling
public interface IJobScheduler
{
    IJobQueue RegisterConsumer(IJobConsumer consumer);
}

This scheme will concentrate all the scheduling on your JobProducer's side, actually  allowing for nearly any possible scheduling mode.

It will demand its fair share of proxies and other stuff, but will greatly simplify your JobClients.


问:
extensible effects in purescript
In Purescript, IO an other effects are managed with the Eff monad, and extensible effects, which are declared like this:

```<code>main :: Eff (trace :: Trace, random :: Random) {}
</code>```

So if I understand well, this main declaration only allows to log to console, and generate random numbers. The trace :: Trace, random :: Random is a row of effect, ie an unordered labeled collection of effects.

Now I get that Trace is an effect, and trace is its label. But why do we need both? It makes sense for records such as { foo::String, bar::String } but I cannot understand why I would need to manage two Random effect with different labels. ie I would write the following:

```<code>main :: Eff (Trace, Random) {} -- no redundant labels
</code>```

Are effect labels useful in purescript? If yes what for?

答:
<s>I have never used PureScript, but the short answer is yes, effect labels are useful for modeling effects in a principled way.

I'm not sure what your background is, so I don't know at what level to answer the question.  Are you familiar with side effects, the downsides of their unrestricted use, functional programming, and why we try to avoid side effects in FP?  If so, that provides a good motivation for effects systems, which make it possible to use effects without allowing their unrestricted use; in statically-typed languages, it is even possible to explicitly track effects in the type system.  One popular effects system is monad transformers (of course they are not without drawbacks -- but they have already been implemented in popular languages and are therefore easy to get started experimenting with).

If you understand all of that, then perhaps your question is simply why would one need/want multiple separate instances of the same effect?  Pseudo-random number generators don't generate random numbers, and the relationships between the generated numbers aren't random -- so with two (or more) separate random effects, you can essentially have two (or more) uncorrelated pseudo-random number streams.</s>

Disclaimer: I have never used PureScript -- this is just my opinion!

Why would one need/want multiple separate instances of the same effect?  Pseudo-random number generators don't generate random numbers, and the relationships between the generated numbers aren't random -- so with two (or more) separate random effects, you can essentially have two (or more) uncorrelated pseudo-random number streams.

Another benefit of using names -- even when there's no more than a single instance of any given effect -- is that some semantic meaning can be attached to the effects through a meaningful label.  In other words, not all States are created equal!

Another example of using multiple instances of the same effect, check out parser combinators.  These are easy to build from effects systems such as monad transformers.  A simple backtracking, error-reporting parser could be built out of the:

State -- handles the input string

Error -- error-reporting

Maybe -- backtracking

effects (sorry, that's Haskell terminology -- I don't know how those map to PureScript's effects).  If you wanted to also track the position (line, column) while parsing, you could add a second State effect.  You could also track global variable declarations using a third State effect (assuming you're parsing a programming language).  While in principle you could combine all three State effects into a single one, that would introduce coupling and be less extensible; having them separate avoids this coupling.

Title: extensible effects in purescript


问:
Broadcast receiver Or Services
I am creating an "Alarm Clock" app in Android. I learned that we can implement OnReciever() method and write those things which we want the alarm to do after an intent is fired.

But I have now come across the "Services" of android which is (might) be useful in the app.

Which one should I prefer, keeping in mind the simplicity of using either of them.

答:
Using a service is a bad idea. The system can kill at any time for example to free memory. You can make it a foreground service to get around this but that requires a persistent notification in the notification bar.

Instead take a look at the AlarmClock class. You have to create BroadcastReceivers to handle ACTION_SET_ALARM and ACTION_SET_TIMER Intents.

Title: Broadcast receiver Or Services


问:
Functional programming strategies in imperative languages
I've been convinced for awhile now that some strategies in functional programming are better suited to a number of computations (i.e immutability of data structures). However, due to the popularity of imperative languages, its unlikely that I will always be working on projects that are functionally implemented. Many languages (Matlab, Python, Julia) support using a functional paradigm, but it feels tacked on in many cases (looking at you, anonymous functions in Matlab).
That being said, what are functional methods and strategies that I can use even in OOP/Imperative code? How can I write solid functional code that does not allow side effects even in languages that have mutable state and global variables?</p>

答:
Prefer pure functions and immutable variables/objects.

Apart from that, keep in mind the limits and the conventions of the language you are using. Don't forget:

Readability. Your colleagues will find your non-idiomatic code harder to understand

Lack of tail call optimization

Lack of laziness

Lack of useful optimizations (ex. stream fusion)

Lack of convenient syntax (ex. for anonymous functions) etc...

In my experience, except for a few maps and filters here and there, pushing functional abstractions too far has never worked well. Functional programming is very powerful, but it doesn't mean it is the "absolute true way" in all contexts.


答:
```<code>ILatLongLocation
{
    double Latitude;
    double Longitude;
}

ILocatable
{
    ILatLongLocation GeoCoordinate;
}
</code>```

Ok, looks sensible so far. I would probably change the names a little, but that's just preference.

```<code>ILocatableProvider<T> : ILocatable
</code>```

You lost me here. Lets maybe specify in the simplest terms what you need the service to perform. From what I can understand, you want a service to take in a zip code, and return you an ILatLongLocation. To put that in code terms.

```<code>IZipToGeoCoords
{
    ILatLongLocation GetGeoCoordsFromZip(string zip);
}
</code>```

This doesn't return ILocatables, because ILocatables are themselves the containers of ILatLongLocations. This service would be used by whatever process is creating the ILocatable when the geo-coordinates must be derived from a zip code.

```<code>ILocatable objectWithGeoCoordinates = new GeoCoordinateWrapperThingy();
objectWithGeoCoordinates.GeoCoordinate = injectedIZipToGeoCoordsService.GetGeoCoordsFromZip(aZipCode);
</code>```

The rest of what you mention, especially the DB context part, seems due to you wanting to encapsulate the creation of ILocatables along with the creation of ILatLongLocations. But to create an ILocatable from a zip code in the first place, you first need some service to derive that.

At whatever point you're taking your object that has a zip code, and want to convert it over to a version of itself that implements ILocatable, whatever is doing that conversion would need the IZipToGeoCoords service constructor injected into it.

Title: How should one implement the dependency-injection for a geocoding client that aggregates different coordinate provider implementations?

Body:
I am new to DI and I would like to know how DI might be used to help resolve this problem.

If I have an ILatLongLocation which implements a Latitude and Longitude, then given two of these I can produce a Distance using a variety of algorithms, but I can also reasonably pick one of these as the "best" algorithm at design-time without losing any sleep.

However, since users will rarely input physical coordinates, I may need to instead compare by zip codes or something similar.

Now, in order to resolve zip codes to coordinates, I could apply a naive algorithm that uses string concatenation, etc to do a rough guess as to the physical coordinates, I could pick a random set of coordinates, etc. But in all likelihood, I will need to resolve the zip codes by using some sort of database mapping zip codes to coordinates.

So being new to DI, I would like to know if the following is a reasonable application of DI and/or if I am overthinking it.

ILocatable has ILatLongLocation

ILocatableProvider<T> : ILocatable has a T RawLocatable and can return an ILatLongLocation.

IZipCodeLocatableProvider : ILocatableProvider<string> has a string RawLocatable and returns an ILatLongLocation.

NaiveZipCodeLocatableProvider is an implementation that just uses patterns in zip codes that are well-known to provide a best-effort guess as to the coordinates.

DbZipCodeLocatableProvider is an implementation that uses a database (maybe through a DbContext or somehow else) to return the coordinates.

Now DbZipCodeLocatableProvider itself must depend on some sort of repository or context or connection or something to access a database (unless it is literally hard-coded)... so then this means I need to have a DbContext or something similar... here is where I get lost.

Am I thinking about this the right way? Is this a legitimate scenario for dependency injection? And how do I discriminate between, say different connection strings vs different strategies altogether for resolving zip codes to coordinates?

Edit: ...and don't forget about WebServiceZipCodeLocatableProvider ... there's another (realistic) option.

Body:
ILatLongLocation
{
    double Latitude;
    double Longitude;
}

ILocatable
{
    ILatLongLocation GeoCoordinate;
}

Ok, looks sensible so far. I would probably change the names a little, but that's just preference.

ILocatableProvider<T> : ILocatable

You lost me here. Lets maybe specify in the simplest terms what you need the service to perform. From what I can understand, you want a service to take in a zip code, and return you an ILatLongLocation. To put that in code terms.

IZipToGeoCoords
{
    ILatLongLocation GetGeoCoordsFromZip(string zip);
}

This doesn't return ILocatables, because ILocatables are themselves the containers of ILatLongLocations. This service would be used by whatever process is creating the ILocatable when the geo-coordinates must be derived from a zip code.

ILocatable objectWithGeoCoordinates = new GeoCoordinateWrapperThingy();
objectWithGeoCoordinates.GeoCoordinate = injectedIZipToGeoCoordsService.GetGeoCoordsFromZip(aZipCode);

The rest of what you mention, especially the DB context part, seems due to you wanting to encapsulate the creation of ILocatables along with the creation of ILatLongLocations. But to create an ILocatable from a zip code in the first place, you first need some service to derive that.

At whatever point you're taking your object that has a zip code, and want to convert it over to a version of itself that implements ILocatable, whatever is doing that conversion would need the IZipToGeoCoords service constructor injected into it.


答:
Seek legal advice in your jurisdiction.

Seriously, because the cases and laws are all over the place...

I perviously delved into the question of font licenses in Can I use a @font-face of "Courier New"? - and while much of that answer is about the font Courier, it exposed things like 'typefaces aren't copyrightable in the US'.  Much about this is said in Policy Decision on Copyrightability of Digitized Typefaces from 1988 which states that the Copyright Act of 1976 rejected the ability to copyright a typeface:

The decision in Eltra Corp. v. Ringer clearly comports with the intention of the Congress.  Whether typeface designs should be protected by copyright was considered and specifically rejected by Congress in passing the Copyright Act of 1976.

There are other forms of protection that may be applied to typefaces, such as design patents (such as the font used by Coca-Cola) and names may be trademarked.  However, the font may not be copyrighted... at least in the US.  The files that specify the font may still be under copyright, but this appears to suggest that one create another font that looks the same (as long as you aren't working from the original) the font and reimplement it and copyright wouldn't protect against that.

And that said, one should also pay attention to Adobe Systems, Inc. v. Southern Software, Inc where it was found that Adobe did have copyright over a font that was implemented as a scalable representation rather than a bitmap.

And all of this is applicable only to the US law... other countries do allow for copyrights on a font face.

So... talk to a lawyer.  There are a number of different findings and laws and such that all intermix in this area that make it impossible for someone who isn't familiar with the law and intellectual property to navigate.

Further reading and referenced works::

Wikipedia: Intellectual property protection of typefaces

Policy Decision on Copyrightability of Digitized Typefaces

Wikipedia: Eltra Corp. v. Ringer

Wikipedia: Adobe Systems, Inc. v. Southern Software, Inc

Title: GPL+FE license also applies to fonts used for the UI of a software?

Body:
The GPL font exception allows the font to be embedded within a digital "document" file without requiring the "document" itself to also be shared with GPL.

Now I wonder, what is considered a "document"? If the GPL+FE font is embedded in a software to render a user interface, the software can be released with a non-GPL license?


问:
Do you rotate agile team members?
I've got long standing developers in my sprint team. They know the domain, they've been with the company 5+ years and as a team we have a pretty good burn down rate.

There are other sprint teams, some with equally knowledgeable developers and others with newer developers who are trying to get up to speed.

My manager is worried that all our eggs are in one basket and wants to rotate out one or two knowledgeable developers in exchange for the some new guys. I can see their point but can also see the problems that go with that - I'm sure there are others but these are just a few off the top of my head.

New developer will have a much lower work rate

New developer will bring down the work rate of at least one experienced person as they constantly ask questions.

New developer leaves the team at the end to join another team - hopefully he'll remember what he did with us.

New developer leaves the company - wow we wasted a whole bunch of time.

I might like to add that the organisation is struggling with agile. It was a traditional waterfall development company and still thinks in big releases and items that are "expected" to be in the release.

If you've been in a similar situation to this I'd love to know you experiences - does rotating out the team members work? Would pair programming or other methods be a better route to take?

答:
New developer will bring down the work rate of at least one experienced person as they constantly ask questions.

This is a good thing, in moderation.

Every process has countless sources of friction - be it tooling-related, design-related, or whatever. Trouble is, a lot of your sources of friction you don't notice. Having someone come on board brings a set of fresh eyes, questioning everything you're doing, and giving an excellent feedback loop.

Sometimes this feedback loop will be obvious: they'll ask why you're doing X instead of Y, and Y will indeed be a better approach.

Sometimes it'll be subtler - you're getting a lot of questions about a particular module, and that's feedback that the module isn't designed well.

Yes, having a new person on the team will slow down your straight-line speed. It's also a great check on whether or not the straight line you're following is the best line to follow.

Title: Do you rotate agile team members?