答:
That's generally correct, not just for Javascript but for any language. Javascript just happens to be the de facto language for doing such. You could use most any language for manipulation of page elements. This is what CGI is. Javascript just happens to "live" in the browser rather than on a server. This makes things like AJAX possible, which in turn makes the modern web as we know it possible.

The reason that Javascript appears different on the "front end" versus on the "back end" is that Javascript on the front end is tied to the DOM while Javascript on the backend doesn't need to be.

Title: Understanding Front End vs Back End Javascript?

Body:
I've been noticing lately, as I've played around with javascript, HTML5, and node.js for the first times that javascript seems to be a language that is used very differently (and with different syntax) depending on where it is used at.  My observation with javascript is this:

-Front end javascript finds the JS embedded in HTML5 pages, where it is used to build dynamic webpages and react to events that occur on the page.

-Back end JS is used as a solo language with node.js and its associated packages to handle web page requests, data transfers, and general server tasks.

Have I accurately summarized front end versus back end JS?


问:
Permutations of an array
I have an array of integers of length 20, filled with fourteen 0s, two 1s, two 2s and two 3s. It is like this:
[0,0,0,3,0,2,0,0,3,0,0,0,1,0,2,0,0,1,0,0].

I need a way to list all of its 20!/(14! 2! 2! 2!) permutations, without repetitions.  (Note that in the list there are duplicate elements!)

I'm just looking for the right idea, it isn't necessary that you write the code.  But, if you prefer writing the code, I only understand C and Java.
Thanks :)

答:
I borrowed algorithm from https://stackoverflow.com/questions/2710713/algorithm-to-generate-all-possible-permutations-of-a-list and made a simple change to it so it ignores same elements when swapping them.</p>

```<code>def permute(xs, low=0):
    if low + 1 >= len(xs):
        yield xs
    else:
        for p in permute(xs, low + 1):
            yield p
        for i in range(low + 1, len(xs)):
            if xs[low] == xs[i]:
                continue
            xs[low], xs[i] = xs[i], xs[low]
            for p in permute(xs, low + 1):
                yield p
            xs[low], xs[i] = xs[i], xs[low]

for p in permute([0, 1, 0, 2, 0, 3]):
    print(p)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Permutations of an array

Body:
I borrowed algorithm from https://stackoverflow.com/questions/2710713/algorithm-to-generate-all-possible-permutations-of-a-list and made a simple change to it so it ignores same elements when swapping them.

def permute(xs, low=0):
    if low + 1 >= len(xs):
        yield xs
    else:
        for p in permute(xs, low + 1):
            yield p
        for i in range(low + 1, len(xs)):
            if xs[low] == xs[i]:
                continue
            xs[low], xs[i] = xs[i], xs[low]
            for p in permute(xs, low + 1):
                yield p
            xs[low], xs[i] = xs[i], xs[low]

for p in permute([0, 1, 0, 2, 0, 3]):
    print(p)


问:
Representing a deck of cards in C (not C++)
So far my best ideas have been as fallows

A) Represent a "card" in one structure and have a "deck" in another
a deck being an array of 52 cards and a card being 2 chars one for and rank one for suit.

B) The second seems like it might be easier to manage but less obvious in code. Creating an array of ints each with a different value ranging from 1-52. Then crating a conversion function that would translate the value to a card structure that would have a string for the suit and a string for the rank. The value of zero could indicate a card that has not been "dealt".

Just trying to find a better way of doing this.

答:
So you either want to represent a card as an int, with the need to convert to suit/rank whenever you need that, or you represent it as a

```<code>   struct Card
   {
       char Suit;
       char Rank;
   };
