答:
Defensive coding is not just a good idea for public code.  It's a great idea for any code that is not immediately thrown away.  Sure, you know how it's supposed to be called now, but you have no idea how well you'll remember this  six months from now when you come back to the project.

Java's basic syntax gives you a lot of baked-in defense compared to a lower-level or interpreted language like C or Javascript respectively.  Assuming that you name your methods clearly and don't have external "method sequencing", you can probably get away with simply specifying arguments as a correct data type and including sensible behavior if properly-typed data can still be invalid.

(On an aside, if Cards always have to be in zone's, I think you get better bang-for-the-buck by having all cards in play be referenced by a collection global to your Game object, and have Zone be a property of each card.  But since I don't know what your Zones do other than holding cards, it's hard to know whether that's appropriate.)


问:
How necessary is it to follow defensive programming practices for code that will never be made publicly available?
I'm writing a Java implementation of a card game, so I created a special type of Collection I'm calling a Zone. All modification methods of Java's Collection are unsupported, but there's a method in the Zone API, move(Zone, Card), which moves a Card from the given Zone to itself (accomplished by package-private techniques).  This way, I can ensure that no cards are taken out of a zone and simply vanish; they can only be moved to another zone.

My question is, how necessary is this kind of defensive coding? It's "correct," and it feels like the right practice, but it's not like the Zone API is ever going to be part of some public library. It's just for me, so it's kind of like I'm protecting my code from myself when I could probably be more efficient by just using standard Collections.

How far should I take this Zone idea? Can anyone give me some advice on how much I should think about preserving the contracts in classes I write, especially for ones that aren't really going to be publicly available?

答:
Defensive programming is a very good thing.

Until it starts getting in the way of writing code.  Then it's not such a good thing.

Speaking a bit more pragmatically...

It sounds like you're right at the edge of taking things too far.  The challenge (and the answer to your question) lies in understanding what the business rules or requirements of the program are.

Using your card game API as an example, there are some environments where everything that can be done to prevent cheating is critical.  Large amounts of real money may be involved, so it makes sense to put a large number of checks in place to make sure that cheating can't occur.

On the other hand, you need to remain mindful of the SOLID principles, especially single responsibility.  Asking the container class to effectively audit where cards are going may be a bit much.  It may be better to have an audit / controller layer between the card container and the function that receives the move requests.

Related to those concerns, you need to understand what components of your API are publicly exposed (and thus vulnerable) versus what is private and less exposed.  I'm not a total advocate of a "hard exterior coating with a soft inside", but the best return of your effort is to harden the exterior of your API.

I don't think the intended end user of a library is as critical of a determination about how much defensive programming you put in place.  Even with modules that I write for my own use, I still put a measure of checking in place to make sure that future me didn't make some inadvertent mistake in calling the library.

ContentLicense: CC BY-SA 3.0


问:
Which of these old criticisms of common lisp still apply today?
In A Critique of Common Lisp written by Rodney A. Brooks and Richard P. Gabriel from Stanford in 1984, some design decisions retained by the normalizing committee of Common Lisp are discussed.  While most of the discussion remains valid, there are two statements that refer to the technology available at the time and may be false today.

These two statements are:

Too many costs of the language were dismissed with the admonition that ‘any good
  compiler’ can take care of them. No one has yet written—nor is likely to without
  tremendous effort—a compiler that does a fraction of the tricks expected of it.

As I am a Common Lisp novice, or even an apprentice, I am not able to be more specific than the authors are.  They seem to state that a great generality and flexibility has been built into several aspects of the language, which makes writing a good compiler quite difficult.

In COMMON LISP a little too much control was
  placed on floating-point arithmetic. And certainly, although the correct behavior of a
  floating-point-intensive program can be attained, the performance may vary wildly.

As far I understand, it seems that writing efficient numerical code in Common Lisp is possible but more challenging than it has to be.

This was thirty years ago. How should I regard these statement today if I am willing to write Common Lisp programs for one of the common free software implementations (CLISP, SBCL et al.)?

答:
The paper is interesting in many ways.

The most interesting part is this: the authors falsified the paper from 1984 just two years later in 1986 themselves. Brooks and Gabriel developed a highly optimizing Lisp compiler and sold it commercially very successful for several years: Lucid Common Lisp (PDF).

Maintenance for this Lisp compiler is still available from LispWorks: it is now called Liquid Common Lisp.

The compiler optimizations of Liquid CL are documented in Chapter 3 of the Advanced User's Guide: Optimizing Lisp Programs.

Several commercial applications have been written and deployed in Lucid CL. For example in my home town the first public transport information system for the HVV (Hamburger Verkehrsverbund) was deployed using Lucid CL on a SUN SPARCstation. It was available for the public in train stations using a large touch screen and in the call center.

Lucid CL was successful because its production mode compiler created fast Common Lisp applications, mainly for Unix / RISC platforms.

Brooks and Gabriel are writing about Lucid Common Lisp in 1986:

The dynamically retargetable compiler has been shown to be a means by
  which ease of compilation for a variety of Lisp implementations can be
  performed; a means of porting Lisp systems to a variety of computers;
  and a tool for producing high-quality, high-performance code for a
  variety of computers from a common source.

Thus they had just implemented what the A Critique of Common Lisp claimed to be difficult or impossible.

Nowadays the more advanced implementations are doing a lot of optimizations, but the hardware is also 1000+ times faster than what we had in 1984. A VAX 11/780 then had one MIPS (million instructions per second) and a Lisp Machine was also in that range. A Motorola 68000 had a clock rate of 8 MHz.

The criticism about floating point performance and generally varying performance is still valid, but this reflects implementors choice. Some implementations are not developed as high-performance compilers. Their main focus could be portability, compactness or something else and thus they have different implementation goals.

As a user/developer one is not forced to write portable code and use all of the ten+ currently supported Common Lisp systems. Use the implementation which is best suited to the application problem.


答:
Defensive coding in API design generally is about validating input and carefully selecting a proper error handling mechanism. Things other answers mention are also worth noting.

This is actually not what your example is about. You are there limiting your API surface, for a very specific reason. As GlenH7 mentions, when the set of cards is to be used in an actual game, with a ('used' and 'unused') deck, a table and hands for example, you definitely want to put checks in place to make sure each card from the set is present once and only once.

That you designed this with "zones", is an arbitrary choice. Depending on the implementation (a zone can only be a hand, a deck or a table in above example) it might very well be a thorough design.

However, that implementation sounds like an derived type of a more Collection<Card>-like set of cards, with a less restrictive API. For example when you want to build a hand value calculator, or an AI, you surely want to be free to choose which and how many of each cards you iterate over.

So it is good to expose such a restrictive API, if the only goal of that API is to make sure each card always is in a zone.

Title: How necessary is it to follow defensive programming practices for code that will never be made publicly available?

Body:
I'm writing a Java implementation of a card game, so I created a special type of Collection I'm calling a Zone. All modification methods of Java's Collection are unsupported, but there's a method in the Zone API, move(Zone, Card), which moves a Card from the given Zone to itself (accomplished by package-private techniques).  This way, I can ensure that no cards are taken out of a zone and simply vanish; they can only be moved to another zone.

My question is, how necessary is this kind of defensive coding? It's "correct," and it feels like the right practice, but it's not like the Zone API is ever going to be part of some public library. It's just for me, so it's kind of like I'm protecting my code from myself when I could probably be more efficient by just using standard Collections.

How far should I take this Zone idea? Can anyone give me some advice on how much I should think about preserving the contracts in classes I write, especially for ones that aren't really going to be publicly available?


问:
Authoritative sources for exception handling best practices
My work place suffers from a bad case of the Pokemon Exception Handling anti-pattern with constructs like the following splattered across the code base:

```<code>try {
    ...
} catch (Exception ex) {
    // Log and pretend nothing happened.
    Log.LogException(ex);
}
</code>```

I've found lots of answers on Stack Exchange sites that explains why the above is bad. But I haven't found any authoritative sources, like books, developer journal articles or msdn pages explaining why you shouldn't write code like the above. Are there any sources like that, if so, where?

Edit: I'd say that "famous" bloggers also count as authoritative sources. My rule for what counts as authoritative or not is not exactly set in stone.

答:
John Skeet and Eric Lippert. I dare you to find someone in the .NET world with more brain power. :)

I'd start here: Vexing Exceptions by Eric Lippert

Then look for anything by either of them related to exceptions. Also +1 to the Clean Code book comment. Clean Code by Robert Martin :)

ContentLicense: CC BY-SA 4.0


答:
In C#, you couldn't ask for a more authoritative source than the Framework Design Guidelines. This is what the authors of the .NET Base Class Library followed when designing the core libraries that come with .NET. It includes comprehensive guidelines on how to work with exceptions.

In particular, it says:

AVOID swallowing errors by catching non-specific exceptions such as System.Exception, System.SystemException, and so on, in application code.

Title: Authoritative sources for exception handling best practices

Body:
My work place suffers from a bad case of the Pokemon Exception Handling anti-pattern with constructs like the following splattered across the code base:

```<code>try {
    ...
} catch (Exception ex) {
    // Log and pretend nothing happened.
    Log.LogException(ex);
}
</code>```

I've found lots of answers on Stack Exchange sites that explains why the above is bad. But I haven't found any authoritative sources, like books, developer journal articles or msdn pages explaining why you shouldn't write code like the above. Are there any sources like that, if so, where?

