问:
Adding complexity by generalising: how far should you go?
Reference question: https://stackoverflow.com/questions/4303813/help-with-interview-question

The above question asked to solve a problem for an NxN matrix. While there was an easy solution, I gave a more general solution to solve the more general problem for an NxM matrix. A handful of people commented that this generalisation was bad because it made the solution more complex. One such comment is voted +8.

Putting aside the hard-to-explain voting effects on SO, there are two types of complexity to be considered here:

Runtime complexity, i.e. how fast does the code run

Code complexity, i.e. how difficult is the code to read and understand

The question of runtime complexity is something that requires a better understanding of the input data today and what it might look like in the future, taking the various growth factors into account where necessary.

The question of code complexity is the one I'm interested in here. By generalising the solution, we avoid having to rewrite it in the event that the constraints change. However, at the same time it can often result in complicating the code. In the reference question, the code for NxN is easy to understand for any competent programmer, but the NxM case (unless documented well) could easily confuse someone coming across the code for the first time.

So, my question is this: Where should you draw the line between generalising and keeping the code easy to understand?

答:
The interview question was probably designed to test the subject would notice that there were only n+1 possible different rows; if any row ended with a zero, it would be the smallest.  Otherwise the smallest row would be 000...001.  Although in general it is better to design methods that will work with arbitrarily-sized NxM matrices rather than NxN, such an assumption is predicated upon the fact that most methods either only make sense with square matrices or else don't really care about matrix shape.  An efficient solution for the general problem will be much more complex than code which simply tests whether the last column contains any zeroes.

To use an analogy, suppose a program will receive a list of 999,999 distinct numbers from 1 to 1,000,000 and tasked to identify the "missing" number.  The simplest algorithm would be to "xor" together all the numbers and compare that result with the xor of the numbers from 1 to 1,000,000.  If the list had only 999,998 distinct numbers, finding even one of the missing numbers would be much harder, but there's no need for an algorithm that can handle that case.

ContentLicense: CC BY-SA 2.5


问:
Meaning of MIT license
Suppose I use this ActionScript API released under MIT license
to build a software: http://www.cove.org/ape/docs/api/

Can I sell that software?

Do I need to give the source code of my software away?

Is anyone receiving my software permitted to resell the software?

答:
You can sell the software.

No, you are not compelled to provide source code.

Anyone who receives source code may do as the license permits. This does not extend to binary distributions.

Read the MIT license. Read the whole thing and understand it. It was meant to be read by ordinary people, unlike other licenses that are very complex:

Copyright (c) year copyright holders

Permission is hereby granted, free of
  charge, to any person obtaining a copy
  of this software and associated
  documentation files (the "Software"),
  to deal in the Software without
  restriction, including without
  limitation the rights to use, copy,
  modify, merge, publish, distribute,
  sublicense, and/or sell copies of the
  Software, and to permit persons to
  whom the Software is furnished to do
  so, subject to the following
  conditions:

The above copyright notice and this
  permission notice shall be included in
  all copies or substantial portions of
  the Software.

THE SOFTWARE IS PROVIDED "AS IS",
  WITHOUT WARRANTY OF ANY KIND, EXPRESS
  OR IMPLIED, INCLUDING BUT NOT LIMITED
  TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF
  CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS
  IN THE SOFTWARE.

Title: Meaning of MIT license

OwnerDisplayName: dwc


答:
As always, consult a lawyer. If this library is released strictly using the MIT license then:

(i) Yes, you can sell your software provided you include the MIT license as part of your product.
(ii) No, you don't have to share your code with the community but it would be nice.
(iii) Yes, reselling is permitted.

MIT License:

Permission is hereby granted, free of
  charge, to any person obtaining a copy
  of this software and associated
  documentation files (the "Software"),
  to deal in the Software without
  restriction, including without
  limitation the rights to use, copy,
  modify, merge, publish, distribute,
  sublicense, and/or sell copies of the
  Software, and to permit persons to
  whom the Software is furnished to do
  so, subject to the following
  conditions:

The above copyright notice and this
  permission notice shall be included in
  all copies or substantial portions of
  the Software.

Title: Meaning of MIT license

Body:
Suppose I use this ActionScript API released under MIT license
to build a software: http://www.cove.org/ape/docs/api/

Can I sell that software?

Do I need to give the source code of my software away?

Is anyone receiving my software permitted to resell the software?

OwnerDisplayName: Aaron Saarela


问:
What do Java developers think of Scala?
I've noted that IDE support is nowhere near as good, but the language itself supports functional programming idioms much more cleanly.</p>

答:
Well, I think Scala is too complex. It feels like C++ in that it has a myriad of different ways of doing things. Some would call this "richness", "expressiveness" or "power", but your mileage may vary. In many real world projects you would have to artificially limit what language features you're going to use and what not, so that all developers involved could speak the same subset of the language.

For functional programming I prefer Clojure, which is way simpler than Scala.

Let the holy war begin ;-)

Title: What do Java developers think of Scala?


答:
According to "Understanding Open Source and Free Software Licensing" by By Andrew M. St. Laurent:

These licenses, as applied to the original licensed code, allow that code to be used in
  proprietary software and do not require that open source versions of the code be dis-
  tributed. Code created under these licenses, or derived from such code, may go
  “closed” and developments can be made under that proprietary license, which are
  lost to the open source community. For the same reason, however, these licenses are
  very flexible and compatible with almost every form of open source license.

Title: Meaning of MIT license

OwnerDisplayName: Swaroop C H


问:
Should I continue stressing development standards?
I've been with my software team for about three years now, and just recently I brought up the concept of variable naming conventions (across all languages, but C#/VB.Net specifically).

We really don't have any solid naming conventions.  I was met with serious resistance - so what?, does it really matter?, blank stares, etc.

I was able to get the others to agree to at least be consistent on a given code file (not ideal, but with this group, any standards that is based around anything other than SQL is a step forward).

My question is this - I've always received resistance to developing standards.

Should I just stop pushing standards and accept the fact that everyone seems to be doing their own thing when they code?

答:
Don't quit yet. Try the following first.

Sell them the idea differently. Sell them the idea as "code quality".

If you are the boss:

Tell them that they need to improve the quality of their code.

Tell them that the naming convention is the major aspect to be considered in the first phase.

Tell them that code quality is going to be considered in their performance appraisal.

If you are only their peer:

Tell them they don't have to change the code that is already done, but apply the conventions in the new code they write.

Use the convention yourself.

Clarify that you are not inventing some in-house convention but using the universally-accepted convention of any given language, the one the official documentation of the language uses.

Prepare a presentation about the benefits of adopting a naming convention.

Talk about the collective ownership of code. They shouldn't apply personal criteria to code that is everyone's to maintain.

Plot/print a poster-sized naming convention cheat-sheet and display it in your cubicle. Offer to plot/print a copy for whomever shows interest.

Do you use unit tests ?

Refactor mercilessly whenever you feel like it. Unit tests will have your back.

If nothing works:

Be faithful to yourself and continue to provide an example.

Remember work is only a part of life. Pursue other, more worthy aims.

ContentLicense: CC BY-SA 3.0


问:
Is using Git Stash as a workflow an antipattern?
I've recently been looking at how me and my team uses Git and how our workflows work. We currently use a feature-branch workflow which seems to work well.

I've also seen some individuals on our team use workflow based on git stash. The workflow goes something like this:

Work on a main branch (like master)

Make commits as you go

If you need to get changes or switch branches, push your uncommitted changes onto the stash

Once your updating is done, pop the changes off the stash.

I should mention that this workflow is used instead of a feature branch workflow. Instead of taking a branch and working on it, developers here only ever work on a single branch and push/pop off the stack as they see fit.

I actually don't think this is a great workflow, and branching would be more appropriate than using git stash in this way. I can see the value of git stash as an emergency operation, but not for using it in a daily, regular workflow.

Would using git stash regularly be considered an anti-pattern? If so, what are some specific problems that could arise? If not, what are the benefits?

答:
I personally only use stash for short, unexpected interruptions, like someone asking a question that requires changing to a different branch.  I do this because I have forgotten about stashes before, then they wouldn't apply cleanly.  Regular commits on feature branches are much harder to forget about, and easier to merge, so now I tend to just make a broken commit, then do a git reset HEAD~1 or a rebase if I don't want to keep it later.

However, the great thing about distributed version control is people can use their preferred workflow in their own repositories, as long as the shared repositories meet the standards.  I would make sure people aren't just using a stash workflow because they don't have enough training or awareness of alternatives, but if they still choose a workflow you find suboptimal, I would leave it be.


问:
Is there a better way to update NoSQL records in bulk?
When we started our application we had the choice of going with the traditional MS-SQL normalized database or with a NoSQL database (RavenDB is what we tried out). Here is a simplified version of our schema:

```<code><Order OrderNumber="1000" OrderVersion="1" ...>
  <Products>
    <Product Code="X58" Price="$5.50" Quantity="3" ... />
    <Product Code="X70" Price="$9.99" Quantity="1" ... />
  </Products>
  <Contacts>
    <Contact ... />
    <Contact ... />
  </Contacts>
</Order>
</code>```