</code>```

with no need to convert to suit/rank whenever you need those values. Performance and memory resources won't differ much between both approaches, I guess they are completely neglectable. So it all boils down to "which alternative is more readable" - and it seems very obvious to me that using a struct Card to represent cards will be much more readable than using an int and doing any unnecessary encoding / decoding.

EDIT: the only reason I can think of why one should use the integer representation is when you need the cardnumber (1...52) mainly as an array index, and you expect the usage as a card with Suit and Rank as very seldom needed in your program.

Body:
So you either want to represent a card as an int, with the need to convert to suit/rank whenever you need that, or you represent it as a

   struct Card
   {
       char Suit;
       char Rank;
   };

with no need to convert to suit/rank whenever you need those values. Performance and memory resources won't differ much between both approaches, I guess they are completely neglectable. So it all boils down to "which alternative is more readable" - and it seems very obvious to me that using a struct Card to represent cards will be much more readable than using an int and doing any unnecessary encoding / decoding.

EDIT: the only reason I can think of why one should use the integer representation is when you need the cardnumber (1...52) mainly as an array index, and you expect the usage as a card with Suit and Rank as very seldom needed in your program.


问:
How to become a Kernel/Systems/Device driver programmer?
I currently work in a professional capacity as a software engineer working with the Android OS. We work at integrating our platform as a native daemon among other facets of the project. I primarily work in Java developing the SDK and Android applications, but get to help with the platform in C/C++.

Anywho, I have a great interest to work professionally developing low level for linux. I am not unhappy in my current position and will hang around as long as the company lets me (as a matter of fact I quite enjoy working there!), but I would like to work my way that direction. I've been working through Linux Kernel Development (Robert Love) and The Linux Programming Interface (Michael Kerrisk) (In addition to strengthening my C skills at every chance I get) and casually browsing Monster and similar sites.

The problem I see is, there are no entry level positions. How does one break into this field? Anytime I see "Linux Systems Programmer" or "Linux Device Driver Programmer" they all require at the minimum 5-7 years of relevant experience. They want someone who knows the ropes, not a junior level programmer (I've been working for 7 months now...).

So, I'm assuming, that some of you on stackoverflow work in a professional capacity doing just what I would like to do. How did you get there? What platforms did you use to work your way there? Am I going to have a more difficult time because I have my bachelors in CSC as opposed to a computer engineer (where they would experience a bit more embedded, asm, etc)?

EDIT FOR CLARIFICATION!
I am aware of the opensource nature of the linux kernel/drivers etc. I plan on contributing regardless of where my day job is. I'm more curious of what kinds of entry level positions will allow me to do relevant work and get paid doing it! Thanks for all the replies so far!

答:
I am a software developer with 15+ years experience working at Motorola and a few other hi tech companies.  I have a BSCE degree.  So I'm not an amateur.

This question... how to break in...  is a common one not only for Linux but for virtually any area of specialization.  Software engineering has become just like medicine in that practitioners must specialize.  But when your company downsizes and lays you off after 10 years of being a specialist, you find the job market has changed and you're not current.  Companies used to not be so selective - frequently now the only candidate who has all the skills in the wishlist are those already working for that company or a direct competitor!  Its become quite tough.

I am in this situation now and while its hard, there are a few strategies you can use to get hired.  But first, you MUST become proficient in the technology because if hired, you'll be expected to produce. Once you feel ready, consider the following:

Look for a small company to start with.  They cannot be so picky about who they hire as are the big guys.  Spend a year or two there and after that, you'll have the professional experience on the resume to qualify.

Consider contracting, especially if you are not working full time.  Companies are much more willing to take a chance on a contractor than full time.  Again, once you have verifiable experience to put on your resume, it opens doors.

Do a small project or two on your own and create a portfolio to present to prospective employers.  This may open the door to entering not only a small company but a midsized one as well.

In addition to the above, consider using a professional recruiter from a company such as Kforce, Aerotek, etc.  The employer pays the recruitment fee and the recruiter will help sell you in a way that you cannot do on your own.

Actually, a "junior programmer" with only 7 months experience has a huge advantage over a guy like me when trying to get hired to do something new.  Companies LOVE "fresh-outs"/"new grads" because they know you won't ask for much money and will be willing to do WHATEVER THEY ASK including long stints overseas if required.   Companies won't hire me for a junior position even if I applied for one because they know I will be looking to leave for a better one straightaway.  Your situation is not that bad.

Good luck!

OwnerDisplayName: accordionfolder

ContentLicense: CC BY-SA 2.5


问:
I'm thinking to CSRF protect all public AJAX requests that return JSON, but I have some concerns
I'm thinking to CSRF protect all public AJAX requests that return JSON, because what's to prevent another site from spoofing the AJAX header and using the JSON as if it were a public API? I think CSRF protection is the best solution for this, however I'm concerned with the way Laravel handles this:

Using laravel's CSRF filter, I notice in app/filters.php that it checks using Session:token, will this require every public visitor to have a session and put additional requirement on server RAM (as opposed to browsing without sessions).

In the CSRF filter, Laravel checks Input::get('token'), but I may want to make POST ajax calls as well. Are POST requests not going to work?

What if a visitor has a window open. They walk away for a bit...then return to perform an ajax request. This would be a problem and we would need to refresh the page, which would seem awkward for a public visitor (as opposed to logged in users, where we could just redirect to a login page).

What if a visitor (or even logged in user) has 2 windows open? They walk away and let the session timeout. Then return and refresh one window (or login in again in one window), then go to the second window to perform an operation (only to find it doesn't work or they are forced to login again).

Can anyone address these concerns in Laravel's implementation of CSRF protection?

答:
Yes, all implementations I've seen for CSRF use sessions to
store the token. This is so users can use the website in multiple tabs or windows without issuing multiple tokens (which effectively overwrites the previously valid token as only one token per user is tracked). I think you'll find the additional server requirements
for using sessions is quite negligible.

Post requests will work. The Input::get() function actually gets variables from $_GET and $_POST. To quote the
documentation (http://laravel.com/docs/requests)

You do not need to worry about the HTTP verb used for the request, as input is accessed
  in the same way for all verbs.

A possible solution would be to pass back a new token in one of the json requests
every time it expires. If you use this method and have normal (non ajax) forms on the
same page you will have to use javascript to replace the token values in each of those
forms.

As the CSRF uses sessions to keep track of the token, and assuming you have solved problem 3, the second window should have no problem performing the operation as the tokens would be automatically refreshed on expiry.

OwnerDisplayName: David Graham


问:
OOP what is meant by object-to-object communication
I've been reading in basic concepts of OOP,as i'm trying to make this shift from transactional scripts to more oop manner in php, and i often come across this definition :

An object stores its state in fields (variables) and exposes its
  behavior through methods (functions). Methods operate on an object's
  internal state and serve as the primary mechanism for object-to-object
  communication

and a simple example like :

Objects like real life objects have state and behavior. Dogs have
  state (name, color, breed, hungry) and behavior (barking, fetching,
  wagging tail).

from definition i see that methods should be either manipulating internal state (setters) or communicating with other objects;

but when i try to apply this to a Blog example. composed of mainly 2 domains User and posts.

what could be the User object Behavior ?

I cannt find any !

login, its an auth lib. thing so i should not include it in user.

posting articles is a Post object thing; again user conduct it; but its more of a post object concern to create a post right ?

User may be the main Aggregate object in a blog; yet the user is more like the Creator of Other Objects but he does not have a Behavior i can think of; he is being used -and his state- by other objects in most cases that all !

in a nutshell : what are allowed type of methods inside an object ?

答:
There are no limits to allowed methods in an object, but there are philosophies about behavior when it comes to good design. There are many heuristics (rules of thumb that don't offer guarantees of a good design, but which have shown merits in the past).

As stated by Bart, software object behaviors can be classified as accessors (which don't change the state of an object but rather usually access information within the object, e.g., getters) and mutators (which do somehow change the state of an object, e.g., setters). Normally, the two should be separated -- an accessor should not also modify the state of the object. Combining those behaviors leads to problems in quality of the software, since it's harder to test how these behaviors work.

Perhaps if you consider object behaviors in terms of responsibilities, it might help. Responsibility-driven design is the name of the paradigm, if you want to find more info.

Software objects are not real-world objects, so I think the numerous examples with behaviors of Dogs, Birds, etc. lead to confusion. Software objects are part of a design to solve a problem that ties to the real world. Using objects should help one to understand the solution to a real-world problem, since an object abstraction is closer to how we think of elements in the real-world problem domain. That said, software behaviors are not necessarily real-world behaviors.

Dogs: If you are designing a software that helps veterinarians manage their business, you might have Dog objects. But their "bark" probably won't matter for this kind of problem and certainly won't be a behavior of the software object. However, it might be if you're trying to simulate something where a dog's barking is part of the problem (e.g., a sim game where police show up if too many of the player's dogs are barking in her back yard because they're hungry or bored).

Blogs: if a Blog has a limit to the number of messages it can contain, a possible behavior might be to "truncate()" itself (although it's debatable whether a blog should enforce this behavior itself or an outside entity). Truncate is an example of a mutator. A behavior to "getAuthor()" of a Blog would be an example of an accessor.

Behaviors should not reveal the implementation of your classes, if you want to strive for information hiding in your design. As for other 'rules of thumb' about behaviors, there are many when you go with responsibility-driven design (and you'll see things get very complicated with gray areas). Check out GRASP and SOLID for a start (some of the rules overlap - it's because OO software design is still a relatively immature discipline, compared to Bridge design or Furniture design).


问:
Are NuGet metadata a good place to exclusively set license for source code?
I've found a library (that I'd like to fork, if it makes any difference).

On NuGet, the project file says it's distributed under the MIT license (with a link to the license). However, in the GitHub repository of the project, I don't see any mentions of the MIT license (or any other license) either in the source code files or in a readme. I'm a little concerned about this, since NuGet is a repository for binaries and I'm interested in the source.

Should I assume that the source code is covered under the MIT license, judging only by the NuGet metadata of a package? Or does this mean that the permissions apply only for the binary and not for the source?

答:
Making assumptions with legal matters, like copyright licenses, is never a good idea. Wrong assumptions is what lawyers can get big fees on.

The fact that there is no explicit copyright license mentioned in the source code archive means that the source code falls under the default copyright 'license' of "all rights reserved", meaning that no permission is given to copy the sources.

As the binaries are distributed with a permissive open-source license, there is confusion about under what rights the author meant to release the software. The best option here is to contact the author of the library and get the license status of the sources clarified.

Without that, the MIT license gives you the right to modify the (binary) library, but you would have to do that through reverse engineering and you would have to be able to legally prove that you didn't use the original source code in your modification, which might be hard to prove.


问:
Finding most Important Node(s) in a Directed Graph
I have a large (≈ 20 million nodes) directed Graph with in-edges & out-edges. I want to figure out which parts of of the graph deserve the most attention. Often most of the graph is boring, or at least it is already well understood. The way I am defining "attention" is by the concept of "connectedness" i.e. How can i find the most connected node(s) in the graph?

In what follows, One can assume that nodes by themselves have no score, the edges have no weight & they are either connected or not.

This website suggest some pretty complicated procedures like n-dimensional space, Eigen Vectors, graph centrality concepts, pageRank etc. Is this problem that complex?

Can I not do a simple Breadth-First Traversal of the entire graph where at each node I figure out a way to find the number of in-edges. The node with most in-edges is the most important node in the graph. Am I missing something here?

答:
Not knowing the real problem your graph solves or the details of your graph, this may not be relevant. But, I suspect your basic solution will be inaccurate in two ways: tie-breaking and what I might call "megalomaniacs." In other words, if you're just counting inbound connections, you'll likely run into nodes with the "same" importance; but, I suspect the intention is that one should be more important. And, in some cases, you may have "islands" of nodes that are all highly interconnected amongst themselves, but loosely so with the majority, yielding nodes that appear much more important than they are (megalomaniacs).

The solution? Well ... Something like pagerank, I imagine!


问:
Is it a code smell if you are frequently creating an object just to call a method on it
I inherited a code base where there is a lot of code that goes something like this:

```<code>SomeDataAdapter sda = new SomeDataAdapter();
sda.UpdateData(DataTable updateData);
</code>```

And then sda is never used again.

Is that a code smell that indicates that those methods should actually be static class methods instead?

答: If holding state makes a given class more utilitarian, functional … re-usable then no. For some reason the command design pattern comes to mind; that reason certainly is not a desire to have Robert Harvey drown.</p>


答:
Should you take the copyright notice from one distribution and assume that it applies to another, of a precursor work to the one that actually provided the notice?  Absolutely Not!

The MIT License is a draft license primarily concerned with preserving original credit and disclaiming all liability.  While it's a fairly broad statement allowing you do do just about whatever you want with the software and documentation, it does not compel the provision of source code, either from the original author or any sub-licensor.

If the NuGet package only included a link as I did so above, it's almost certainly not a proper-form release.  You need to contact the developer of the software if you want to use it.  Either someone stole their project and released it in error, or (much more likely), they didn't realize that they have to do more than click the "MIT license" box to actually release "Software" under an MIT license.

Let me be as clear as I possibly can.  If you have any doubt as to the license of software, assume you CAN'T and ASK FOR PERMISSION.  (Expect a reply pointing to the [updated] license file.)

Title: Are NuGet metadata a good place to exclusively set license for source code?

Body:
I've found a library (that I'd like to fork, if it makes any difference).

On NuGet, the project file says it's distributed under the MIT license (with a link to the license). However, in the GitHub repository of the project, I don't see any mentions of the MIT license (or any other license) either in the source code files or in a readme. I'm a little concerned about this, since NuGet is a repository for binaries and I'm interested in the source.

Should I assume that the source code is covered under the MIT license, judging only by the NuGet metadata of a package? Or does this mean that the permissions apply only for the binary and not for the source?


问:
Inverse of Extract Interface refactoring
I'm working with a Java project that has several interfaces, many of which have only one implementation. (See related question)

For a given revision of the software, one could think this acceptable because the interfaces were some plan for future extensions. However, when I look at the 200+ revisions over several years, those interfaces never had more than one implementation, (nor were they used in unit-testing).

It seems that in these cases of probable bloat (YAGNI) owing to the Interface Anti-pattern, it would be useful to apply the inverse of Extract Interface. However, Inline Class (the supposed inverse according to refactoring.com) is not what I'm referring to.

What's the name of the refactoring that removes an unused interface, substituting the sole class that implements it?

答:
Merge Interface (on the expectation that the class has at least some other members)?

As suggested, Merge Interface and Implementation would be even more descriptive. I don't recall ever seeing it in an IDE.


问:
Need advice on design in Ruby On Rails
For personal educational purposes I am making a site for a conference. One of the object that exist in a conference is a session, which has different states and in each state it has slightly different attributes:

When submitted it has a speaker (User in the system), Title and abstract.

When under review it has reviews and comments (in addition to the basic data)

When accepted it has a defined time-slot but no reviewers anymore.

I feel that it is not the best thing to add a "status" attributes and start adding many if statements...

So I thought it would be better to have different classes for each state each with it's own validations and behaviors.

What do you think about this design? Do you have a better idea?

答:
Agreed that gnarly if statements and conditional ActiveRecord validations are not the answer.

It seems like your idea is to have several classes such as Submission, UnreviewedSubmission, and AcceptedSubmission.  I think this is an improvement, but you might have issues linking data.  If I want to view all unreviewed submissions, how will I do that?  If I reviewed a submission and want to undo that, how can I reverse my approval and get that reviewers list back?

If you're OK with losing historical data, the approach above could work.

I'd also consider storing the initial Submission model and separately, an immutable list of state changes to it.  For instance, a Review object could be created to signify that someone reviewed a submission.  To figure out the state of a Submission, you'd find the original Submission object and then go through all the Review objects.  There'd be a run-time performance penalty but you'd gain history tracking and clearer validations on state change.

Title: Need advice on design in Ruby On Rails


问:
Is better Show() + Hide() or SetVisible(bool visible)?
What is better and why? (From interface-design point of view) :

a) To have two Show() and Hide() functions

b) To have one SetVisible(bool visible) function

EDIT: For example some object have visibility state and this functions is used to change it.

c) To have all three Show(), Hide(), SetVisible(bool visible) functions

答:
I would suggest using SetVisible(bool) if any only if toggling the visibility twice (show and re-hide, or hide and re-show) would leave things in the essentially the same state as before the operation was performed (it's fine if showing and re-hiding something or vice versa leaves objects in need of a redraw, provided that can be expected to happen "automatically").  If hiding and showing an object will have no effect other than changing one bit of state, then it would make sense to outside code to have some methods which accept a visibility parameter, and the writing of such code will be facilitated by SetVisible.

If hiding and re-showing an object might have side-effects such as changing the Z order, such actions should more likely be performed by separate methods.  In such cases, the usefulness of outside methods which accept a "visibility" parameter will be limited, and so there will be little advantage to facilitating them.  Further, a SetVisible method will (wrongly) suggest that changes to the visibility of objects can be accomplished without side-effects.


问:
Trying to understand what Travis CI does and when it should be used
I am very new to Git and I am planning to contribute to some open-source project on GitHub after discovering a small error in it. Upon forking it and fixing the error, I purposed a pull request and I noticed this showing up:

Failed — The Travis CI build failed

Looking into the details I discovered it was caused by Could not find .travis.yml, which made perfect sense since I had not signed in to Travis Cl with and add .travis.yml to the repository.

This is my first time hearing about Travis CI. And it sounds pretty cool so in order to learn more about it, I looked it up on Wikipedia.

Travis CI is a hosted, distributed continuous integration service
  used to build and test projects hosted at GitHub. Travis CI automatically detects when a commit has been made and pushed to a GitHub repository that is using Travis CI, and each time this happens, it will try to build the project and run tests. This includes commits to all branches, not just to the master branch.

My current understanding of Travis CI is that what it does is automatically pushing the project upon git commit -am ".." and I don't quite understand some part of it.

By building the project and run tests, what tests is it going to run? And how is it going to "build" the project? (like compiling it to binary?)

It states that "This includes commits to all branches" - but what if I don't want to commit to all branches?

Is it alright if I don't use Travis Cl at all? Under what circumstances is it best to use it (or it must be used)?

答:
Whatever tests are part of the overall project. Unit tests and integration tests are part of some projects that are supposed to run after code changes are done to ensure that functionality still works as originally intended. Failed tests may have to be changed or there may be bugs that were missed in the initial code change. There is likely some kind of makefile in the project that is used to compile the project into whatever end form it has,e.g. an executable, DLL, website or other component.

While there may be an option to change this somewhere, it may be that the changes are intended to go into all future releases and thus the commit should be reflected in all the branches outstanding I'd think.

That may depend on who runs the project as the general idea of CI is to check that a commit doesn't break the software or tests. Consider the case that if you commit code with typos that doesn't compile. This is generally bad and a CI server will catch this quickly so that it can be fixed. Similarly, there may be regression tests that aren't usually run that a CI server may catch when developers commit their changes. Some people believe in the idea that commits shouldn't break the build ever and so only commit once things are working while others believe in one often committing changes whether it breaks the build or not. When to commit code has various answers that may be useful on this point.


答:
I believe that the Hide()/Show() alternative is attractive because it's easier to understand what's going on than with SetVisible(true), while having a single function is preferable because it avoids lots of conditionals.

If that's the case then I suggest using an enumeration as the input to SetVisible, so you get either SetVisible(Visibility.Visible) or SetVisible(Visibility.Hidden). You have a single function you can instantly read what action is being taken.

Using Java's naming conventions, you would have maybe setVisible(Visibility.VISIBLE) or setVisible(Visibility.HIDDEN).

Title: Is better Show() + Hide() or SetVisible(bool visible)?

Body:
What is better and why? (From interface-design point of view) :

a) To have two Show() and Hide() functions

b) To have one SetVisible(bool visible) function

EDIT: For example some object have visibility state and this functions is used to change it.

c) To have all three Show(), Hide(), SetVisible(bool visible) functions


问:
Euclidean Space Fully Connected Nondirectional Graph: Shortest Path to all nodes
So this may be a question that is born of my inability to properly express my intentions to Google.

In a fully connected non-directional graph such that any three points can be properly represented in a triangle in Euclidean geometry it would seem that a greedy first algorithm which chooses the shortest edge would find the shortest path from a starting point to visit all other points.

I can't find a condition under which this is false, but one of my neighbors (another programmer) insists that I am wrong, though still cannot come up with a condition where I am wrong.

Edit:

I am not sure this question is an instance of of the general TSP, which I know is NP hard, or if it is I thought that all of the constraints on the allowed graphs would have impacted the difficulty.

From wiki: TSP is the shortest possible route that visits each city exactly once and returns to the origin city. In this problem there is no requirement to return to the origin city. Further, we don't care about selecting the optimal origin city since the origin city is set in our specific example that we were discussing.

Additionally, the graph in this problem must conform to the constraints of euclidean distances in either 2 or 3 dimensions so a three node graph such as below (key is the node, val is the distances between other nodes) could not exist since the edge from A to B would make the edges from C to A and B infeasible.

A:{B:80, C:10}, B:{A:80, C:5}, C:{A:10, B:5}

Also by fully connected I meant all nodes have edges between them and every other node.

Sorry if the description came off as confusing, but I am wondering if given all these constraints, does it become solvable in a more simplistic manner.

答:
(Edit:  Sorry, I missed that you wanted to visit all nodes in the graph, disregard my first answer, as I thought you wanted to find a path from point A to point B, rather than a path through every point.)

The name of the problem you're trying to solve is the Travelling Salesman Problem.

If you mean by "fully connected" a graph that is not disconnected, then it's the Euclidean plane version of the TSP, and it's NP-hard (although the algorithm you suggest is actually a pretty good heuristic).

If you take a graph that's a bunch of squares, like graph paper, picking the smallest edge would give lots of ties, and getting an optimal path by the algorithm you give would involve a whole lot of lucky guesses.  This would be true even if you're talking about a complete graph (every node connected to every other node).

Edit: Since a fixed starting point was specified, I've got a counterexample.  Take a triangle with nodes A, B, and C.  Edge AC > edge BC > edge AB.  Start at A, and we get AB, BC.  Start at B and we get BA, AC.  These are different paths with different lengths, so the algorithm given will not always give an optimal path.

The name for what you meant by "fully connected" is "complete".  From wikipedia: "The requirement of returning to the starting city does not change the computational complexity of the problem, see Hamiltonian path problem."


问:
Porting an open source project from ISC license and public domain
I have ported libsodium and NaCl to .NET.

NaCl is the original project that is in the public domain while libsodium is a derived work from NACL and is using the ISC license. I looked at both projects to port the code to .NET.

For my project I prefer to use MPL v2, but I'm not sure I'm allowed to change the original license. I know ISC is a permissive but it's not clear if I can use another license for my work. Any help would be appreciated.

答:
Everything you are allowed to do is explicitly covered by each of those licences, and explained by related FAQs or similar documents. You really need to read them.

But the answer is you're probably OK. Public domain says do what you like with the code (other than pretend you wrote it). ISC is the BSD licence, which is very permissive and popular with commercial users. MPL is specifically intended to play well with other licences, so unless you're planning on doing something commercial, you're pretty safe.

Two notes of caution. A high proportion of .NET users are commercial, and if you want your code widely use you need to understand their needs. MPL has some copyleft-ish features and may prevent commercial usage. The products you started from didn't have those restrictions. You might want to consider a friendlier licence.

The other is: never take advice from a place like this if you're even thinking of making money out of it. If anyone could possibly suffer commercial loss, you need competent legal advice to be sure you're not doing something that creates a liability.


问:
Given n distinct keys, how many different 2-3/Red-black trees can be constructed?

Memory refresher/My understanding:

A 2-3 tree is a balanced search tree that allows two types of nodes.

2-node: Normal node with two children.

LChild < Parent and RChild > Parent

3-node: Node with two parents and three children.

Parent1 < Parent2

LChild < Parent1, Parent1 < MChild < Parent2, RChild >Parent2

A 2-3 tree is always balanced, and grows when the root raises the height of the tree by one.

http://en.wikipedia.org/wiki/2%E2%80%933_tree

My question is then as follows,
given n distinct keys, how many different 2-3 trees can one construct?

My math skills are poor, so if anyone knows how I should "math" in order to approach an answer, then that would be awesome! :)

答:
Let T[n] be the number of 2-3-trees with n keys. We have:

T[n] = sum with k from 1 to n of T[k - 1] * T[n - k], because we can make a 2-node with the key k, with left tree with keys 1, ..., k - 1 and right tree with keys k + 1, ..., n. For each arrangement of the left tree, we have the arrangements of the right tree, so we must multiply the two. This counts the case when we're dealing with 2-nodes;

T[n] += sum with k from 1 to n of sum with p from k + 1 to n of T[k - 1] * T[p - k - 1] * T[n - p]. This counts the case when we're dealing with 3-nodes;

Base case is T[0] = 1.

OwnerDisplayName: IVlad


问:
What is the traditional way to maintain extensibility in a database-driven application like this?
I'm working on a simple application for a game in Java that allows a user to record whether they have collected a given item and how much experience it contains. This will work for multiple item types (weapons, armor) and each will have its own tab with a list of all items that qualify under it. Making changes as new types are added is not such a big deal (if a clothing slot is added, for instance), but new items are added to the game all the time in biweekly patches, and I'm not sure what the traditional/customary way to make sure the application is user-extensible without requiring me to would be.

Whether that would be adding a configuration menu that allows users to add news items (new rows to the local SQLite database) or a text file with something similar, but I'm certain there's a well-accepted way to do this that I'm not aware of. I'm new to databases and ignorant of the solution, so what's the professional/futureproof way to do this?

答:
Three points.

You need your code to be stable. Occasionally you will have to change it to add new item types or features, but it will always have to be backward compatible.

So new items, and as far as possible new types of items will be added in data, not code. It matters not a bit whether you use a database, text file, XML, JSON or binary blobs, because...

You need to provide a user interface for updating the data. When new things have to be added, the user goes to a form or screen or data entry device that allows new stuff to be added and checked for validity. That is how it's done (or should be done).

When you do need to add new functionality, as well as backward compatibility you need to upgrade/migrate existing databases. Users don't like to lose what their work just for your convenience.


问:
Implementing the Interface Segregation Principle
Does this IConvertible interface satisfy the Interface Segregation Principle (ie. the "I" in SOLID)?

Here is the definition:

```<code>public interface IConvertible
{
    TypeCode GetTypeCode();
    bool ToBoolean(IFormatProvider provider);
    byte ToByte(IFormatProvider provider);
    char ToChar(IFormatProvider provider);
    DateTime ToDateTime(IFormatProvider provider);
    decimal ToDecimal(IFormatProvider provider);
    short ToInt16(IFormatProvider provider);
    int ToInt32(IFormatProvider provider);
    long ToInt64(IFormatProvider provider);
    sbyte ToSByte(IFormatProvider provider);
    float ToSingle(IFormatProvider provider);
    string ToString(IFormatProvider provider);
    object ToType(Type conversionType, IFormatProvider provider);
    ushort ToUInt16(IFormatProvider provider);
    uint ToUInt32(IFormatProvider provider);
    ulong ToUInt64(IFormatProvider provider);
}
</code>```

So if I would like to have a class which will implements this IConvertible interface the I have to implement all of those methods, right? Or if I don't implement all of them, then I have to at least make an empty method or throw an Exception, right?.

In my opinion, the better way is to make more interface with fewer methods, for example:

```<code>public interface IConvertibleInt
{
        short ToInt16(IFormatProvider provider);
        int ToInt32(IFormatProvider provider);
        long ToInt64(IFormatProvider provider);
}
</code>```

Or even:

```<code>public interface IConvertibleInt16
{
        short ToInt16(IFormatProvider provider);
}