Edit: I'd say that "famous" bloggers also count as authoritative sources. My rule for what counts as authoritative or not is not exactly set in stone.


答:
Here's an article from Krzysztof Cwalina, a Principal Architect at Microsoft.  It was written six years ago, but it's still my go-to for reminding myself what to do about various exception types:

How to Design Exception Hierarchies

He divides up exceptions into three types:

Usage errors, such as a NullReferenceException, fixed by correcting your code.

Logical errors, such as FileNotFoundException, that technically can't be avoided.  (Even if you use File.Exists, someone could delete it between when you check and when you use the file.)  You have to handle these.

System failures, such as OutOfMemoryException, which you can't handle.

There's a lot of good information in the article.


问:
How do I evaluate an IDE?
I don't want to know which IDE is best, because that's subjective. I'd like to know how to evaluate an IDE. I'm primarily a vim user, and realistically happy there, but occasionally look at languages that have powerful IDE's and I consider using them.

The problem I run into is that they mostly seem the same to me. Certainly any of them will work, but when trying to decide which IDE to invest time in how do I decide?

What features should I be testing to see if I like the way A or B works better? Obviously some IDE's are specifically tailored to a language, but given a choice between say Netbeans, Eclipse, and Intellij IDEA, how would I decide? as a novice they seem the same.

When evaluating I generally try the editor, a few configuration options, file browser. I think my colleagues all basically the same as me and don't use IDE. I also doubt I'd end up using the IDE for work, because Perl shop, and I'm happy with vim for that, I'm simply trying to figure out how to use them in the context of languages that aren't day job and have solid IDE support.

答:
Trying them out is obvious.

I'd create a list of show stoppers: things that can't be true about an IDE that I use. Some examples:

Does it fail to run on some machines my developers use?

Is the company making it (or community backing it) dead or dying?

Is it crash-prone? If crashed (or hung and killed), does it have trouble starting?

Does it make you wait at random moments?

Does it have known serious bugs or shortcoming in areas that matter to me?

This can be summed up:

Does it make you curse often?

Does it make you switch to other tools often?

If it does, probably it won't fly.

But don't forget to actually learn how to use each IDEs first. Faithfully follow introductory texts or videos, however obvious the material might seem; your stereotypes might be holding you back from using a great but unconventional way to do something.

Title: How do I evaluate an IDE?


答:
Okay, this feels more like one of those questions where somebody needs to dig deep down and find the real question, which based on your comments, I suspect is:

"Is it okay that I hate IDEs?"

My answer would be "Bravo, yes. Over-reliance on IDEs to handle too much for you can make you weak and lose touch with the value of carefully designed architecture that ultimately makes a code base more maintainable with or without the crutch. Also, for devs who've really mastered less complex/lighter-weight tools like VIM they can do more to get in your way than actually help you."

But don't get too smug. Even if your code is clean and neat enough to be more easily dealt with in a non-IDE fashion, that doesn't mean everybody's is or that yours always will be if you find yourself having to continually add layers to something you had intended to refactor before you took it any further, but oops, now there's money and employees involved and you just need to get 'er done in time to see whether people get Christmas bonuses this year. (disclaimer: no, I've only worked for that guy)

It took exactly one legacy code-base from Hell to convince me that no, IDEs have their uses. These are:

Making the illegible less illegible - It is not possible to understand the code in a code base where every single class has a minimum of 1 interface and a super-class or a sub-class merely by looking at the code. It's just not. It at least helps to have something you can quickly find where stuff actually begins and ends.

Debugging crap-procedural wolves in OOP sheep's clothing - Sometimes you just have to give up and realize that all the OOP architecture is really just crap that further obfuscates what's going on. When it takes 30 method calls to make a basic web service call for some static data in a DB you're going to want some help figuring out where it went wrong.

Helping you with a language that you don't know that well - The mere presence of auto-complete and param hinting can help out in a big way on this front. Typing at 70-80WPM when intoxicated in a snow storm doesn't help you when you have to Google your way through Microsoft or J2EE documentation to do the simplest things.

Managing complexity - I have to admit. Once your actual code file count grows beyond 20 or so, it's really nice to just be able to right-click something and see where the heck it was defined or rename it 6 different files at once. Especially when working with something you didn't write the bulk of when dealing with a team.

So, if perhaps you're fairly convinced as I always had been that IDEs are often a symptom of a disease, I don't think you're entirely wrong. But I'm a JavaScript dev and I have to admit, WebStorm is pretty neat. I still open Scite more often than not, but once there's a lot of dependencies to manage and some stupid code in the mix, I'll take the IDE option.

If I'm not wrong and you're at least similar to me in historical outlook on IDEs, I would go with the four things I actually have found them useful for as things to rank the value of an IDE on.

Title: How do I evaluate an IDE?

Body:
I don't want to know which IDE is best, because that's subjective. I'd like to know how to evaluate an IDE. I'm primarily a vim user, and realistically happy there, but occasionally look at languages that have powerful IDE's and I consider using them.

The problem I run into is that they mostly seem the same to me. Certainly any of them will work, but when trying to decide which IDE to invest time in how do I decide?

What features should I be testing to see if I like the way A or B works better? Obviously some IDE's are specifically tailored to a language, but given a choice between say Netbeans, Eclipse, and Intellij IDEA, how would I decide? as a novice they seem the same.

When evaluating I generally try the editor, a few configuration options, file browser. I think my colleagues all basically the same as me and don't use IDE. I also doubt I'd end up using the IDE for work, because Perl shop, and I'm happy with vim for that, I'm simply trying to figure out how to use them in the context of languages that aren't day job and have solid IDE support.


问:
is it really necessary for python to differentiate between tuples, lists, dicts, ordered dicts and sets?
i have been learning python over the past month or so. i like many of the things about the language, but i find the differentiation between tuples, lists, dicts, ordered dicts, and sets to be cumbersome. i know these each have their own performance benefits and tradeoffs, but it seems to me that it would be far simpler to combine them all into a single data structure - maybe a dict but which maintains the order originally specified - pretty much like json...

would this be a massive performance hit, or could the optimizer fully compensate to maintain equal performance?

i'm guessing the answer is that it could not be done more simply and efficiently any other way - otherwise the language would already have been written that way. this being the case, can anyone explain why not?

also, would there be any other downsides to replacing tuples, lists, dicts, ordered dicts and sets with a single json type data structure?

答:
It sounds like you may have preconceived notions that come from PHP. I don't think any other commonly used language has such a "do-everything" data structure as PHP's arrays.

One purpose of multiple different kinds of collections is to clarify to the reader what the data structure might be used for. For example, if you're given a list you know that you can't ask for a["foo"]. If you're given a set you know that it doesn't make sense to ask for the fifth element. If you're given a tuple you know that you're not expected to be able to make changes to it.

As you mention, there are also performance considerations. While it is possible to construct a general purpose data container that has reasonable performance over most common cases, you can do better by constructing more specialised data structures.

These considerations simplify and clarify the processes of (a) constructing the software in the first place, and (b) making it easier for readers to understand the purpose of your data structures. If everything were a general purpose container such as the PHP "array", then it is less clear how the data ought to be used.

Finally, you mention a "single JSON type data structure", but JSON doesn't have a single type of data. The aggregate types within JSON are sequential arrays denoted with [], and name-value associates denoted with {}. That's already two different data types not counting the scalar types.


答:
this being the case, can anyone explain why not?

The optimizer cannot compensate because the optimizer works at compile time. It cannot know how your collections will be used, so it cannot optimize the collections to the operations that are most common. Worse yet, the common operations may not be the important ones. Say you do 1000 inserts, but all those exist to let you do one quick lookup later. The inserts might not matter because they're done in the background while your app loads. There's no way for the optimizer to know.

would this be a massive performance hit

As with all things, it depends. Let me try to provide a quick, high level explanation why.

The reason that there cannot be one universal data structure is because of tradeoffs. If there existed a structure that was quick to insert, quick to search, quick to delete, quick to sort, memory efficient, thread safe, with no resizing penalties... well we'd certainly use it. The problem comes that if you optimize a data structure for say, quick insertions - something else will suffer. This table (thanks to this question) shows what all those tradeoffs.

And those tradeoffs are pretty significant. Having code do something common in O(n) (or worse) rather than O(1) is what takes the runtime of your app from milliseconds to seconds and from seconds to minutes or hours.

So yes, it is necessary to have all of these collections.

That said, it often doesn't matter if you use them. In C# for example, there's List<T> which is "good enough" for any basic collection and Dictionary<K,V> which is "good enough" when you need a lookup. Few apps need to be highly performant, and in those apps a small fraction of the app accounts for the majority of the runtime. Using the default collections until your profiler tells you differently is a fine approach for beginners, as long as you know that the other collections exist, and why they exist.

Title: is it really necessary for python to differentiate between tuples, lists, dicts, ordered dicts and sets?

Body:
i have been learning python over the past month or so. i like many of the things about the language, but i find the differentiation between tuples, lists, dicts, ordered dicts, and sets to be cumbersome. i know these each have their own performance benefits and tradeoffs, but it seems to me that it would be far simpler to combine them all into a single data structure - maybe a dict but which maintains the order originally specified - pretty much like json...

would this be a massive performance hit, or could the optimizer fully compensate to maintain equal performance?

i'm guessing the answer is that it could not be done more simply and efficiently any other way - otherwise the language would already have been written that way. this being the case, can anyone explain why not?