While we could have went with a MS-SQL database, we didn't because we wanted all of our data for an order to be kept historically; we did not want to FK the contact even if they had the same name and address because while it might change, the order should have the contact info at the time of purchase. Also, yes, we could have FK our Products instead of using the Code to reference the product, but Products never get deleted, and again... if they are updated we want to capture their information at the time of purchase. Basically, every Order seems to be a self-contained document that should never rely on FKs.

OrderVersion is just to keep track of our process version when the order was created, we could easily just have used OrderDate to track versioning.

Anyways, so our decision was to go with RavenDB. We built out our application and website, and internally we are testing it out. The one scenario we are running into problems is: "How do you do a bulk update on records as good as SQL does it?"

For example, if we had just pushed our code to production during offline maintenance and somehow all records from MA with ZipCodes that have a leading zero (0) had the zero trimmed off (i.e. the zip code now read 1234 instead of 01234)?

Normally, we would patch things immediately on one fail-over server at a time, and updating records would be easy:

```<code>UPDATE c
SET c.ZipCode = ...
FROM Contact c
    INNER JOIN Order o ON c.OrderId = o.OrderId
WHERE o.Version = 1
  AND ...
</code>```

But, it seems that the best solution we could come up with if we use RavenDB is to get all documents, then programmatically update the records through a custom C# console app. It seems that TSQL is much easier/faster. I'm not sure if there is a better way that we are unaware of, or is this a common shortcoming of using RavenDB (or any NoSQL document store)?

My biggest worry is, while our console app seemed to run just fine enough with a sample of 100K orders, what happens if we get to the point of 50M+ orders!? Or, is that also an issue with T-SQL that we would eventually run into with the example I gave?

答:
Wow, there are sure a lot of extraneous statements in your question.  I think I can boil it down to:

How do I update documents in RavenDB?

That question already has been answered on StackOverflow here and here, which will point you at RavenDB's Patching API.  There's also extensive documentation available here, and you can even kick off a bulk patch operation from the RavenDB Studio, as described here.  (No custom app required.)

Also, I wouldn't fall into the trap of assuming that the SQL Server way is necessarily better.  It's just different.  Have you ever tried updating 50M+ records with a single update statement in SQL Server?  I think you'll find that the locking model is quite prohibitive.   It's likely you would get timeouts or deadlocks.  You'd probably have to implement some batching and retry operations.  With RavenDB, while it may take a while, you're at least ensured that the operation will complete eventually, and your database will stay online during the process.


问:
Does Play framework approach necessarily leads to confuse code?
I want to start a new project and I just got in touch with Play framework, which has a ruby on rails -like approach that called my attention.
I am not an expert in rails, but I think that the productivity in these frameworks are great.

I am following some tutorials but I am wondering:
Play has the Model, which is used to populate the view but also used to perform DB queries. I find that somehow awkward, but I noticed that rails has also this approach.

I wonder if using the same entity for Object Relational Mapping and to populate the view may cause troubles. Here are two examples I can think of:

My view required only a name and an ID from a big entity

My view requires information from different entities

For the second case, I suppose I would be able to perform a join. But it seems somehow messy: joins in my controller, DB entities being used to populate views.

Am I missing some point here? I mean, these frameworks seem great and I would like to use them, but I wonder if my code wound turn into an spaghetti code. It seems to be on the opposing direction of I learned about separation of concerns.

If I separate in a layered architecture (models for my views, business logic layer and DAO layers), should I keep using play or should I move to something different like Spring?

答:
Your concerns are valid.

Default pattern of Rails-like frameworks are great for small(er) programs coded by less-experienced programmers that don't have a grasp on software architecture -- framework provides a skeleton for the whole application, all abstractions are defined, after coding 3 classes we have something on the screen. This use case is also good for prototyping.

It doesn't mean that framework of this kind can't be used when doing more serious software development - it can (and probably should), but more as a tool than as main structure of the program.

Decoupling business objects from the view is certainly a good habit. I'm sure it can be done as easily when using Play framework as it is with Spring. You can check out Robert Martin's Keynote to Ruby Midwest 2011, where he presents an architecture that completely decouples business logic from the framework (or "delivery mechanism", as he calls it). He uses Rails as an example.


问:
What benefits are there to native JavaScript development?
Given how much simpler jQuery development is, when compared to native JavaScript, what makes people forgo libraries like jQuery altogether?

Is this because jQuery has limitations or it is slow? I mean, if jQuery is so easy compared to native javascript, what reasons do people have to still use pure javascript?

答:
Mike

I think people hedge against using some libraries are due to dependency on that infrastructure/library solution to perform some task.

But let's be careful to remember languages come and go like libraries in the long run.

So maybe it's temporal scope.  Maybe people are hesitant to invest in a library that just might not be there - or have have as much momentum behind it in the long run.

Myself? I have no objection to using JQuery in particular.  I also look at say Box2d.js or three.js and would much rather embrace them even if short term shelf life than miss out on what fruits they have to offer.

Mike bottom line is there is risk in the shelf life of a library you choose, and I think some in the javascript community may have experienced loss due to a library or project coming to an end, and may have just said - never again.

OwnerDisplayName: Mike


问:
Calculating NPath Complexity
I'm trying to calculate the NPath Complexity within a function, but I'm unsure what parts I count.

My understanding is that it'll sum:

If

Else

Else If

Switch

Case

Default

Do

While

Is this correct? Or am I missing something?

答:
The NPath Complexity is the sum of the possible routes through your code (ignoring cycles).

The complexity therefore depends on the structure of your code rather than just the tokens:

```<code>if (x) {
   if (y) {
     // Do something
   } else {
    // Do something else
   }
} else {
  // Do something even more else
}
</code>```

Has 3 possible paths that could be taken, depending on the values of x and y.

As you nest control structures more deeply, the number of possible paths increases exponentially.

Skimming this code: http://pmd.sourceforge.net/pmd-4.3/xref/net/sourceforge/pmd/rules/design/NpathComplexity.html
will give an idea of the complexity of calculating the complexity:-)

OwnerDisplayName: James

Title: Calculating NPath Complexity

Body:
The NPath Complexity is the sum of the possible routes through your code (ignoring cycles).

The complexity therefore depends on the structure of your code rather than just the tokens:

if (x) {
   if (y) {
     // Do something
   } else {
    // Do something else
   }
} else {
  // Do something even more else
}

Has 3 possible paths that could be taken, depending on the values of x and y.

As you nest control structures more deeply, the number of possible paths increases exponentially.

Skimming this code: http://pmd.sourceforge.net/pmd-4.3/xref/net/sourceforge/pmd/rules/design/NpathComplexity.html
will give an idea of the complexity of calculating the complexity:-)


问:
Who can learn to program?
I always hesitate when talking to professors about trying to improve the percentage of people who graduate with a CS type degree compared to the number that start out thinking that is what they want. On one hand I really do think it is important for professionals to be involved and give this feedback, on the other hand it would be better if less sub-par students ended up with CS degrees.

I don't think every mind is built for this field and you have to be a good life long student. You have to have a high degree of patience and problem solving skills just to eek by. If you do have the "right" kind of brain, those hard problems are what drives you to continue. If you just get a long list of easy problems you get bored so these people are actually not good at more repetitive jobs. I don't need to go into all the details... if you are reading this you probably know what I'm getting at.

So the question is: How do you find the balance of a degree program that is accessible to enough people to be funded and considered successful but also doesn't turn out people who aren't really cut out for the job? Maybe a better question is, what metric do you use to know if the changes you are making in a degree program are making it better? I don't know that a higher graduation rate is a good metric. And it seems that the feedback that you could try to capture many years later about the jobs that the graduates hold would be too far delayed.

I've struggled with this question for a long time, mostly because I don't think there is an answer. But I thought I'd ask to see if anyone knows of any research that has actually been done on it.

Addition: I recently had a very wise professor remind me that not everyone who graduates with a CS degree even wants to be a full-time programmer once they have actually discovered what that means. But, with the education that they received they could possibly make great Project Managers, Managers, system admins, etc. I think this was a very good point that I hadn't thought to consider here. There are a very high percentage of people who don't end up working in the field they majored in, CS isn't an exception to that. Having the extra folks helps not only in budget for the degree but also to expand the percentage of non-programmers who still know enough about it to work with programmers.

答:
To program is to instruct in a logical manner so as to achieve some desired output. In other words it is telling the computer to do some task. The only way to move forward is by practicing.

Just as learning English or any other language you need to start by learning the syntax (alphabet) and then move on to grammar and other constructs. The amount of time required varies depending on the complexity of the language. Coding in higher level languages like SQL, Python is almost like writing English.

Title: Who can learn to program?


问:
Agile development challenges
With Scrum / user story / agile development, how does one handle scheduling out-of-sync tasks that are part of a user story?

