问:
Advise on loose coupling between user controls
I have 5 user controls on the page and each control implements it's own interface that contains properties and events. In order to enable communication between user controls, I am creating a property of target user control inside other user control. Through this property, it's state can be altered and be able to register its events.

Below is the pseudo code of results user control. It subscribes to OnSearch event of Search user control.

```<code>public interface IResults
{
     //other fields
    ISearch SearchControl { get;}
}

public partial class Results : IResults
{
 //other fields

 public ISearch SearchControl
 {

    get{
    this.Page.Parent.FindControl("UCSearch") as ISearch;}
 }

 protected override void Page_Load(object sender, EventArgs e)
 {
    this.SearchControl.OnSearch += new EventHandler(testMethod);
 }
}
</code>```

Is it ok to have the reference properties inside user controls to subscribe to the events and manipulating the state. Does it create any maintenance problem in future.

Does FindControl and type casting degrade the performance of the application.

答: In general you might want to establish in your architecture, a rule of thumb that controls in your design will not know about other control(s). If they do, you can end up with spaghetti and cross-referencing difficulties. Consider introducing a Mediator, where only the Mediator knows about all the controls. If a control wants to talk to another control, it can do so only through the Mediator. The control raises an event, which is fielded by the Mediator. The Mediator has knowledge of what that event means to some other control on the page. It calls that control to do the work. The control that raised the event does not even know the other control exists.</p>


问:
Why is the usage of string keys generally considered to be a bad idea?
This has been bugging me for a while. Most of the time, when it comes to storing data in structures such as hashtables, programmers, books and articles insist that indexing elements in said structures by String values is considered to be bad practice.
Yet, so far, I have not found a single such source to also explain WHY it is considered to be bad practice.
Does it depend on the programming language? On the underlying framework? On the implementation?

Take two simple examples, if it helps:

An SQL-like table where rows are indexed by a String primary key.

A .NET Dictionary where the keys are Strings.

答: Lots of trade offs and no one right answer. Many programmers would never consider using string keys in the database because they aren't aware of hashing and how a database works. String keys as long as they are either extremely stable, or meaningless (surrogates), are a good design choice in many circumstances. </p>

ContentLicense: CC BY-SA 3.0


问:
Relative encapsulation design
Let's say I am doing a 2D application with the following design:

There is the Level object that manages the world, and there are world objects which are entities inside the Level object.

A world object has a location and velocity, as well as size and a texture. However, a world object only exposes get properties. The set properties are private (or protected) and are only available to inherited classes.

But of course, Level is responsible for these world objects, and must somehow be able to manipulate at least some of its private setters. But as of now, Level has no access, meaning world objects must change its private setters to public (violating encapsulation).

How to tackle this problem? Should I just make everything public?

Currently what I'm doing is having a inner class inside game object that does the set work. So when Level needs to update an objects location it goes something like this:

```<code>void ChangeObject(GameObject targetObject, int newX, int newY){
 // targetObject.SetX and targetObject.SetY cannot be set directly
 var setter = new GameObject.Setter(targetObject);
 setter.SetX(newX);
 setter.SetY(newY);
}
</code>```

This code feels like overkill, but it doesn't feel right to have everything public so that anything can change an objects location for example.

答:
This code feels like overkill, but it doesn't feel right to have everything public so that anything can change an objects location for example.

Encapsulation is part of the problem, but I'd argue that you should design objects with services to clients (responsibilities) which are more abstract than simple methods (sets and gets).

setLocation(x,y) is an example of a service. Reveal that service only to clients who should be able to do it. If x and y are things you might change (and thus want to hide), abstract them into a Location object, e.g., setLocation(new Location(x,y)). Location's implementation could actually be an angle and a distance from the origin. You could have two ways to access locations, theta + distance or x,y (it's just an example).

Another reason to do think of services is that you can avoid objects being in an inconsistent state between setters. For example, if a client does set(x) then fails to call set(Y), the object's location could be inconsistent. Putting the operation into a service (setLocation) allows you to enforce consistency rules on the object's state.

Finally, one important purpose of hiding things from the outside with encapsulation is so that you'll be allowed to change them later. If you're 100% sure nothing will change, make everything public. This is generally a bad idea, because in reality things do change. Whatever you make public will possibly be a headache later if it changes (your client classes will potentially break).

TL;DR Designers have to design two aspects of each class - the public part, and the private part. Make the public part be useful services to the clients (classes that will use the class being designed).

Read more in Hiding the implementation chapter of Thinking in Java by Bruce Eckel.

Title: Relative encapsulation design


问:
What happens to equal elements when inserting into a binary search tree?
Most BST examples show a sample of a BST with unique values; mainly
to demonstrate the order of values. e.g. values in the left subtree are smaller than the root, and values in the right subtree are larger.

Is this because BSTs are normally just used to represents SETs ?

If I insert an element say 4 which already exists in the BST, what should happen ?
e.g. In my case, 4 is associated with a payload. Does it mean I override the existing node's payload.

答:
The classic examples of the BST demonstrate a set where there is one entry for a given value in the structure.  An example of this is the TreeSet in Java (yes, thats a red-black tree behind the scenes - but its a tree and a set).

However, there's nothing saying that there can't be additional values stored at the location indicated by the value.  Once you decide to do this, it becomes an associative array (sometimes called a map).  Again, going to Java for the example, there is the TreeMap.

An example of this could be:

```<code>TreeMap<Integer, String> ageToName = new TreeMap<Integer, String>();
ageToName.put(4,"Alice");
ageToName.put(25,"Bob");
ageToName.put(16,"Charlie");
</code>```

The structure of this would look like:

```<code>      16 -> Charlie
     /             \
    /               \
4 -> Alice          25 -> Bob
</code>```

A balanced binary tree (the red-black part of that structure) with a left child and a right child.  You access it by looking for the value 4, or 16, or 25 and get back the associated data stored in that node.

One aspect of the tree is that you can't have two different values with the same index.  There is no way with this design to insert David at age 16 also.  However, one could put another data structure such as a list instead of the String at the node and allow you to store multiple items in that list.

But the (binary) tree, by itself, is a set that requires the indexes into it to be comparable (orderable) and that it will contain only distinct values (no duplicates).

Realize that everyone is free to implement their own trees and sets and how they deal with the addition of another item with the same key.  With a TreeSet, if you add an already existing value, the add function returns false and leaves the set unchanged.  With a TreeMap, if you call put with a key that already exists, it replaces the old value and returns the replaced value (null if nothing was there).

What should happen is whatever you need to have happen for that implementation.  There's no inscribed tablet that all the computer scientists signed that dictates how any abstract data structure should behave.  They behave as they should and when they need to behave other ways, document it and do it that way.

Body:
The classic examples of the BST demonstrate a set where there is one entry for a given value in the structure.  An example of this is the TreeSet in Java (yes, thats a red-black tree behind the scenes - but its a tree and a set).

However, there's nothing saying that there can't be additional values stored at the location indicated by the value.  Once you decide to do this, it becomes an associative array (sometimes called a map).  Again, going to Java for the example, there is the TreeMap.

An example of this could be:

TreeMap<Integer, String> ageToName = new TreeMap<Integer, String>();
ageToName.put(4,"Alice");
ageToName.put(25,"Bob");
ageToName.put(16,"Charlie");

The structure of this would look like:

      16 -> Charlie
     /             \
    /               \
4 -> Alice          25 -> Bob

A balanced binary tree (the red-black part of that structure) with a left child and a right child.  You access it by looking for the value 4, or 16, or 25 and get back the associated data stored in that node.

One aspect of the tree is that you can't have two different values with the same index.  There is no way with this design to insert David at age 16 also.  However, one could put another data structure such as a list instead of the String at the node and allow you to store multiple items in that list.

But the (binary) tree, by itself, is a set that requires the indexes into it to be comparable (orderable) and that it will contain only distinct values (no duplicates).

Realize that everyone is free to implement their own trees and sets and how they deal with the addition of another item with the same key.  With a TreeSet, if you add an already existing value, the add function returns false and leaves the set unchanged.  With a TreeMap, if you call put with a key that already exists, it replaces the old value and returns the replaced value (null if nothing was there).

What should happen is whatever you need to have happen for that implementation.  There's no inscribed tablet that all the computer scientists signed that dictates how any abstract data structure should behave.  They behave as they should and when they need to behave other ways, document it and do it that way.


问:
Do compiler-writers actually need to 'understand' machine code?
Might be kind of an odd question.

A guy writing a C++ compiler (or whatever non-VM language): Does he need to be able to read/write raw machine language? How does that work?

EDIT: I am specifically referring to compilers that compile to machine code, not to some other programming language.

答:
You don't need to start with a detailed knowledge of the semantics of your input and output languages, but you better finish with an exquisitely detailed knowledge of both, otherwise your compiler will be unusably buggy.
So if your input is C++ and your output is some specific machine language you will eventually need to know the semantics of both.

Here are some of the subtleties in compiling C++ to machine code: (just off the top of my head, I'm sure there are more I'm forgetting.)

What size will int be?  The "correct" choice here is an art, based on both the natural pointer size of the machine, the performance of the ALU for various sizes of arithmetic operations, and the choices made by existing compilers for the machine.  Does the machine even have 64-bit arithmetic?  If not then addition of 32-bit integers should translate to an instruction while addition of 64-bit integers should translate to a function call to do the 64-bit add.  Does the machine have 8-bit and 16-bit add operations or do you have to simulate those with 32-bit ops and masking (e.g. the DEC Alpha 21064)?