public interface IConvertibleInt32
{
        int ToInt32(IFormatProvider provider);
}

public interface IConvertibleInt64
{
        long ToInt64(IFormatProvider provider);
}
</code>```

Is my reasoning correct?

答:
I like to interpret Interface Segregation Principle as

Interface should be closer related to the code that uses it than code that implement it. So the methods on the interface are defined by which methods client code needs than which methods class implements.

This implies that for each interface, there is always code that uses this interface. This is not the case of IConvertible. The interface itself doesn't make much sense. I also never saw property or function that was typed IConvertible, which empowers my claims. I even wonder how would code that only works on IConvertible looks and what would it do.


问:
Developing a virtual machine / sandbox
I'm interested in learning how a virtual machine/sandbox actually works. I have developed an 8051 emulator and also wrote a dissassembler for x86, so this part of a virtual machine is not really the problem.
What I'm interested in, is the sandbox functionality of it. To illustrate what I mean consider this example.

Let's assume I have a function which simply opens a file. So nothing fancy.

```<code> int fd = open(path);
</code>```

Now when this code is executed natively it will go to the operating system and opens the file (assuming that it exists). Now when I run this in a virtual machine environment, the specified path is not the one that the operating system sees, but rather something that the VM will substitute, thus redirecting the open call.
So what I'm interested in is, how a VM can do this, when the executed code is run natively (like x86 on a x86) because for an interpreted VM it is rather obvious.

When I google for virtual machines I either find only links talking about interpreters like Java, LLVM or similar, but nothing that goes into more detail. I downloaded the sourcecode from Oracle Virtual Box, but as this is a rather big codebase, it's quite hard to understand the concept just form digging in that code.

答:
So the question is how to write a sandbox, in which a program can run and do no harm. I shall assume Windows, and no cooperation from the target program. I know of two ways, and they're both pretty hard.

One is to provide an environment in which every system call is emulated. Every Windows executable loads DLLs and calls entry points in them, so you have to provide your own DLLs for the program to load (via your own LoadLibrary). For each entry point you either pass it through, or block it, or modify it somehow.

The other is to rely on a suitable 'hook' feature built into the O/S. Vista and later have security features on many system APIs. You can write a filter driver to control access to disk. You can intercept the lowest level of system call and redirect those. The possibilities are endless, but rest assured, every one of them is a lot of hard work.

The typical O/S VM (VMware, HyperV) work at the driver level because emulating devices and disks is a necessary part of doing what they do.

This is all rather generic stuff. I don't know of any resources to quote, but you could certainly take a close look at Sandboxie, Chrome native client, or one of the others listed here: http://downloadsquad.switched.com/2009/03/11/five-sandboxing-apps-to-protect-your-windows-computer/.

Title: Developing a virtual machine / sandbox


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies.

— C.A.R. Hoare

LastEditorDisplayName: Roger Pate


答:
Now when I run this in a virtual machine environment, the specified path is not the one that the operating system sees, but rather something that the VM will substitute

This is not true for the vast majority of VMs (VMWare, VirtualBox, QEmu, Parallels, VirtualPC, …) These are all hardware virtualizers, they don't virtualize the OS. So, the open call will simply go to the OS inside the VM, which (typically) doesn't even know that it is running inside a VM. (There are performance advantages if the OS knows that it is running inside of a VM and talks to the VM instead of talking to the virtualized or emulated hardware, but that is technically no longer virtualization, it is paravirtualization.)

Of course, this just pushes the question one layer down: when the OS kernel wants to write to some specific block on the hard disk, how does that work? Well, in the worst case, the VM has to intercept the BIOS calls and map the block numbers to some file on the host system's hard disk. But this is where paravirtualization comes in: no modern OS uses the BIOS anymore, they use specialized drivers. And you could then simply provide a "virtual" driver that knows how to talk to the VM directly.

You still need to map the block numbers, of course. The simplest solution is to create a file in the host system that is the same size as the emulated hard disk. However, since hard disks tend to be mostly empty, this would be a waste of space, so most VMs employ a lazy scheme where the file only grows when needed. They might also use compression.

What you are talking about is more like OS virtualization (aka containers) than hardware virtualization. But really, it works the same way: instead of virtualizing the x86 instruction set, it virtualizes the "Linux Kernel ABI Instruction Set". IOW: it simply treats the Linux Kernel as an interpreter for a certain language (the syscalls) and then puts another interpreter on top. That's how OpenVZ works on Linux, for example, or Solaris Zones, or DLPAR on the IBM PowerSeries.

Title: Developing a virtual machine / sandbox

Body:
I'm interested in learning how a virtual machine/sandbox actually works. I have developed an 8051 emulator and also wrote a dissassembler for x86, so this part of a virtual machine is not really the problem.
What I'm interested in, is the sandbox functionality of it. To illustrate what I mean consider this example.

Let's assume I have a function which simply opens a file. So nothing fancy.

```<code> int fd = open(path);
</code>```

Now when this code is executed natively it will go to the operating system and opens the file (assuming that it exists). Now when I run this in a virtual machine environment, the specified path is not the one that the operating system sees, but rather something that the VM will substitute, thus redirecting the open call.
So what I'm interested in is, how a VM can do this, when the executed code is run natively (like x86 on a x86) because for an interpreted VM it is rather obvious.

When I google for virtual machines I either find only links talking about interpreters like Java, LLVM or similar, but nothing that goes into more detail. I downloaded the sourcecode from Oracle Virtual Box, but as this is a rather big codebase, it's quite hard to understand the concept just form digging in that code.


问:
Is it a bad practice to cite URLs as references in comments?
Sometimes I think it's useful to cite a webpage (e.g. Stack Overflow questions) to justify and explain a piece of code. Is this considered bad practice?

答:
You may put URLs inside your comments, but consider the problems it might raise:

No-one actually copies the link, and goes to read what the content of the URL actually say.

The link/site might not be there a year in the future, or even next week

You might forget to update the comment when the code below it changes, which will confuse a future reader even further.

I believe that you should not put URLs inside your comments unless you also paste the relevant quote from it, and then the URL is only used as a re-enforcement for the comment, or as in-depth further reading.


答:
As long as you and your team are disciplined about comments, sure.

Use long-term reliable sites for your references:

a) wiki or other internal sites maintained by your team for the life of the project.

b) internal sites maintained by your organization that have a long-term maintenance agreement regarding preserving links.

c) external sites that have commitments to long-term maintenance of links. E.g., wikipedia, stack exchange, open source vendor sites, etc.

The alternatives to putting links into your comments are often worse.

1) Multiple maintenance: don't repeat yourself in an explanation of a coding instance, especially when it affects multiple pieces of source code.

2) Trying to summarize a board discussion when you've already implemented the code is frequently redundant.

Title: Is it a bad practice to cite URLs as references in comments?

Body: Sometimes I think it's useful to cite a webpage (e.g. Stack Overflow questions) to justify and explain a piece of code. Is this considered bad practice?


问:
Is it reasonable to insist on reproducing every defect before diagnosing and fixing it?
I work for a software product company. We have large enterprise customers who implement our product and we provide support to them. For example, if there is a defect, we provide patches, etc. In other words, It is a fairly typical setup.

Recently, a ticket was issued and assigned to me regarding an exception found by a customer in a log file that has to do with concurrent database access in a clustered implementation of our product. So this customer's specific configuration may well be critical in the occurrence of this bug. All we got from the customer was their log file.

The approach I proposed to my team was to attempt to reproduce the bug in a configuration setup similar to that of the customer and get a comparable log. However, they disagree with my approach saying that I don't need to reproduce the bug as it's overly time-consuming and will require simulating a server cluster on VMs. My team suggests I simply "follow the code" to see where the thread- and/or transaction-unsafe code is and put in the change working off of a simple local development, which is not a cluster implementation like the environment from which the occurrence of the bug originates.

To me, working out of an abstract blueprint (program code) rather than a tangible, visible manifestation (runtime reproduction) seems difficult, so I wanted to ask a general question:

Is it reasonable to insist on reproducing every defect and debug it before diagnosing and fixing it?

Or:

If I am a senior developer, should I be able to read multithreaded code and create a mental picture of what it does in all use case scenarios rather than require to run the application, test different use case scenarios hands-on, and step through the code line by line? Or am I a poor developer for demanding that kind of work environment?

Is debugging for sissies?

In my opinion, any fix submitted in response to an incident ticket should be tested in an environment simulated to be as close to the original environment as possible. How else can you know that it will really remedy the issue? It is like releasing a new model of a vehicle without crash testing it with a dummy to demonstrate that the air bags indeed work.

Last but not least, if you agree with me:

How should I talk with my team to convince them that my approach is reasonable, conservative and more bulletproof?

答:
Both activities (code review and testing) are necessary, neither are sufficient.

You could spend months constructing experiments trying to repro the bug, and never get anywhere if you hand't looked at the code and formed a hypothesis to narrow the search space. You might blow months gazing into your navel trying to visualize a bug in the code, might even think you've found it once, twice, three times, only to have the increasingly impatient customer say, "No, the bug is still there."

Some developers are relatively better at one activity (code review vs constructing tests) than the other. A perfect manager weighs these strengths when assigning bugs. A team approach may be even more fruitful.

Ultimately, there may not be enough information to repro the bug, and you have to let it marinate for awhile hoping another customer will find a similar problem, giving you more insight into the configuration issue. If the customer who saw the bug really wants it fixed, they will work with you to collect more information. If this problem only ever arose one time, it's probably not a high priority bug even if the customer is important. Sometimes not working a bug is smarter than blowing man-hours flailing around looking for a really obscure defect with not enough information.


问:
Does the Composite design pattern implement recursive behavior?
The Composite design pattern allows us to call an operation() on a 'composite' node in a tree structure, and this operation() will be called on all of the children, subchildren and so on.

When an element's operation() is invoked, it is it's responsibility to call operation() on all of it's children, and so on. Each child responsible to invoke the operation on it's own direct children.

I understand why this has a recursive nature. When we learn of this design, the word 'recursion' is inside our heads all the time.

But can this be considered 'recursive behavior' in the strict sense of the word?

I always thought that recursion simply means a process where 'a function calls itself'. ('function' or 'method' or 'procedure' etc).

However, in the Composite design pattern, no method calls itself. A method calls the identically-named method in the objects composed with it (serving as it's 'children') - but it never calls itself (aka void operation(){ this.operation(); } never happens).

So, does the Composite design pattern create recursive behavior? Or does it create behavior resembling the nature of recursion? Is my definition of recursion wrong because it's too strict? If so, how would you define recursion?

答:
Composite creates Recursive Data Type which then needs recursive functions or operations to fully traverse. In a sense Composite creates tree-like structure.

Then yes, Composite has recursive behavior.


答:
The composite pattern is recursive in two dimensions - it is a recursive data structure, and the operation method is likewise called recursively

See http://en.wikipedia.org/wiki/Recursion_(computer_science) for a detailed explanation and more.

Note: the method Operation() is defined by the class, and under the hood it just takes a reference to an instance as an argument, so the method is, in fact, calling itself.

Title: Does the Composite design pattern implement recursive behavior?

Body:
The Composite design pattern allows us to call an operation() on a 'composite' node in a tree structure, and this operation() will be called on all of the children, subchildren and so on.

When an element's operation() is invoked, it is it's responsibility to call operation() on all of it's children, and so on. Each child responsible to invoke the operation on it's own direct children.

I understand why this has a recursive nature. When we learn of this design, the word 'recursion' is inside our heads all the time.

But can this be considered 'recursive behavior' in the strict sense of the word?

I always thought that recursion simply means a process where 'a function calls itself'. ('function' or 'method' or 'procedure' etc).

However, in the Composite design pattern, no method calls itself. A method calls the identically-named method in the objects composed with it (serving as it's 'children') - but it never calls itself (aka void operation(){ this.operation(); } never happens).

So, does the Composite design pattern create recursive behavior? Or does it create behavior resembling the nature of recursion? Is my definition of recursion wrong because it's too strict? If so, how would you define recursion?


问:
Python - only one return per method?
I'm trying to sort out whether this is just a personal preference thing or whether it's actually bad practice to do this one way or another. I did try to reference PEP8 first, and I did not see an answer.

What I'm talking about here is the use of more than one return statement. In these examples, it's not such a big deal, as they are very short and easily read.

```<code>def foo(obj):
    if obj.condition:
        return True
    return False