We are a small gaming company working with a few remote consultants who do graphics and audio work. Typically, graphics work should be done at least a week (sometimes 2 weeks) in advance of the code so that it's ready for integration. However, since SCRUM is supposed to focus on user stories, how should I split the stories across iteration so that they still follow the user story model? Ideally, a user story should be completed by all the team members in the same iteration, I feel that splitting them in any way violates the core principle of user story driven development.

Also, one front end developer can work at 2X pace of backend developers. However, that throws the scheduling out of sync as well because he is either constantly ahead of them or what we have done is to have him work on tasks that not specific to this iteration just to keep busy. Either way, it's the same issue as above, splitting up user story tasks.

答:
We face a similar problem, because our work often requires external resources (cooperation from technology partners, or in-house resources such as a new server or a configuration change).

What we do:

We create tasks in the story for those external dependencies (like "Organize new server for load testing", "Run test with technology partner X", "Get new icon for button X"). We then try to start work on those tasks as soon as we start with the story, in the hope that it can run in parallel to our own work an be done when our work is done.

Sometimes the external dependency is ready in time, sometimes it is not. If it is not, we mark the story as "blocked", to indicate that we cannot continue work on it due to external factors.

We have organized our team board such that these stories stand out, and resolving the blockers is treated as high priority. Additionally, there is a list of blockers across teams, to give management an insight into areas where teams may need support.

Usually this work well, and a story is only delayed a week or two at most. If the delay gets longer, we try to split off the part that requires external resources, or find a workaround (like a default icon). If there is no way to get by without the external resource, the story just stays blocked.

This does mean that in rare cases a story stays open for months. This is ugly, but it accurately reflects reality, so we feel this is the best solution.

Note: We use Kanban, not Scrum, so there is no problem with meeting iteration commitments.

OwnerDisplayName: Bob

Title: Agile development challenges


问:
What to do about "stopping point syndrome"?
I have noticed a behavior in myself that I call "stopping point syndrome"... it means I cannot stop working until I reach a "stopping point" (or I become exhausted).  In other words, if I am in the zone working on getting a feature completed, I won't stop until I get it done.   If it's a bug I'm working on, this effect is even more pronounced... I won't stop until it's fixed, or at the very least, understood.  Even though I work from a laptop and have VPN and could easily go home and pick up on the work later that evening, that fact does not help me leave work... it's like I'm afraid I will die before I find the bug.

I have a very hard time explaining this to family members who can't figure out why I never come home from work at the same time and sometimes come home at 11 pm.  Even managers have been mystified by this, and I've noticed that most of my colleagues have no trouble working the same hours every day.

Does anyone else have this problem?  Should I be worried about this and/or try to change it?  If so how?

答: Nah, you're not alone. I have the same problem. You might want to check out the answers in the similar question I asked a while ago: What to do when the programming activity becomes a problem?</p>


问:
Should putting html tags into localization files be avoided?
We are localizing all parts of our website to many languages. We use XML localization files. I think this scenario is so common, and even there should be a standard solution to this, but still I couldn't find any good advice, and every developer here has different opinion about it, so I'm asking you.

Suggest the following example:

If you have question, please ask our Customer support or write an email to Jane Doe  our specialist.

Or a long, formatted text:

```<code> <p>A very long, marketing blah-blah. A very long, marketing blah-blah. A very long, marketing blah-blah concluding in a list:</p>
 <ul>
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>
</code>```

1) Would you put html tags into the localization XML file?

My concern is the View is separated into 2 files: your page and your localization file. People will forget to check the localization file. Also, there's logic and style embedded in html as well (see target="_blank", or the fact that the above mentioned list is unordered...)

2) Or splitting it to smaller parts?

<msg id="IfYouHaveQuestion">If you have question, please ask our</msg>

<msg id="CustomerSupport">Customer support</msg>

<msg id="OrWrite">or write an email to</msg>
...

Now, View can contain all the markup and style. It's easy to change it, flexible.

But.

There's absolutely no guarantee that the word order will be the same in all languages. Also, this would make the translator's work a nightmare, making it a puzzle.

3) Or introduce BB-style markdown?

<msg id="HaveQuestion">If you have question, please ask our [link url="{customersupportlink}" title="{{CustomerSupportTitle}}">Customer support[/link] or write an email ...</msg>

But probably this is over-complicating the issue, and also we have to write our own parser for this (though, I think it wouldn't be so hard). And probably does not solve the long, formatted text problem.

4) ??? (Your golden solution here) :)

答:
With PHP gettext implementations we use placeholder string substition for placing varying content inside translatable texts.

For instance, in WordPress (__() is a WP specific gettext function used to extract strings from source) you can do this:

```<code>$content = sprintf( __( 'Send us a message or %1$sview our contact information%2$s.' ), '<a href="...">', '</a>' );
</code>```

Which gives is a .pot source string

```<code>Send us a message or %1$sview our contact information%2$s.
</code>```

After PHP parses and executes sprintf you get the following output (in the wanted language of course):

```<code>Send us a message or <a href="...">view our contact information</a>.
</code>```

This way all the markup and other non-translatable data resides inside the application logic and stays out of the translation string data. The only gotcha is to instruct translators to actually copy over the placeholders properly.

Depending on your implementation you could use placeholders too. A custom implementation of sprintf wouldn't be that difficult either. So in essence your "BB-code" variant would be closest.

ContentLicense: CC BY-SA 4.0

Body:
With PHP gettext implementations we use placeholder string substition for placing varying content inside translatable texts.

For instance, in WordPress (__() is a WP specific gettext function used to extract strings from source) you can do this:

$content = sprintf( __( 'Send us a message or %1$sview our contact information%2$s.' ), '<a href="...">', '</a>' );

Which gives is a .pot source string

Send us a message or %1$sview our contact information%2$s.

After PHP parses and executes sprintf you get the following output (in the wanted language of course):

Send us a message or <a href="...">view our contact information</a>.

This way all the markup and other non-translatable data resides inside the application logic and stays out of the translation string data. The only gotcha is to instruct translators to actually copy over the placeholders properly.

Depending on your implementation you could use placeholders too. A custom implementation of sprintf wouldn't be that difficult either. So in essence your "BB-code" variant would be closest.


问:
Viable method of sharing our PHP project
We are two developers that have no previous experience in sharing one PHP project. In particular, cakePHP.

We both use NetBeans and we have set the project up as a "PHP application from a remote server". For the project we also use git + bitbucket for version control as well.

Now the problem is that whenever one of us makes any changes to the code and saves it, it gets updated on the server, but not in the other developer's environment.

Is this the right path we are taking for sharing the project?

How to make the code updates and how to avoid overriding other code?

答:
I suggest you read the Git book - http://git-scm.com/book

You need to commit your changes after you make them and push the data to bitbucket.

Once you have done this your partner can fetch the changes from Bitbucket and merge the changes, before repeating the process.

Version Control is designed to prevent you overriding each others code but you must first understand how to use it, there are also plenty of tutorials on youtube etc.


答:
It doesn't have to lead to confused code, but there are trade-offs. Sometimes you may find that your ORM is pulling all the fields of data from a row when you only need two, sometimes the queries would not be the same as those you would use or you may need to get a greater depth of entities than the ORM will automatically query so you end up going back to the database a couple of times when perhaps you could theoretically have got all that information in one trip.

These types of thing are standard outcomes of using an ORM system and aren't tied specifically to any particular platform.

The question you need to ask yourself is really about that balance and consequently about what you feel is important:

Do you want to write very detailed code, or get code written quickly?

Do you want to save your processor time, or do you want to save yourself time?

Would it be better value to use a more powerful server, or to spend longer writing code in the first place?

When it comes to MVC as opposed to MV-VM-C, that again comes down to personal choice- in MVC settings I have seen logic in models that possibly didn't theoretically belong there, in cases where ViewModels are used, I have seen totally redundant empty classes being created just to ensure that every model had a corresponding ViewModel even when neither had any discernable logic in them.

The important thing is that before you choose a platform, you read up on its advantages and disadvantages and when you make your choice, you learn to use it in a way that means you can write code that fits with the ethos of the platform and that you ( and other developers ) will be able to read in future. Honestly that is more important than whether the platform you are using is an ideal implementation of a specific design pattern or a currently fashionable twist on it. I mean I know people who write good code in PHP - sometimes it's important to look at the bigger picture. And lets not forget that design patterns themselves are more like guidelines than actual rules.

Title: Does Play framework approach necessarily leads to confuse code?

Body:
I want to start a new project and I just got in touch with Play framework, which has a ruby on rails -like approach that called my attention.
I am not an expert in rails, but I think that the productivity in these frameworks are great.

I am following some tutorials but I am wondering:
Play has the Model, which is used to populate the view but also used to perform DB queries. I find that somehow awkward, but I noticed that rails has also this approach.

I wonder if using the same entity for Object Relational Mapping and to populate the view may cause troubles. Here are two examples I can think of:

My view required only a name and an ID from a big entity

My view requires information from different entities

For the second case, I suppose I would be able to perform a join. But it seems somehow messy: joins in my controller, DB entities being used to populate views.