also, would there be any other downsides to replacing tuples, lists, dicts, ordered dicts and sets with a single json type data structure?


问:
Is it ethical or even legal to track user data/metrics using IP
This one is a bit tough. It is publicly available information, is it not? But it's can also be used maliciously. So is it legal/ethical to store and/or gather information on users based on IP?  It's mostly for curiosity, but it would also be important for marketing purposes, and maybe something to anonymously post on the homepage.

One use for this is detecting attacks and, for some products, limiting your release to one part of the world. I can see no real downsides from a business point of view, but I can also see how it would make users feel uncomfortable, and may actually be illegal.

Right now, I'm simply storing the user-agent and ip strings in a slightly randomized line-break format, so if a vulnerability is found by a web bot, there's less of a chance for ips to be properly scraped. But I'd like to eventually compile a map of users, and put a little dot where each user logged in. It would be a world-wide map, so the fine details would not be disclosed. But for some reason, I feel like I'm guilty of something or will get into trouble for collecting this data.

On the legal side of things, I've noticed articles similar to this: http://www.adexchanger.com/the-debate/why-ip-tracking-is-a-bad-idea/, and I've read about companies like Google and Facebook getting into hot water with users for collecting data.

I am in the United States, and the server will most likely operate somewhere in the US, but I have the impression that the per-country laws pertained to the client visiting.

答:
You asked two very different questions.

Is tracking user metrics by IP legal?

I'm about 98% sure that keeping your log of HTTP requests and extracting the IP address of each session, and then building a geographic distribution of where your users are based on said IP address is perfectly legal everywhere in the globe.

But asking "is this thing that I'm doing legal" is asking for legal advice, and you shouldn't get legal advice from strangers on the internet.  As far as I know you could be under a court order making it a misdemeanor or felony for you to even use a website.  If you want legal advice, find a lawyer.

Is tracking user metrics by IP ethical?

Yes.  Absolutely, emphatically yes.  People complain about some of the tracking that Google and Facebook do, but that's the explicit contract those same users make when they use those websites.

The only possible requirement you might have is to honor "do not track" settings in web browsers, and to take some reasonable effort to both secure individually identifiable records and dispose of them once you no longer have a need.

(In the early days of the web, EVERY http request was tracked and logged.  Most still are by default, although most admins have the logs set to delete very quickly so they don't have to deal with subpoenas from law enforcement.)


问:
Sharing only part of code with git
The situation

I have code which has features X and Y.

Bob needs access to the code to help develop feature X further.

Normally I would allow Bob to clone the code, but the problem is that feature Y is confidential, so this is not possible. Bob does not need to be able to view feature Y code to develop feature X further.

If I create a new branch to share with Bob and delete feature Y from the code, it will still be viewable in the commit history.

So I guess the only option is:

Create a new branch and delete feature Y.

Create a completely new repository to share with Bob

Copy the files (while the new Y-less branch is checked out) to the new repository.

Give Bob access to that new repository.

After Bob develops feature X further, cherry pick relevant lines and files, and put them into my master. (painful)

Question

Is there a better way to go about this?

答:
A no less effort but more permanent fix would be to split feature X and Y each into their own repositories. Then the master would just reference the other repositories as libraries (best practice for this is to use submodules).

This way you do not need to manually add the new development to feature X as you are using it straight from its own repository.

Title: Sharing only part of code with git


问:
API for expanation of complicated calculation or business rules?
In online shops there are areas with complicated rules. For example

is a product visible in the product catalog

is a product sold out

what is the price for the product (Discounts, Promotions, ...)

Is it a good idea to have an additional explanation API for each complicated rule?

Example: boolean isProductVisible() has an additional String explainIsProductVisible()?

How to make understanding these rules easier?

Background:

Yesterday I as a software developer had the problem that my standard-testproduct on my local test system was "sold out" and I needed this product
to test the order-confirmation page.

So I had to debug the IsProductAvailable routine to correct the test data before I was able to do the original
task "test the order-confirmation page".

In order to find out, why my test product was sold out an explanation message would have been helpful.

In a similar situation in the price calculation engine I already added log messages like this

```<code>double calculateItemPriceForProduct(Product product, int quantity, Cart cart, ...)
{
    double cumulatedPrice = 0;
    ...
    if (quantity > 1) {
        Price price = getScalePrice(product, quantity);
        if (price != null) {
            cumulatedPrice = price.getValue();
            if (log.isDebugEnabled()) {
                log.debug("calculateItemPriceForProduct("+
                    product.getCode()+
                    ") using scalePrice " +
                    price.getCode() + " for quantity " +
                    quantity + ":" + price.getValue());
            }
        }
    }
    ...
}
</code>```

As a developer I can look into the server log and hopefully find out what happened.

If I were a product manager it would be more comfortable to have role-specific tooltips on the webpage that shows the explanation part.

Of course these tooltips would not be available for ordinary customers, just for developers and product managers.

My questions:

Are there other ways to make understanding complicated rules easier?

Is it a good idea to have an additional explanation API for each complicated rule?

Does such a feature pay off the cost of developing this feature?

答:
The idea to return an explanation is very good.

If you calculate price and availability together, you could return an object describing all at once:

```<code>enum StockAmount {
  NONE, // unavailable
  LITTLE, // will not last
  ENOUGH, // some safe amount
  PLENTY  // the store is full
}

interface ProductAvailability {
  int getPrice(); // money is never a float! I'd store price * 100.
  StockAmount getAmount();
  int getDiscount(); // again, in cents
  String getExplanation();
}

// usage, crudely

ProductAvailability prod = store.getProductAvailability(product_id,...);
if (prod.getAmount() == NONE) {
  return "Sold out!";
} else if (prod.getAmount() == LITTLE) {
  return "Take while it lasts! Only " + formatMoney(prod.getPrice()) + "!";
} else {
  return "In stock";
}
</code>```

The description part is tricky.

If all you need is some explanation to you and probably the sales operator, a crude string you currently create is adequate.

If your explanations are complicated and are presented to the customer, you'll need a way to nicely formulate it using all the data. I'd build a Tree<String> as the explanation, with children being 'because' parts of a parent. Then I'd synthesize a nicely-worded sentence looking at the entire tree, outside the price/availability calculation method. Here you can decide where to put 'because', 'and', 'but', etc, what to put first, what set expression to use for a particular tree configuration, and so on.

Body:
The idea to return an explanation is very good.

If you calculate price and availability together, you could return an object describing all at once:

enum StockAmount {
  NONE, // unavailable
  LITTLE, // will not last
  ENOUGH, // some safe amount
  PLENTY  // the store is full
}

interface ProductAvailability {
  int getPrice(); // money is never a float! I'd store price * 100.
  StockAmount getAmount();
  int getDiscount(); // again, in cents
  String getExplanation();
}

// usage, crudely

ProductAvailability prod = store.getProductAvailability(product_id,...);
if (prod.getAmount() == NONE) {
  return "Sold out!";
} else if (prod.getAmount() == LITTLE) {
  return "Take while it lasts! Only " + formatMoney(prod.getPrice()) + "!";
} else {
  return "In stock";
}

The description part is tricky.

If all you need is some explanation to you and probably the sales operator, a crude string you currently create is adequate.

If your explanations are complicated and are presented to the customer, you'll need a way to nicely formulate it using all the data. I'd build a Tree<String> as the explanation, with children being 'because' parts of a parent. Then I'd synthesize a nicely-worded sentence looking at the entire tree, outside the price/availability calculation method. Here you can decide where to put 'because', 'and', 'but', etc, what to put first, what set expression to use for a particular tree configuration, and so on.


问:
Which is better approach for writing automated tests?
Writing tests in single file or writing each test in a separate file?
I have found few advantages of keeping test cases in separate file.

Easy to maintain, better readability, easy to run single test.

There can be 80 to 100 lines of code for every test case including comments. Say if we write 10 tests in a single file then there will be ~1000 lines of code which will be very hard to manage. Typically we will have more than 10 tests in a functionality.  On the other hand if we have it as single file we can easily identify tests from the file name itself.

答:
At first, the question looks superfluous. For a decently sized product, no one would even think of writing all tests in a single file of course.

When it comes to functional/performance/integration/etc tests, these are usually involved to set up and already quite large by their nature, such that separation is again the obvious choice.

There is, however, the case of unit tests where we do have advantages when keeping tests in a single file:

If the test file grows too large, it is an indication that your tested unit/class is too large as well. So what is a downside for other tests becomes a useful warning signal for unit tests.

You have exactly all relevant tests for the respective unit together. Other tests, like integration tests, tend to encompass multiple system components, which means it is inherently difficult to identify all parts. For unit tests, there is always just that one unit, and it wouldn't make much sense to have to find multiple test files for it.

Continuous testing: While you can theoretically run your whole test suite each time you save your source file, this is infeasible due to the long runtime of some more involved tests. Unit tests on the other hand are supposed to execute blazingly fast and having all tests for your unit in one file, you can edit away mercilessly whilst having the guarantee that on every save the complete unit is tested. This is possible in theory with split files as well, but practically, the CT tools assume one unit - one test.

The last reason above is sufficient for me personally to warrant not splitting unit tests. Especially with IDEs you get support for things like moving between unit and test code via a simple shortcut key, or in other words: there is absolutely no effort needed to find/execute/do anything with the relevant test code of your unit. Something which is simply no longer possible on tests that encompass multiple units.

So in summary, I'd argue that your given advantages are really only present for non-unit tests. When considering unit tests, quite the opposite holds true: having them in one file means they are easy to maintain and run, and as explained above, excessive size is useful as a code smell detector in that case.


答:
General guideline is to mimic the code files. For example,

If we have two class files:

Employee

Department

We should create test files like below:

EmployeeTest

DepartmentTest

Naming the test file based on the code file with 'Test' suffix is also a guideline. These guidelines make tests easy to structure/discover eg in a large project you don't have to tell a developer/tester where to find the test for a particular feature, it is intuitive.

However, it is just a guideline and not a rule.

Title: Which is better approach for writing automated tests?

Body:
Writing tests in single file or writing each test in a separate file?
I have found few advantages of keeping test cases in separate file.

Easy to maintain, better readability, easy to run single test.

There can be 80 to 100 lines of code for every test case including comments. Say if we write 10 tests in a single file then there will be ~1000 lines of code which will be very hard to manage. Typically we will have more than 10 tests in a functionality.  On the other hand if we have it as single file we can easily identify tests from the file name itself.


问:
Design for syncing data in Android
I have been seeing two implementations for syncing data between the server and the client on majority of the apps. This assumes no GCM is set up:-

Running an intent service periodically which downloads the data from the network and stores in the database.

Implementing a Sync Adapter which runs periodically.

Which of the above would you recommend to have in your app and why?

答:
Sync Adapters should be used unless you need real time data because,
It automates data transfer based of variety of criteria, like data changes, elapsed time, time of day, etc.
It centralizes all data transfers so your data transfer is done in conjunction with data transfers from other apps, which reduces battery usage.

For instantaneous tasks we can use,

AsyncTask for task that are of short duration, may be 3-4 seconds.

IntentService for long running tasks.

Title: Design for syncing data in Android


问:
What is the real responsibility of a class?
I keep wondering if it is legitimate to use verbs that are based on nouns in OOP.

I came across this brilliant article, though I still disagree with the point it makes.

To explain the problem a bit more, the article states that there shouldn't be, for instance, a FileWriter class, but since writing is an action it should be a method of the class File. You'll get to realize that it's often language dependent since a Ruby programmer would likely be against the use of a FileWriter class (Ruby uses method File.open to access a file), whereas a Java programmer wouldn't.

My personal (and yes, very humble) point of view is that doing so would break the Single Responsibility principle. When I programmed in PHP (because PHP is obviously the best language for OOP, right?), I would often use this kind of framework:

```<code><?php

// This is just an example that I just made on the fly, may contain errors

class User extends Record {

    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }

}

class UserDataHandler extends DataHandler /* knows the pdo object */ {

    public function find($id) {
         $query = $this->db->prepare('SELECT ' . $this->getFields . ' FROM users WHERE id = :id');
         $query->bindParam(':id', $id, PDO::PARAM_INT);
         $query->setFetchMode( PDO::FETCH_CLASS, 'user');
         $query->execute();
         return $query->fetch( PDO::FETCH_CLASS );
    }

}

?>
</code>```

It is my understanding that the suffix DataHandler doesn't add anything relevant; but the point is that the single responsibility principle dictates us that an object used as a model containing data (may it be called a Record) shouldn't also have the responsibility of doing SQL queries and DataBase access. This somehow invalidates the ActionRecord pattern used for instance by Ruby on Rails.

I came across this C# code (yay, fourth object language used in this post) just the other day:

```<code>byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);
</code>```

And I gotta say that it doesn't make much sense to me that an Encoding or Charset class actually encodes strings. It should merely be a representation of what an encoding really is.

Thus, I would tend to think that:

It is not a File class responsibility to open, read or save files.

It is not a Xml class responsibility to serialize itself.

It is not a User class responsibility to query a database.

etc.

However, if we extrapolate these ideas, why would Object have a toString class? It's not a Car's or a Dog's responsibility to convert itself to a string, now is it?

I understand that from a pragmatic point of view, getting rid of the toString method for the beauty of following a strict SOLID form, that makes code more maintainable by making it useless, is not an acceptable option.

I also understand that there may not be an exact answer (which would more be an essay than a serious answer) to this, or that it may be opinion-based. Nevertheless I would still like to know if my approach actually follows what the single-responsibility principle really is.

What's a class's responsibility?

答:
I came across this C# code (yay, fourth object language used in this
  post) just the other day:

```<code>byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);
</code>```

And I gotta say that it doesn't make much sense to me that an
  Encoding or Charset class actually encodes strings. It should
  merely be a representation of what an encoding really is.

In theory, yes, but I think that C# makes a justified compromise for the sake of simplicity (as opposed to Java's more strict approach).

If Encoding only represented (or identified) certain encoding - say, UTF-8 - then you'd obviously need an Encoder class, too, so that you can implement GetBytes on it - but then you need to manage the relation between Encoders and Encodings, so we end up with our good ol'

```<code>EncodersFactory.getDefaultFactory().createEncoder(new UTF8Encoding()).getBytes(myString)
</code>```

so brilliantly lampooned in that article you linked to (great read, by the way).

If I understand you well, you're asking where the line is.

Well, on the opposite side of spectrum is the procedural approach, not hard to implement in OOP languages with the use of static classes:

```<code>HelpfulStuff.GetUTF8Bytes(myString)
</code>```

The big problem about it is that when the author of HelpfulStuff leaves and I'm sat in front of the monitor, I have no way of knowing where GetUTF8Bytes is implemented.

Do I look for it in HelpfulStuff, Utils, StringHelper?

Lord help me if the method is actually implemented independently in all three of those... which happens a lot, all it takes is that the guy before me did not know where to look for that function either, and believed there wasn't any yet so they snapped out another one and now we have them in abundance.

To me, proper design is not about satisfying abstract criteria, but about my ease to carry on after I sit in front of your code. Now how does

```<code>EncodersFactory.getDefaultFactory().createEncoder(new UTF8Encoding()).getBytes(myString)
</code>```

rate in this aspect? Poorly as well. It's not an answer I want to hear when I shout to my workmate "how do I encode a string into a byte sequence?" :)

So I'd go with moderate approach and be liberal about single responsibility. I'd rather have the Encoding class both identifying a type of encoding and doing the actual encoding: data unseparated from behaviour.

I think it passes as a facade pattern, which helps to grease the gears. Does this legitimate pattern violate SOLID? A related question: Does the Facade pattern violate SRP?

Note that this might be how getting encoded bytes are implemented internally (in .NET libraries). The classes are just not publicly visible and only this "facadeous" API is exposed outside. It's not that hard to verify if that's true, I'm just bit too lazy to do it right now :) It probably isn't, but that doesn't invalidate my point.

You may choose to simplify the publicly visible implementation for the sake of friendliness while maintaing a more severe, canonical implementation internally.

Body:
I came across this C# code (yay, fourth object language used in this
  post) just the other day:

byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);

And I gotta say that it doesn't make much sense to me that an
  Encoding or Charset class actually encodes strings. It should
  merely be a representation of what an encoding really is.

In theory, yes, but I think that C# makes a justified compromise for the sake of simplicity (as opposed to Java's more strict approach).

If Encoding only represented (or identified) certain encoding - say, UTF-8 - then you'd obviously need an Encoder class, too, so that you can implement GetBytes on it - but then you need to manage the relation between Encoders and Encodings, so we end up with our good ol'

EncodersFactory.getDefaultFactory().createEncoder(new UTF8Encoding()).getBytes(myString)

so brilliantly lampooned in that article you linked to (great read, by the way).

If I understand you well, you're asking where the line is.

Well, on the opposite side of spectrum is the procedural approach, not hard to implement in OOP languages with the use of static classes:

HelpfulStuff.GetUTF8Bytes(myString)

The big problem about it is that when the author of HelpfulStuff leaves and I'm sat in front of the monitor, I have no way of knowing where GetUTF8Bytes is implemented.

Do I look for it in HelpfulStuff, Utils, StringHelper?

Lord help me if the method is actually implemented independently in all three of those... which happens a lot, all it takes is that the guy before me did not know where to look for that function either, and believed there wasn't any yet so they snapped out another one and now we have them in abundance.

To me, proper design is not about satisfying abstract criteria, but about my ease to carry on after I sit in front of your code. Now how does

EncodersFactory.getDefaultFactory().createEncoder(new UTF8Encoding()).getBytes(myString)

rate in this aspect? Poorly as well. It's not an answer I want to hear when I shout to my workmate "how do I encode a string into a byte sequence?" :)

So I'd go with moderate approach and be liberal about single responsibility. I'd rather have the Encoding class both identifying a type of encoding and doing the actual encoding: data unseparated from behaviour.

I think it passes as a facade pattern, which helps to grease the gears. Does this legitimate pattern violate SOLID? A related question: Does the Facade pattern violate SRP?

Note that this might be how getting encoded bytes are implemented internally (in .NET libraries). The classes are just not publicly visible and only this "facadeous" API is exposed outside. It's not that hard to verify if that's true, I'm just bit too lazy to do it right now :) It probably isn't, but that doesn't invalidate my point.

You may choose to simplify the publicly visible implementation for the sake of friendliness while maintaing a more severe, canonical implementation internally.


答:
It heavily depends on what kind of syncing you need.

Periodic

If your app is a news app that publishes posts at a certain time every day(lets say at 7.45 AM every day), then you run a periodic task in a background service, say at 8 AM.

e.g.: Drippler. They notify me once every day(around 6.30 PM). I believe they use a periodic task.