What is the calling convention used by other compilers, libraries and languages on the machine?  Do the parameters get pushed on the stack right-to-left or left-to-right?  Do some parameters go in registers while others go on the stack?  Are ints and floats in different register spaces?  Do the register allocated parameters need to get treated specially on varargs calls?  Which registers are caller-saved and which are callee-saved?  Can you perform leaf-call optimizations?

What does each of the machine's shift instructions do?  If you ask to shift a 64 bit integer by 65 bits what is the result?  (On many machines the result is the same as shifting by 1 bit, on others the result is "0".)

What are the memory consistency semantics of the machine?  C++11 has a very well defined memory semantics that places restrictions on some optimizations in some cases, but permits optimizations in other cases.  If you are compiling a language that does not have well defined memory semantics (like every version of C/C++ before C++11, and many other imperative languages) then you will have to invent the memory semantics as you go along, and usually you will want to invent the memory semantics that best matches your machine semantics.


问:
How has an increase in the complexity of systems affected successive generations of programmers?
As a "new" programmer (I first wrote a line of code in 2009), I've noticed it's relatively easy to create a program that exhibits quite complex elements today with things like .NET framework for example. Creating a visual interface, or sorting a list can be done with very few commands now.

When I was learning to program, I was also learning computing theory in parallel. Things like sorting algorithms, principles of how hardware operates together, boolean algebra, and finite-state machines. But I noticed if I ever wanted to test out some very basic principle I'd learned in theory, it was always a lot more difficult to get started because so much technology is obscured by things like libraries, frameworks, and the OS.

Making a memory-efficient program was required 40/50 years ago because there wasn't enough memory and it was expensive, so most programmers paid close attention to data types and how the instructions would be handled by the processor. Nowadays, some might argue that due to increased processing power and available memory, those concerns aren't a priority.

My question is if older programmers see innovations like these as a godsend or an additional layer to abstract through, and why might they think so? And do younger programmers benefit more learning low-level programming BEFORE exploring the realms of expansive libraries? If so then why?

答:
"if older programmers see innovations like these as a godsend or an additional layer to abstract through, and why might they think so?"

I've been programming since I was in high school, about 34 years, starting with Basic and Z80 Assembler, moving to C, various 4GL languages, Scheme, SQL, and now various Web languages. The scope, scale, and depth of the problems addressed by the profession experienced an inflationary period over that time, particularly in the 1990's. Constructs such as libraries, frameworks, and OS services are all contrivances meant to address the complexity that goes along with the expanded space of problems.  They are not a godsend nor a burden in and of themselves - just a continued exploration of a vast solution space.

But, IMHO, "innovation" is better understood in terms of novel forms, and not mistaken for sideways movement - reintroducing forms we've already seen introduced. In some ways, the fecundity of an ecosystem suffers when the primitive forms don't compose, when they fixate decisions made early in the evolution, or can't reprocess their own detritus. Some, if not most, of the constructs we remain focused upon do not prioritize long-term sustenance of value as a concern. That has started changing - approaches like Service Orientation and Domain Driven Design, not to mention hypertext and graph-based models, for instance are altering the landscape. Like any ecosystem, eventually the dominant forms will give way to new forms; we are best served by allowing diversity, broadly and in small increments rather than large-scale top-down standardization followed by all-at-once collapse.

"And do younger programmers benefit more learning low-level programming BEFORE exploring the realms of expansive libraries? If so then why?"

I would argue that most human language is based on metaphors long since forgotten, so while I'd support learning low-level programming from a scientific/numeric literacy standpoint, it is more important that we seek primitives that will support the scale and scope of the problems we are tackling in a way that we can safely ignore the lower level of detail. A framework isn't a primitive, nor is an OS or a library - they are fairly poor at doing the kind of abstraction we really need. Real progress will take people who (a) know what went before and (b) can think in a novel enough manner to come up with something different enough to explore a space of solution that hasn't been explored before or was explored and forgotten.

OTOH, even if your goal is to work as a technician/mechanical level, some level of low-level programming exposure is still going to be helpful to developing your problem solving skills.


问:
What is "using namespace" pollution?
I was looking at the google coding guide [here] and they do not recommend that one use the using namespace or namespace::function - if I did not misinterpret it.

Does this apply to std as well? cout<< does not work without it. This book, recommends the same. So how do I go about using cout<< without using namespace std; or std::cout<< ?

What is the recommended way? std::cout<<? Most c++ text books teach beginners with using namespace std; are they propagating poor coding practice?

答:
This is because:
1) it defeats the entire purpose of namespaces, which is to reduce name collision;
2) it makes available to the global namespace the entire namespace specified with the using directive.

For example, if you include  and define your own max() function, it will collide with std::max().

http://en.cppreference.com/w/cpp/algorithm/max

The preference is to use std::member_you_wish_to_use because it explicitly states which namespace to use.

ContentLicense: CC BY-SA 4.0

Title: What is "using namespace" pollution?


问:
Relationship between user story, feature, and epic?
As someone who's still new to agile, I'm not sure I completely understand the relationship or difference between user story, feature, and epic.

According to this question, a feature is a collection of stories.  One of the answers suggests that a feature is actually an epic. So are features and epics considered the same thing, that is basically a collection of related user stories?

Our project manager insists that there's a hierarchical structure:

Epic -> Features -> User stories

And that basically all user stories must fall within this structure.  Therefore all user stories must fall under an umbrella feature and all features must fall under an epic.

To me, that sounds awkward.  Can someone please clarify how user stories, features, and epics are related?  Or is there an article that clearly outlines the differences?

答:
Our organization has over 2,000 developers, so the answer to this question is important to fluent and clear communication between the hundreds of Agile teams we have working together on our common product. For a very small organization, you can have a very simple structure that doesn't even need to be hierarchical (as others have answered). However, for large organizations, there is definitely a need for some organized, scaled, consistent hierarchy - and therein lies the problem in striving to make a hierarchy out of something that's not strictly hierarchical.

Incidentally, we refer to each of these disparate levels as "work items". Some organizations (including some of the respondents above) refer to disparate levels as Stories or User Stories (and we have in the past too), but we found this too ambiguous, so we now refer to them generically as Work Items.

The best we have "officially" done thus far is to follow Dean Leffingwell's SAFe structure of Investment Themes and Business Epics being at the top (and second from the top) of the hierarchy, then Features under that, and finally Stories under Features. According to Agile, Tasks are always under Stories, so we are careful not to reuse that term any higher up. We chose to follow SAFe to at least have SOME consistency across all our teams.

But this is still insufficient for our needs. We define a Feature as a clearly valuable deliverable to a consumer of our software product (i.e. we list these Features on our announcements of upcoming Releases). And we define a Story as a smaller amount of scope and work that can be delivered in a single Sprint by a single Agile dev team. We are also now STARTING to follow the SAFe definition of Investment Theme and Business Epic at the Portfolio level (and not below this level). And we are STARTING to NOT use our OLD definitions of "Theme" and "Epic".

We are now slowly evolving in this direction, but the wheels of progress grind slowly. We are still struggling with how to split work into bite-sized chunks so that we can define the work and get it done smoothly by multiple teams. To do this, we see a need for a "Sub-Feature" which is smaller than a Feature but bigger than a Story. Sub-Features can be used for chunks of work done on a Feature by EACH INDIVIDUAL team, or chunks of work done by a SINGLE team at different times (in different Sprints, or even different Releases).

We also need multiple hierarchical levels between Feature and Business Epic, but we haven't solved this one yet, other than to just call them "Themes" - which we know is not the correct term, as it's easily confused with SAFe Investment Themes. For some big projects (releases) we have as many as 5-8 different hierarchical levels, each one breaking the work down into smaller and smaller chunks. You can think of these Themes as being "Feature Groups", but that's not necessarily the correct term either.

I think it's important to try to use terms that offer clarity rather than ambiguity. So anyone referring to a Story means the smallest unit of work that can be done in a single Sprint (except for the Tasks under the Story), and Sub-Feature means the smallest unit of work on a Feature that can be done by a single team. Likewise, a Feature Group is one hierarchical level above Feature. Above that it gets a little fuzzy, so we usually just call them Themes, and we allow Themes as parents and children of other Themes. We try to restrict the Feature, Sub-Feature, and Story levels to a single level each (Features should not be children of other Features) but we are not yet 100% successful in restricting this.

I know we could use "Tags" to organize some of this, but tags don't give us the organizational work breakdown structure that we need to categorize the work between all of our teams. By definition, tags are ambiguous (many-to-many relationships), but a hierarchy is strictly one-to-many.

The bottom line is that this is still a work-in-progress for us, and we're still struggling with it. But adhering to the SAFe definitions of Theme, Epic, Feature, and Story has us moving in the right direction!


问:
Estimed number of tries
Problem:

The Oscar Committee wants to decide which person should get the best actor award among the given N actors.For that they decided to use a random function random_bit() which returns either 0 or 1 with equal probablity. For the results to be fair,the committee was asked to generate a random number between 1 to N (inclusive) , such that all
actors have equal probability of being chosen (which in this case should always be equal to 1 / N.

First of all Committee wants to know the expected number of times they will need to call random_bit() function to generate a random number between 1 to N.Also, while calling the function, they should follow the optimal strategy (i.e. the strategy that minimizes the expected number of function calls)

This is problem of  past contests at codechef.com and here's the link to it.

This site allows to see other users solution and till now only one solution has been accepted. The solution is in C++ code:

```<code>#include <iostream>
using namespace std
int main() {
    int T;
    cin >> T;
    for(int ii = 0; ii<T; ++ii)
    {
         int N;
         cin >> N;
         double p = 1, ans = 0;
         int x = 1 % N;
         for(int i = 0; i<100000; ++i)
         {
              ans += x * p;
              x = (x * 2) % N;
              p /= 2;
         }
         cout << ans;
    }
    return 0;
}
</code>```

I know how the code runs and what it does, but I can't find the logic behind it. Any help/ clue?

Also it would be nice if someone can post another algorithm.

答:
It looks like the code interprets the string of random bits as a binary fraction, converts this to a N-ary fraction, and looks at the first digit of that N-ary fraction to determine the winner.

The question then becomes: How many random bits do we need until the first digit of the N-ary fraction is stable?

For all examples, I'll use N=3. The 3-ary fraction will start with

a 0 when the fraction is between 0 and 0.333333

a 1 when between 0.333333 and 0.666667

a 2 when between 0.666667 and 1.000000

E.g. 0.11... (binary) = at least 0.75... (decimal) = 0.2.. (3-ary) as it lays between 0.666667 and 1.

In this case, we could stop after 2 bits of input. However, in some cases, we can't decide yet because the number is still too close to a boundary.

E.g. 0.01.... (binary) = between 0.25 and 0.5, so could be 0.0... (3-ary) or 0.1... (3-ary). So we need to look at more bits:

If that next bit is 1: 0.011... (binary) = between 0.375 and 0.5, so will always start with 0.1... (3-ary).

If that next bit is zero: 0.010... (binary) = between 0.25 and 0.375, so still we can't decide whether it is 0.0... (3-ary) or 0.1... (3-ary). So we ask for another bit.

So we always need at least two bits, sometimes a third, in even less cases a fourth, and so on.

Apparently but I'm not sure,  x*p tracks the chance for needing yet-another-bit. ans is the sum of those chances. I can't fully explain this part of the algorithm, maybe somebody else can?

x*p gets smaller over time. At first it is stable, as each iteration p gets halved and x gets doubled. But sometimes x is reduced by the % N part. At some point, the current value of ans will dwarf x*p and the answer is as close as you can get. (However, 100000 iterations seems an awful lot. See below)

I hope this helps to understand what's going on.

Some additional observations about the code:

Once x becomes equal to zero, it will stay zero, and ans will not change anymore. The for loop could break at that point. This only happens when N is a power of 2, so is pretty rare (e.g. for N=3, x cycles through 1, 2, and back to 4=1).

100000 looks like a insanely high upper limit. p is a double and starts at 1.0, so can be halved at most 1024 times before becoming denormalized. 53 halvations later, p will be so small that it will be rounded to zero.

Even stronger: as x and p both start at 1, ans will be set to 1 during the first iteration. At some point, x*p will become less than 2^-53, and when added to ans will be too small to matter and will be ignored due to rounding. As p will be halved each iteration, this will take between 53 and, say, 100 iterations max, depending on N.

Title: Estimed number of tries


问:
what are the things to take in consideration when designing a database that likely will be distributed after some time?
We are small start-up now, we don't have a DBA.

if our project succeed, it will have a lot of data that will likely need to be distributed over several machines.

So we want to make that step easier, so what we should take in consideration now to make it so?

What we can think of now is using uuid instead of autoincrement ids, but even that we don't know how much that will affect performance?

So i using uuid is right choice? and what else we should do?

答:
UUID or GUID are used to be globally unique identifier. as discussed in the Postgres Documentation. there are no methods that are totally appropriate to generate it.However, postgres have some useful generators.

The performance effect on your software depends on the overall database  size and the average query size.in my own opinion there is very small effect when using the Guid over auto increment id which is negligible.

I wish you the best with your start up, and in order to have a solid software solutions company you need to pay attention for software architecture and design pattern to make highly scalable , easy to maintain software.

Good luck.


问:
Is machine language always binary?
I know absolutely nothing in low-level stuff, so this will be a very newbie question. Please excuse my ignorance.

Is machine language - the series of numbers to that tell the physical computer exactly what to do - always binary? I.e. always composed of only zeros one ones? Or could it also be composed of numbers such as 101, 242, 4 etc.?

答:
All numbers stored in most computers are technically stored in a binary form.  At a hardware level everything is represented as a series of high and low voltage signals.  High voltage signals are ones/true values, low voltage signals are zeros/false values.  These are the bits (short for binary digits) mentioned when talking about   32 bit or 64 bit machines.  The number (32,64) in this case refers to how many bits can be addressed out of memory at a time.

So in most modern computers the machine code is just normal values stored in memory, but all of memory is made of bits.

Title: Is machine language always binary?


答:
Everything in a computer (to be precise, in any typical contemporary computer) is binary, at a certain level.  "1s and 0s" is an abstraction, an idea we use to represent a way of distinguishing between two values.  In RAM, that means higher and lower voltage.  On the hard drive, that means distinct magnetic states, and so on.  Using Boolean logic and a base 2 number system, a combination of 1s and 0s can represent any number, and other things (such as letters, images, sounds, etc) can be represented as numbers.

But that's not what people mean when they say "binary code."  That has a specific meaning to programmers:  "Binary" code is code that is not in text form.  Source code exists as text; it looks like a highly formalized system of English and mathematical symbols.  But the CPU doesn't understand English or mathematical notation; it understands numbers.  So the compiler translates source code into a stream of numbers that represent CPU instructions that have the same underlying meaning as the source code.  This is properly known as "machine code," but a lot of people call it "binary".

Title: Is machine language always binary?

Body:
I know absolutely nothing in low-level stuff, so this will be a very newbie question. Please excuse my ignorance.

Is machine language - the series of numbers to that tell the physical computer exactly what to do - always binary? I.e. always composed of only zeros one ones? Or could it also be composed of numbers such as 101, 242, 4 etc.?


问:
Compiler Warnings
Many compilers have warning messages to warn the programmers about potential runtime, logic and performance errors, most times, you quickly fix them, but what about unfixable warnings?

How do you deal with unfixable warnings? Do you re-write a portion of the code, or rewrite it in the "long, hackless way" or disable warnings all together? What should be the best practice?

What if you are editing someone else's code and his code has warnings?

Here is a good example:
jQuery has a lots of JavaScript warnings as a Mozilla-class browser detected, why the jQ developers don't fix them? If you contribute to jQuery, are you going to fix them?

答:
Warnings and errors are messages that the compiler uses to tell the programmer "something you wrote didn't make sense" -- the difference between them is that with a warning, the compiler is willing to make a guess as to the programmer's intentions, whereas with an error, the compiler can't even make a guess.

Compiler errors will get addressed (I'm not going to say fixed), but all too frequently, programmers (even experienced ones) will ignore the warnings. The problem with ignoring the warnings is that sometimes the compiler guesses wrong and if you've got 1000+ warning messages, it's easy to miss a warning message that indicates that the compiler is guessing wrong.

From a sociological standpoint, programs that have many warning messages are Broken Windows.

Title: Compiler Warnings


问:
Multi-Branch Retail System,how to control items quantity for various branches?
Currently I am developing Multi-Branch Retail software. All branches have the same set of items. However, each one has its own stock quantity.

My question is, what is the best practice to apply in branch quantity control for items?

I am currently thinking about the following design:

```
Item Table
========
-Id
-Description

Branch Table
========
-Id
-Description

Branch Quantities Table
========
-Id
-ItemId (FK to Item Table)
-BranchId (Fk to Branch Table)
-Quantity (This contains the quantity for a specific item)

```

Is this a good design? or any suggestions?

答:
This is a good start, possibly suitable as a classroom assignment.  If I had no more information than what is presented in the question this is what I'd use.

As MichaelT noted in the comments, a production system would likely be much more complicated.  Describing such a system is beyond the scope of Programmers.

If this is a work assignment, you'll eventually need a lot more detail from your business analysts to clearly define what you are building.  "Multi-branch retail software" isn't very descriptive - the final solution could be anything.

You might want to do some googling on Enterprise Resource Planning and/or Customer Relationship Management.


答:
Whenever someone uses the phrase "the ones and zeros" in most contexts, especially this context, they are, in my opinion, significantly misrepresenting what's going on, and thus leading to confusion.

The computer doesn't really just read "the ones and zeros" any more than when you read a book, you are reading "the letters". Sure, both are strictly true, but those statements are leaving out a substantial piece of information: the structure of each.

In the case of English, the letters are structured into words, and the words make up sentences, according to a set of rules. The order of letters in words and the order of words in sentences can completely change the meaning.

A similar process is in play with computers and with machine language. The computer looks at the ones and zeros in discrete chunks, in bytes, and in groups of bytes.

Other posters have mentioned various ways that numbers can be encoded as individual bits. There are ints, floating point, text strings, etc, which give structure to the stream of bits and bytes.

Ultimately, the computer is conceptually looking at groups of bits, so it's rarely ever looking at "10101010", its looking at 101, 242, or 4, etc. What those numbers mean, depends on their context in the given 'sentence' they are part of.

Title: Is machine language always binary?


答:
they do not recommend that one use the using namespace ornamespace:function` - if I did not misinterpret it.

You did. The disrecommendation only applies to the using namespace directive (which is commonly referred to as abusing namespace, not entirely humorously). It is strongly preferred that you use the fully qualified name of a function or object, such as std::cout.

Title: What is "using namespace" pollution?

Body:
I was looking at the google coding guide [here] and they do not recommend that one use the using namespace or namespace::function - if I did not misinterpret it.

Does this apply to std as well? cout<< does not work without it. This book, recommends the same. So how do I go about using cout<< without using namespace std; or std::cout<< ?

What is the recommended way? std::cout<<? Most c++ text books teach beginners with using namespace std; are they propagating poor coding practice?


答:
Quoting the link you provide:

You may use a using-declaration anywhere in a .cc file, and in functions, methods or classes in .h files.

// OK in .cc files.

// Must be in a function, method or class in .h files.

using ::foo::bar;

Google style forbids you using importing namespaces in global context, but allows to do so in local ones.

Everywhere where using declaration only affects a limited and clearly visible portion of code it is perfectly acceptable.

When you pollute global context, unrelated code is affected (by implicilty using your header). Nothing happens when you do so in local context.

Title: What is "using namespace" pollution?


问:
Java Singleton fields implementation
I have singleton in Java and I have realized, that I could make its fields static and it would work same way as regular instance fields.

Would there be a performance / optimization difference? If so, what would turned out better? Is there a preferred way to implement singleton fields? (again, I am talking fields, not methods)

答:
Yes, there could be a performance difference. If you were, for example, to write a class for a Logger, and in the entire runtime of the application you never logged anything, then you wouldn't have needed to initialize the logger. If you wrote this class as static, then you would initialize it at the beginning of the program regardless of whether you use it. If you were to create it as a singleton, you could perform lazy initialization, which solves this issue.

In terms of the "Preferred Way," from what I've heard, it is preferred to implement it as a Singleton or similar if your object has state, and static if otherwise. This is to improve testability, because testing a static object with state is a pain in the butt, and it isn't reliable. But that is for a different question.

In your case, with fields, the answer is definitely to go with a singleton unless you have strong reason to do otherwise.

Title: Java Singleton fields implementation


问:
Splitting and hiding headers in a static library
I am writing a static library for C/C++ (personal project). As my headers became rather large, I thought that splitting my headers would be a good idea.

Right now a header looks like this:

MainClass.hpp:

namespace impl: implementation details enclosed in a namespace impl

forward declarations of classes declared below (when needed)

MainClass declaration

MainClass free functions declarations

MainClass specialization declaration

MainClass specialization free function declarations

AuxiliaryClass1 declaration

AuxiliaryClass1 free functions declarations

…

AuxiliaryClassN declaration

AuxiliaryClassN free functions declarations

MainClass definition

MainClass free functions definitions

MainClass specialization definition

MainClass specialization free function definition

AuxiliaryClass1 definition

AuxiliaryClass1 free functions definitions

…

AuxiliaryClassN definition

AuxiliaryClassN free functions definitions

Where:

AuxiliaryClassK is a class logically or structurally related to MainClass (e.g. an iterator for MainClass, a nested class within MainClass, a derived class of MainClass etc.)

ClassX free functions as recommended in How Non-Member Functions Improve Encapsulation and Monoliths "Unstrung"

definitions are in header because they are templates.

This is becoming very crowded and difficult for me to navigate so I thought that splitting across multiple headers would help. However I do not know how to do it right.

Here is how I think the structure could look like:

MainClass.hpp:

forward declarations (when needed)

small classes/structs definitions & declarations

#include the other headers

_Class.hpp:

_Class declaration

_Class free functions declarations

_Class.inl:

_Class definition

_Class free functions definitions

With a _Class for each: MainClass, MainClass specialization, AuxiliaryClassK.

My questions are:

Is it reasonable to want to split a header (all are functionalities of MainClass) (I have headers over 1000 lines long and I foresee even longer ones) or should I leave it as it is?

Is the above split scheme ok? Should I further split a class and the free functions related to that class? Are there other solutions to make the code more maintainable?

How to hide the other headers (not in a sense of obfuscating / making the code unavailable, but avoid exposing the headers the users see (e.g. in a GUI with autocomplete)? They should include and be aware only of MainClass.hpp. Seeing other headers without being clear that they are behind–the–scenes headers will produce unnecessary confusion. One idea is to add a prefix like an _ (underscore) or to put them in a impl folder. (Again, this is not about hiding classes (I do that with a namespace), but to hide the split behind a header they should use).

答:
You can do the following:

split the code into one class per header file.

in the case of templates, the implementation of the class functions can/should reside in the same header file (there is probably no scenario when you will want include the header, but not those definitions).

dependencies (your AuxiliaryClassK) should be #included instead of being defined directly. This makes your headers smaller, promotes code reuse (as you can include them - and only them - elsewhere) and keeps your code cleaner.

split your code into directories. The directory structure is normally a matter of policy; You could use your impl folder idea, or (for example) you could group them like boost does (one directory per functional area with all the implementation files, and one include file for convenience, which you can include in a single line in client code).

use pimpl idiom to minimize compile times.

As a rule, I would not use _Class file names. They are unusual (you increase the WTF/LOC measurement of your code which is never good).


问:
What goes within the Architecture Overview of a Design Specification?
I have designed an management system for a medical practice and I am writing the design specification and I am kind of stumped by what to write for a section. </p>

<p>It asks for me to write about the components of a system but I am perplexed. What exactly are components within a system? Is this generally considered as the features that a system has or does it mean something else altogether? </p>

答:
The architecture of a system deployment is like a map to guide people to understanding what all the other pieces are and how they relate to each other; it's somewhere that people start out with when figuring out what is going on, before they delve into the detail in the other sections.
I'd talk about major components like “database”, “email system”, etc.

Some parts may need subsidiary architectures, others (like the database) don't because they're essentially just brought in from third-party providers.


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
I only turn it of to browse Pr0n (bad neighborhood!) ;-)

I gave up trying to turn it off for regular browsing because things broke too much. And sometimes I do not even know that it was broken until I turned it back on.

ContentLicense: CC BY-SA 2.5


问:
Why must essential mutable derived data have an inverse function?
I was reading the paper Out of the Tar Pit authored by Ben Moseley and Peter Marks when I came across the following section on page 25 regarding essential mutable derived data:

Essential Derived Data — Mutable

As with immutable essential derived data, this can be excluded (and the data re-derived on demand) and hence corresponds to accidental state.

Mutability of derived data makes sense only where the function (logic) used to derive the data has an inverse (otherwise — given its mutability — the data cannot be considered derived on an ongoing basis, and it is effectively input). An inverse often exists where the derived data represents simple restructurings of the input data. In this situation modifications to the data can simply be treated identically to the corresponding modifications to the existing essential state.

I don't understand why essential mutable derived data must have an inverse function. For example consider the following JavaScript code:

inputbox.onchange = function () {
    outputbox.value = md5(inputbox.value);
};
```

Here inputbox.value is input to the system and outputbox.value is the essential mutable derived data. It is derived from inputbox.value using the md5 function. However the md5 function doesn't have an inverse. Nevertheless inputbox.value is still essential, mutable and derived.

So what do the authors actually mean when they say that “mutability of derived data makes sense only where the function (logic) used to derive the data has an inverse (otherwise — given its mutability — the data cannot be considered derived on an ongoing basis, and it is effectively input)”?

Do you have any examples to elucidate their point?

答:
Not being the authors, I can only guess, but I think they're hinting at the difference between mutable data and time-variant data.  If the user can actually modify outputbox.value arbitrarily, then it's truly mutable, but it's also not derived data (it only uses derived data as a default value of sorts).  If, on the other hand, outputbox.value changes on its own in tandem with inputbox.value, but the user can't change it directly, then it's no longer mutable but time-variant instead.

A good example of data that is both truly mutable and truly derived is so-called views.  Imagine we have a complicated and efficient data structure for storing list of a certain type of value, but we want the users to be able to use it as though it's an ordinary mutable array.  We might specify any number of helpful operations on the data, but in the end, the easiest way is to expose an array as derived mutable data:  in other words, we allow the users to convert our data structure to an array, and then when they change the array, we change our data structure in tandem.  This is what is meant by derived mutable data having an "inverse"; if I wanted to be a bit more mathematically precise, I might call it an adjoint.

The difference between mutable data and time-variant data is a fundamental one, and is at the heart of much of the confusion of newcomers to Functional Reactive Programming.  If you are interested in this kind of thing, I would highly recommend looking into Elm, especially this high-level overview of FRP.


答:
A component is an underlying element of a complex system. For example, the braking system of a vehicle has components like brake pads, calipers, hydraulic cylinders and so on.

So likely components of your managements system would be billing, scheduling, or med inventory. It is not so much about features, though the features do relate to the components that provide them. Features would be the abilities of the system, components would be the constructs that enable the features.

Title: What goes within the Architecture Overview of a Design Specification?

Body:
I have designed an management system for a medical practice and I am writing the design specification and I am kind of stumped by what to write for a section. </p>

<p>It asks for me to write about the components of a system but I am perplexed. What exactly are components within a system? Is this generally considered as the features that a system has or does it mean something else altogether? </p>


答:
You have to determine why the db is being distributed.

Replication:  A company may have branch offices each with their own database server that replicates their data to the corporate office which has its own server. Different brands handle this differently and probably recommend guids or the main server uses compound keys like: RegionID & UID.

Fault Tolerance  What to do when your database server crashes? How much time can you afford to be down? You'll need another one to switch over if you want to shorten this time. It may be located in a different datacenter. I don't think you design the database all that differently. There are just other software and ways of doing the switching and getting the production box back in service.

I'm guessing you're concerned with outgrowing a single machine for performance reasons. There are many steps you can take before you get there.

Design your app to make changing the database as easy as possible.

Design the database correctly. You may not have the luxury of
normalization. Throwing indexes at the problem needs some thought as
well.

Query data efficiently. Know you database brand. Utilize tools available (query analyzers). Compare and contrast different methods.

Look for tools to cache the data. I can't remember what they use, but I believe SO sites do this, as well as, basecamp.com. Pretty big sites that as far as I know have managed to use RDBMS, provide lots of info with one big box.

Buy a bigger server or increase the power of an existing one. If the money is there, this could be your first choice, but don' let it be a crutch.

Based on the claims of servers like NUODB.COM, you can just create your app using good old SQL and just keep throwing servers at various failure points (transactions, writing to disk, etc.) on the fly without making any app changes.

If at some point you need more database power, I hope this is a result of generating more revenue. With that, you can hire at least a part time DBA with skills in database tuning.

Title: what are the things to take in consideration when designing a database that likely will be distributed after some time?

Body:
We are small start-up now, we don't have a DBA.

if our project succeed, it will have a lot of data that will likely need to be distributed over several machines.

So we want to make that step easier, so what we should take in consideration now to make it so?

What we can think of now is using uuid instead of autoincrement ids, but even that we don't know how much that will affect performance?

So i using uuid is right choice? and what else we should do?


答:
Since all branches identify items the same way by codes and name, a single item table that doesn't differentiate for branches is fine.

You have a many-to-many type relationship here with items and branches, so there are no limits there as far as combinations. It would be easy to put a unique constraint on itemid & branchid since you have a surrogate key instead of a natural key.

You're fairly normalized here. There's no need to update data in more than one place unless your keys change. No reason why that should happen. You can throw some cascading updates and deletes if you see fit.

The quantity field is a questionable. How does that get updated? Does the system "do the math" for purchases and sales? Is there someone in the store who does an inventory count and updates this number? You may need some function to recalculate, make adjustments if it gets out of whack. It helps with performance to have this number pre-calculated, but there are draw-backs.

If this is the only data in the system for quantity, the real problem is you can only tell me the quantify of the item since it was last updated. How many did I have at the end of last month? Have there been items added to the inventory that have never been sold?

Discuss this with the project owner or someone who knows how to do this on paper to see what it needs to do.

Title: Multi-Branch Retail System,how to control items quantity for various branches?

Body:
Currently I am developing Multi-Branch Retail software. All branches have the same set of items. However, each one has its own stock quantity.

My question is, what is the best practice to apply in branch quantity control for items?

I am currently thinking about the following design:

```
Item Table
========
-Id
-Description

Branch Table
========
-Id
-Description

Branch Quantities Table
========
-Id
-ItemId (FK to Item Table)
-BranchId (Fk to Branch Table)
-Quantity (This contains the quantity for a specific item)

```

Is this a good design? or any suggestions?


问:
How much time do you spend on design before coding?
In my experience, it is useful to spend a little while sketching plans for a project before getting into code. Such planning usually includes choosing frameworks/tools, writing requirements and expectations, and doing mockups.

I usually only do this for serious projects though, not so much for one-off or short-lived attempts.

I'd be interested to hear how much time you spend on planning/designing projects before starting to do the coding. Do you do it for every project, or just the "serious" ones?

答:
As Much As It Takes

to understand the project, the model, the risks, and the unknowns

especially the risks and unknowns


问:
How to name filename parameter to make clear it should contain full path?
I'm seeking vital naming of string filename parameter in parameter list used in various methods where filename with full path is expected. In many cases also UNC path can be actually supplied as full path because many libraries handle it natively.

I usually call the parameter just filename, but it can be misleading in two ways:

Beginners tend to think it is only name of file – without path.

If there is a need of splitting the value into path and filename, term filename sticks better with filename part without path which appeared after split. Anyway, it is not easy to give that second part better name than filename. Alternative of splitting filename to path and filenameOnly looks weird to me.

I think it might be better to use clearly distinguishable term for filename with path than borrowing filename which already has stronger meaning for something else.

I was thinking about term absoluteFilePath or fullyQualifiedFilename to stand as argument names. Maybe they are good and I need only some encouragement to start using them, but I would like to understand your best practices.

EDIT: I would still like to stick with official VB.NET naming and capitalization conventions, so the only thing I need help sharpening is clear self-documenting wording of the term. (Not whether I should use Hungarian notation or not – I cannot.)

答:
It sounds like you'd be safer defining a code contract.

You can say a precondition of this method is that the path supplied is an absolute path.

You can make this clearer by naming the input parameter String absolutePathToFile.

And finally, you can make your method fail early if the preconditions aren't met.  Do this by checking if the absolutePathToFile is indeed an absolute path.  If not, throw an argument exception.

So, instead of simply picking a parameter name and hoping the next developers a) pay attention to it, and b) understand it the same way you do (both of which are unlikely), you do the following:

Code Contract: Explicitly declare your method preconditions.  You can put this in your documentation, or as inline method documentation (if your language/ide supports it)

Self Documenting Code: Choose a parameter name that describes what you want as clearly as possible (not always easy)

Defensive Programming: Check your method parameters to see if they're valid.  If not, fail hard and fail early.


问:
DATABASE design for storing specifications?
I am creating , a site like gsmarena , can any one help me with database design to store mobile specifications like here "http://www.gsmarena.com/asus_padfone_infinity_lite-6120.php"
as user can add more custom specification ,</p>

答:
You can have Phone table where you store phone.
Create two another attributes and sub-attribute tables.

Attribute Table will look like below:

AttributeId (PK, auto generated int is recommended)

PhoneId (FK to Phone tablet, not null)

AttributeKey (String, not null - text like "DISPLAY" "DATA" etc.)

AttributeValue (string, null)

SubAttribute Table will look like below:

SubAttributeId (PK, auto generated int is recommended)

AttributeId (FK to Attribute tablet, not null)

SubAttributeKey (String, not null - text like "Dimensions" "Size" etc.)

SubAttributeValue (string, null)


答:
If your concern is storage, meaning that you fear that a single (database) machine will not be able to keep all your data, you better design in a way that will enable you to scale out by sharding your data.