Am I missing some point here? I mean, these frameworks seem great and I would like to use them, but I wonder if my code wound turn into an spaghetti code. It seems to be on the opposing direction of I learned about separation of concerns.

If I separate in a layered architecture (models for my views, business logic layer and DAO layers), should I keep using play or should I move to something different like Spring?


问:
Data persistence for transactional customer emails
I'm developing a system to handle sending transactional emails to our customers. This is how it works:

An event occurs during the order's life cycle, for example 'shipped'

This event will trigger the creation of an email in the database (email queue)

A separate windows service is polling the db table for new emails to send. When it finds one it calls a Web service with all the required data. It's the Web service's responsibility to handle the actual sending of the email.

My question relates to step 2. When an email triggering event occurs, should I take a snapshot of all the data required by the service (thereby duplicating data and introducing new tables) or should I get the required data from the transactional db tables only at the point where I'm ready to call the Web service.

[Note: I'm not at all concerned with the body of the email, all I'm doing is passing the data to a Web service. The email templates etc are handled by another system. My concern is purely to queue the email notification and pass the required data to the Web service.]

答:
In this case I would serilize the objects needed to pass to the web service and store them in the database. The two services should operate as independently from one another as they can. Serialization of the complete "driving" objects will allow you to update and adjust the mailer without having to update and adjust the event listener.

You could also create a data containing class and pass just the information you need, but then you make 3 updates where there only needs to be one down the line.

However, it seems like your building a very complex system, that shouldn't be. Assuming that you need to call the web service to send an email, then why not just  call the web service in the event listener.  If you need to store something to the database, then you can do that too, in the event listener.


答: You also need to include operators such as && || and ? :, since these themselves can produce alternate execution paths.

Title: Calculating NPath Complexity

Body:
I'm trying to calculate the NPath Complexity within a function, but I'm unsure what parts I count.

My understanding is that it'll sum:

If

Else

Else If

Switch

Case

Default

Do

While

Is this correct? Or am I missing something?


问:
Git Submodule for untracked folder?
I have a git repository with a folder in it. The folder is listed in my .gitignore file. I cloned another repository into that ignored folder from github. I may want to work inside of the new repository but I don't see any reason for it to be a part of the original repository. Perhaps I should just keep it outside of the original repository but it seems (to me anyway) like a reasonable place for it thematically (its in a place where I would know to look for it).

I guess I'm having a hard time getting my head around the concept of a submodule. My specific question is "Should I use a submodule in this situation, even when the folder is ignored?"

I noticed that "git status" gives me status of my original repository even though I issue the command inside of the ignored folder

答:
It really depends on the relationship between the original repository and this new repository. Is one a dependency of the other?

Quoting from the git-submodule documentation:

[...] submodules are meant for different projects you would like to make
  part of your source tree, while the history of the two projects still
  stays completely independent [...]

If the new repository is something that your original repository depends on, and you would like to keep it in a specific place in your source tree, it would make sense to make it a submodule. That would give you the ability to:

Automatically clone and check out the submodule repository in the right place, after cloning the main repository

Pin the submodule repository to a specific commit

Work on (and see the status of) the submodule repository more easily, with git submodule status or git submodule summary

However, since you say:

I don't see any reason for it to be a part of the original repository.

it sounds like the repositories have no relation and submodules might not benefit you. If this is the case, it would probably be simplest to keep the repositories separate.

Title: Git Submodule for untracked folder?


问:
Beginning a sentence with a function name?
Occasionally while typing something up that relates to a case-sensitive programming language I end up starting a sentence with a function name. Now the rules of English state that the first word in a sentence needs to be capitalized; the function name is lowercase, though. If you are wondering what could I be saying that would result in the first word being a function name, take this example:

Your fread implementation is broken. fread needs to return how many bytes were read.

I understand that I could change the second instance of fread to It but I want to know the best way of handling this other than just rewriting the sentence. Should I capitalize the function name? The only way I would like to hear "rewrite the sentence" as an answer is if starting the sentence with a function name violates some English rule that I am not aware of.
Edit: I really thank everyone for these answers. They have changed and improved my insight into the issue. I have learned quite a bit from this. I am very surprised that I did not think of these simple but good solutions.

I do think my stance on alternating the sentence was too tough and now I realize due to these good answers that overall altering the sentence appears to be the best option for dealing with these cases be it adding parenthesis after the function or saying The function before the function name and if available using formatting for the function name.

答:
The Linux man page for fread(3) that others linked is a great example of four common solutions.

Begin your sentence with "The function foo" or "The foo function". "The function fread needs to return ...".

Mark the function name with extra characters according to the convention used by your programming language community. In the case of C, an empty pair of parentheses, so "fread() needs to return ...".

Use typography (bold , fixed width characters or italics) to highlight the function name, as: "fread needs to return ..."

On systems that use man, if your function has a man page, refer to the chapter of the manual in parentheses. So "fread(3) needs to return ..."

All four approaches will be instantly recognizable by hackers, and you should be able to choose one that matches your house style or your personal voice.

As you said, you cannot rely on typography to highlight your function name. Markdown's syntax is meant to make readable documentation even when a markdown interpreter is unavailable, so by all means surround your function name by a pair of backticks. (This is, I guess, a combination of options 2 and 3.)

Option 2 varies according to programming language. For example, Ruby and Smalltalk docs often precede instance method names with a hash, like #fread.  Meanwhile, Lispers might prefer the function name to be bare, but will understand if you write a skeleton function call, such as (fread ...) or (fread). Rinse and repeat for all languages you document.


问:
Algorithms for making image mosaics - is there a quicker way than this?
I've been playing with making image mosaics.  My script takes a large number of images, scales them down to thumbnail size and then uses them as tiles to approximate a target image.

The approach is actually quite pleasing:

I compute the mean square error for every thumb in every tile position.

At first I just used a greedy placement: put the thumb with the least error on the tile it best fits, and then the next and so on.

The problem with greedy is that it leaves you eventually placing the most different thumbs on the least popular tiles, whether they match closely or not.  I show examples here:
http://williamedwardscoder.tumblr.com/post/84505278488/making-image-mosaics

So I then do random swaps until the script is interrupted.  The results are quite OK.

A random swap of two tiles is not always an improvement, but sometimes a rotation of three or more tiles results in a global improvement i.e. A <-> B may not improve, but A -> B -> C -> A1 may..

For this reason, after picking two random tiles and discovering they do not improve, I pick a bunch of tiles to evaluate if they can be the third tile in such a rotation.  I do not explore if any set of four tiles can be profitably rotated, and so on; that'd be super-expensive real soon.

But this takes time.. A lot of time!

Is there a better and faster approach?

Bounty Update

I tested out various Python implementations and bindings of the Hungarian Method.

By far the fastest was the pure-Python https://github.com/xtof-durr/makeSimple/blob/master/Munkres/kuhnMunkres.py

My hunch is that this approximates the optimal answer; when run on a test image, all other libraries agreed on the result but this kuhnMunkres.py, whilst being orders of magnitude faster, only got very very very close to the score the other implementations agreed on.

Speed is very data-dependent; Mona Lisa rushed through kuhnMunkres.py in 13 minutes, but the Scarlet Chested Parakeet took 16 minutes.

Results were much the same as random swaps and rotations for the Parakeet:

(kuhnMunkres.py on the left, random swaps on the right; original image for comparision)

However, for the Mona Lisa image I tested with, the results were noticeably improved and she actually had her defined 'smile' shining through:

(kuhnMunkres.py on the left, random swaps on the right)

答:
Yes, there are two better and faster approaches.

Simpler problem : for each tile, choose the best thumb (with possible duplication). Ok, that's cheating, but can only lead to better visual result.

Your take is algorithmically more interesting, and boils down to "linear assignment problem", assuming you take MSE as match costs whose sum must be minimal. Such problem can be solved in polynomial time, via eg the "Hungarian Method"

Then, you can adjust your costs by replacing MSE by a more visually accurate distance, without changing the underlying algorithm.


答:
I think the part of your question that is an anti-pattern is the use of a single shared master branch.  However, if you were to include a develop branch in addition to the master branch and then use stashes to deal with your own context switches in the develop branch, that would not be an anti-pattern, and it very closely mirrors some of the workflow describe by organizations like Etsy and Facebook.

That having been said, @Greg Burghardt's answer above is a bit too favourable to the so-called git-flow or feature-branch work flow. I used to advocate for a similar strategy but after realizing that it adds unnecessary complexity and creates a false sense of security, I no longer do. It's also a holdover from the days of non-decentralized version control systems like subversion.

Firstly since Git is a decentralized version control system unlike subversion, a developer's local repository is essentially a giant branch of the code in and of itself. What an individual develop does locally doesn't and shouldn't have an impact on the other team members unless broken or buggy code is pushed up to any shared branches in a shared repository.

The rebase command, however, can damage the history of branch when there is a merge conflict in one of the replayed commits. From http://ryantablada.com/post/the-dangers-of-rebasing-a-branch

The rest of the rebase goes along smoothly, tests all seem to pass. A PR is made.