def bar(obj):
    answer = False
    if obj.condition:
        answer = True
    return answer
</code>```

It bugs me to assign a variable every time bar() is called, instead of just determining the answer and returning it. But in a longer function a second return might be hidden and so someone reading the code may have not realized that the function might return a value before hitting the end of the line:

```<code>def spam(obj):
    blurb = "Francis"
    if obj.condition:
        blurb = map(gormf, [z for z in porp(obj)])
        return blurb[2]
    elif not obj.condition and dreg(obj.jek):
        blurb = obj.hats * 17
        if blurb % 13: return blurb
    else:
        blurb = obj.name
    return "Whales and %s" blurb
</code>```

That's a terrible function, but I think you see what I'm poking at.

So is it preferable to create a function to have a single, clear exit - even if it's a few more operations than you actually need? Or should one try to root this out whenever possible in favor of shorter code?

答:
Setting aside the fact that "if true then true else false" is silly, one thing to keep in mind is that foo() only has two returns because if is a statement in Python, not an expression. In a functional language like Standard ML, where everything is an expression that returns a value, foo() would look like this:

```<code>fun foo (obj) =
    if obj.condition
    then True
    else False
</code>```

So, conceptually, your foo() could be considered to have a single return.

Multiple returns starts to get confusing is when you combine them with side effects and looping statements. In that case in can get tricky to follow the execution of the function and determine whether it'll abort early or not. But once that's an issue, rewriting the function to be easier to follow and understand is far more important than adhering strictly to some style guide or another.

Title: Python - only one return per method?

Body:
Setting aside the fact that "if true then true else false" is silly, one thing to keep in mind is that foo() only has two returns because if is a statement in Python, not an expression. In a functional language like Standard ML, where everything is an expression that returns a value, foo() would look like this:

fun foo (obj) =
    if obj.condition
    then True
    else False

So, conceptually, your foo() could be considered to have a single return.

Multiple returns starts to get confusing is when you combine them with side effects and looping statements. In that case in can get tricky to follow the execution of the function and determine whether it'll abort early or not. But once that's an issue, rewriting the function to be easier to follow and understand is far more important than adhering strictly to some style guide or another.


问:
Collection vs data structure vs aggregate
I know three terms that have to do with storing objects or data. I'm not sure I understand the exact differences between the terms. Please confirm if what I'm about to write is accurate.

A data structure is a group of data types or objects of the same type, grouped together in some formation.

A collection is the same as a data structure (I don't mean a Java Collection, I mean a collection in the more general meaning).

An aggregate is an object containing a collection or data structure, providing an interface to communicate with the inner data structure. For example, the object someContainer, which contains an inner ArrayList, is an aggregate because it contains a data structure, encapsulates it, and provides an interface to manipulate it.

Is all of this accurate?

答:
A Data Structure is any structure that holds data.  Data Structures are distinguished from each other by their memory usage and performance characteristics.  For example, the lookup performance of a Hash Table is O(1), while that of a balanced binary tree is O(log n).

A Collection is any data structure that can hold zero or more data items.  Generally, the data items will be of the same type or, in languages supporting inheritance, derived from some common ancestor type.  Collections can utilize certain data structures, such as Hash Tables and Balanced Binary Trees, to improve their memory and performance characteristics.

An Aggregate, in the general sense, is a whole combined from individual elements (the individual elements can form a collection).  Examples include Sum and Average functions, the results of those functions, and the process by which data is combined in a data warehouse to speed up retrieval.


问:
Writing an API that is syntactically valid in multiple programming languages
I'm planning to write a single API that is syntactically valid in most major programming languages (to the greatest extent possible, so that only minimal amounts of code will need to be re-written when moving from one language to another). I think the simplest way to do this would be to write a group of functions that consisted entirely of function calls and variable assignments, since the syntax for function calls is almost exactly the same in all major programming languages.

Of course, I'd need to write "wrapper" functions for if-statements and while-loops, since the syntax of each of these is different in each programming language.

Here's a proof-of-concept for one "polyglot" function that should work in most programming languages:

```<code>//JavaScript syntax
function proofOfConcept(){
    printSomething("This is just a proof of concept."); //the function printSomething will
    //                      need to be implemented separately in each programming language.
}