Event Triggered

If your data transfer is triggered by user action, then use a background service or an AsyncTask for the data transfer.

e.g.: DropBox/Evernote. They sync when I interact with the app.

Instantaneous

If your app runs instant messaging/mails/non-periodic important updates, then you need push notifications, because you want to alert the user immediately. Use either GCM or Parse for this case. e.g: WhatsApp/Google chat. Since you explicitly mentioned you don't want to use GCM, I will tell why you should use a standard push notification provider instead of writing your own:

Push notifications work instantaneously - there is very little delay(in the order of seconds, rarely minutes). If you were to implement your own solution/library for doing this - in a naive model, you would ping the server every second or 5 seconds or a minute to check for the status. This is very inefficient as it consumes CPU(and hence battery), bandwidth on the mobile and load on your server. However, in GCM/Parse, they always keep a port open with the server(see here). This is the standard and most efficient way. Plus, if 10 apps use GCM, you don't need 10 open connections, you only need one per device. And you really don't want to develop your own solution unless you have a valid reason/funds/time to do so.

A note on Sync Adapter: Sync Adapter works well for all the above three cases. Check Running a Sync Adapter and you will see that it either depends on GCM or your own mechanism(event trigger or custom solution) or network availability(event trigger) or periodic event. All in all, this is a good convenient class for syncing data without having to do a long list of initializations every time or to implement all the above cases at one place.

Title: Design for syncing data in Android

Body:
I have been seeing two implementations for syncing data between the server and the client on majority of the apps. This assumes no GCM is set up:-

Running an intent service periodically which downloads the data from the network and stores in the database.

Implementing a Sync Adapter which runs periodically.

Which of the above would you recommend to have in your app and why?


答:
It is important to be able to explain the result.

I would create only one function for this purpose. When you want a detailed explanation of the result, the logic to calculate the price and the logic to return the explanation are very similar. Like in this pseudo code :

```<code>if(product is discounted){
    price = 2
    explain = 'product is discounted'
} else price = 10
</code>```

I see two implementations :

Your function returns an object containing the result and the explanation.

Your function returns the result and takes an optional argument by reference, which will contain the explanation.

I'd prefer the second for two reasons :

less code refactoring

You could skip some code in the function if the argument was not passed.

Title: API for expanation of complicated calculation or business rules?

Body:
In online shops there are areas with complicated rules. For example

is a product visible in the product catalog

is a product sold out

what is the price for the product (Discounts, Promotions, ...)

Is it a good idea to have an additional explanation API for each complicated rule?

Example: boolean isProductVisible() has an additional String explainIsProductVisible()?

How to make understanding these rules easier?

Background:

Yesterday I as a software developer had the problem that my standard-testproduct on my local test system was "sold out" and I needed this product
to test the order-confirmation page.

So I had to debug the IsProductAvailable routine to correct the test data before I was able to do the original
task "test the order-confirmation page".

In order to find out, why my test product was sold out an explanation message would have been helpful.

In a similar situation in the price calculation engine I already added log messages like this

```<code>double calculateItemPriceForProduct(Product product, int quantity, Cart cart, ...)
{
    double cumulatedPrice = 0;
    ...
    if (quantity > 1) {
        Price price = getScalePrice(product, quantity);
        if (price != null) {
            cumulatedPrice = price.getValue();
            if (log.isDebugEnabled()) {
                log.debug("calculateItemPriceForProduct("+
                    product.getCode()+
                    ") using scalePrice " +
                    price.getCode() + " for quantity " +
                    quantity + ":" + price.getValue());
            }
        }
    }
    ...
}
</code>```

As a developer I can look into the server log and hopefully find out what happened.

If I were a product manager it would be more comfortable to have role-specific tooltips on the webpage that shows the explanation part.

Of course these tooltips would not be available for ordinary customers, just for developers and product managers.

My questions:

Are there other ways to make understanding complicated rules easier?

Is it a good idea to have an additional explanation API for each complicated rule?

Does such a feature pay off the cost of developing this feature?

Body:
It is important to be able to explain the result.

I would create only one function for this purpose. When you want a detailed explanation of the result, the logic to calculate the price and the logic to return the explanation are very similar. Like in this pseudo code :

if(product is discounted){
    price = 2
    explain = 'product is discounted'
} else price = 10

I see two implementations :

Your function returns an object containing the result and the explanation.

Your function returns the result and takes an optional argument by reference, which will contain the explanation.

I'd prefer the second for two reasons :

less code refactoring

You could skip some code in the function if the argument was not passed.


问:
What do programmers "micro-optimize" for today?
Back in the "good ol' days," when we would copy shareware onto floppies for friends, we also used a fair bit of assembly. There was a common practice of "micro-optimization," where you would stare and stare at lines of assembly until you figured out a way to express it in one fewer instruction. There was even a saying, which was mathematically impossible, that "You can always remove one more instruction." Given that changing runtime performance by small constant factors isn't a major issue for (most) programming today, are programmers transferring these micro-optimization efforts elsewhere?

In other words, Can a best-practice be taken to an extreme state where it's no longer adding anything of value? And instead is wasting time?

For example: Do programmers waste time generalizing private methods that are only called from one place? Is time wasted reducing test case data? Are programmers (still) overly concerned about reducing lines of code?

There are two great examples of what I'm looking for below: (1) Spending time finding the right variable names, even renaming everything; and (2) Removing even minor and tenuous code duplication.

Note that this is different from the question "What do you optimize for?", because I'm asking what other programmers seem to maximize, with the stigma of these being "micro" optimizations, and thus not a productive use of time.

答:
I'm all for the don't-optimise-unless-really-necessary principle. And I'm all for the profile-first principle. And in principle, I will only optimise something that will make a needed difference.

That's in principle. But principle is a liar.

I have a habit of taking care with functions in frequently used libraries that I think will be used a lot in inner loops. And then, when you spot something in another function, that isn't so often used...

Oh - and then there's the "I'm writing it - of course it's an important library" logic.

Oh - and BTW. I have never yet used a profiler to guide an optimisation. Don't have access to a commercial one, and never quite built up the motivation to figure out gprof.

Basically, I'm a hypocrite. These principles apply to other people, but I have too much fear of someone saying "but why did you write it that slow and crappy way?" so I can never really apply them properly to myself.

I'm not really as bad as I make out here, though. And I'm completely immune to self-deception, so you know I'm right about that!

EDIT

I should add - one of my major stupid hang-ups is call overheads. Not everywhere, of course, but in those I-think-it'll-be-used-a-lot-in-inner-loops cases (where I have no objective evidence of a problem). I have written nasty offsetof-based code to avoid making virtual method calls more than once. The result may even be slower, since it probably isn't a style of coding that optimisers are designed to deal with well - but it's cleverer ;-)

ContentLicense: CC BY-SA 2.5


问:
Should I use one database per application or share a single database amongst multiple applications
I have multiple applications some that use data from the same sources.
Is it best practice (or what are the pros/cons) to:

leave the data in databases shared by multiple applications

saves space as only one database is needed

complicates indexing as different applications have different querying needs

import data daily into per-app databases

uses more space as duplicated data exists in per-app databases

easier indexing as each app can focus on its individual needs

I may have left out other advantages/disadvantages, please list if any, also how is this done at your workplace?

答:
Can you elaborate more about your application architecture?

If your database functions just as a data repository without application logic such as triggers or business package code, it would be better to have a single database and encapsulate business level functionality to services that use the database for all their actions.  If you have triggers or code in database schema you will get into great trouble by using a single database which can be troublesome in many cases.


问:
is using a PUT with side affects acceptable (REST)
I want to create an undo history whenever the user updates a form. Because it's an update, I want to use a PUT request. However, I read that PUT needs to have no side effects.

Is it acceptable to use PUT here? Are there better alternatives?

PUT  /person/F02E395A235

```<code>{
   time: 1234567,
   fields: {
      name: 'John',
      age: '41'
   }
}
</code>```

In the server

```<code>doPut('person/:personId',
   // create a new person snapshot
)
</code>```

Edit:

The history will be visible to the user, calling multiple times would result in multiple versions.

The solution was to check if the version was unique before creating it.

答:
You are correct that PUT needs to have no side affects, however I would add something to this.

PUT needs to have no side affects on the resource for which that PUT operation is being performed

You are updating a person resource which is identified as F02E395A235, so using PUT is correct. Now as a business rule you also keep track of changes which is invisible to the calling entity (consumer of the REST service). This will not add a new item in the person resource. The historical snapshot will not be accessible using the /person/ endpoint. So I believe, PUT should be perfectly acceptable in this case.


问:
I have a unexceptional exception. That is thrown by a API used in my project. Is it standard to log errors like these or handle them without logging
The API has a Throttle on the number of requests you can make. So we queue our requests in a local database and make as many requests as possible until the "Throttle exception" is thrown. Upon catching we exit the program and a scheduled task starts the process over again in 15 minutes.

Is it standard to log this type of exception or just exit the program since  this exception is expected

答:
I'd log (at info level) the reason I was exiting the program, though not the stack trace. I might log at debug level the details of the thrown exception, and configure debug logging off in production but on when in my IDE.

Having programs exit without obvious reason is just plain wrong. Your support team will curse you every time – or maybe start ignoring it when the program exits for some other reason, because they will assume that it is for the reason they know about.

And developers always want all the information – and know how to disable it if they don't care at the moment.