And then some more code is written that relies on the commentsForAllPosts property and everything is broken. But who do we go and ask for help? git blame shows that line of code has only been written by the server side engineer and he throws up his hands.

Now your front-end engineer is out on vacation, sick leave, or who knows. No one can figure out what that code should look like!

Rebase has killed the team's ability to look at the history to find what went wrong because any merge conflicts on the child branch are killed and the original code is lost forever.

If this same merge conflict came up and merge was used, the blame would show that that line of code had been touched in the merge process, the commit on the parent branch, and the commit on the child branch. Some toying around with the three permutations and you can get the original intent back into the code base and working without a ton of head scratching a finger pointing. And all you really had was another commit

Furthermore, a multiple branching model presupposes that no two branches could ever contain interdependent code changes. When that does inevitably occur, the developer now has to juggle yet more branches to work efficiently.

The fundamental anti-pattern that I see is not related to branches vs. stashes, but rather more about the kinds of problems that some very smart people have been talking about for a while now:  do you have confidence in your code via the use of unit tests and a good architecture?  Are you able to make incremental changes to your code such that your developers can reason about changes easily and understand what a change will do? Do your developers even run through new code once to see if it actually works? (Yes I have seen this before).

If the answer to those questions is no, then it doesn't really matter how many branches you have-- developers will say that code is ready, working, and fit for production when it really isn't, and no number of branches will help you when that code goes up to production anyway.

Title: Is using Git Stash as a workflow an antipattern?

Body:
I've recently been looking at how me and my team uses Git and how our workflows work. We currently use a feature-branch workflow which seems to work well.

I've also seen some individuals on our team use workflow based on git stash. The workflow goes something like this:

Work on a main branch (like master)

Make commits as you go

If you need to get changes or switch branches, push your uncommitted changes onto the stash

Once your updating is done, pop the changes off the stash.

I should mention that this workflow is used instead of a feature branch workflow. Instead of taking a branch and working on it, developers here only ever work on a single branch and push/pop off the stack as they see fit.

I actually don't think this is a great workflow, and branching would be more appropriate than using git stash in this way. I can see the value of git stash as an emergency operation, but not for using it in a daily, regular workflow.

Would using git stash regularly be considered an anti-pattern? If so, what are some specific problems that could arise? If not, what are the benefits?


问:
Website compatibility with old operating systems
I'm a web developer. I most often come across this critical situation when the website layout fits with the design when run on Windows 7 or 8 and Mobile Operating Systems (Android, iOs, Windows 8).

But when the website is visited by old operating systems like Windows XP and Windows 1998 the whole layout collapses very badly. And specially when visited on old operating systems with Internet Explorer.

If we take into account the old operating systems (and/or IE on them) it creates havoc for us. Sometimes, even the well supported front-end frameworks like Twitter Bootstrap give up there and won't support the older browsers.

When clients or management request to make the website compatible with all the OS out there including Win XP, how to address this?

答:
This absolutely depends on your individual needs and your audience. If you're targeting a largely well-off audience, you can write off old versions pretty freely. If your audience includes a lot of people with older equipment (lower income people, older people, people in the developing world, etc.) you may still find you need to support IE 7 on Windows XP in order to reach everyone. If you're targeting corporate audiences, you will need to put a premium on IE 8 support, because a lot of big companies still require their employees to use it. If you're leaning towards a tech-savvy audience, you may not want to bother with the limitations IE 8 creates.

Thankfully, non-IE browsers, following Chrome's lead, generally strongly push users to upgrade to the latest version, so except in very weird circumstances, testing in old versions of Chrome or Firefox is usually unnecessary.


问:
Are mutliple database calls really significant with a network call for a web API?
At one of my employers, we worked on a REST (but it also applies to SOAP) API. The client, which is the application UI, would make calls over the web (LAN in typical production deployments) to the API. The API would make calls to the database.

One theme that recurs in our discussions is performance: some people on the team believe that you should not have multiple database calls (usually reads) from a single API call because of performance; you should optimize them so that each API call has only (exactly) one database call.

But is that really important? Consider that the UI has to make a network call to the API; that's pretty big (order of magnitude of milliseconds). Databases are optimized to keep things in memory and execute reads very, very quickly (eg. SQL Server loads and keeps everything in RAM and consumes almost all your free RAM if it can).

TLDR: Is it really significant to worry about multiple database calls when we are already making a network call over the LAN? If so, why?

To be clear, I'm talking about order of magnitude -- I know that it depends on specifics (machine hardware, choice of API and DB, etc.) If I have a call that takes O(milliseconds), does optimizing for DB calls that take an order of magnitude less, actually matter? Or is there more to the problem than this?

Edit: for posterity, I think it's quite ridiculous to make claims that we need to improve performance by combining database calls under these circumstances -- especially with a lack of profiling. However, it's not my decision whether we do this or not; I want to know what the rationale is behind thinking this is a correct way of optimizing web API calls.

答:
Two thoughts:

First, to the consumer using the API, he is making one call to accomplish a task. What happens after your server receives the call to fill the request should not be so rigid. If that one call from a consumer requires 10 sub-work items to pull the data together and return it, then that should be acceptable.

Second: Do you see an actual database performance problem with the process in question? My experience has shown that often trying to put all aspects of a database request into a single call can result in a less efficient call than simply making three or four calls for data. Modern databases are very efficient in caching and execution plans. Often, when you try to do too much you will see procedures with cursors (very bad for performance because data is acted on row by row, not as a set at once) and code that results in a less efficient plan than if you had broken the call up into several small easy steps.

Out of simple organization of code, I do agree that each API call should possibly call a single stored procedure (or db function) which in turn is responsible for filling the request. There may be more than one step in the procedure.


答:
Sounds like your team is optimizing before they have a reason to.  Have you measured time to execute these requests?  Chances are forcing this paradigm will create worse performance for the end user as the round trips to the web server will have a much higher latency than the connection time from the web server to the database.  On top of that most web browsers will only make 2 concurrent connections to a single web server, so for complex pages you will likely run into a bottleneck there.

Either way optimization decisions should not be made without data to back it up.  Measure it and figure out what is best for your application.

Title: Are mutliple database calls really significant with a network call for a web API?

Body:
At one of my employers, we worked on a REST (but it also applies to SOAP) API. The client, which is the application UI, would make calls over the web (LAN in typical production deployments) to the API. The API would make calls to the database.

One theme that recurs in our discussions is performance: some people on the team believe that you should not have multiple database calls (usually reads) from a single API call because of performance; you should optimize them so that each API call has only (exactly) one database call.

But is that really important? Consider that the UI has to make a network call to the API; that's pretty big (order of magnitude of milliseconds). Databases are optimized to keep things in memory and execute reads very, very quickly (eg. SQL Server loads and keeps everything in RAM and consumes almost all your free RAM if it can).

TLDR: Is it really significant to worry about multiple database calls when we are already making a network call over the LAN? If so, why?

To be clear, I'm talking about order of magnitude -- I know that it depends on specifics (machine hardware, choice of API and DB, etc.) If I have a call that takes O(milliseconds), does optimizing for DB calls that take an order of magnitude less, actually matter? Or is there more to the problem than this?

Edit: for posterity, I think it's quite ridiculous to make claims that we need to improve performance by combining database calls under these circumstances -- especially with a lack of profiling. However, it's not my decision whether we do this or not; I want to know what the rationale is behind thinking this is a correct way of optimizing web API calls.


问:
Communication/Updates between units of works/entity framework contexts, colliding with user changes
I'm developing a WPF application using Entity Framework for my database communication. The application has a hierarchy of tabs where each tab has a db context. Each tab allows the user to view some particular object, make changes, save, update, close or open tabs for related objects.

My crux is that some tabs contain information that depends on other objects as well, an object O of type A may be related to other A objects (o_1,...,o_n) in a parent-children relationship, where I have a graphic indicator showing wether property P in O has the same value as P in all the children of O, for example. Red indicator means they are unequal, green means they are equal.

The "overlap" in information between contexts will only be presentation-wise, the different tabs will not be stepping on each others toes by changing each others data.

Now if I have Tabs for O and o_3 opened, change P in o_3 and save, the indicator in the tab for O might need to change as well, but since that tab has its own (now outdated) db context, the indicator still shows the old value, which might be confusing to the user.

This seems like a very general and common problem considering how many application has this architecture.

How would you solve the problem? I see a few different but flawed/problematic solutions.

A. Make the user aware of the fact that tabs can become "obsolete" when saving others. This feels like a forfeit to technological troubles.

B. Force updates of related tabs when saving. This would either overwrite user changes or I would have to build some system (repository pattern?) that maintains information of user changes and mediates what to update and what to keep, what to tell the user and so on.

C. Indicate outdated:ness of related tabs. This seems like the pragmatic solution, but the user is left to wonder what would be affected if updating the tab manually, and any changes made would have to be dismissed

D. Communicate the change to the other tab without involving the db context. This would sort of work, but could lead to complicated problems by introducing state that is not related to the db context, overall it would increase complexity