//Java syntax
public static void proofOfConcept(){
    printSomething("This is just a proof of concept."); //the function printSomething will
    //                      need to be implemented separately in each programming language.
}

//Python syntax
def proofOfConcept():
    printSomething("This is just a proof of concept."); //the function printSomething will
    //                      need to be implemented separately in each programming language.

//C syntax
void proofOfConcept(){
    printSomething("This is just a proof of concept."); //the function printSomething will
    //                      need to be implemented separately in each programming language.
}
</code>```

Would this be a useful design strategy, or is there a better way to do this? I think this would be a useful strategy for developing libraries in multiple programming languages, althogh it would require a small number of "language-specific" functions to be written for each target language.

答:
The Katahdin programming language was designed to solve this problem. Its documentation includes this example, which combines Fortran and Python functions in one file:</p>

```<code>import "fortran.kat";
import "python.kat";

fortran {
    SUBROUTINE RANDOM(SEED, RANDX)
        INTEGER SEED
        REAL RANDX
        SEED = 2045*SEED + 1
        SEED = SEED - (SEED/1048576)*1048576
        RANDX = REAL(SEED + 1)/1048577.0
        RETURN
    END
}

python {
    seed = 128
    randx = 0
    for n in range(5):
        RANDOM(seed, randx)
        print randx
}
</code>```

Body:
The Katahdin programming language was designed to solve this problem. Its documentation includes this example, which combines Fortran and Python functions in one file:

import "fortran.kat";
import "python.kat";

fortran {
    SUBROUTINE RANDOM(SEED, RANDX)
        INTEGER SEED
        REAL RANDX
        SEED = 2045*SEED + 1
        SEED = SEED - (SEED/1048576)*1048576
        RANDX = REAL(SEED + 1)/1048577.0
        RETURN
    END
}

python {
    seed = 128
    randx = 0
    for n in range(5):
        RANDOM(seed, randx)
        print randx
}


问:
Building presentation layer directly on data layer
My application is currently quite a mess and I'm trying to untangle it all. My current idea is that I should have 3 separate layers:

data layer that knows how to keep stuff in database (and handle data schema changes, so it's not really that trivial)

domain layer (is that correct name?) that does all the magic changing the objects and processing events triggered by user requests

presentation layer that knows how to show to user only what that user is allowed to know (some data is hidden from user just because)

My initial idea was that having a data object I can build domain object from it, then build a view object from that one and then serve it to user. However I'm now thinking about building view object directly from data object.

If the user just queries some information, I fetch the data from database, get the nice presentation of it, then serve it to user. Not touching the domain layer at all.

If user performs an action, I fetch the data, build models from it, do the magic object interaction, save it all back to data layer, then wrap it into presentation and serve.

How bad is such design?

Unfortunately I am not well-versed in software architecture/design terminology thus I might be failing to find the answer just because I don't know how to name things.

Edit: I don't mean to discard the Model part completely. I just mean that I will have Model sitting on Data and View sitting on Data too.

答:
Consider working for awhile with an MVC framework like ASP.NET MVC or Ruby on Rails.

In these frameworks, most of the architectural decisions are made for you by convention.  So you will be building a simple application on well-trodden ground.  After awhile, you will begin to realize that most of the architecture is really not all that difficult to comprehend, and essentially boils down to three simple principles:

Organization,

Decoupling, and

Separation of Concerns.

In MVC, the View has only one function: to show something to the user.  It is decoupled from the Model via objects called ViewModels, which take data from the Model and transform it into the "shape" needed by the View in order for the view to properly display it.  The Controller and the routing engine collectively form a switchyard, shunting requests from the web browser to an appropriate method for execution.

The Model contains everything else; your data, and all of your business logic.  You can complicate this all you like, but the most typical way is either to create a service layer or repository.  One one side of the repository is your data layer, on the other side are your controllers.

After a little while longer, you begin to realize that MVC is really just a UI metaphor and some endpoints that marry your URLS with application functionality.  Your model and service layer, if designed correctly, can live quite happily just as easily in a Winforms application or a mobile application, so it only has to be written once.


答: You should have a Model, which encapsulate your business logics, and maybe a Viewmodel, if the data you are presenting is very different from your Model. The point is, trying avoid any business logic in your view layer, and make it really a dummy one. This way, your app is easy to test (UI is notoriously hard to test).</p>

Title: Building presentation layer directly on data layer

Body:
My application is currently quite a mess and I'm trying to untangle it all. My current idea is that I should have 3 separate layers:

data layer that knows how to keep stuff in database (and handle data schema changes, so it's not really that trivial)

domain layer (is that correct name?) that does all the magic changing the objects and processing events triggered by user requests

presentation layer that knows how to show to user only what that user is allowed to know (some data is hidden from user just because)

My initial idea was that having a data object I can build domain object from it, then build a view object from that one and then serve it to user. However I'm now thinking about building view object directly from data object.

If the user just queries some information, I fetch the data from database, get the nice presentation of it, then serve it to user. Not touching the domain layer at all.

If user performs an action, I fetch the data, build models from it, do the magic object interaction, save it all back to data layer, then wrap it into presentation and serve.

How bad is such design?

Unfortunately I am not well-versed in software architecture/design terminology thus I might be failing to find the answer just because I don't know how to name things.

Edit: I don't mean to discard the Model part completely. I just mean that I will have Model sitting on Data and View sitting on Data too.


答:
My personal preference is to allow multiple returns at the very beginning and the very end, but not in the middle (where they could be easily missed).

Of course, one might argue that if a subroutine is so long that it has a "beginning", "middle" and "end", it is too long anyway.

I am specifically fond of using the trailing Perl-style conditionals as sort-of "guard expressions" (example in pseudo-Ruby, but applies equally to other languages):

```<code>def sort(list)
  return []         if list.empty?
  return list.clone if list.size == 1
  ... actual sorting here