Sharding means that each database machine will hold only part of your data, each atomic part is called a 'shard', with database nodes holding one or more shards, each shard has one or more replicas.

The idea behind sharding is that, given that you know on which shard the relevant data is, you query only a server which might have the data. Writing data is also done only in the relevant nodes, which minimizes database locks. Some NoSQL databases support this out of the box (like elastic search).

Not all data can be sharded, since it breaks if you want to query the whole dataset, or if you can't figure out reliably and idempotently on which shard your data should be, but if your data is isolated (for example - you have many users, but each user is interested only in his own data) - it could be done quite easily.


答:
When they say immutable derived data, think of the derived value as always being calculated by a function, so the output is never changed except as a result of the input changing first.  Put another way, if you have a GUI with an input box and a derived output box, that output box would be read only.  The function is immutable, even if its input isn't.

For your md5 example, since it isn't invertible, you would never change the md5 value in the GUI and derive new input data from that.  You have to change the input data.  If you don't want to store that input (for example if it's a password), then the md5 data must become an input after it is calculated.

For an example of mutable derived data, consider a color picker that shows both rgb and hsv representations of a color, but stores it as rgb.  The hsv can be considered derived data, but it doesn't need to be immutable because it has an inverse.  If you change the hsv value directly, you can get an rgb value from that to be your input.

Title: Why must essential mutable derived data have an inverse function?

Body:
I was reading the paper Out of the Tar Pit authored by Ben Moseley and Peter Marks when I came across the following section on page 25 regarding essential mutable derived data:

Essential Derived Data — Mutable

As with immutable essential derived data, this can be excluded (and the data re-derived on demand) and hence corresponds to accidental state.

Mutability of derived data makes sense only where the function (logic) used to derive the data has an inverse (otherwise — given its mutability — the data cannot be considered derived on an ongoing basis, and it is effectively input). An inverse often exists where the derived data represents simple restructurings of the input data. In this situation modifications to the data can simply be treated identically to the corresponding modifications to the existing essential state.

I don't understand why essential mutable derived data must have an inverse function. For example consider the following JavaScript code:

inputbox.onchange = function () {
    outputbox.value = md5(inputbox.value);
};
```

Here inputbox.value is input to the system and outputbox.value is the essential mutable derived data. It is derived from inputbox.value using the md5 function. However the md5 function doesn't have an inverse. Nevertheless inputbox.value is still essential, mutable and derived.

So what do the authors actually mean when they say that “mutability of derived data makes sense only where the function (logic) used to derive the data has an inverse (otherwise — given its mutability — the data cannot be considered derived on an ongoing basis, and it is effectively input)”?

Do you have any examples to elucidate their point?


答:
Let's have a look at an actual machine instruction.  Suppose we have an ARM CPU and we want to add 143 to the value in register 2, placing the result in register 1.  In ARM assembly language that's written

```<code>ADD  R1, R2, #143
</code>```

This assembly instruction can be encoded as a single machine instruction.  The specification of how that's done is on physical page 156 of the ARM ARM, the amusingly-named Acorn RISC Machine Architecture Reference Manual.  It's also necessary to look at the definition of "shifter operand", which begins on physical page 444.

```<code> 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
|    Cond   | 0  0  I  0  1  0  0  S|     Rn    |     Rd    |          shifter operand          |
</code>```

As you seem to already understand, machine instructions are numbers, and on the ARM, they are numbers of a fixed size: 32 bits, divided into several fields.  To encode the above ADD, we fill in the fields like this:

```<code>| cond | fmt | I | opcode | S | Rn | Rd | rot | imm |
|    E |  00 | 1 |  0100  | 0 | 2  | 1  | 0   | 143 |
</code>```

(The "shifter operand" got divided into "rot" and "imm" because I set I=1.)  Now, to make that into a single 32-bit number, we have to expand it out to binary, because many of the fields are not tidy numbers of bits long:

```<code> 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
  1  1  1  0  0  0  1  0  1  0  0  0  0  0  1  0  0  0  0  1  0  0  0  0  1  0  0  0  1  1  1  1
</code>```

To humans that is a big blur; hexadecimal is easier for us to understand:

```<code>1110  0010  1000  0010  0001  0000  1000  1111
   E     2     8     2     1     0     8     F
</code>```

And so usually, in communication with other humans, we say that the "machine instruction" corresponding to ADD R1, R2, #143 is the hexadecimal number E282 108F.  We could equally say that it is the decimal number 3,800,174,735, but that obscures the pattern of fields more than hex does.  (Someone with a lot of practice debugging on the bare metal on ARM would be able to pick condition code E, source and destination registers 2 and 1, immediate operand 8F = 143 out of E282 108F with relative ease.)

All of the above representations encode the same machine instruction!  I have only changed how I wrote it down.

In terms of "ones and zeroes", if you load a program containing this instruction into RAM on a real computer, somewhere in memory the bit pattern 1110 0010 1000 0010 0001 0000 1000 1111 will appear (possibly backwards, because of endianness).  But it is equally valid to say that somewhere in memory the hexadecimal number E282 108F, or the decoded instruction ADD R1, R2, #143 appears.  Bit patterns in RAM have no meaning in themselves; meaning comes from context.  Conversely, that bit pattern / hexadecimal number isn't necessarily an instruction at all!  It would also appear in a program that made use of the unsigned 32-bit integer 3,800,174,735, or the single-precision IEEE floating point number -1.199634951 × 1021 as data.

Title: Is machine language always binary?

Body:
Let's have a look at an actual machine instruction.  Suppose we have an ARM CPU and we want to add 143 to the value in register 2, placing the result in register 1.  In ARM assembly language that's written

ADD  R1, R2, #143

This assembly instruction can be encoded as a single machine instruction.  The specification of how that's done is on physical page 156 of the ARM ARM, the amusingly-named Acorn RISC Machine Architecture Reference Manual.  It's also necessary to look at the definition of "shifter operand", which begins on physical page 444.

 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
|    Cond   | 0  0  I  0  1  0  0  S|     Rn    |     Rd    |          shifter operand          |

As you seem to already understand, machine instructions are numbers, and on the ARM, they are numbers of a fixed size: 32 bits, divided into several fields.  To encode the above ADD, we fill in the fields like this:

| cond | fmt | I | opcode | S | Rn | Rd | rot | imm |
|    E |  00 | 1 |  0100  | 0 | 2  | 1  | 0   | 143 |

(The "shifter operand" got divided into "rot" and "imm" because I set I=1.)  Now, to make that into a single 32-bit number, we have to expand it out to binary, because many of the fields are not tidy numbers of bits long:

 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
  1  1  1  0  0  0  1  0  1  0  0  0  0  0  1  0  0  0  0  1  0  0  0  0  1  0  0  0  1  1  1  1

To humans that is a big blur; hexadecimal is easier for us to understand:

1110  0010  1000  0010  0001  0000  1000  1111
   E     2     8     2     1     0     8     F

And so usually, in communication with other humans, we say that the "machine instruction" corresponding to ADD R1, R2, #143 is the hexadecimal number E282 108F.  We could equally say that it is the decimal number 3,800,174,735, but that obscures the pattern of fields more than hex does.  (Someone with a lot of practice debugging on the bare metal on ARM would be able to pick condition code E, source and destination registers 2 and 1, immediate operand 8F = 143 out of E282 108F with relative ease.)

All of the above representations encode the same machine instruction!  I have only changed how I wrote it down.

In terms of "ones and zeroes", if you load a program containing this instruction into RAM on a real computer, somewhere in memory the bit pattern 1110 0010 1000 0010 0001 0000 1000 1111 will appear (possibly backwards, because of endianness).  But it is equally valid to say that somewhere in memory the hexadecimal number E282 108F, or the decoded instruction ADD R1, R2, #143 appears.  Bit patterns in RAM have no meaning in themselves; meaning comes from context.  Conversely, that bit pattern / hexadecimal number isn't necessarily an instruction at all!  It would also appear in a program that made use of the unsigned 32-bit integer 3,800,174,735, or the single-precision IEEE floating point number -1.199634951 × 1021 as data.


答:
I always have JavaScript on. I also always have my minimum restore kit, at my side.

We need line veto disabling of JavaScript, so I could say "no alerts, no redirects, no websockets."  The functionality is in WebKit at least, judging from the console and various inspectors.

But yes, always JavaScript on.  Mainly because very soon people will use web sockets to wreak all sorts of evil, exactly like what happened when Flash got the "cool" VM.  Then I'll turn off JavaScript. If they let me of course.

I want to enjoy as much of the good as I can. So I have some pleasant memories of this era.  I want to be impressed, I want to giggle at the JavaScript  follies, because I really miss what we had back in 2007, free sweet information flow like spring water, open sources everywhere.

I won't turn it off until I have to.

Title: How important is graceful degradation of JavaScript?

Body:
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?


问:
Kerberos web authentication
I'v developed an internal singe-page web-app (unix, apache & postgresql) protected by a simple login page. Currently, the users have their own login role with a password.

This is starting to get cumbersome for a couple reasons:

Users have multiple passwords (for my web-app and Active Directory, the company-network is windows).

Storing user information in two different places (would like to centralize).

I've been looking into Kerberos to the point, I've set-up a KDC and am able connect to the database through GSSAPI authentication (command-line only).

From what I understand I should be able to use my own KDC that will integrate with Active Directory.

My problem I'm working through at the moment is web-app authentication via kerberos:

If a user is on the web - how can I obtain/verify kerberos credentials? Can I store the credentials in a cookie? Do I have
        to resort using OAuth,Webauth, or something similar?

To clarify, What I want to do is:

If a user doesn't have valid credentials, give them the login page to obtain credentials (via kinit, but how through the browser?) and return valid credentials.
         (how can I store credentials in browser, can I create a cookie from the Kerberos credentials?).

I've googled, and read a fair-few pdf's and web-resources, but unfortunately none of them were able to dumb it down enough for me to get a solid grasp of how to accomplish kerberos web authentication.

If you didn't notice, I'm confused on how to piece everything together and would appreciate a conceptual over-view of how everything fits together.

答:
The usual way you would go about this, is just whenever processing authentication requests in your web application, you would authenticate against Kerberos to check for valid login/password.

I do not think you will find another way to check for current user's authentication details in e.g. Windows session, as that wouldn't be secure by design. If you would store the user/password combination, you would have to store it in accessible form, and that would also make it open for hijacking.

Title: Kerberos web authentication


答:
If the user does not have a valid id in their cookie, they are redirected to a login page.

They submit credentials in a form / ajax post to the server which checks they are valid via any means (Kerberos, database, etc.)

If they are valid, set their username in their session (which should have a unique id) and send them back the session id in a cookie.

As far as the contents of the cookie, you NEVER want to store the credentials in it or any other sensitive information. You only need to store a unique and random identifier. When the user makes another request to your page you use this identifier to access their session data. It can look something like this

auth-id: abc123

If they are authenticated, their session data should contain the username they authenticated under. You also don't need to store the kerberos credentials server-side either, you only need them to check if they are valid, then store the username in the session.

Again it's important to understand that HOW the authentication is done on the server is irrelevant to how you maintain their session / authenticated state.

Title: Kerberos web authentication

Body:
I'v developed an internal singe-page web-app (unix, apache & postgresql) protected by a simple login page. Currently, the users have their own login role with a password.

This is starting to get cumbersome for a couple reasons:

Users have multiple passwords (for my web-app and Active Directory, the company-network is windows).

Storing user information in two different places (would like to centralize).

I've been looking into Kerberos to the point, I've set-up a KDC and am able connect to the database through GSSAPI authentication (command-line only).

From what I understand I should be able to use my own KDC that will integrate with Active Directory.

My problem I'm working through at the moment is web-app authentication via kerberos:

If a user is on the web - how can I obtain/verify kerberos credentials? Can I store the credentials in a cookie? Do I have
        to resort using OAuth,Webauth, or something similar?

To clarify, What I want to do is:

If a user doesn't have valid credentials, give them the login page to obtain credentials (via kinit, but how through the browser?) and return valid credentials.
         (how can I store credentials in browser, can I create a cookie from the Kerberos credentials?).

I've googled, and read a fair-few pdf's and web-resources, but unfortunately none of them were able to dumb it down enough for me to get a solid grasp of how to accomplish kerberos web authentication.

If you didn't notice, I'm confused on how to piece everything together and would appreciate a conceptual over-view of how everything fits together.


答:
We use Scrum at my job, so I would say at a minimum you have to give enough design thought to break down your user stories into tasks.  You need a pretty good idea of what's needed to write tasks.  Remember that the key is to write them so someone else could theoretically do the implementation.  I usually fold the little details (e.g., which algorithm to use) into the time estimate for my tasks.  If I need to do some no-kidding research, I'll make that its own task.

When dealing with an Epic (a project that lasts multiple sprints), I'm a lot freer with what I call "design."  Design in that case usually involves a rough sketch of the basic architecture and a handful of user stories that I expect to do.  It's not cowboy coding, but it's not a rigorous design process (think traditional waterfall model) either.  Something will come up (a requirements change or an a-ha moment) that changes the game somewhere down the road.  I try not to invest too much time in something that will likely get thrown out or heavily modified.

Title: How much time do you spend on design before coding?

Body:
In my experience, it is useful to spend a little while sketching plans for a project before getting into code. Such planning usually includes choosing frameworks/tools, writing requirements and expectations, and doing mockups.

I usually only do this for serious projects though, not so much for one-off or short-lived attempts.

I'd be interested to hear how much time you spend on planning/designing projects before starting to do the coding. Do you do it for every project, or just the "serious" ones?


问:
what is the javascript internal data structure?
Consider a basic js object:

```<code>var obj={x:1,y:'2'};
</code>```

Is this stored internally as a hashtable or does js use a different mechanism for key value pairs? If they are hash tables does anyone know how they handle collisions?

答:
"javascript internal" doesn't really mean anything, as far as I know, such thing isn't specified for Javascript.

For some Javascript engine or interpreter, the internal representation can be any number of things, whatever works for any given situation.

For long-lived objects of indeterminate lifetime, it's most likely a hash table, but also a list (or whatever) of property names in natural ("alphabetical") sorted order probably exists at least temporarily.

Arrays, as much as they exist in Javascript, probably also have a custom, optimized internal data structure, which may support faster indexed access than going through creating a hash table hash.

And then a JS engine doing JIT might for example see that the object is never used for anything, in which case that object can be nothing internally, the instance is just optimized away and never actually created.


问:
Responding to app feature requests I'm not going to implement
I'm a new app developer and after like 20 downloads of my app (free and ad-free) I already got two feature requests, and I'm not going to implement either.

Should I respond to these feature requests and if so, how? I'd prefer not responding at all because I'd rather spend the time to work on my app, but being a new developer, a couple of poor ratings in the app store could hurt my app.

答:
I think that you can only lose by choosing not to communicate.

If you don't plan to implement the feature now, at least suggest users that it is not in the current plan to implement, but might be considered in the future. This would not let users think that it's a feature they can expect soon and will send a message that you are not planning on it either. At the end, you might change your mind in the future (e.g. if these requests will occur more often, maybe it's something users would pay for?).

If you are sure that you are not implementing this feature ever because let's say that you want to go completely different direction with your app, then just ask user to consider trying to use the app your-way.

Communication with your users is important process if you want to build a user-base for you application and a short reply will not take you a lot of the time to write.


问:
Advantages and disadvantages of making one DB per customer
I'm starting to design a web application, and I'm evaluating some decisions regarding the general structure of it. My use case is as follows:

I plan to have multiple customers on a single server. Initially there won't be many customers, probably two to start (but the system should be ready for more, of course). As I'm working as a single developer, I want to save cost in servers, SSL certificates and so on

Each customer can have different users for their own data, with different permissions

A customer should not be able to access data from other customer, unless the other explicitly allows him (i.e. creating a user for him)

I was evaluating how to handle this multiple customer scenario, and right now I'm planning to separate each customer in its own DB (and deciding which DB to connect with the customer URL, for example). Managing everything in the same DB would be, I think, error-prone (an error in the app would let a customer view data it shouldn't) and complicate my design (I would have to store the customer with all data).

So I would like to know what advantages and disadvantages come with this kind of design. Is there a performance issue? Maintenance problems? Security problems?

If that matters, my platform of choice is Python + Flask + SQLAlchemy (though I'm evaluating Django too)

答:
There are potential problems with storing customers together in the same database--you hit on two of them. The third that comes to mind deals with data statistics. If one customer uses the service lightly, and another heavily, it can throw off the statistics for everyone, making all the queries perform badly. I've seen that happen before (but only when the disparity is massive; something like five orders of magnitude difference).

One the other hand, separating everyone into different databases is certainly an exercise in code duplication. Everything, including stuff that isn't necessarily customer-specific, will have to reside in each database. Trying to pick the correct database could be very tricky, especially where users have access to multiple customers.

My experience is that adding a customer field to every table is no big deal, and the wrong data is almost never returned if it becomes a standard to always filter on the customer. I would stick with same DB--you'll likely have less headaches than if you're dealing with multiple out-of-sync databases.


答:
Ideally, you should use such requests as an opportunity to help you and users better understand the application.

If you think of it, the very reasons why you prefer to ignore these requests are quite important information and you'd rather have them stored and documented than buried and forgotten deep down in your mind.

If a request is ignored because you don't have time to implement it, but generally looks like good idea, you better keep a knowledge of that somewhere. Later on, when you have time, you may get back to it and reconsider.

Or, if a request is ignored because it is really bad idea and you can write down an explanation for why it's so, this would also be useful knowledge to store somewhere. Doing so will make it easier to address similar requests from other users, or even help yourself if you eventually forget why you thought it's a bad idea.

Keep in mind that spelling out and writing down reasons why some features may do more harm than good will help yourself better understand your application, it's intended use, limitations and strong points.

As an example, take a look at the very Stack Exchange network. Feature requests that are decided not to implement here aren't buried down. Quite the opposite, these are made public, thoroughly analysed and kept for further references conveniently tagged status-declined at Stack Exchange meta site.

Title: Responding to app feature requests I'm not going to implement

Body:
I'm a new app developer and after like 20 downloads of my app (free and ad-free) I already got two feature requests, and I'm not going to implement either.

Should I respond to these feature requests and if so, how? I'd prefer not responding at all because I'd rather spend the time to work on my app, but being a new developer, a couple of poor ratings in the app store could hurt my app.


答: The ECMAScript specification does not prescribe any particular implementation strategy. And why would it? Having different engines compete for performance using different implementation strategies is a Good Thing™.</p>

Title: what is the javascript internal data structure?

Body:
Consider a basic js object:

```<code>var obj={x:1,y:'2'};
</code>```

Is this stored internally as a hashtable or does js use a different mechanism for key value pairs? If they are hash tables does anyone know how they handle collisions?


答: Put together a stock "thank you for your interest" letter that covers the possibilities of a) features you will NEVER implement even if I show up on your doorstep with a bag of gold, b) features you don't PLAN to implement but maybe, and c) features you'd like to implement but can't right now. Send that. Because you ALMOST never know when you might find yourself moving something from a) to b), or from b) to c). </p>


答:
Javascript is disabled by default for those of us on a Windows Server box.  Our IT policy blocks so many sites, the only way to read some content is to surf on a server, where JS is disabled by default.

Although it isn't my preferred configuration, it's what I have to do sometimes.


问:
Browser security and payments
I've been finding a lot of blog posts claiming JS encryption is unsafe, here's a couple of detailed ones:

http://www.matasano.com/articles/javascript-cryptography/

http://rdist.root.org/2010/11/29/final-post-on-javascript-crypto/

My question is, if browsers truly are inherently unsafe then, by extension, entering any PCI-related info in the browser is unsafe - regardless of JS encryption, HTTPS, or any other security measures? Which would imply that malicious parties should be taking major advantage of this fact, right? Could someone provide specific examples where browser vulnerabilities were leveraged to steal massive amounts of PCI-info/PII (by "massive" I mean comparable to the amount that could be obtained by hacking into the hosting servers/DB)?

Also, despite all those posts describing security flaws there's a proliferation of payment services and JS crypto libraries - does that indicate that most companies/communities:

are unaware of browser vulnerabilities?

are simply disregarding the underlying issues and jumping on the bandwagon to make some dough?

have weighted the (possibly low) likelihood of someone going through the trouble of exploiting browsers and decided it's still worth to capture payments through browsers?

EDIT

Using SSL/TLS addresses some of the issues, but definitely not all. Here are a few notable issues that fall outside of the area that SSL/TLS can solve (quoted directly from the Matasano blog post):

The prevalence of content-controlled code.

We mean that pages are built from multiple requests, some of them conveying Javascript directly, and some of them influencing Javascript using DOM tag attributes (such as "onmouseover").

The malleability of the Javascript runtime.

There is no reliable way for any piece of Javascript code to verify its execution environment. Javascript crypto code can't ask, "am I really dealing with a random number generator, or with some facsimile of one provided by an attacker?" And it certainly can't assert "nobody is allowed to do anything with this crypto secret except in ways that I, the author, approve of". These are two properties that often are provided in other environments that use crypto, and they're impossible in Javascript.

What else is the Javascript runtime lacking for crypto implementors?

Two big ones are secure erase (Javascript is usually garbage collected, so secrets are lurking in memory potentially long after they're needed) and functions with known timing characteristics. Real crypto libraries are carefully studied and vetted to eliminate data-dependant code paths --- ensuring that one similarly-sized bucket of bits takes as long to process as any other --- because without that vetting, attackers can extract crypto keys from timing.

Again, my main point is that, technically, once a credit card number (or some other important piece of info) is entered into a text field of a page there's a chance that it's been compromised - and at that, compromised more easily then if it were entered in the native application.

答:
EDIT: I felt compelled to address the transport side of the question understanding that the OP was not advocating using JavaScript encryption in lieu of SSL/TLS. But I've certainly seen that and a number of other unsafe variations done multiple times.  However; with respect directly to the issue of how safe it is to input data into a text field in a web browser--that does not require JavaScript. If you post a form to a server then JavaScript isn't part of the equation at all. Yet there is a lot of JavaScript browser-based validation code floating around out there, and that sort of thing certainly could leave sensitive data in memory on the client, depending on the implementation. Still, doesn't the end user bear at least some responsibility for trying to ensure that their computer is free of malware? Because the only way that sort of thing really causes a problem is if the client's machine has been hijacked by some rogue code that can read its memory.

ORIGINAL: Show me the standard reference implementation of JavaScript-based cryptography in a browser.

There isn't one. As far as I know, the only cryptographically relevant primitive in JavaScript is a pseudo-random number generator.  The rest has to be implemented in JavaScript itself.

Cryptography is not trivial to get right. Taking shortcuts is extremely ill-advised. Even taking the shortcut of doing user authentication over HTTPS then switching to HTTP is extremely ill-advised, because it opens a system wide to man-in-the-middle attacks.

Using half-baked roll-your-own cryptography is a really good way to compromise the security of your users.

To do even a barely adequate job of encrypting a password sent over HTTP (rather than HTTPS) from a client to a server, to protect it from prying eyes would require Asymmetric encryption keys (RSA style), with the private key kept aggressively safe on the server, and the public key disseminated to users.

But there are some serious problems with a solution that simple, including:

The encryption could only go one way, from client to server. ANYTHING the server encrypted with the private key could be decrypted by anybody with access to the public key.

By definition, that's everybody.

Asymmetric encryption is really expensive compared to symmetric encryption, so even without the one-way-encryption problem, asymmetric encryption is a terrible way to carry on a long conversation. That's one of the chief reasons why SSL/TLS uses asymmetric encryption to exchange a shared secret key for symmetric encryption, so that server and client can use an order-of-magnitude faster symmetric algorithm for ongoing secure communication.

There is no provision for forward secrecy. A third party could intercept a communication session, later obtain the private key and have all they need to decrypt both sides of the communication (we've already established that they have all they need to decrypt anything sent from the server, by design).

So, let's be honest, to actually do an adequate job of even exchanging a password would require:

Asymmetric encryption keys (RSA style)

A session-initiation handshake algorithm for securely transmitting an ephemeral shared secret symmetric encryption key.

To be actually secure rather than just fooling yourself into thinking you're secure, a forward secrecy or perfect forward secrecy mechanism, so that the asymmetric keys used to exchange the ephemeral symmetric key are themselves ephemeral and discarded sometime soon after use, so that the session cannot be recorded then broken later merely by obtaining the private key from the server.

If you add all of that up, you more or less have SSL/TSL.

So why even consider re-inventing the wheel with a custom solution that will take a lot of time, be very difficult to get right, take even more time and energy to keep up-to-date, with full-on security bugs that you really just don't have the time, resources or know-how to detect and fix?

Even if you come up with a reason to have the JavaScript client encrypt data for some kind of local persistence, you have a key-management issue. The very strongest encryption is only as strong as your key management. You could manage that key on the server, but then you still need a secure mechanism for transmitting it to the client.

Again, it looks like SSL/TLS is the go-to solution.

The current state of cryptography basically boils down to two types: Asymmetric and Symmetric.

Asymmetric is the RSA-style public/private key cryptography. Anything signed or encrypted with the private key can be validated or decrypted with the public key, and vice-versa.

Symmetric is the standard "shared secret" pattern, used by AES and other symmetric algorithms.

Stir the various message digest or "hash" algorithms into the mix, and you're able to generate smallish fixed-length "thumbprints" of large data sets for integrity checks (digital signatures), password hashes, and more.

To securely transmit anything between two endpoints using symmetric encryption, you have to figure out how to get a shared secret to both ends without anybody in the middle intercepting the secret and using it to masquerade their way into your system or covertly tapping communications.

To securely transmit anything between two endpoints using asymmetric encryption requires a multiple-round-trip handshake, for each transfer, with challenges and responses and hashing and signature verification and so on.

On top of all the rest, having SSL/TLS certificates signed by a trusted Certificate Authority provides a measure of security via the ability for the client to confirm that the certificate being presented does indeed come from a valid source, hasn't been tampered with, is not expired, and has not been revoked for any reason.

Title: Browser security and payments


问:
REST object with resources
I am designing a HTTP-based REST API.
Let's say I have an entity called Entity that has a bunch of properties. Some of its properties are files. Let's say Entity has following properties:

```<code>name: string
description: string
photos: array of photos
videos: array of videos
</code>```

API is designed to be used from mobile devices and should work well under conditions of slow or unstable connection. The thing is the object should be not considered as complete until I upload all the resources the client have.

What it the best way to construct a new object?

For now I come up with the following solution. Add readiness flag isReady, first post basic object data within single json:

```<code>POST /entities/ {name: "somename", description: "description", isReady: false}
obtain id of newly created `entityId`
</code>```

Then upload resources one by one:

```<code>POST /entities/{entityId}/photos/ <photo data>
POST /entities/{entityId}/videos/ <video data>
</code>```

And then update object's readiness flag

```<code>PUT /entities/{entityId}/ {isReady: true}
</code>```

The second solution that comes to mind is to create separate endpoints for photos, videos. Then I'll be able to first post photos and videos and then create Entity with references to resources.

```<code>POST /photos <photo data>
obtain ids
POST /videos <video data>
obtain ids

POST /entities/ {name: "somename", description: "description", photos: ids[], videos:ids[]}
</code>```

The question with the second solution: is it okay for resource to be referenced by multiple URIs?

```<code>/entities/photos/{photoId}
/photos/{photoId}
</code>```

Is the first solution correct? Wouldn't the second one be overcomplicated?

Thanks in advance

答:
I have successfully used both patterns; and both will work fine. I wouldn't say that either is more complicated than the other. One thing that you might also consider, for the first pattern, is to include in your entity description a "promise" to fulfill.  For example, you might have a JSON object that enumerates the data you'll be providing:

```<code>photos_promise: {
    expect: 5,
    checksums: [..., ..., ..., ..., ...]
}
</code>```

Then, when you upload the five photos, you can do an additional validation to ensure that the photo file you've received matches one of the provided checksums.  When you've received five photos and they all match, you can have the service automatically "enable" your Entity resource.  You can take it a step further and have "partial states" for these objects, such that when you get this entity after having posted three photos, you'd get:

```<code>photos: [{url: ..., ...}, ...],
photos_promise: {
    received: 3,
    expect: 2,
    checksums: [..., ...]
}
</code>```

This obviously does add complication, but it's also rather elegant.

Title: REST object with resources

Body:
I have successfully used both patterns; and both will work fine. I wouldn't say that either is more complicated than the other. One thing that you might also consider, for the first pattern, is to include in your entity description a "promise" to fulfill.  For example, you might have a JSON object that enumerates the data you'll be providing:

photos_promise: {
    expect: 5,
    checksums: [..., ..., ..., ..., ...]
}

Then, when you upload the five photos, you can do an additional validation to ensure that the photo file you've received matches one of the provided checksums.  When you've received five photos and they all match, you can have the service automatically "enable" your Entity resource.  You can take it a step further and have "partial states" for these objects, such that when you get this entity after having posted three photos, you'd get:

photos: [{url: ..., ...}, ...],
photos_promise: {
    received: 3,
    expect: 2,
    checksums: [..., ...]
}

This obviously does add complication, but it's also rather elegant.


问:
How much time a week do you spend on extracurricular programming?
Background: I'm a microsoft DBA/IT type person by day, an iOS and Mac developer by night. I have one app in the App Store and another one in the works. I try to spend as much time as possible working on my two apps, but with a new daughter and other (non computer) hobbies, I find it hard to spend more than a few hours every week programming.

I'm wondering how this compares to other developers. I see a lot of apps out there written by single developers who don't do iOS development as their main job. Are they spending 4 hours a night working on their projects, or do they just plug away for a year or two before releasing anything?

答:
As much as I can.

Easier said than done, coming from a full time university student. Schoolwork must take priority, of course, but I try to block off a couple of hours every few evenings, and on weekends, to work on one of my numerous projects.

Classes just finished, so I have some more time on my hands, and plan to put it to good use. I'll have to remember to squeeze in some study time for finals!