答:
In the desktop application I am currently working at we solved similar problems by introducing an event mechanism, centered around a global "Event Manager". We have got a handful of "main business objects" (~10 different types), and whenever one dialog changes a business object, it raises a "change" event, including the type and the ID of the related object (the ID is also the primary DB key, we have uniform integer keys for all our objects). There are also "add" or "deleted" events for newly created or deleted objects.

Now dialogs use the publisher-subscriber pattern, if they are "interested" in getting notifications about changes for a specific object type, they register themselves at the event manager, which then will pass notifications for the specific type to every registered listener.

But how does this solve the problems you mentioned? Well, the answer is: every dialog can now decide for himself what to do when he gets a change event for a related object. That makes changes and collision handling much more simpler and manageable as if one dialog would have to make decisions for another "parent" or "child" dialog. For example, when getting a change notification, a dialog can test if the ID in the change events is equal to the ID of one of the objects it is currently presenting, and decide to refresh the object in stake from the DB. Or, if there were pending changes made to that object by the user in a second dialog, it could present the user with some kind of "collision resolve" dialog, do some automatic collision handling, or just notify the user about the collision and let him deal with that. That is actually what you mentioned under "B". How the "collision resolve" strategy has to look like depends very much on the amount and importance of the data, how much data in the "unit of work" can get lost when you implement only a simple strategy like "last change wins", or if you need a very sophisticated "compare-and-merge" tool.

Note that this event management works only within the local application, we did not implement such a thing across different clients, so when one user working at client 1 changes an object a second user working at client 2 has on its display, it is possible that client 2 still shows the old data for some time. The purpose is just not to confuse the user by showing the same object in different states simultanously on the same screen.


答:
All examples here are picking on IE 6.  Feel free to mentally swap it with Gingerbread or whatever software you are dealing with when reading this.

The larger the set of systems that you need to deal with, the more development and testing it will take.  This includes resources like actualizing having a machine that still runs IE 6 (for those holdouts).

As such, there is a cost and return that need to be factored in.  Saying "oh yea, it still needs to support IE 6" is not free.

Now, once you realize there is a cost associated with it this becomes a question for the managers and clients to answer - "are you willing to spend ${money} and ${time} more to have it support ${old os}?"

When asking this question you should have the information about the estimates for the additional cost that you will incur supporting the system.  Furthermore, have the information about the current market share using your service.  Dig through your logs and see how many requests are actually coming from the ancient software today.

It's quite possible that your boss or client will say "yes, we want you to support that and are willing to spend the extra time and money to do so" in which case you're doing it - thats what the requirements are.

Your job is to make sure that this decision is fully informed both on the cost and reward.

Title: Website compatibility with old operating systems

Body:
I'm a web developer. I most often come across this critical situation when the website layout fits with the design when run on Windows 7 or 8 and Mobile Operating Systems (Android, iOs, Windows 8).

But when the website is visited by old operating systems like Windows XP and Windows 1998 the whole layout collapses very badly. And specially when visited on old operating systems with Internet Explorer.

If we take into account the old operating systems (and/or IE on them) it creates havoc for us. Sometimes, even the well supported front-end frameworks like Twitter Bootstrap give up there and won't support the older browsers.

When clients or management request to make the website compatible with all the OS out there including Win XP, how to address this?


问:
Why were default and static methods added to interfaces in Java 8 when we already had abstract classes?
In Java 8, interfaces can contain implemented methods, static methods, and the so-called "default" methods (which the implementing classes do not need to override).

In my (probably naive) view, there was no need to violate interfaces like this. Interfaces have always been a contract you must fulfill, and this is a very simple and pure concept. Now it is a mix of several things. In my opinion:

static methods do not belong to interfaces. They belong to utility classes.

"default" methods shouldn't have been allowed in interfaces at all. You could always use an abstract class for this purpose.

In short:

Before Java 8:

You could use abstract and regular classes to provide static and default methods. The role of interfaces is clear.

All the methods in an interface should be overriden by implementing classes.

You can't add a new method in an interface without modifying all the implementations, but this is actually a good thing.

After Java 8:

There's virtually no difference between an interface and an abstract class (other than multiple inheritance). In fact you can emulate a regular class with an interface.

When programming the implementations, programmers may forget to override the default methods.

There is a compilation error if a class tries to implement two or more interfaces having a default method with the same signature.

By adding a default method to an interface, every implementing class automatically inherits this behavior. Some of these classes might have not been designed with that new functionality in mind, and this can cause problems. For instance, if someone adds a new default method default void foo() to an interface Ix, then the class Cx implementing Ix and having a private foo method with the same signature does not compile.

What are the main reasons for such major changes, and what new benefits (if any) do they add?

答:
The correct answer is in fact found in the Java Documentation, which states:

[d]efault methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

This has been a long-standing source of pain in Java, because interfaces tended to be impossible to evolve once they were made public. (The content in the documentation is related to the paper that you linked to in a comment: Interface evolution via virtual extension methods.) Furthermore, rapid adoption of new features (e.g. lambdas and the new stream APIs) can only be done by extending the existing collections interfaces and providing default implementations. Breaking binary compatibility or introducing new APIs would mean that several years would pass before Java 8's most important features would be in common use.

The reason for allowing static methods in interfaces is again revealed by the documentation: [t]his makes it easier for you to organize helper methods in your libraries; you can keep static methods specific to an interface in the same interface rather than in a separate class. In other words, static utility classes like java.util.Collections can now (finally) be considered an anti-pattern, in-general (of course not always). My guess is that adding support for this behavior was trivial once virtual extension methods were implemented, otherwise it probably wouldn't have been done.