答:
As Tristan said, splitting the features into their own repositories is the best practice, if possible.  However, there are alternatives if the code is too intertwined.

One is to use MOE, which is a program that basically automates translating a repository between an open source and a closed source version.

Another option is to create a Bob branch, then copy out the parts you want to send to him.  When he sends you changes, just check out that branch and copy all his files back in.  Then it's a simple merge back into your main branch.  I've used this method when the changes were in a different VCS.

Title: Sharing only part of code with git

Body:
The situation

I have code which has features X and Y.

Bob needs access to the code to help develop feature X further.

Normally I would allow Bob to clone the code, but the problem is that feature Y is confidential, so this is not possible. Bob does not need to be able to view feature Y code to develop feature X further.

If I create a new branch to share with Bob and delete feature Y from the code, it will still be viewable in the commit history.

So I guess the only option is:

Create a new branch and delete feature Y.

Create a completely new repository to share with Bob

Copy the files (while the new Y-less branch is checked out) to the new repository.

Give Bob access to that new repository.

After Bob develops feature X further, cherry pick relevant lines and files, and put them into my master. (painful)

Question

Is there a better way to go about this?


答:
The people drafting HTTP/2 were a lot more verbose about their ideas of what HTTP should do, while retaining the old meaning. Let's see what the HTTP/2 draft spec has to say about idempotence:

4.2.2.  Idempotent Methods

A request method is considered "idempotent" if the intended effect on
the server of multiple identical requests with that method is the
same as the effect for a single such request.Of the request methods
defined by this specification, PUT, DELETE, and safe request methods   are idempotent.

Like the definition of safe, the idempotent property only applies to
what has been requested by the user; a server is free to log each
request separately, retain a revision control history, or implement
other non-idempotent side-effects for each idempotent request.

The intended effect on the server for each such a PUT request is to update the resource identified by that URI. This is exactly what happens in your case.

That you decide to version resources doesn't really matter here. If you don't want to create a new version when nothing has changed, you'll need to compare the payload in the PUT request with the most recent (or otherwise identified) version of the resource, and when none of the properties have changed you can choose to not create a new version.

Your edit:

The history will be visible to the user, calling multiple times would result in multipleversions

As far as the resource is concerned, that is no side effect. The resource at that URI does not change (the same properties get PUT). History is just metadata, as it most probably is requested by a different URI or with different request headers.

Title: is using a PUT with side affects acceptable (REST)

Body:
I want to create an undo history whenever the user updates a form. Because it's an update, I want to use a PUT request. However, I read that PUT needs to have no side effects.

Is it acceptable to use PUT here? Are there better alternatives?

PUT  /person/F02E395A235

```<code>{
   time: 1234567,
   fields: {
      name: 'John',
      age: '41'
   }
}
</code>```

In the server

```<code>doPut('person/:personId',
   // create a new person snapshot
)
</code>```

Edit:

The history will be visible to the user, calling multiple times would result in multiple versions.

The solution was to check if the version was unique before creating it.


答:
HTTP distinguishes between two properties:

Idempotency

Safety

Idempotency is defined by the spec as follows:

Methods can also have the property of "idempotence" in that (aside from error or expiration issues) the side-effects of N > 0 identical requests is the same as for a single request. The methods GET, HEAD, PUT and DELETE share this property. Also, the methods OPTIONS and TRACE SHOULD NOT have side effects, and so are inherently idempotent.

And safety:

In particular, the convention has been established that the GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval. These methods ought to be considered "safe". This allows user agents to represent other methods, such as POST, PUT and DELETE, in a special way, so that the user is made aware of the fact that a possibly unsafe action is being requested.

Naturally, it is not possible to ensure that the server does not generate side-effects as a result of performing a GET request; in fact, some dynamic resources consider that a feature. The important distinction here is that the user did not request the side-effects, so therefore cannot be held accountable for them.

Note that safety implies idempotency: if a method has no side-effects then performing it multiple times will yield the same side-effect as performing it once, namely none.

This puts the methods into three categories:

safe (and thus also idempotent): GET, HEAD, OPTION, TRACE

idempotent but not necessarily safe: PUT, DELETE

neither idempotent nor safe: POST

PUT needs to have no side affects.

That is wrong. PUT is idempotent but not safe. The whole point of PUT is to have a side-effect, namely updating a resource. What idempotency means is that updating the same resource with the same contents multiple times should have the same effect as updating it only once.

Note the last paragraph in the section about safety [emphasis mine]:

Naturally, it is not possible to ensure that the server does not generate side-effects as a result of performing a GET request; in fact, some dynamic resources consider that a feature. The important distinction here is that the user did not request the side-effects, so therefore cannot be held accountable for them.

Although this sentence talks about GET and safety, we can assume that the authors also meant to apply the same reasoning to PUT and idempotency. IOW: PUT should have only one user-visible side-effect, namely updating the named resource. It may have other side-effects, but the user cannot be held responsible for them.

For example, the fact that PUT is idempotent means that I can retry it as often as I want: the spec guarantees that executing it multiple times will be exactly the same as executing it once. It's perfectly valid to create a backlog of old revisions as a side-effect of those multiple PUT requests. However, if, as a result of multiple retries, your database fills up with a backlog of old revisions, that is not my problem, it's yours.

IOW: you are allowed to have as many side-effects as you want, but

it must look to the user as if their requests were idempotent

you are responsible for those side-effects, not the user


问:
Simplest possible Paxos algorithm (distributed consensus) explanation
I am looking for a simple explanation of the Paxos algorithm that can be used for reaching consensus in a distributed environment (possibly peer to peer network).

Every explanation I have encountered so far was a tough reading of multiple pages. I am looking for a simplified explanation that still preserves the core principles.

答:
I've found this explanation in the context of Cassandra lightweight transactions useful.

Prepare/promise is the core of the algorithm. Any node may propose a value; we call that node the leader. (Note that many nodes may attempt to act as leaders simultaneously! This is not a “master” role.) The leader picks a ballot and sends it to the participating replicas. If the ballot is the highest a replica has seen, it promises to not accept any proposals associated with any earlier ballot. Along with that promise, it includes the most recent proposal it has already received.

If a majority of the nodes promise to accept the leader’s proposal, it
  may proceed to the actual proposal, but with the wrinkle that if a
  majority of replicas included an earlier proposal with their promise,
  then that is the value the leader must propose. Conceptually, if a
  leader interrupts an earlier leader, it must first finish that
  leader’s proposal before proceeding with its own, thus giving us our
  desired linearizable behavior.

References

http://www.datastax.com/dev/blog/lightweight-transactions-in-cassandra-2-0


问:
Can I release a script that depends on both proprietary and GPL'd libraries to be run?
I'm writing my thesis project in GNU Octave. My project basically consists of a bunch of ".m" files that are written in Octave. I'm also using a proprietary (and unreleased) shared library developed by my supervisor.

To be able to access the library, I've written an OCT-file wrapper (dynamic extension for Octave). My question is: am I allowed to distribute my ".m" files that depend on both Octave internals and the proprietary library? I'm not going to distribute any dependencies nor the wrapper files, just the ".m" files. Is it illegal to distribute these (I don't mind being forced to release them under a specific license) if they depend on a proprietary piece of software to be fully functional? Even if it's just to document my experiments?

I've already asked at the Octave forums, but they were too passionate and aggressive and didn't give any useful arguments. I would like to hear facts, not ideology.

PS: I know I could use MEX, which is the only explicitly allowed means of communication with proprietary libraries in Octave. However, it's not possible for technical reasons to use MEX in my case.

答:
The FAQ has a useful section about this:

If I write code using Octave do I have to release it under the GPL?

Code written entirely in the scripting language of Octave (interpreted
  code in .m files) may be released under the terms of whatever license
  you choose.

If your supervisor's library is written using the native plug-in interface, then according to the same section in the FAQ, that library needs to be GPL:

Code written using Octave's native plug-in interface (also known as a
  .oct file) necessarily links with Octave internals and is considered a
  derivative work of Octave and therefore must be released under terms
  that are compatible with the GPL.

However, that doesn't affect the licensing of your code, just of your supervisor's.


问:
Is a senior programmers advice about always using books a good idea?
I am a junior developer and have only been in the industry for 5 years. At my current company there is a senior let's call him Infestus. Occasionally I am being given opportunity to shine and do something completely brand new from scratch.

One of the most recent examples was that I had to make a singleton in the multithreaded application. I have decided to use this method. As soon as Infestus saw it, he quickly proceeded to call me stupid and told me to use this approach. Upon asking him why he just brushed it off as this is better and that's how this and this book about Java says it is better.

And it is a common pattern: whenever I get a chance to do something new, I quickly get shot down by Infestus and the only reasoning why his method is better is because those books were written by famous programmers. He is always trying to give me books to read so that I may "learn" which ways to program.

I have only been programming for money for 5 years, but is it always a good idea to just blindly follow the book on best ways for solving a problem, or should I try experimenting every now and then? The constant barrage of complaints from the Infestus is starting to cause me to never try anything new and follow examples in books.

EDIT: I am utterly lost. Yes I know that following anything blindly is a bad idea. But this godlike programmer Infestus who seems to know a lot, tells me that the only way to program properly is by reading books and following everything down to a T. All the rules he imposes are the ones written in books, so I am just wondering if books are the only correct way.

EDIT2: Infestus is not my boss. He is just one of senior developers in charge of reviewing the code. And most of his comments after reviews consist of book names where such and such method is wrong.