end
</code>```

Or in Python:

```<code>def sort(list):
  if not list:       return []
  if list.size == 1: return list.clone
  ... actual sorting here
end
</code>```

Title: Python - only one return per method?

Body:
I'm trying to sort out whether this is just a personal preference thing or whether it's actually bad practice to do this one way or another. I did try to reference PEP8 first, and I did not see an answer.

What I'm talking about here is the use of more than one return statement. In these examples, it's not such a big deal, as they are very short and easily read.

```<code>def foo(obj):
    if obj.condition:
        return True
    return False

def bar(obj):
    answer = False
    if obj.condition:
        answer = True
    return answer
</code>```

It bugs me to assign a variable every time bar() is called, instead of just determining the answer and returning it. But in a longer function a second return might be hidden and so someone reading the code may have not realized that the function might return a value before hitting the end of the line:

```<code>def spam(obj):
    blurb = "Francis"
    if obj.condition:
        blurb = map(gormf, [z for z in porp(obj)])
        return blurb[2]
    elif not obj.condition and dreg(obj.jek):
        blurb = obj.hats * 17
        if blurb % 13: return blurb
    else:
        blurb = obj.name
    return "Whales and %s" blurb
</code>```

That's a terrible function, but I think you see what I'm poking at.

So is it preferable to create a function to have a single, clear exit - even if it's a few more operations than you actually need? Or should one try to root this out whenever possible in favor of shorter code?

Body:
My personal preference is to allow multiple returns at the very beginning and the very end, but not in the middle (where they could be easily missed).

Of course, one might argue that if a subroutine is so long that it has a "beginning", "middle" and "end", it is too long anyway.

I am specifically fond of using the trailing Perl-style conditionals as sort-of "guard expressions" (example in pseudo-Ruby, but applies equally to other languages):

def sort(list)
  return []         if list.empty?
  return list.clone if list.size == 1
  ... actual sorting here
end

Or in Python:

def sort(list):
  if not list:       return []
  if list.size == 1: return list.clone
  ... actual sorting here
end


问:
What's in a name? Revision vs Timestamp
Apparently naming things is one of the hardest things in programming..!

I have a synchronisation implementation which uses timestamps (number of seconds since unix epoch) to sync.

Currently, the timestamps have simply replaced an older revision field. My question is, does it make sense to name it "Revision" or is "Timestamp" better?

Revision makes sense to me since that's what's used to version an entity - to know what's created, updated, deleted. But if I needed to increase the granularity of the revision field in the future (ie. to become a decimal, to include fractions of a second), I wouldn't be sure that a decimal revision would make sense. On the other hand, perhaps I want to move away from timestamps in the future (ie. to sequence numbers) in which case revision would make sense.

答:
If it's simply a time stamp, and that is its only function, then call it a timestamp.  If it has a larger purpose (i.e. Revision), then name it that.

Generally, it is better to name things by their function rather than their type.  As you yourself pointed out, the type can change over time.

Title: What's in a name? Revision vs Timestamp


答:
Revision implies that the field is updated when the object is changed. Revision does not necessarily imply that the field is a date/time, just that value is bumped each time the object is revised.

Timestamp implies that the field refers to the date/time that something happened. What? That's not implicitly clear. Last change? Creation? Last time examined? The world can be used to refer to any of these conditions, so often another word is added to indicate what you're tracking -- "Creation Timestamp", "Modification Timestamp", etc.

Title: What's in a name? Revision vs Timestamp

Body:
Apparently naming things is one of the hardest things in programming..!

I have a synchronisation implementation which uses timestamps (number of seconds since unix epoch) to sync.

Currently, the timestamps have simply replaced an older revision field. My question is, does it make sense to name it "Revision" or is "Timestamp" better?

Revision makes sense to me since that's what's used to version an entity - to know what's created, updated, deleted. But if I needed to increase the granularity of the revision field in the future (ie. to become a decimal, to include fractions of a second), I wouldn't be sure that a decimal revision would make sense. On the other hand, perhaps I want to move away from timestamps in the future (ie. to sequence numbers) in which case revision would make sense.


答: If you skip your business or domain layer the issue is that you will need to put your business logic somewhere, and it will likely end up in both your ui and data layer, which will make your application increasingly difficult to maintain.  The other issue is that your ui and data layer will likely need to be replaced, such a when you want to move to wpf from winforms, or SQL to EF.  So even though it might take a bit longer, create your business later up front, with proper unit tests.</p>


答: Revision to me is a count of how many times the object has been edited, and possibly even with an audit history. A timestamp though is just that, a stamp of he last time changed, often used for concurrency checks.  I'd obsolete the old property and create a new one for the timestamp.</p>

Title: What's in a name? Revision vs Timestamp


问:
Why isn't Java more widely used for game development?
I'm not a game developer or anything, but I know that Java is not very widely used for game development. Java should be fast enough for most games, so where's the catch? I can think of some reasons:

Lack of game developers with expertice in Java

Lack of good game development frameworks

Programmers don't want to accept Java as a games programming language. Most only accept C++ as that?

No support for game consoles (though the PC market still exists)

It could of course be something else. Could someone who knows the business better than me explain why Java isn't getting momentum when it comes to game development?

答:
Okay, theres a lot of misinformation in this thread.

I know the game business extremely well, having been in it for 25 years. I also know Java in games extremely well having been Sun's Java Game technical evangelist and lecturing Java performance programming expert.

In terms of computational speed, Java beats C++ in many scientific computing benchmarks today.  You can write pathological code in either language that performs badly if you want to, but over-all, they are at par and have been for a long time.

In terms of memory usage, Java does have some over-head.  HelloWorld is a 4K program in java.  But that overhead is pretty meaningless in todays multi GB systems.  Finally, Java does have more of a startup time.  I would not recommend using Java for short run-time utilities like Unix command line commands.  In those cases startup will dominate your performance.  In a game however, its fairly insiginficant.

Properly written Java game code does not suffer GC pauses.  Just like C/C++ code, it does require some active memory management but not to the level C/C++ does.  As long as you keep your memory usage to either long lived objects (persist for an entire level or game) and very short lived objects (vectors and such, passed around and quickly destroyed after calculation) gc should not be a visible issue.

In terms of direct memory access, Java has had that for a LONG time; since Java 1.4 in the form of Native Direct Byte Buffers.  Bit twiddling in Java can be slightly annoying due to the lack of unsigned integer types but the work rounds are all well known and not terribly onerous.

While its true Java has never had a Direct3D binding, thats because Java technologies strive for portability.  It has TWO OpenGL bindings (JOGL and LWJGL) and OpenAL binding (JOAL) and a portable input binding (JInput) that binds under the hood to DirectInput on Windows, HID Manager on OSX, and a Linux binding (I forget which).

Its true that no complete game engines have featured Java the way, say Unity, has featured C# and that is a weakness in the independent space.  On the other hand, there were two good Scenegraph level APIS that were totally platform portable across Windows, OSX and Linux.  Both written by Josh Slack, the first was called JMonkey engine and the second Ardor3D.

The top poster is correct that the two biggest things that held Java back in game development were prejudice and portability.  The latter was the biggest issue.  Although you could write a Java game and ship it on Windows, OSX and Linux, there was never a console VM.  This was due to total ineptitude in Sun middle management.  The few of us working on Java in games actually had deals with Sony no less then 3 times to get a VM on a Playstation and all 3 times Sun middle management killed it.

While Sun flirted with client technologies, the fact of the matter is that Sun management never got consumer products.  Thats why Java as a client language from Sun never succeeded in any form, and why it took Google and Dalvik (the Android java-like VM) to make Java a platform success anywhere.

And thats why I code games in C# today.  Because Mono went where Sun management refused to.


问:
Derivations in BNF
I get how to do a derivation of a BNF. My text books do a good job of explaining it (much better than the on-line lecture notes of many profs etc). Example below then my questions:

```<code><program> => begin <stmt_list> end
<stmt_list> => <stmt>
                   | <stmt>; <stmt_list>