On a similar note, an example of how these new features can be of benefit is to consider one class that has recently annoyed me, java.util.UUID. It doesn't really provide support for UUID types 1, 2, or 5, and it cannot be readily modified to do so. It's also stuck with a pre-defined random generator that cannot be overridden. Implementing code for the unsupported UUID types requires either a direct dependency on a third-party API rather than an interface, or else the maintenance of conversion code and the cost of additional garbage collection to go with it. With static methods, UUID could have been defined as an interface instead, allowing real third-party implementations of the missing pieces. (If UUID were originally defined as an interface, we'd probably have some sort of clunky UuidUtil class with static methods, which would be awful too.) Lots of Java's core APIs are degraded by failing to base themselves on interfaces, but as of Java 8 the number of excuses for this bad behavior have thankfully diminished.

It's not correct to say that [t]here's virtually no difference between an interface and an abstract class, because abstract classes can have state (that is, declare fields) while interfaces cannot. It is therefore not equivalent to multiple inheritance or even mixin-style inheritance. Proper mixins (such as Groovy 2.3's traits) have access to state. (Groovy also supports static extension methods.)

It's also not a good idea to follow Doval's example, in my opinion. An interface is supposed to define a contract, but it is not supposed to enforce the contract. (Not in Java anyway.) Proper verification of an implementation is the responsibility of a test suite or other tool. Defining contracts could be done with annotations, and OVal is a good example, but I don't know whether it supports constraints defined on interfaces. Such a system is feasible, even if one does not currently exist. (Strategies include compile-time customization of javac via the annotation processor API and run-time bytecode generation.) Ideally, contracts would be enforced at compile-time, and worst-case using a test suite, but my understanding is that runtime enforcement is frowned upon. Another interesting tool that might assist contract programming in Java is the Checker Framework.


答:
We can't tell you.

We don't what your queries look like. We don't know how long they take to complete. We don't know how much overhead is involved in each request to your API server. We don't know how geographically dispersed your clients are. Etc.

If this is a scenario that requires optimization and is one in which you can decide whether to split or join the calls together, you need to benchmark it both ways: Decide what you're optimizing for (UI latency, server CPU load, contention, etc.) and pick the one the one that better achieves your optimization goal.

Aside from that, the only one thing I can add with relative certainty is this:

Within a single request, you should perform all the queries you need to perform to build a response.

In other words, if the response can't be generated until all N queries are performed, it's usually senseless to separate them. If you can generate meaningful results, whether intermediate or complete, after each query, start benchmarking.


问:
Benefits of Java ByteArrayInputStream vs byte array?
I have a scenario where my Java process will be receiving a stream of binary data:

```<code>public class DataHandler {
    public void handleData(DATA data) {
        // TODO: Do something with data
    }
}
</code>```

I am trying to figure out the proper typing for DATA. I could use a byte[]:

```<code>public class DataHandler {
    public void handleData(byte[] data) {
        // TODO: Do something with data
    }
}
</code>```

Or a ByteArrayInputStream:

```<code>public class DataHandler {
    public void handleData(ByteArrayInputStream dataStream) {
        // TODO: Do something with dataStream
    }
}
</code>```

To me, "ByteArrayInputStream" implies a continuous stream of data that is constantly being modified. Based on that, it feels like ByteArrayInputStream is better suited for my use case as it probably adds a bunch of bells and whistles on top of a plain 'ole byte[]. But then I see that its constructor takes byte[] and doesn't allow you to add more bytes to it post-construction, which might not necessarily do anything for me in this particular case.

So my questions:

In my use case, are there any benefits to ByteArrayInputStream over byte[]? Why/why not? What are the factors that drive this decision (in general)?

Is there a better way to represent a true stream of flowing data (which ultimately comes in as bytes) besides the methods I've recommended here?

答:
InputStream itself is already an abstraction of a stream of bytes that can be read. A ByteArrayInputStream is a specific implementation of InputStream that gets the bytes in the stream from an underlying byte array (that's the one the constructor wants you to supply).

For your method here, there is probably not much benefit in having a ByteArrayInputStream, an InputStream definitely would, as clients could then pass all kinds of byte sources to your method, whereas otherwise they'd have to read them in an array themselves. A stream also has the advantage that you don't have to have all bytes in memory at the same time, which is convenient if the size of the data is large and can easily be handled in small chunks.


答:
If the database is on a different server than your REST service, each database call will result in a network roundtrip and that can significantly hurt performance:

I once observed a single webservice call be translated to about 500 database queries - this was hardly a problem when both the webservice and the database are located on the same machine, but turned into a response time of 6-7 seconds when they were on different machines.

Obviously, 500 roundtrips to the database is pretty extreme. I'm not sure what your performance requirements are, but as a rule-of-thumb I would say that if you stay under around 10 database queries per REST-call you should not experience a significant performance hit.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答: I once had a long "discussion" with a pointy-haired boss who insisted that we could store a 2 in a bit datatype because it was "only one digit."</p>


答:
But is that really important? Consider that the UI has to make a network call to the API; that's pretty big (order of magnitude of milliseconds). Databases are optimized to keep things in memory and execute reads very, very quickly (eg. SQL Server loads and keeps everything in RAM and consumes almost all your free RAM if it can).

The Logic

In theory, you are correct.  However, there are a few flaws with this rationale:

From what you stated, it's unclear if you actually tested / profiled your app.  In other words, do you actually know that the network transfers from the app to the API are the slowest component?  Because that is intuitive, it is easy to assume that it is.  However, when discussing performance, you should never assume.  At my employer, I am the performance lead.  When I first joined, people kept talking about CDN's, replication, etc. based on intuition about what the bottlenecks must be.  Turns out, our biggest performance problems were poorly performing database queries.

You are saying that because databases are good at retrieving data, that the database is necessarily running at peak performance, is being used optimally, and there is nothing that can be done to improve it.  In other words, databases are designed to be fast, so I should never have to worry about it.  Another dangerous line of thinking.  That's like saying a car is meant to move quickly, so I don't need to change the oil.

This way of thinking assumes a single process at a time, or put another way, no concurrency.  It assumes that one request cannot influence another request's performance.  Resources are shared, such as disk I/O, network bandwidth, connection pools, memory, CPU cycles, etc.  Therefore, reducing one database call's use of a shared resource can prevent it from causing other requests to slow down.  When I first joined my current employer, management believed that tuning a 3 second database query was a waste of time.  3 seconds is so little, why waste time on it?  Wouldn't we be better off with a CDN or compression or something else?  But if I can make a 3 second query run in 1 second, say by adding an index, that is 2/3 less blocking, 2/3 less time spent occupying a thread, and more importantly, less data read from disk, which means less data flushed out of the in-RAM cache.

The Theory

There is a common conception that software performance is simply about speed.

From a purely speed perspective, you are right.  A system is only as fast as its slowest component.  If you have profiled your code and found that the Internet is the slowest component, then everything else is obviously not the slowest part.

However, given the above, I hope you can see how resource contention, lack of indexing, poorly written code, etc. can create surprising differences in performance.

The Assumptions

One last thing.  You mentioned that a database call should be cheap compared to a network call from the app to the API.  But you also mentioned that the app and the API servers are in the same LAN.  Therefore, aren't both of them comparable as network calls?  In other words, why are you assuming that the API transfer is orders of magnitude slower than the database transfer when they both have the same available bandwidth?  Of course the protocols and data structures are different, I get that, but I dispute the assumption that they are orders of magnitude different.

Where it gets murkey

This whole question is about "multiple" versus "single" database calls.  But it's unclear how many are multiple.  Because of what I said above, as a general rule of thumb, I recommend making as few database calls as necessary.  But that is only a rule of thumb.

Here is why:

Databases are great at reading data.  They are storage engines.  However, your business logic lives in your application.  If you make a rule that every API call results in exactly one database call, then your business logic may end up in the database.  Maybe that is ok.  A lot of systems do that.  But some don't.  It's about flexibility.

Sometimes to achieve good decoupling, you want to have 2 database calls separated.  For example, perhaps every HTTP request is routed through a generic security filter which validates from the DB that the user has the right access rights.  If they do, proceed to execute the appropriate function for that URL.  That function may interact with the database.

Calling the database in a loop.  This is why I asked how many is multiple.  In the example above, you would have 2 database calls.  2 is fine.  3 may be fine.  N is not fine.  If you call the database in a loop, you have now made performance linear, which means it will take longer the more that is in the loop's input.  So categorically saying that the API network time is the slowest completely overlooks anomalies like 1% of your traffic taking a long time due to a not-yet-discovered loop that calls the database 10,000 times.

Sometimes there are things your app is better at, like some complex calculations.  You may need to read some data from the database, do some calculations, then based on the results, pass a parameter to a second database call (maybe to write some results).  If you combine those into a single call (like a stored procedure) just for the sake of only calling the database once, you have forced yourself to use the database for something which the app server might be better at.

Load balancing: You have 1 database (presumably) and multiple load balanced application servers.  Therefore, the more work the app does and the less the database does, the easier it is to scale because it's generally easier to add an app server than setup database replication.  Based on the previous bullet point, it may make sense to run a SQL query, then do all the calculations in the application, which is distributed across multiple servers, and then write the results when finished.  This could give better throughput (even if the overall transaction time is the same).

TL;DR

TLDR: Is it really significant to worry about multiple database calls when we are already making a network call over the LAN? If so, why?

Yes, but only to a certain extent.  You should try to minimize the number of database calls when practical, but don't combine calls which have nothing to do with each other just for the sake of combining them.  Also, avoid calling the database in a loop at all costs.


问:
Proper Response to HTTP Request When Too Much Data is Requested
I'm building an API for an ad serving platform that will allow you to request tracker data for ad campaigns. Campaigns often exceed hundreds of millions of requests, which means there will be many terabytes worth of data. Therefore we need to prevent API consumers from requesting too much data at once (such that the request times out), but I'm not sure what the best practice is for doing so is.

Options I've already identified are:

add an extra parameter to the request that indicates which section of the data is desired

truncate the data and somehow tell the client that they need to use more specific filters

respond with HTTP status code 413 (but this appears to be for large request bodies, not responses)

switching to a streaming API (like twitter's streaming APIs)

But my question is, what is the standard practice / proper response for this kind of situation?

Note: DoS attacks aren't much of a concern since this will not be a public API

答:
Not sure about a best practice, but in our case we do have parameters in our API that are set to some kind of maximum value (think Integer.MAX_VALUE from Java). These parameters are often not available to the UI/client-side of the application, only to server-side calls.

Basically, the approach would be to set a maximum on records returned by your request. Seems to work well, particularly when data doesn't need to be organized or paginated in any way.

If a client (human or otherwise) need more than this maximum, you may want to consider increasing it or batching your data somehow.

OwnerDisplayName: Griffin


答:
To expand on what @joshin4colours said, I think you have a false dichotomy (trichotomy?). Why not provide all three solutions? Maybe the default is to return a 413 but with other flags you can either get some of what you want with an embedded error in the data and/or provide a way of batching the data.

It really depends on what your specific customer/consumer of the API expects and how they want to use your API. Are they ever going to want a 413? Should the default response include some data and indicate how much more there is?  Maybe.  You could also put yourself in the client's shoes and think about what they would want, i.e. what would be useful to them.

What I've usually done is give the first batch of data with an idea of how much more there is. Returning a 413 isn't very friendly, but maybe that's want you want in some cases. From what I've experienced, usually there's a default batch size but people can ask for a certain batch size up to some limit.

Also, you could consider aggregation or sampling to reduce batch size. For example, I want 50,000 results as a random sample of 5,000,000 matching records.  There are different ways to slice and dice depending on how statistically significant you want your results to be.

Title: Proper Response to HTTP Request When Too Much Data is Requested

Body:
I'm building an API for an ad serving platform that will allow you to request tracker data for ad campaigns. Campaigns often exceed hundreds of millions of requests, which means there will be many terabytes worth of data. Therefore we need to prevent API consumers from requesting too much data at once (such that the request times out), but I'm not sure what the best practice is for doing so is.

Options I've already identified are:

add an extra parameter to the request that indicates which section of the data is desired

truncate the data and somehow tell the client that they need to use more specific filters

respond with HTTP status code 413 (but this appears to be for large request bodies, not responses)

switching to a streaming API (like twitter's streaming APIs)

But my question is, what is the standard practice / proper response for this kind of situation?

Note: DoS attacks aren't much of a concern since this will not be a public API


问:
What does it mean when some technology is a "standard"?
I started learning Java EE 7 and I am frequently coming across this term "standard", and I don't understand what it means.

So, for example, here is a quotation from this book:

Contrary to SOAP and the WS-* stack, which rely on W3C standards, REST
  has no standard and is just a style of  architecture with design
  principles. REST applications rely heavily on many other standards:
  HTTP, URI, URL...

I have some idea of what that might mean, but I'm not sure.

The best explanation that I have come across is the definition from here.

答:
A technology standard is a specification such that two implementations of the same standard are expected to be interoperable or interchangeable. Examples: USB, Bluetooth, Java EE7, HTTP.

Then there are "de facto" standards: conventions that enable interoperability, but without an explicit agreed-upon specification. Example: The Microsoft DOC format has historically been a de facto standard, since many products could read and write DOC, but canonical specifications were not available (until much later). Documents were still commonly distributed in the DOC format, with the expectation that any receiver would be able to read it, thus it had become a de facto standard.

To address your specific example, REST doesn't have an explicit agreed-upon specification and is therefore not a true standard, and barely a de facto standard since it has considerable ambiguity in how it should be done correctly, and no dominant implementations exist that resolves these ambiguities. (I'm not against REST. It is a very good way to build web services)


问:
State Change Tests
In Chapter 3 of his book The Art of Unit Testing: with Examples in C#, Roy Osherove describes the concept of testing state change of a system.

The example code under test he uses looks like this:

```<code>public class LogAnalyzer
{
    public bool WasLastFileNameValid { get; set; }

    public bool IsValidLogFileName(string filename)
    {
        WasLastFileNameValid = false;

        if (string.IsNullOrEmpty(filename))
        {
            throw new ArgumentException("filename has to be provided");
        }

        if (filename.EndsWith(".SLF", StringComparison.InvariantCultureIgnoreCase))
        {
            WasLastFileNameValid = true;
            return true;
        }
        return false;
    }
}
</code>```

and we want to test state of the WasLastFileNameValid property.

To this end, the author uses the following test:

```<code>[Test]
public void IsValidFileName_WhenCalled_ChangesWasLastFileNameValid()
{
  LogAnalyzer la = MakeAnalyzer();

  la.IsValidLogFileName("badname.foo");

  Assert.False(la.WasLastFileNameValid);
}
</code>```

However, I see the following issues with this test:

The 'outcome' part of the test name is ChangesWasLastFileNameValid, but the test doesn't really check whether the property value changes; it may have been false even before the call to IsValidLogFileName.

The test is only testing the one case where the last call was an invalid filename.

I would use the following test instead (using xunit.net)

```<code>    [Theory]
    [InlineData(true, "fileWithValidExtension.SLF", true)]
    [InlineData(true, "fileWithBadExtension.FOO", false)]
    [InlineData(false, "fileWithValidExtension.SLF", true)]
    [InlineData(false, "fileWithBadExtension.FOO", false)]
    public void IsValidLogFileName_WhenCalled_ChangesWasLastFileNameValid(
        bool preState, string filename, bool postState)
    {
        LogAnalyzer analyzer = new LogAnalyzer();
        analyzer.WasLastFileNameValid = preState;

        analyzer.IsValidLogFileName(filename);

        Assert.Equal<bool>(postState, analyzer.WasLastFileNameValid);
    }
</code>```

Here I test whether the value changes, and I also test all scenarios. Is this a better test?

答:
To answer your specific concerns:

Whether a state change occurs is not necessarily relevant, only that the correct state exists at the time of testing.

Both states should be tested against their relevant conditions, not just one or the other.

It's probably a better software design if the IsValidLogFileName() method is called at the moment that an evaluation of the file name is needed, rather than trying to maintain a state variable with that information.  It should be redesigned to be stateless, in other words (all other things being equal).

Title: State Change Tests


答:
Return the harshest, unfriendliest result possible in the event of a malformed request (one that returns more data than your metering allows is malformed). I suggest returning a 4** error code. Then, also provide paging parameters, so that users may request pages. oData has this feature, for instance. Do not truncate the data silently, under any circumstances.

Consulting with customers is a bad idea. They are going to tell you to do whatever possible to minimize errors, which is a bad engineering approach. This is your decision, take it by the horns and do the right thing.

An example of a paginated api is oData:

http://www.odata.org/documentation/odata-version-2-0/uri-conventions/


答:
I know this has already been answered, and the accepted answer's pretty good, but I just want to clarify something.

In proper English grammar, the bottom line is this: Sometimes proper nouns are given names that do not start with a capital letter, and in most such cases, they are every bit as attached to not being capitalized as "normal" proper nouns are to being capitalized.  In such cases - which would certainly include most function names in C-descended languages - you absolutely do not capitalize the name, even at the beginning of a sentence.  In fact, it is bad English grammar and spelling to do so.  This is actually a part of the same principle as to why it's correct to spell Sony's gaming console "PlayStation", but not "Playstation".

There are other cases in which a proper noun is not supposed to be capitalized by default, and yet it can be (and should be) when used at the beginning of a sentence.  The name of the language brainfuck is an example of this.  Functions in C-descended languages are not.  myFunc() and MyFunc() are two totally different things in languages like that, and starting a sentence with the word "MyFunc()" will only refer to the latter, not to the former.  In VB.NET though, this is a grey area, since these two functions would be the same thing in that language, although function names would also retain user-specified capitalization schemes, on some level or another.

Also, even though English rules are set in stone in this case, they tend to get kind of hazy around things like this as a rule.  English wasn't designed with things like this in mind, so for other things like this, there is room for improvisation.

Title: Beginning a sentence with a function name?

Body:
Occasionally while typing something up that relates to a case-sensitive programming language I end up starting a sentence with a function name. Now the rules of English state that the first word in a sentence needs to be capitalized; the function name is lowercase, though. If you are wondering what could I be saying that would result in the first word being a function name, take this example:

Your fread implementation is broken. fread needs to return how many bytes were read.

I understand that I could change the second instance of fread to It but I want to know the best way of handling this other than just rewriting the sentence. Should I capitalize the function name? The only way I would like to hear "rewrite the sentence" as an answer is if starting the sentence with a function name violates some English rule that I am not aware of.
Edit: I really thank everyone for these answers. They have changed and improved my insight into the issue. I have learned quite a bit from this. I am very surprised that I did not think of these simple but good solutions.

I do think my stance on alternating the sentence was too tough and now I realize due to these good answers that overall altering the sentence appears to be the best option for dealing with these cases be it adding parenthesis after the function or saying The function before the function name and if available using formatting for the function name.


答: I echo Neil's and other's comments. Just as you also said in your second point, you never, ever want to split the message into chunks if you are localizing the software. It is a translator's nightmare (although it happens regularly, so it wouldn't surprise them) and it will delay the translation more than you can ever imagine because of the time it will take for the translators and QA specialists to fix the problems due to different word arrangement and order in other languages. It will also negatively affect other parts of the process, including the translation memory, which will wreak havoc on future iterations of the text strings. Tags are an unresolved problem with localization. We've used several methods to deal with it including protecting the tags and using hidden placeholders, and then reconstructing the file after translation, but no method is perfect. Ideally, you should try to minimize tagging within the text as much as possible. However, at the same time, translators and translation companies are accustomed to dealing with some level of tagging within the text, so it isn't the end of the world if you have some tagging in your files.</p>

Title: Should putting html tags into localization files be avoided?

Body:
We are localizing all parts of our website to many languages. We use XML localization files. I think this scenario is so common, and even there should be a standard solution to this, but still I couldn't find any good advice, and every developer here has different opinion about it, so I'm asking you.

Suggest the following example:

If you have question, please ask our Customer support or write an email to Jane Doe  our specialist.

Or a long, formatted text:

```<code> <p>A very long, marketing blah-blah. A very long, marketing blah-blah. A very long, marketing blah-blah concluding in a list:</p>
 <ul>
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>
</code>```

1) Would you put html tags into the localization XML file?

My concern is the View is separated into 2 files: your page and your localization file. People will forget to check the localization file. Also, there's logic and style embedded in html as well (see target="_blank", or the fact that the above mentioned list is unordered...)

2) Or splitting it to smaller parts?

<msg id="IfYouHaveQuestion">If you have question, please ask our</msg>

<msg id="CustomerSupport">Customer support</msg>

<msg id="OrWrite">or write an email to</msg>
...

Now, View can contain all the markup and style. It's easy to change it, flexible.

But.

There's absolutely no guarantee that the word order will be the same in all languages. Also, this would make the translator's work a nightmare, making it a puzzle.

3) Or introduce BB-style markdown?

<msg id="HaveQuestion">If you have question, please ask our [link url="{customersupportlink}" title="{{CustomerSupportTitle}}">Customer support[/link] or write an email ...</msg>

But probably this is over-complicating the issue, and also we have to write our own parser for this (though, I think it wouldn't be so hard). And probably does not solve the long, formatted text problem.

4) ??? (Your golden solution here) :)