答:
You are going to run into programmers like this your entire career.  There is nothing wrong with experimentation and learning on your own.  Sure books are great.  Many times the examples work in a clean environment, but if you are developer for another company there is no such thing as a clean (without interference from others) environment.

It's always nice to know how to do things the "right" way, but opinions change year to year.  So learn what you can.  Take what you can from the senior developer, blend it with your knowledge that you learn on your own.  Eventually, you will be a senior developer and will be taking from these experiences and teaching junior devs.

Just don't be a jerk about it.


答:
Per the FAQ quoted by Gustav, Octave DOES NOT force a license onto your .m files. You can release .m files under ANY license that you choose.

It sounds like Octave will force a license on the library you are using, if you want to distribute it. So if you need to release that, you'll have to work that out with your supervisor.

As far as I can see from my cursory look, .m files can't reasonably be considered derivative works. (If they were, then they'd be derivative works of the built-in Octave functions, and all .m files would have to be GPL.)

Since it's clearly the case (it says so in the FAQ) that all .m files don't have to be GPL, I would conclude that while you probably have to GPL the library to distribute it, there's no need to GPL your .m files.

Title: Can I release a script that depends on both proprietary and GPL'd libraries to be run?

Body:
I'm writing my thesis project in GNU Octave. My project basically consists of a bunch of ".m" files that are written in Octave. I'm also using a proprietary (and unreleased) shared library developed by my supervisor.