<stmt> => <var> = <expression>
<var> => A | B | C;
<exression> => <var> + <var>
                   |<var> - <var>
                   |<var>
</code>```

Generates:

```<code><proogam> => begin<stmt_list> end
      => begin<stmt>;<stmt_list> end
      => begin<var> = <expression>;<stmt_list>end
      => begin a = <expression>;<stmt_list>end
      => begin a =  <var> + <var>;<stmt_list>end
      => begin a = b + <var> ; <stmt_list>end
      => begin a = b + c ; <stmt_list> end
      => begin a = b + c; <var> = <expression>; <stmt_list>end
      => begin a = b + c; b  = <expression>; end
      => begin a = b + c; b = <var> + <var>;<stmt_list> end
      => begin a = b + c; b = c + <var>; <stmt_list> end
      => begin a = b + c; b = c + a; <stmt_list> end
      => begin a = b + c; b = c + a; <var> + <expression>
      => begin a = b + c; b = c + a; c = <expression>;
      => begin a = b + c; b = c + a; c = <var>;
      => begin a = b + c; b = c + a;  c = b;
</code>```

I get the how mostly and I know the benefit of BNF. But regarding derivations, why do we do them token by token when it's quite obvious what the resultant code would be?

Also, with BNF derivation, when an OR is used in the syntax how do we translate this? Such as:

```<code><if_stmt>  if (<logic_expr>) <stmt>|
                   if (<logic_expr>) <stmt> else <stmt>
</code>```

答:
Because the resultant structure will not be obvious to a compiler. A compiler will move through the grammar, step by step, in a systematic fashion. In practice, there are techniques that can shortcut this but if we want to formally and rigorously reason about grammars, we want it to all be as explicit as possible.

This directly leads to the OR syntax. The if_stmt is either if (<logic_expr>) <stmt> or if (<logic_expr>) <stmt> else <stmt>. This means that we can then nest ifs within elses and so forth. Otherwise, they are two entirely different statements and like I said before, we want to be as explicit as possible with BNF grammars. Grammars for computers must be unambiguous. If we leave out steps or are careless with how we array our grammatical structures, we can wind up with ambiguous grammars in short order. This in-turn can lead to substantial compiler errors.

Example:

```<code>some_statment ::= statement_components
    | other_possible_configuration
    | another_possible_configuration
    | yet_another_configuration
</code>```

In the above example, each pipe (properly a Sheffer Stroke) functions as a "guard" that acts kind of like a case statement in a programming language. You fall through the options until you reach one that matches and then that one gets selected (technically you do it backwards when parsing but I digress).

Title: Derivations in BNF

Body:
Because the resultant structure will not be obvious to a compiler. A compiler will move through the grammar, step by step, in a systematic fashion. In practice, there are techniques that can shortcut this but if we want to formally and rigorously reason about grammars, we want it to all be as explicit as possible.

This directly leads to the OR syntax. The if_stmt is either if (<logic_expr>) <stmt> or if (<logic_expr>) <stmt> else <stmt>. This means that we can then nest ifs within elses and so forth. Otherwise, they are two entirely different statements and like I said before, we want to be as explicit as possible with BNF grammars. Grammars for computers must be unambiguous. If we leave out steps or are careless with how we array our grammatical structures, we can wind up with ambiguous grammars in short order. This in-turn can lead to substantial compiler errors.

Example:

some_statment ::= statement_components
    | other_possible_configuration
    | another_possible_configuration
    | yet_another_configuration

In the above example, each pipe (properly a Sheffer Stroke) functions as a "guard" that acts kind of like a case statement in a programming language. You fall through the options until you reach one that matches and then that one gets selected (technically you do it backwards when parsing but I digress).


问:
Examples of designing a database that handles point tracking?
I'm attempting to expand my knowledge of how database designs and concepts work. I'm working on a hobby web/mobile app for practice that will challenge me. However, I am running into an issue.

What my novel concept is that there are two buttons 'yes' and 'no'.

The buttons can only be clicked once a day.

If 'yes' is clicked then a counter keeps tracks of how many clicks (days) it has been pushed. Example "You've tied your shoes 95 days in a row!"

If 'no' is clicked then the counter "resets" for example "It has been 0 days since you've tied your shoe."

I've done some reading but I haven't been able to find too many examples that are like this.
I've read several posts here (a sample of them below)
(
implementing dynamic query handler on historical data

Storing stop/start points in a database

In an online questionnaire, what is a best way to design a database for keeping track of users all attempts?
)

but I'm still pretty confused on how to move forward. My initial idea was to have a

user table (id | user | password)

points table (id | point | date)

If a person clicks on yes then it adds an entry into the points table. If they don't click anything then no entry occurs. If they click no it's a -1.

However, I'm not certain this is a solid way to build out the database especially if I want to track it.

My questions are:

Given the few tasks above, how to setup the database?

How would I be able to display a counter that once someone hits no it 'resets'? For example the database tracks that the individual has tied their shoes for the last 9 days in a row but once they say no they didn't tie their shoes the counter resets to 0.

How to proceed with analytics side, to show how many times they've clicked no, yes, so on but that's down the road.

答:
If I understand correctly, you have 3 distinct bits of information: user, date, state (yes/ no)

So create a table with those fields (plus a unique primary key).

You can then query this table to find how many yeses there have been in a row, whether to show the buttons for the current day, yeses per month etc


问:
How do searches fit into a RESTful interface?
When designing a RESTful interface, the semantics of the request types are deemed vital to the design.

GET - List collection or retrieve element

PUT - Replace collection or element

POST - Create collection or element

DELETE - Well, erm, delete collection or element

However, this doesn't seem to cover the concept of "search".

E.g. in designing a suite of web services that support a Job Search site you might have the following requirements:

Get individual Job Advert

GET to domain/Job/{id}/

Create Job Advert

POST to domain/Job/

Update Job Advert

PUT to domain/Job/

Delete Job Advert

DELETE to domain/Job/

"Get All Jobs" is also simple:

GET to domain/Jobs/

However, how does the job "search" fall into this structure?

You could claim it's a variation of "list collection" and implement as:

GET to domain/Jobs/

However, searches can be complex and it's entirely possible to produce a search that generates a long GET string.  That is, referencing a SO question here, there are issues using GET strings longer than about 2000 characters.

An example might be in a faceted search - continuing the "job" example.

I may allow for searching on facets - "Technology", "Job Title", "Discipline" as well as free-text keywords, age of job, location and salary.

With a fluid user interface and a large number of technologies and job titles, it is feasible that a search could encompass a large number of facet choices.

Tweak this example to CVs, rather than jobs, bring in even more facets, and you can very easily imagine a search with a hundred facets selected, or even just 40 facets each of which are 50 characters long (e.g. Job Titles, University Names, Employer Names).

In that situation it might be desirable to move a PUT or POST in order to ensure that the search data will get correctly sent.  E.g.:

POST to domain/Jobs/

But semantically that's an instruction to create a collection.

You could also say you'll express this as the creation of a search:

POST to domain/Jobs/Search/

or (as suggested by burninggramma below)

POST to domain/JobSearch/

Semantically it may seem to make sense, but you're not actually creating anything, you're making a request for data.

So, semantically it's a GET, but GET isn't guaranteed to support what you need.

So, the question is - Trying to keep as true to RESTful design as possible, whilst ensuring that I'm keeping within the limitations of HTTP, what is the most appropriate design for a search?

答:
TL;DR: GET for filtering, POST for searching

I make a distinction between filtering the results from listing a collection vs a complex search.  The litmus test I use is basically if I need more than filtering (positive, negative, or range) I consider it a more complex search requiring POST.

This tends to be reinforced when thinking about what will be returned.  I usually only use GET if a resource has a mostly complete life-cycle (PUT, DELETE, GET, collection GET). Typically in a collection GET I'm returning a list of URIs which are the REST resources that make up that collection.  In a complex query I may be pulling from multiple resources in order to construct the response (think SQL join) so I won't be sending back URIs, but actual data.  The problem is the data will not be represented in a resource, so I will always have to return data.  This seems to me a clear cut case of requiring a POST.

--

It's been awhile and my original post was a bit sloppy so I thought I would update.

GET is the intuitive choice for returning most kinds of data, collections of REST resources, structured data of a resource, even singular payloads (images, docs, etc).

POST is the catchall method for anything that doesn't seem to fit under GET, PUT, DELETE, etc.

At this point I think simple searches, filtering do intuitively make sense through GET.  Complex searches is up to personal preference especially if you are throwing in aggregation functions, cross correlations (joins), re-formatters, etc.  I would argue the GET params should not get too long, and it a largish query (however it's being structured) can often make more sense as a POST request body.

I also consider the experience aspect of API usage.  I generally want to make most of the methods as easy to use and intuitive as possible. I'll push calls that are more flexible (and therefore more complex) into POSTs and on a different resource URI, especially if it's inconsistent with the behavior of other REST resources in the same API.

Either way, consistency is probably more important than whether you are doing search in GET or POST.

Hope this helps.

ContentLicense: CC BY-SA 4.0


问:
how should I change the representation (not mimetype) of a resource?
I'm looking at how I can change the representation of a payload at runtime for varied potential advantages, but I'm not sure how to do it. Specifically collections.

Array of Pairs

```<code>[{ <resource_uri> : { <entity> }, ...}]
</code>```

Array of Objects

```<code>[<entity>,...]
</code>```

Array of Resources

```<code>[<resource_uri>]
</code>```

Map of entities

```<code>{ <resource_uri> : { <entity> }, ... }
</code>```

My problem is, I'm not sure if I should put these different representations of the sets at different URI's, give them slightly varied mime types, e.g. application/foomap+json or perhaps use an optional query parameter ?format=map, or resource /entities/map. The UI is going to hide this, this is for programmatic web service access only (which the "UI's JS will have to call).

答:
TL;DR: Not mime types. Probably query parameters

When writing REST APIs I usually have the underlying structure of my responses the same, regardless of mime type.  The mime type is just the particular representation of the underlying structure.  This allows for things like caching to not care what the mime type is because the data is the same.

Using a query parameter seems like the best option to provide a way to vary the actual structure in the response.

Although I do like the concept of creating something akin to a view resource which would allow you to restructure and rename other resource responses.


问:
How to structure a set of RESTful URLs
Kind of a REST lightweight here... Wondering which url scheme is more appropriate for a stock market data app (BTW, all queries will be GETs as the client doesn't modify data):

Scheme 1 examples:

```<code>/stocks/ABC/news
/indexes/XYZ/news
/stocks/ABC/time_series/daily
/stocks/ABC/time_series/weekly
/groups/ABC/time_series/daily
/groups/ABC/time_series/weekly
</code>```

Scheme 2 examples:

```<code>/news/stock/ABC
/news/index/XYZ
/time_series/stock/ABC/daily
/time_series/stock/ABC/weekly
/time_series/index/XYZ/daily
/time_series/index/XYZ/weekly
</code>```

Scheme 3 examples:

```<code>/news/stock/ABC
/news/index/XYZ
/time_series/daily/stock/ABC
/time_series/weekly/stock/ABC
/time_series/daily/index/XYZ
/time_series/weekly/index/XYZ
</code>```

Scheme 4: Something else???

The point is that for any data being requested, the url needs to encapsulate whether an item is a Stock or an Index. And, with all the RESTful talk about resources I'm confused about whether my primary resource is the stock & index or the time_series & news. Sorry if this is a silly question :/

Thanks!

答:
TL;DR: Scheme 3

If you only ever support the individual "leaf" resources then it doesn't make much of a difference.  If you consider extending functionality to GET'ting collections; then I think scheme 3 becomes the obvious choice.  It creates a more usable hierarchy for querying.  You can get all the relevant news for that user, or possibly filtered by any attribute.  The time series data could also be made more interesting if filtering was supported so I could query for all entries that went above or below a threshold.

Title: How to structure a set of RESTful URLs


问:
Tablet development for a dedicated system
I need to make an architectural decision for developing (actually porting) my embedded solution on a tablet.

The choice comes down to Ubuntu or Android, so I have some specific questions to help me decide.

On Android, is it possible to develop applications outside of Dalvik, using Python? If yes, can I access the hardware this way, without the API's provided by the Android SDK?

On Android, can I control the process' core_affinity to bind a process to a single core? And can i use isolcpus to isolate other processes from that core making it a (almost) dedicated core for a process? This is possible in regular linux, not sure if it can be done in Android.

On Ubuntu, how much control over the HW do I have outside Ubuntu SDK?

答:
Start with the proposition that an application has a user interface. How do you want that to look and behave? You have 4 choices.

Android native. You're going to write Java, but you can extend it in C++ using the NDK.

HTML5/Javascript. You're probably going to write Javascript, but you can extend it using a server or a wormhole.

Renderer. You can write any language you like because you're going to be drawing your own widgets on a render surface, and they won't be native.

Somebody's devkit. It will eventually do one of the above. Xamarin, Qpython, QT, etc. Whatever.

There is a lot to read eg (https://stackoverflow.com/questions/101754/is-there-any-way-to-run-python-on-android). None of it matters until you decide what kind of UI you want. If you want native you are going to write Java.

In answer to your questions:

Yes, can write and run code, basically via the NDK or similar. Doesn't help with the UI.

Dunno, but once you get down to the NDK you can do most stuff.

Ubuntu is not Android. I'll leave that to others.

Regarding the NDK, I can tell you that it provides a reasonably fully-featured C++ development environment. Most (but not all) standard C++ library features are provided, as well as a set of APIs that hook into the Android process APIs (so you can write Activities entirely in C++), and a JNI capability.

There are device APIs (things like the accelerometer and GPS) that are intended to be accessed from Java, so we go via JNI. You may be able to access devices directly from C++, but I would expect you would tend to lose portability (across manufacturers) and higher level features.

Below that there are device drivers, a HAL, a Linux kernel and other interesting things. If that's where you want to play, there is plenty to read: http://s.android.com/devices/index.html.


答:
Just my opinion, but I would call it timestamp (or more precisely, modification timestamp), not revision.

It is a timestamp, so when it's named timestamp, someone seeing the field can infer when the file was last changed, whereas when it's called revision, people might be confused to see a huge number, like 1395653358, when it's just the first or second revision of the file.

If you want to change the format of the field, e.g. towards using decimal time (fractions of seconds) or a revision count, I would suggest using a different field for that, anyway. Imagine the confusion when the value of the revision field is 1395653358, and then for the next revision it's 3!

Having said that, the best option might be to create a dedicated class for this. This not only hides the internal representation (which can also be made up of several field, like date of creation and last change, revision count, comment, etc.), but can provide methods for comparing revisions or generating new revision numbers, whatever format is internally used.

Title: What's in a name? Revision vs Timestamp


问:
Do you experiment with unconventional ways to use design patterns?
We stick to standard usages and best practices because they work and communicate intent well, but without trying new things we can't really grow. Have you ever tried something that seemed absurd but worked out really well? When it works, how do you avoid confusing other developers with non-standard usages? And what do you do when things go horribly wrong - refactor, start over, or just go with it?</p>

答:
Yes, but with simplicity wrappers.

Most users will only need to access through the simplicity wrappers. The system would be very familiar to them, because the simplicity wrappers are designed to be very similar to the older systems. However, advanced users who need extra power, and developers on the new system team, will need to become fluent in the new pattern.

If things go horribly wrong, the entire project has to be thrown away. This is why early feedback (integration) is important, so that you can stop loss earlier.

Also, put some effort on educating your fellows about the inside, and any special precautions needed. Put a lot of effort on testing.