To be able to access the library, I've written an OCT-file wrapper (dynamic extension for Octave). My question is: am I allowed to distribute my ".m" files that depend on both Octave internals and the proprietary library? I'm not going to distribute any dependencies nor the wrapper files, just the ".m" files. Is it illegal to distribute these (I don't mind being forced to release them under a specific license) if they depend on a proprietary piece of software to be fully functional? Even if it's just to document my experiments?

I've already asked at the Octave forums, but they were too passionate and aggressive and didn't give any useful arguments. I would like to hear facts, not ideology.

PS: I know I could use MEX, which is the only explicitly allowed means of communication with proprietary libraries in Octave. However, it's not possible for technical reasons to use MEX in my case.


答:
Reading a book shouldn't be blind: the author should try to convince you of the merits of his/her approach as he presents it. It's reasonable for your senior to point you to a book explaining his preferred approach, rather than asking him to explain it himself: though he should be able to explain the benefits of his preferences without relying on the book, it's also a duplication of effort that the book's author has already made.

So, read the book, see what the book's author says, and if it confuses you, or you'd like to confirm your understanding, or you don't agree, then talk to your senior about it, but now you'll be able to have a more productive discussion.

Title: Is a senior programmers advice about always using books a good idea?

Body:
I am a junior developer and have only been in the industry for 5 years. At my current company there is a senior let's call him Infestus. Occasionally I am being given opportunity to shine and do something completely brand new from scratch.

One of the most recent examples was that I had to make a singleton in the multithreaded application. I have decided to use this method. As soon as Infestus saw it, he quickly proceeded to call me stupid and told me to use this approach. Upon asking him why he just brushed it off as this is better and that's how this and this book about Java says it is better.

And it is a common pattern: whenever I get a chance to do something new, I quickly get shot down by Infestus and the only reasoning why his method is better is because those books were written by famous programmers. He is always trying to give me books to read so that I may "learn" which ways to program.

I have only been programming for money for 5 years, but is it always a good idea to just blindly follow the book on best ways for solving a problem, or should I try experimenting every now and then? The constant barrage of complaints from the Infestus is starting to cause me to never try anything new and follow examples in books.

EDIT: I am utterly lost. Yes I know that following anything blindly is a bad idea. But this godlike programmer Infestus who seems to know a lot, tells me that the only way to program properly is by reading books and following everything down to a T. All the rules he imposes are the ones written in books, so I am just wondering if books are the only correct way.

EDIT2: Infestus is not my boss. He is just one of senior developers in charge of reviewing the code. And most of his comments after reviews consist of book names where such and such method is wrong.


问:
Is the Java package name convention flawed?
We're all familiar with the Java package name convention of turning the domain name around. I.e. www.evilcorp.com would, by convention, chose to have their java packages com.evilcorp.stuff.

Increasingly I'm getting fed up with this. As a commercial programmer, I encounter time and again that the software package name is completely irrelevant due to some rebrand, acquisition or similar.

In the opensource world there's less name changes so there it makes sense. However it seems to me the shelf life of many pieces of (commercial/internal) software are much longer than that of the organisation making them.

The problem is often made worse by software projects taking the marketing department's lead to use the name du jour they use refer to a certain project. A name that will, without fail, change 3 months down the line to make the emperor's new clothes feel fresh and new.

Because of this, I've mostly stopped using the reverse domain as package name. Granted, if this is done on a large scale, there's risk of name collisions, but surely this is mitigated by either using "unique" software names, avoiding generic words, or use the reverse domain for projects intended to be sold/released as libraries.

Other thoughts?

答:
When I start a new project, I always insist on an internal and unchangeable name that the marketing people may or may not know, as it will only be referred to in the source code. That way, I do not have to worry about project name changes and namespace pollution.

This scenario fits me, because the source code is not usually an important part of the product, i.e. projects are usually a closed-source, proprietary systems. However, in open-source projects where the source code is the product, this might not be feasible.


答:
My experience is that when concerned about programming subject matter, the quality and presentation of information with adequate explanations in books is a magnitude better then when searching for same subject information on the internet.
Internet often lacks proper explanation, context and quality.

The quantity of said information on the internet is higher.

So my general strategy is to learn from books to get a deeper understanding and after that learn from the internet to get exposed to different implmentations and widen my experience.(and often see how not to do stuff).


问:
Are "TDD Tests" different to Unit Tests?
I read Stephen Walther's article about Test Driven Development (TDD) and unit testing.

I think it was an excellent article.

The author makes a distinction between what he calls "TDD Tests" and unit testing. They appear to be different tests to him.

Previous to reading this article I thought unit tests were a by-product of TDD. I didn't realise you might also create "TDD tests".

The author seems to imply that creating unit tests is not enough for TDD as the granularity of a unit test is too small for what we are trying to achieve with TDD. So his TDD tests might test a few classes at once.

At the end of the article there is some discussion from the author with some other people about whether there really is a distinction between "TDD Tests" and unit testing. Seems to be some contention around this idea.

The example "TDD tests" the author showed at the end of the article just looked like normal MVC unit tests to me - perhaps "TDD tests" vs unit tests is just a matter of semantics?

I would like to hear some more opinions on this, and whether there is / isn't a distinction between the two tests.

答: There used to be an IEEE definition for unit testing that I liked because it was more general and didn't go with the whole TDD concept of testing the smallest testable units possible. Now that definition has been altered to match the EP-version which I find silly. To me, unit testing means checking points of interaction between larger sets of components where you're most likely to have some volatility when changes are made. If you see variations on definitions out there, it's because the phrase got co-opted by the EP/TDD crowd. I find it one of the more irritating phenomena in programmer culture. Why can't we just come up with new phrases rather than re-invent old ones?</p>


答:
There are three key elements to any healthy relationship. Communication, honesty and trust. That counts for all relationships, even working relationships. You should be talking to your supervisor about these concerns.

If you don't understand his reasons for advocating a certain design, then tell him that. Tell him that you haven't read the book, and that you'd like to understand why his way of doing it is better. The key is that you should be trying to understand his way of doing things.

I think you should also treat this person with more respect. In your head, you're calling him derogatory names, and criticizing his approach to what you think of as "learning". Watch out for that. On the other hand, you did say he called you stupid. That's not cool, and you should tell him that's not cool to call someone stupid.

Ideas can be stupid. We all make mistakes and miss things, even the senior guys. When there's a flaw in a design, the best question to ask is "Why are you doing it this way? Won't it break in situation X,Y,Z? Won't design B be better?"

Keep in mind that you're working on this software with other people. That's a hard skill to learn. It doesn't matter that you're not writing anything from scratch, there is always room to shine by making your code the best code you can.

And "best" very often means readable and understandable. We programmers spend a lot of time reading other people's code. If that code is clear and readable, then that makes the code really valuable. One of the ways we learn to write great code is by reading lots of good code. You very often find very good code in books. So reading one or two good programming books will likely make you a better programmer.


答:
In the company where you work, it probably is. This is what they require you to do.

This engineer Infestus does a very poor job educating junior developers by telling them "this is written in the book, and that's why". He's not a preacher, he's an engineer, and he should be able to break it down and present the concepts so that juniors would be able to learn from his experience.

I would encourage you to speak to knowledgeable developers in your company, ask them questions about the pros and cons of different programming techniques etc. This along with reading books and blogs (I would recommend Joel on Software - just Google it, it's a must) should give you a better understanding.


答:
Experiment on your own and learn all that you can. After you read enough books, you're going to discover that there are multiple books on particular subjects and they may contradict one another. Try the one you think is best and try both if you have the time or want to compare/contrast.

Dealing with your boss is an entirely different subject and approach. If I wanted someone to do something the exact way it was in a book, I'd tell them. That's just me because I don't associate with mind readers. Your boss makes this a habit, just ask if he recommends any books or references when you get a new project.

Whatever you do, don't stop working on new projects. I know it is easy for all of us to give tips on how to deal with this situation and they may or may not work, but you're the one who has to live with it and suffer the negativity. You're going to get better, but that usually comes from writing more code on new things, learning from the sucesses and failures.


答:
.m files are not required to be licensed GPL, so you can distribute them as you see fit.  Even if they were required to be licensed GPL, there's nothing in the GPL that requires you to publish working source code, or all of your source code, unless you also publish binaries built from that source code.

Part of the confusion on the Octave forums stems from the fact that a common way to try to circumvent GPL requirements is to publish a binary, but only publish select parts of the source code that built that binary.  Since you aren't publishing a binary, that doesn't affect you.

Another source of confusion is that depending on if your use of the proprietary library counts as your supervisor distributing a derivative work of Octave, the library may have to be published as GPL, but that's not your concern.


答: You should ask him what in particular is wrong with your method. If he is unable to answer it clearly, you might be pretty sure that it is just a common guy who likes to feel superior.</p>


问:
Queries in three tier architecture
I am wondering where should the DB queries need to be in the three tier architecture.

The first association that think is in the DAL. But then if the BL want to search for an object, the DAL need to publish methods for each possible search (Unrealistic - a lot of work).

The second option, is in the BL. But then the BL need to know how the DB designed... (Encapsulation is not good)

The third option, is that the DAL will publish some object like "QueryBuilder" or something similar, and the BL build the query with weak association (but still needed) to the DB.

What is the best option to allow BL to do a search?

答:
If your data access layer doesn't provide the methods to access data that you need, why would you have it at all?

The point of a DAL is not just to provide generic methods for accessing whatever data the caller wants. The database driver already provides those, and if you want to be independent of the particular database, you want a wrapper or adapter, but not an entire layer of architecture.

No, in my view the data access layer has exactly this job to do: to provide methods for those queries that you actually use in your application (rather than the near-infinite number of queries that SQL would theoretically allow).

Title: Queries in three tier architecture


问:
Help me think in C++
I mainly use dynamic languages.  For many years I see statically typed hello world examples like

```<code>const int STACK_SIZE = 100;
</code>```

And I will think "wow, I can't think like that".  I understand memory management, syntax, pointers (mostly).  Please let me into your brain for a second and analyze this use case with me.

Let's say we have a command line application that's going to let us manage employees (exciting!).  Let's just focus on adding new employees.  We're a trendy new startup that's going to do a moonshot so our employee list size is going to start at 1 but we're eventually going to add 7 billion co-founders and maybe more (aliens?  dogs?  cats?).

In ruby/python/javascript, I'd just create an array and suffer/refactor later when performance is terrible.  Of course, you'd use a database in either C++ or some other language.  But let's entertain this for a second.  Would a C++ person break the problem down past one data structure?  I think of this problem as "an array" problem.  But maybe someone with more low-level experience thinks like this?

Create a buffer to hold the list as the user adds in names, this can be fixed size

Periodically flush the buffer to a file or something like that.

Is that realistic?  I understand the requirements here are contrived and vague.  But let's say a C++ developer was creating this small application for themselves.  Would they just use a smart pointer or something that would grow over time or would they create a std::string*?

Let me give another example.  Let's say you write a problem to loop through a file and do something with each line.  Some people (including myself) start thinking with a small example file.  Then later, you find that your problem can't handle large files.  Whoops.  Sometime I feel like lower level programmers would naturally pre-optimize out of discipline or experience to read the file in a buffer or something like that.  Do you agree?

答:
Small, fixed-size buffers might be used for any of the following reasons:

constraints: either limited memory, or cache performance, or some other speed requirement that absolutely prohibits dynamic (re)allocation

laziness: IMO this is mostly a hang-over from C, which didn't have a rich container library

correctness: if you're matching some external entity (hardware, or a file format or wire protocol) that genuinely has fixed size elements, then why not represent them exactly?

So, let's look at your employee DB example.

is it constrained in memory or performance? Not to start with, even if you're running it on a wristwatch these days

are we either lazy, or writing C 20 years ago? No!

are we reflecting some external truth? Maybe if we move to a DB later, and decide to make some column VARCHAR(100), then having an array of size 100 might be reasonable. But we'd be doing it for expressiveness , not to show our low-level l33tness. And besides, you excluded this case in your question.

The right way to do it would probably be to:

choose a standard container that suits your access patterns (std::list and std::vector are popular all-purpose choices)

write some class to represent an employee

write some code to (de)serialize this employee

If you do this right, it manages all the memory for you, and doesn't require any fixed-length anything. It will also look somewhat similar to the equivalent logic in Python or javascript.

tl;dr

your stated problem is not a low-level problem, so there's no reason to trade off clarity or simplicity for low-level magic.

If you had a low-level problem, those low-level design decisions would proceed from the problem & solution domains.

Using low-level style on a high-level problem is just bad style, because it doesn't match the problem domain.

Title: Help me think in C++


答:
Following books blindly is a bad idea, but there's a difference between following a book exactly and following it blindly.

When you're trying to understand stuff in a book, it generally is appropriate to follow it exactly at first, while you're getting a feel for what it's trying to teach you. Odds are that you still won't understand everything when you're done -that's how things like this usually go- but following the book exactly at first will give you something to experiment with, as you try to understand your questions. Odds are again good that you'll find ways that you disagree with what's in the book, but you will have an understanding of the issues that the book was trying to address, so that when the time comes to write your own code, you can address them in your own way (or maybe their way, at least in part) rather than just leaving those issues to bite you later.

One other thing which isn't inherently specific to Java, but is nevertheless especially common in that community. I think I can guess which books you're talking about, and they form a major part of the lexicon of the Java community. Understanding them, and the ways they describe things, will help immensely when you need to understand other Java code that you find. That's a valuable skill in its own right.


答:
Just because C++ programmers tend to delve into the lower layers of abstraction more often doesn't mean we always live there.  When faced with a high-level problem, we use high-level abstractions.

Your example problem would likely be solved with a vector at first, refactored into an EmployeeList class backed by a vector as complexity grew, then refactored to be backed by a database as the size grew.  C++ programmers aren't prescient about how their application will grow or not.  We're just as bound by design principles like YAGNI.

If there wasn't a standard library vector, a good C++ programmer would write his own, and a bad programmer would suffer with the limitations that were handed him.  People who fail to use abstraction appropriately are bad programmers in any language.

Title: Help me think in C++

Body:
I mainly use dynamic languages.  For many years I see statically typed hello world examples like

```<code>const int STACK_SIZE = 100;
</code>```

And I will think "wow, I can't think like that".  I understand memory management, syntax, pointers (mostly).  Please let me into your brain for a second and analyze this use case with me.

Let's say we have a command line application that's going to let us manage employees (exciting!).  Let's just focus on adding new employees.  We're a trendy new startup that's going to do a moonshot so our employee list size is going to start at 1 but we're eventually going to add 7 billion co-founders and maybe more (aliens?  dogs?  cats?).

In ruby/python/javascript, I'd just create an array and suffer/refactor later when performance is terrible.  Of course, you'd use a database in either C++ or some other language.  But let's entertain this for a second.  Would a C++ person break the problem down past one data structure?  I think of this problem as "an array" problem.  But maybe someone with more low-level experience thinks like this?

Create a buffer to hold the list as the user adds in names, this can be fixed size

Periodically flush the buffer to a file or something like that.

Is that realistic?  I understand the requirements here are contrived and vague.  But let's say a C++ developer was creating this small application for themselves.  Would they just use a smart pointer or something that would grow over time or would they create a std::string*?

Let me give another example.  Let's say you write a problem to loop through a file and do something with each line.  Some people (including myself) start thinking with a small example file.  Then later, you find that your problem can't handle large files.  Whoops.  Sometime I feel like lower level programmers would naturally pre-optimize out of discipline or experience to read the file in a buffer or something like that.  Do you agree?


问:
How does the Scrum Master participate in Daily Stand-Ups?
We have a professional Scrum Master consultant [*] who recently joined our project. Unfortunately, we don't know her name (she never introduced herself to us, she just came in one day and said "we are having a daily stand-up"), and she doesn't seem to do much else except chair a daily stand up meeting  - when I half-jokingly asked her to also give daily feedback in the meeting, she was quite affronted, saying it's the Scrum Master's job to "facilitate, not participate".

This seems fairly anti-Agile (having worked on other agile projects, where the teams were self directed), which is supposed to be egalitarian, but I am not sure about how it works in the Scrum Methodology. I suspect she doesn't do much all day, and that's the reason for her defensiveness on this issue.

Does the Scrum Master take part in the "yesterday, today, impediments" spiel during the stand-up meeting, or is their role to just chair ("facilitate") the meeting?

[*] We weren't actually told what her job is, we just assume, since she calls herself the Scrum Master

答:
I have 3 Scrum Teams in my position as Scrum Master and we use an electronic Taskboard in our agile practice.  All my teams, with the exception of one, provides their status on all tasks they're working on, moving from one person to the next, in the typical standup process.  The exception team decided they wanted to do their standup going story by story and has now asked that I lead this by being the one to drive the meeting.

Is there any justification for a Scrum Master to take this role on during standup?  I can understand if the team has more than 7 resources, but it seems as if it's a babysitting role designed to make everyone pay attention instead of the team being responsible adults because they don't want to take the trouble themselves to self-organize.

One of the members of this team is also doing work for one of the other teams and has mentioned in the sprint retro how much faster the meeting goes when each person steps up and takes the lead for themselves on the board.  It didn't make any difference to the team and the PO has pushed the team to stand their ground on the story-by-story method.