答:
Consider the cost/benefit ratio of your two options:

Would reusing the same name cause confusion or naming conflicts? Probably not, since they're in different folders. The name "player_stats/generator.js" is equivalent to "player_stats_generator.js". However, if you see, in the future, a reason to merge your js files into a single directory (deployment? I dunno), then this should be a good indicator to give unique names.

Would using the longer names involve a lot of extraneous typing? Probably not. Not only do many JS IDEs autocomplete filenames in the project for you, it's also a piece of code that's probably only written - at most - once per file. The code that gets typed a lot is the classes and functions inside the js files, and those (hopefully) don't conflict.

When debugging, what sort of information do you get about an error? If the most common bug report is "Error in line 34 of <filename.js>", then consider giving them unique names, since receiving errors in just generator.js and then trying to divine, through context, which generator it was can be a hassle.

Title: Is it a bad practice to give two very different files with the same general purpose the same name?

Body:
Is it a bad practice to give two very different files with the same general purpose the same name, separating them into different directories?

```<code><script src="client_scripts/app/player_stats/generator.js"></script>
<script src="client_scripts/app/coach_settings/generator.js"></script>
</code>```

I'd like to keep my file names short, and both of the files have the same general purpose without being identical. I'm not sure whether or not this would be considered a bad practice in a professional programming environment. I'd like to know what the best practice is in this situation.

Alternatively, at the expense of the name's short length, I could use:

```<code><script src="client_scripts/app/player_stats/player_stats_generator.js"></script>
<script src="client_scripts/app/coach_settings/coach_settings_generator.js"></script>
</code>```


问:
Print the next smallest from 2^i * 5^j where i,j >= 0
I was asked this question during a technical phone screening recently and didn't do well. The question is included verbatim below.

Generate {2^i * 5^j | i,j >= 0} sorted collection. Continuously print the next
  smallest value.

Example: { 1, 2, 4, 5, 8, 10...}

"Next smallest" makes me think a min-heap is involved, but I didn't really know where to go from there and no assistance was provided by the interviewer.

Does anyone have advice on how to solve such a problem?

答:
The set-based solution was probably what your interviewer was looking for, however, it has the unfortunate consequence of having O(n) memory and O(n lg n) total time for sequencing n elements.

A bit of math helps us find a O(1) space and O(n sqrt(n)) time solution. Notice that 2^i * 5^j = 2^(i + j lg 5). Finding the first n elements of {i,j > 0 | 2^(i + j lg 5)} reduces to finding the first n elements of {i,j > 0 | i + j lg 5} because the function (x -> 2^x) is strictly monotonically increasing, so the only way for some a,b that 2^a < 2^b is if a < b.

Now, we just need an algorithm to find the sequence of i + j lg 5, where i,j are natural numbers. In other words, given our current value of i, j, what minimizes the next move (i.e., gives us the next number in the sequence), is some increase in one of the values (say j += 1) along with a decrease in the other (i -= 2). The only thing that's limiting us is that i,j > 0.

There are only two cases to consider - i increases or j increases. One of them must increase since our sequence is increasing, and both don't increase because otherwise we're skipping the term in which we only have one of i,j increase. Thus one increases, and the other stays the same or decreases. Expressed in C++11, the whole algorithm and its comparison to the set solution are available here.

This achieves constant memory since there are only a constant amount of objects allocated in the method, aside from the output array (see link). The method achieves logarithmic time every iteration since for any given (i,j), it traverses for the best pair (a, b) such that (i + a, j + b) is the smallest increase in the value of i + j lg 5. This traversal is O(i + j):

```<code>Attempt to increase i:
++i
current difference in value CD = 1
while (j > 0)
  --j
  mark difference in value for
     current (i,j) as CD -= lg 5
  while (CD < 0) // Have to increase the sequence
    ++i          // This while will end in three loops at most.
    CD += 1
find minimum among each marked difference ((i,j) -> CD)

Attempt to increase j:
++j
current difference in value CD = lg 5
while (j > 0)
  --i
  mark difference in value for
     current (i,j) as CD -= 1
  while (CD < 0) // have to increase the sequence
    ++j          // This while will end in one loop at most.
    CD += lg 5
find minimum among each marked difference ((i,j) -> CD)
</code>```

Every iteration attempts to update i, then j, and goes with the smaller update of the two.

Since i and j are at most O(sqrt(n)), we have total O(n sqrt(n)) time. i and j grow at the rate of the square of n since for any maximum valiues imax and jmax there exist O(i j) unique pairs from which to make our sequence if our sequence is n terms, and i and j grow within some constant factor of one another (because the exponent is comprised of a linear combination fo the two), we know that i and j are O(sqrt(n)).

There's not too much to worry about regarding floating point error - since the terms grow exponentially, we'd have to deal with overflow before flop error catches up with us, by several magnitudes. I'll add more discussion to this if I have time.

ContentLicense: CC BY-SA 3.0

Body:
The set-based solution was probably what your interviewer was looking for, however, it has the unfortunate consequence of having O(n) memory and O(n lg n) total time for sequencing n elements.

A bit of math helps us find a O(1) space and O(n sqrt(n)) time solution. Notice that 2^i * 5^j = 2^(i + j lg 5). Finding the first n elements of {i,j > 0 | 2^(i + j lg 5)} reduces to finding the first n elements of {i,j > 0 | i + j lg 5} because the function (x -> 2^x) is strictly monotonically increasing, so the only way for some a,b that 2^a < 2^b is if a < b.

Now, we just need an algorithm to find the sequence of i + j lg 5, where i,j are natural numbers. In other words, given our current value of i, j, what minimizes the next move (i.e., gives us the next number in the sequence), is some increase in one of the values (say j += 1) along with a decrease in the other (i -= 2). The only thing that's limiting us is that i,j > 0.

There are only two cases to consider - i increases or j increases. One of them must increase since our sequence is increasing, and both don't increase because otherwise we're skipping the term in which we only have one of i,j increase. Thus one increases, and the other stays the same or decreases. Expressed in C++11, the whole algorithm and its comparison to the set solution are available here.

This achieves constant memory since there are only a constant amount of objects allocated in the method, aside from the output array (see link). The method achieves logarithmic time every iteration since for any given (i,j), it traverses for the best pair (a, b) such that (i + a, j + b) is the smallest increase in the value of i + j lg 5. This traversal is O(i + j):

Attempt to increase i:
++i
current difference in value CD = 1
while (j > 0)
  --j
  mark difference in value for
     current (i,j) as CD -= lg 5
  while (CD < 0) // Have to increase the sequence
    ++i          // This while will end in three loops at most.
    CD += 1
find minimum among each marked difference ((i,j) -> CD)

Attempt to increase j:
++j
current difference in value CD = lg 5
while (j > 0)
  --i
  mark difference in value for
     current (i,j) as CD -= 1
  while (CD < 0) // have to increase the sequence
    ++j          // This while will end in one loop at most.
    CD += lg 5
find minimum among each marked difference ((i,j) -> CD)

Every iteration attempts to update i, then j, and goes with the smaller update of the two.

Since i and j are at most O(sqrt(n)), we have total O(n sqrt(n)) time. i and j grow at the rate of the square of n since for any maximum valiues imax and jmax there exist O(i j) unique pairs from which to make our sequence if our sequence is n terms, and i and j grow within some constant factor of one another (because the exponent is comprised of a linear combination fo the two), we know that i and j are O(sqrt(n)).

There's not too much to worry about regarding floating point error - since the terms grow exponentially, we'd have to deal with overflow before flop error catches up with us, by several magnitudes. I'll add more discussion to this if I have time.


问:
Is recursion an instance of being "too clever" when programming?
I've read several books and learned through experience that optimizing code to the point where it is inscrutable, or coming up with an extremely fast but extremely complex solution to a problem is not desirable when working in teams, or even when you're working by yourself and have to understand your clever solution some time later.

My question is, should recursion be treated in the same manner?  Does the average programmer understand recursion easily and thus one should use it with impunity, or does the average programmer not understand recursion very well and one should stay away from it for the sake of overall team productivity?

I know there are simple answers of, "Any programmer who doesn't understand recursion isn't worth a grain of salt, so don't worry about them" but I was wondering if you all had some real world experience you would like to share that would illuminate the issue more than the opinion I just mentioned.

答:
Recursion is a foundational principle in most functional programming languages.  Iteration (looping) in functional languages is usually accomplished via recursion.

Functional languages have seen somewhat of a renaissance lately, due to the need to elegantly handle more processor cores; functional languages help achieve this kind of concurrency by providing ways to better reason about your program without the complexity involved in locking mutable structures.

ContentLicense: CC BY-SA 2.5


问:
Is it a bad practice to give two very different files with the same general purpose the same name?
Is it a bad practice to give two very different files with the same general purpose the same name, separating them into different directories?

```<code><script src="client_scripts/app/player_stats/generator.js"></script>
<script src="client_scripts/app/coach_settings/generator.js"></script>
</code>```

I'd like to keep my file names short, and both of the files have the same general purpose without being identical. I'm not sure whether or not this would be considered a bad practice in a professional programming environment. I'd like to know what the best practice is in this situation.

Alternatively, at the expense of the name's short length, I could use:

```<code><script src="client_scripts/app/player_stats/player_stats_generator.js"></script>
<script src="client_scripts/app/coach_settings/coach_settings_generator.js"></script>
</code>```

答:
Just as a practical matter, if your IDE shows file names in tabs, if you use the same name for each file, you'll end up with tabs that all show the same name.  That can be very annoying. One project I took over maintaining has that problem, and it is a major pain to have 15 tabs open, half of them with the same file name.

So... use more descriptive names.


问:
If the UI layer depends on the Application layer. Who starts the application/process?
This is related to DDD for a desktop application in c#...with 4 layers ui/application/domain/infrastructure. Actually 3 desktop applications sharing part of the domain and part of the infrastructure.

In an effort to avoid developers crossing the wrong layers and using the wrong classes, I separated the layer in assemblies and set the reference/dependencies in accordance. If the infrastructure is a dll/assembly and the domain another dll/assembly and the application is an exe/assembly and the ui is a dll/assembly... then the project cannot the build. Who's gonna load the the ui.dll? Am I missing something here?

The only solution i have come with is creating a fifth layer called Program. That layer will have the entry point of the program and will wire everything together (I'm using DI with Unity )

Any idea?

答: The Program solution seems fine to me. Thats usually how it really is. And if you are worried about developers putting stuff in wrong assemblies, you should either apply some kind of code review process. Or if you want to go into extreme, separate them by "project". Eg. Domain could be it's own separate project with separate feature and bug tracking, planning, release, etc.. That is only way to actually force complete separation of the domain.</p>


问:
What's so difficult about SVN merges?

Possible Duplicate:

  I’m a Subversion geek, why should I consider or not consider Mercurial or Git or any other DVCS?

Every once in a while, you hear someone saying that distributed version control (Git, HG) is inherently better than centralized version control (like SVN) because merging is difficult and painful in SVN.  The thing is, I've never had any trouble with merging in SVN, and since you only ever hear that claim being made by DVCS advocates, and not by actual SVN users, it tends to remind me of those obnoxious commercials on TV where they try to sell you something you don't need by having bumbling actors pretend that the thing you already have and works just fine is incredibly difficult to use.

And the use case that's invariably brought up is re-merging a branch, which again reminds me of those strawman product advertisements; if you know what you're doing, you shouldn't (and shouldn't ever have to) re-merge a branch in the first place.  (Of course it's difficult to do when you're doing something fundamentally wrong and silly!)

So, discounting the ridiculous strawman use case, what is there in SVN merging that is inherently more difficult than merging in a DVCS system?

答:
There is nothing too difficult about SVN merging... anymore... if you follow the right philosophy

What I see in most other answers seems to come from people who haven't used SVN in a while. As someone accurately mentions: "it wasn't fixed early enough to dispel the myth".

From my current experience of using SVN 1.6 to 1.8 on a legacy project I inherited recently, SVN has gone a long way towards making merging a much easier thing. It is not foolproof, though, and I think it does not easily suffer users deviating from the intended use.

While I knew SVN quite well and had also tried Mercurial for personal projects in the meantime, I had never done a lot of branching in SVN prior to this project. There was quite a bit of trial and error and I got a lot of unexpected merge conflicts when I started.

Ultimately, though, I realized that everytime I got one (or some other issue), it was because I hadn't done things properly (aka "the SVN way" -- arguably, the proper version control way). I believe this is where the difficulty lies: you cannot do whatever you want in an unorganized way and expect SVN to work perfectly, especially with merges. Merges require rigorous discipline from the user(s) before they show their true power.

Here are things I've noticed are strong recommendations, if not requirements, for a clean use of merges:

Use a recent version of SVN (1.6 and up in my opinion). More and more automation and checks are done for you.

Use the default "trunk, branches, tags" structure and apply its philosophy (don't commit to tags). SVN won't check anything for you. If you use a tag as a branch (that's the state I found that project repository in), it can still work, but you need to be consistent.

Know what branches are and when to create them. Same with tags.

Keep side branches up-to-date with their source branch (usually trunk, but you can branch out from any branch technically). This is mandatory IF you want SVN to do auto-merges. SVN 1.8 actually prevents you from auto-merging if things are not up-to-date, and also if you have pending modifications in your working copy (this behavior seems to have disappeared again in 1.8.5).

Do "proper" commits. They should only contain modifications on a very specific concept. As much as possible, they should contain a small amount of change. You do not want to have a single commit contain modifications about two independant bugs for example. If you have already fixed both and they're in the same file, you should store away the changes of one bug so you can commit just the changes of the other first, then commit the second set of changes. Note that TortoiseSVN allows this easily through "Restore after commit".

Doing so makes it possible to revert a specific independant set of changes AND makes it possible to only merge such a set into another branch. Yes, SVN allows you to merge cherry-picked revisions.

If you ever use sub-branches (branching off trunk, then branching off that new branch), respect the hierarchy. If you update the sub-branch with the trunk or vice versa, you're in for some pain. Merges should be cascaded down or up the hierarchy.

After a few months of experimenting, I can vouch that this might be the most important part. Tried creating two sub-branches from the same trunk and then merging bits between the sub-branches, or sometimes between sub-sub-branches from either side. This can trip up SVN (or the user). It can work OK if you're merging specific revisions. Auto-merge may have trouble with it.

I have had trouble specifically when synchronizing sub-branch A with trunk, and then trying to merge something from sub-branch A into sub-branch B. SVN seems to think the "synchronize from trunk" revision should legitimately be merged into sub-branch B and this leads to a mass of conflicts.

As much as possible, merge from the root of the branch. Otherwise, SVN will only keep track of the merges done for the sub-folder and when you do try to auto-merge from the root, you may get warnings about missing unmerged revisions. It's fixable by simply merging these from the root, but best avoid the confusion.

Be careful which branch you commit to. If you use Switch to have your working copy point to various branches through time, be sure where you're committing to.

It's especially bad if you really didn't want the change in that branch. I'm still not clear on that one, but depending on how you get rid of it / transfer it into the right branch (reverting, merging), you can get something messy. It's fixable, but you'll either have to merge revision by revision to avoid or immediately solve potential conflicts, or you'll have to fix a possibly more complex conflict after the auto-merge.

Do not keep branches untouched for too long. Actually, it's not a matter of time but of how many revisions were committed to the branch and the trunk and how much changed in these. Merges between two branches, 3-way merges, always get compared to most recent common revision between the branches. The more changes in-between, the more change the automatic merging will fail. This is, of course, much worse if you changed the structure of your code in the meantime (moved or renamed files).

If you don't follow the above, you're quite likely to get conflicts. They're always solvable, but not terribly fun to spend time on.

Oh, one more thing about merging where, from all I've read and tried, SVN really sucks: deleted/moved/renamed files/folders. Apparently, SVN still cannot deal with a file being renamed, deleted or moved in one branch, and its original version modified in another branch... and then merging these together. It just won't know where the file went in one way, and will "forget" the changes in the other way. One change is obviously unsolvable (you either delete or change the file, can't do both), but applying changes to moved/renamed files should work and it doesn't. Hopefully this gets fixed soon.

So, all in all, is SVN merging easy? I guess not. Not in a carefree way, for sure. Is it bad? I don't think so. It only spits back in your face when you use it the wrong way and don't think enough about what you're doing.

Based on this, I can see why people might prefer Mercurial (for example) as it's a little more lenient about these things from my experience and had everything automated from the get-go (at least from the early versions I started with). SVN has caught up quite a bit, though, so it's not worthy of so much bashing anymore.

Title: What's so difficult about SVN merges?


答:
There is a clear deciding factor here: DRY (Don't Repeat Yourself).

Every file name doesn't have to be different; that's what paths are for. Can you imagine how many different system or program files are on your computer? What if each of them had to have a unique name? At some point, we're just making the file name a copy of the path.

If the best description of a Javascript file in the context of client_scripts > app > player_stats really is generator, it's path should be client_scripts/app/player_stats/generator.js.

This question is at programmers.stackexchange.com/questions/250481. There is also serverfault.com/questions/250481. 250481 it is one thing in the context of Programmers questions, and something else in the context of Server Fault questions.

Paths (or URLs) are nice because they are nested identifiers. Let's use them that way :)


答:
It depends of technology that you are working with. Names should identify items, and paths should identify context. I agree good naming is important but hey, paths are names too. But from practical point of view, if you are using something like Javascript it is probably better to keep more precise names for end items. If you are working with tools that take this into consideration, like Python, recomended way would be to use same name with different path (module, namespace). If you take look at Java, you'll also find classes with same name and different packages. One could go step further and say methods are named actions in context of class, and we have methods named same in different classes, which themselves can be named same but placed in different packages. The Zen of Python says:

Namespaces are one honking great idea -- let's do more of those!

But javascript has it quirks and perks so I would recommend you go with different names (even if files are in different paths). Also you may look up for module pattern in javascript which could help you write cleaner code:

```<code>    var playerStatsGenerator = player_stats.Generator();
    var coachSettingsGenerator = coach_settings.Generator();
</code>```

You could have your cake and eat it too.

Body:
It depends of technology that you are working with. Names should identify items, and paths should identify context. I agree good naming is important but hey, paths are names too. But from practical point of view, if you are using something like Javascript it is probably better to keep more precise names for end items. If you are working with tools that take this into consideration, like Python, recomended way would be to use same name with different path (module, namespace). If you take look at Java, you'll also find classes with same name and different packages. One could go step further and say methods are named actions in context of class, and we have methods named same in different classes, which themselves can be named same but placed in different packages. The Zen of Python says:

Namespaces are one honking great idea -- let's do more of those!

But javascript has it quirks and perks so I would recommend you go with different names (even if files are in different paths). Also you may look up for module pattern in javascript which could help you write cleaner code:

    var playerStatsGenerator = player_stats.Generator();
    var coachSettingsGenerator = coach_settings.Generator();

You could have your cake and eat it too.


问:
Potentially justifiable use case for const_cast or bad design?
I'm designing a data structure in C++, and I want to expose an interface to the user to traverse the structure in some order. Instead of creating several different types of enumerators, I want to keep it simple and provide a single enumerator, while maintaining const-correctness.

My design is summarised as follows:

```<code>class DataStructureNode; // The basic building block of the structure

class DataStructureEnumerator
{
public:

    friend class DataStructure;

    DataStructureEnumerator GetNext() { ... }
    DataStructureEnumerator GetPrevious() { ... }

private:

    const DataStructureNode* m_Node;
    ...
};

class DataStructure
{
public:

    DataStructureEnumerator GetEnumerator() { ... }

    DataStructureNode* GetNodeFromEnumerator(const DataStructureEnumerator& e)
    {
        // Let's assume this function also ensures the node belongs to this structure
        return const_cast<DataStructureEnumerator&>(e).m_Node; // <--- Ooo! const_cast!
    }

    const DataStructureNode* GetNodeFromEnumerator(const DataStructureEnumerator& e) const
    {
        // Let's assume this function also ensures the node belongs to this structure
        return e.m_Node;
    }
};
</code>```

This design has the benefit that there is only one type of enumerator that handles both mutable and immutable structures.

Of course, the alternative (and the conventional) design in C++ is to have two (or more) enumerator classes, such as DataStructureEnumerator and DataStructureConstEnumerator. The conventional design comes with added code-bloat, more templates, and an uglier interface (in my opinion!), but it's the norm in C++ communities.

I'm interested in hearing opinions of the community on this design. Are there any potential pitfalls that I'm missing with my design?

答: The biggest flaw is that your enumerator is similar to the C++ concept of an iterator, but doesn't follow the interface for an iterator. This means that your enumerators can't be used in conjunction with algorithms that are based on iterators (i.e. all algorithms in the standard library and in Boost). See the answer by @giantskin for an alternative.</p>


问:
Project is nearly done, but procedural spaghetti code. Do I rewrite or just keep trying to ship it?
I'm a beginner web developer (one year of experience).

A couple of weeks after graduating, I got offered a job to build a web application for a company whose owner is not much of a tech guy. He recruited me to avoid theft of his idea, the high cost of development charged by a service company, and to have someone young he can trust onboard to maintain the project for the long run (I came to these conclusions by myself long after being hired).

Cocky as I was back then, with a diploma in computer science, I accepted the offer thinking I can build anything.

I was calling the shots. After some research I settled on PHP, and started with plain PHP, no objects, just ugly procedural code. Two months later, everything was getting messy, and it was hard to make any progress. The web application is huge. So I decided to check out an MVC framework that would make my life easier. That's where I stumbled upon the cool kid in the PHP community: Laravel. I loved it, it was easy to learn, and I started coding right away. My code looked cleaner, more organized. It looked very good.

But again the web application was huge. The company was pressuring me to deliver the first version, which they wanted to deploy, obviously, and start seeking customers.

Because Laravel was fun to work with, it made me remember why I chose this industry in the first place - something I forgot while stuck in the shitty education system.

So I started working on small projects at night, reading about methodologies and best practice. I revisited OOP, moved on to object-oriented design and analysis, and read Uncle Bob's book Clean Code.

This helped me realize that I really knew nothing. I did not know how to build software THE RIGHT WAY. But at this point it was too late, and now I'm almost done. My code is not clean at all, just spaghetti code, a real pain to fix a bug, all the logic is in the controllers, and there is little object oriented design.

I'm having this persistent thought that I have to rewrite the whole project. However, I can't do it... They keep asking when is it going to be all done.

I can not imagine this code deployed on a server. Plus I still know nothing about code efficiency and the web application's performance.

On one hand, the company is waiting for the product and can not wait anymore. On the other hand I can't see myself going any further with the actual code. I could finish up, wrap it up and deploy, but god only knows what might happen when people start using it.

Do I rewrite, or just keep trying to ship, or is there another option that I've missed?

答:
You're a beginning web developer, with no good developer present to advice you, your boss hired you knowing this fully well. I think you are doing just as well as anyone could expect you to do. Actually, the fact that you have the insight that the job could have been better, and that you actually learned things that would allow you to do it better, means you are doing better than most. Remember for your own sanity that the version of you who started the job couldn't have done it better. Someone more experienced (and therefore better paid), or you with one project worth of experience, could have done it better.

What to do now: Be happy that you are a better developer than a year ago. The next project you will do better (and at the end you will be more experienced again and not happy with what you've done; that's normal). Changing or rewriting the last project will give the business very little benefit for the cost. What you can do is replacing bad code with good code when you need to make changes anyway; that makes sense because modifying badly maintainable code can be harder than replacing it with good code. And if you get a new inexperienced developer to help, tell them that this code is not an example that they should copy.


问:
Comparing two software versions in C#
I´m working on a mod update checker for minecraft, but there is a big problem: The modders and online database that I´m using for update checks has no standard software versions e.g.:

```
Local: rv0-stable-10 Online: rv1-alpha-13
Local: R1.1-83 Online: r1.1-81
Local: 1.7.10-0.2.250 (1.7.10 is indicating the Minecraft version) Online: 0.2.274
Local: 1.1.0c Online: 1.1.0e
Local: 2.2.526 Online: 2.2.526-experimental
```

Is there an algorithm or something like that, that is able to compare such different versions?

答:
Seems you are in trouble, if missing a public API based on semantic versioning you must know   the rules which govern the release update.

Quote from Semantic Versioning 2.0.0 by Tom Preston-Werner

In the world of software management there exists a dread place called
  "dependency hell." The bigger your system grows and the more packages
  you integrate into your software, the more likely you are to find
  yourself, one day, in this pit of despair. In systems with many
  dependencies, releasing new package versions can quickly become a
  nightmare. If the dependency specifications are too tight, you are in
  danger of version lock (the inability to upgrade a package without
  having to release new versions of every dependent package). If
  dependencies are specified too loosely, you will inevitably be bitten
  by version promiscuity (assuming compatibility with more future
  versions than is reasonable). Dependency hell is where you are when
  version lock and/or version promiscuity prevent you from easily and
  safely moving your project forward.

As a solution to this problem, I propose a simple set of rules and
  requirements that dictate how version numbers are assigned and
  incremented. These rules are based on but not necessarily limited to
  pre-existing widespread common practices in use in both closed and
  open-source software. For this system to work, you first need to
  declare a public API. This may consist of documentation or be enforced
  by the code itself. Regardless, it is important that this API be clear
  and precise. Once you identify your public API, you communicate
  changes to it with specific increments to your version number.
  Consider a version format of X.Y.Z (Major.Minor.Patch). Bug fixes not
  affecting the API increment the patch version, backwards compatible
  API additions/changes increment the minor version, and backwards
  incompatible API changes increment the major version.

I call this system "Semantic Versioning." Under this scheme, version
  numbers and the way they change convey meaning about the underlying
  code and what has been modified from one version to the next.

I think you should rely to a more empirical method in which it is possible to extract the minimum fixed information, but in the examples that you have mentioned is very difficult to establish a pattern recognizable as:

[Major Release].[Minor Release].[hot Fix].[build]

from which tokenizing the strings with the dot as delimiter and then compare the integer translation side by side, begining from the left.

In essence, NO, if there are no uniformly accepted rules that govern the release of those software versions, NO, there is no algorithm that can help you; sorry.

Title: Comparing two software versions in C#


问:
How should I include jQuery in a library?
I'm writing a JavaScript graphing library using canvas which I am licensing under MIT, and I'm using jQuery, as well as a couple of other open sourced libraries, all under MIT. I'm also using bower to manage my front-end dependencies. How should I best handle these dependencies without violating the license?

Preferably, the user would not have to include multiple scripts, just one , and it would include all of the plugins.

Should I just ask the user to include jQuery and the other libraries in its own script tag, or should I concat all of the scripts together into one big file, headers included?

答:
How should I best handle these dependencies without violating the
  license?

If you would packaging your dependency modules, you should only ensure to mantain the MIT requirements

The MIT License is a free software license originating at the
  Massachusetts Institute of Technology (MIT). It is a permissive free
  software license, meaning that it permits reuse within proprietary
  software provided all copies of the licensed software include a copy
  of the MIT License terms. Such proprietary software retains its
  proprietary nature even though it incorporates software under the MIT
  License. The license is also GPL-compatible, meaning that the GPL
  permits combination and redistribution with software that uses the MIT
  License.

Should I just ask the user to include jQuery and the other libraries
  in its own script tag, or should I concat all of the scripts together
  into one big file, headers included?

I think its completely up to you, but I think the user have not problems to include JQuery if they would use Bootstrap


问:
Managing unique data correctly in SQL
Here in Brazil we have a personal identifier called CPF. This identifier has a sequence of 11 digits and is unique for each Brazilian citizen. Possibly in other countries there is something like that too.

How is a unique identifier, I chose to set it in the database like a UNIQUE KEY. And now that things get complicated. A user could be registered by an administrator and be removed by some kind of problem. However, it is not actually removed, but hidden by a deleted flag. And in another moment, he could be recreated again (there is a need to recreate it, and not re-enable it).

Because it is an individual identifier, the CPF would be reused on recreated user and would conflict in UNIQUE KEY.

In this situation, I thought of some practical solutions to solve the problem as well as its disadvantages. But I like what is the most appropriate way to solve this kind of problem.

Do not use a UNIQUE KEY. The disadvantage is that it could increase the query time, which could perhaps be solved by a KEY-only column.

Set the column to NULL on pseudo-DELETE. The disadvantage is that I lose the information, however, could solve just creating a second column to store its value before being annulled.

The UNIQUE KEY could group the column with a date removal column (NULL by default). The disadvantage is having to use two columns for each group UNIQUE KEY.

Create a second table to store data removed without UNIQUE KEY. The disadvantages here are almost incalculable!

Remove the row, rather than hide it. The disadvantage here is that I could lose the references in a user FK.

Currently I prefer the first option, and if very necessary, I would opt for the second or third option. But I wonder if there is a more correct way, following the concept more accepted by the community.

答:
what you've described is a unique key - only you're thinking of it as a unique column.

You can create a unique constraint on any number of columns in a table, so here you'd combine the CPF with the deleted (or some other column if you could have multiple deleted records) column as well.

For example:

```<code>ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
</code>```

Title: Managing unique data correctly in SQL

Body:
what you've described is a unique key - only you're thinking of it as a unique column.

You can create a unique constraint on any number of columns in a table, so here you'd combine the CPF with the deleted (or some other column if you could have multiple deleted records) column as well.

For example:

ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)


问:
Can I use GPL software in a commercial application
I have 3 questions about the GPL here:

If I use GPL software in my application, but don't modify or distribute it, do I have to release my application under the GPL?

What if I modify some software that my application uses. Then do I have to release my application under the GPL, or can I just supply the modified software under the GPLs terms.

And what if I use GPL software, but don't modify it, can I distribute it with my application?

My case in point is, I have a PHP framework which I use the GeSHi library to highlight some output.

Because GeSHi is GPL, does my framework have to be GPL?

Can I modify GeSHi for particular use cases of my application if I supply the modifications back to the GeSHi maintainers?

Can I redistribute my framework with GeSHi?

答:
This very strongly seems to disagree if you are using it on a website, rather than re-distributing an executable:

You may copy, distribute and modify the software as long as you track
changes/dates of in source files and keep modifications under GPL. You
can distribute your application using a GPL library commercially, but
you must also provide the source code. GPL v3 tries to close some
loopholes in GPL v2.

Specifically:

If you distribute this library in an executable, you must disclose
your source code by providing it either alongside your distribution or
list an accessible way (URL, physical copy) to obtain the source for 3
years. Does not apply if you serve through a web portal.

https://tldrlegal.com/license/gnu-general-public-license-v3-%28gpl-3%29

ContentLicense: CC BY-SA 4.0


问:
Best patterns for variable-scope disposables
I have Client which uses a disposable Connection for talking to a remote service. A Connection is somewhat expensive to set up and needs to be Dispose()d properly.

I want to allow multiple methods in Client to share a connection, like this:

```<code>using (client._connection = client.Connect())
{
  client.SyncTime();
  client.UpdateUsers();
  client.SomeOtherOperation();
}
</code>```

But I don't want to insist on Client's consumers managing connections. They should be allowed to call individual single Client methods without being aware or concerned with Connections.

Here is the pattern I'm using at the moment. It makes SRP cry. Any suggestions on how I can do this better, or should I be doing this at all?

```<code>public class Client
{
  Connection _connection;

  public void SyncTime()
  {
    bool wasConnected = _connection == null;
    try
    {
      if (!wasConnected)
        _connection = Connect();

      _connection.ActuallyDoSomeWork();
      ...

    }
    finally
    {
      if (!wasConnected)
        _connection.Dispose()
    }
  }
}
</code>```

答:
You could wrap your disposable Connection in a reference-counted disposable wrapper, like so:

```<code>public abstract class RefCountDisposable<TDisposable> : IDisposable where TDisposable : class, IDisposable
{
    TDisposable reference;

    protected RefCountDisposable(TDisposable reference)
    {
        this.reference = reference;
    }

    public TDisposable Reference { get { return reference; } private set { reference = value; } }

    public bool IsDisposed { get { return reference == null; } }

    public void Dispose()
    {
        // Dispose of unmanaged resources.
        Dispose(true);
        // Suppress finalization.  Since this class actually has no finalizer, this does nothing.
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (IsDisposed)
            return;
        if (disposing)
        {
            // Free any other managed objects here.
            Reference = null;
        }
        // Free any unmanaged objects here.
    }

    public override string ToString()
    {
        if (IsDisposed)
            return base.ToString() + ": Disposed";
        else
            return base.ToString() + ": " + reference.ToString();
    }
}

public sealed class RefCountDisposableFactory<TDisposable> where TDisposable : class, IDisposable
{
    Func<TDisposable> getReference;
    TDisposable reference;
    int refCount;
    object padlock = new object();

    sealed class RefCountDisposable : RefCountDisposable<TDisposable>
    {
        readonly RefCountDisposableFactory<TDisposable> factory;

        internal RefCountDisposable(RefCountDisposableFactory<TDisposable> factory, TDisposable reference)
            : base(reference)
        {
            if (factory == null)
                throw new ArgumentNullException("factory");
            this.factory = factory;
        }

        protected override void Dispose(bool disposing)
        {
            if (IsDisposed)
                return;
            try
            {
                if (disposing)
                {
                    // Free any other managed objects here.
                    factory.DisposeReference(Reference);
                }
                // Free any unmanaged objects here.
            }
            finally
            {
                base.Dispose(disposing);
            }
        }
    }

    public RefCountDisposableFactory(Func<TDisposable> getReference)
    {
        this.getReference = getReference;
        this.reference = null;
        this.refCount = 0;
    }

    public RefCountDisposable<TDisposable> Create()
    {
        lock (padlock)
        {
            if (reference == null)
                reference = getReference();
            refCount++;
        }

        return new RefCountDisposable(this, reference);
    }

    void DisposeReference(TDisposable reference)
    {
        if (reference == null)
            return; // already disposed.
        lock (padlock)
        {
            if (reference != this.reference)
            {
                string msg = string.Format("invalid reference {0}", reference);
                Debug.Assert(false, msg);
                throw new ArgumentException(msg);
            }
            if (refCount <= 1)
            {
                if (reference != null)
                    reference.Dispose();
                reference = null;
                refCount = 0;
            }
            else
            {
                refCount--;
            }
        }
    }
}
</code>```

The idea here is that the RefCountDisposableFactory allocates a Connection the first time you need it and returns it in a RefCountDisposable<Connection> wrapper.  Subsequent requests for a Connection increment a reference count and return new wrappers to the same reference Connection.  Once the last wrapper is disposed, the Connection is disposed and set to null so that subsequent requests will create a new instance.

My prototype factory isn't robust against somebody disposing the underlying disposable reference directly.  Do you think it should be?

I also note Microsoft itself has something called RefCountDisposable, but it isn't generic and I can't find any useful documentation.

Body:
You could wrap your disposable Connection in a reference-counted disposable wrapper, like so:

public abstract class RefCountDisposable<TDisposable> : IDisposable where TDisposable : class, IDisposable
{
    TDisposable reference;

    protected RefCountDisposable(TDisposable reference)
    {
        this.reference = reference;
    }

    public TDisposable Reference { get { return reference; } private set { reference = value; } }

    public bool IsDisposed { get { return reference == null; } }

    public void Dispose()
    {
        // Dispose of unmanaged resources.
        Dispose(true);
        // Suppress finalization.  Since this class actually has no finalizer, this does nothing.
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (IsDisposed)
            return;
        if (disposing)
        {
            // Free any other managed objects here.
            Reference = null;
        }
        // Free any unmanaged objects here.
    }

    public override string ToString()
    {
        if (IsDisposed)
            return base.ToString() + ": Disposed";
        else
            return base.ToString() + ": " + reference.ToString();
    }
}

public sealed class RefCountDisposableFactory<TDisposable> where TDisposable : class, IDisposable
{
    Func<TDisposable> getReference;
    TDisposable reference;
    int refCount;
    object padlock = new object();

    sealed class RefCountDisposable : RefCountDisposable<TDisposable>
    {
        readonly RefCountDisposableFactory<TDisposable> factory;

        internal RefCountDisposable(RefCountDisposableFactory<TDisposable> factory, TDisposable reference)
            : base(reference)
        {
            if (factory == null)
                throw new ArgumentNullException("factory");
            this.factory = factory;
        }

        protected override void Dispose(bool disposing)
        {
            if (IsDisposed)
                return;
            try
            {
                if (disposing)
                {
                    // Free any other managed objects here.
                    factory.DisposeReference(Reference);
                }
                // Free any unmanaged objects here.
            }
            finally
            {
                base.Dispose(disposing);
            }
        }
    }

    public RefCountDisposableFactory(Func<TDisposable> getReference)
    {
        this.getReference = getReference;
        this.reference = null;
        this.refCount = 0;
    }

    public RefCountDisposable<TDisposable> Create()
    {
        lock (padlock)
        {
            if (reference == null)
                reference = getReference();
            refCount++;
        }

        return new RefCountDisposable(this, reference);
    }

    void DisposeReference(TDisposable reference)
    {
        if (reference == null)
            return; // already disposed.
        lock (padlock)
        {
            if (reference != this.reference)
            {
                string msg = string.Format("invalid reference {0}", reference);
                Debug.Assert(false, msg);
                throw new ArgumentException(msg);
            }
            if (refCount <= 1)
            {
                if (reference != null)
                    reference.Dispose();
                reference = null;
                refCount = 0;
            }
            else
            {
                refCount--;
            }
        }
    }
}

The idea here is that the RefCountDisposableFactory allocates a Connection the first time you need it and returns it in a RefCountDisposable<Connection> wrapper.  Subsequent requests for a Connection increment a reference count and return new wrappers to the same reference Connection.  Once the last wrapper is disposed, the Connection is disposed and set to null so that subsequent requests will create a new instance.

My prototype factory isn't robust against somebody disposing the underlying disposable reference directly.  Do you think it should be?

I also note Microsoft itself has something called RefCountDisposable, but it isn't generic and I can't find any useful documentation.


问:
What is a good design for a method that can return several logically different results?
The question title is probably too abstract, so let me provide a particular example of what I have in mind:

There is a webservice that encapsulates a process of changing passwords for users of a distributed system. The webservice accepts user's login, his old password and a new password. Based on this input, it can return one of the following three results:

In case user was not found, or his old password does not match, it will simply return with HTTP 403 Forbidden.

Otherwise, it takes a new password and makes sure that it conforms to a password policy (e.g. it is long enough, contains a proper mix of letters and numbers, etc.). If it does not, it will return an XML describing why the password does not conform to the policy.

Otherwise, it will change the password and return an XML containing an expiration date of the new password.

Now, I'd like to design a class, ideally with a single method, to encapsulate working with this webservice. My first shot was this:

```<code>public class PasswordManagementWebService
{
    public ChangePasswordResult ChangePassword(string login, string oldPassword, string newPassword)
    {
        ChangePasswordResult result;

        // send input to websevice, it's not important how; the httpResponse
        // will contain a response from webservice
        var httpResponse;
        if (HasAuthenticationFailed(httpResponse)
        {
            throw new AuthenticationException();
        }
        else if (WasPasswordSuccessfullyChanged(httpResponse))
        {
            result = new ChangePasswordSuccessfulResult(httpResponse);
        }
        else
        {
            result = new ChangePasswordUnsuccessfulResult(httpResponse);
        }

        return result;
    }
}

public abstract class ChangePasswordResult
{
    public abstract bool WasSuccessful { get; }
}

public abstract class ChangePasswordSuccessfulResult
{
    public ChangePasswordSuccessfulResult(HttpResponse  httpResponse)
    {
        // initialize the class from the httpResponse
    }

    public override bool WasSuccessful { get { return true; } }
    public DateTime ExpirationDate { get; private set; }
}

public abstract class ChangePasswordUnsuccessfulResult
{
    public ChangePasswordUnsuccessfulResult(HttpResponse  httpResponse)
    {
        // initialize the class from the httpResponse
    }

    public override bool WasSuccessful { get { return false; } }

    public bool WasPasswordLongEnough { get; private set; }
    public bool DoesPasswordHaveToContainNumbers { get; private set; }
    // ... etc.
}
</code>```

As you can see, I've decided to use separate classes for return cases #2 and #3 - I could have used a single class with a boolean, but it feels like a smell, the class would have no clear purpose. With two separate classes, an user of my PasswordManagementWebService class now has to know which classes inherit from ChangePasswordResult and to cast to a correct one based on the WasSuccessful property. While I now do have a nice, laser-focused classes, I made a life of my users more difficult than it should be.

As for the case #1, I've just decided to throw an exception. I could have created a separate exception for the case #2, too, and only return something from the method when the password was successfully changed. However, this doesn't feel right - I don't think that a new password being invalid is a state exceptional enough to warrant throwing an exception.

I am not very sure how would I design things were there more than two un-exceptional result types from the webservice. Probably, I would change a type of WasSuccessful property from boolean to an enum and rename it to ResultType, adding a dedicated class inherited from ChangePasswordResult for each possible ResultType.

Finally, to the actual question: Is this design approach (i.e. having one abstract class and forcing clients to cast to a correct result based on a property) a correct one when dealing with problems like this? If yes, is there a way to improve it (perhaps with a different strategy for when to throw exceptions vs. return results)? If no, what would you recommend?

答:
I think this approach is over-using inheritance which adds additional (unnecessary) complexity. Favor composition over inheritance when possible. Especially if it's a Success/Non-Success thing that is easily represented with a boolean it doesn't warrant the need for sub-classing.

You could include everything you need to into a single class, and based on the result you can use the properties accordingly. The class still has a single purpose, to return information about the password change. The fact that there are several different outcomes is an essential complexity of the task.

```<code>class ChangePasswordResult
{
    public bool Result { get; private set; }
    public DateTime ExpirationDate { get; private set; }
    public bool WasPasswordLongEnough { get; private set; }
    public bool DoesPasswordHaveToContainNumbers { get; private set; }
}
</code>```

Edit:

jhewlett Brings up a very good point too about serialization. With a single result structure being returned you have a more stable interface clients can interact with. When you document your interface you can say "this endpoint returns X" as opposed to "this endpoint returns X OR Y depending on..."

Body:
I think this approach is over-using inheritance which adds additional (unnecessary) complexity. Favor composition over inheritance when possible. Especially if it's a Success/Non-Success thing that is easily represented with a boolean it doesn't warrant the need for sub-classing.

You could include everything you need to into a single class, and based on the result you can use the properties accordingly. The class still has a single purpose, to return information about the password change. The fact that there are several different outcomes is an essential complexity of the task.

class ChangePasswordResult
{
    public bool Result { get; private set; }
    public DateTime ExpirationDate { get; private set; }
    public bool WasPasswordLongEnough { get; private set; }
    public bool DoesPasswordHaveToContainNumbers { get; private set; }
}

Edit:

jhewlett Brings up a very good point too about serialization. With a single result structure being returned you have a more stable interface clients can interact with. When you document your interface you can say "this endpoint returns X" as opposed to "this endpoint returns X OR Y depending on..."


问:
In plain English, what is recursion?
The idea of recursion is not very common in real world. So, it seems a bit confusing to the novice programmers. Though, I guess, they become used to the concept gradually. So, what can be a nice explanation for them to grasp the idea easily?</p>

答: The calling of a function from within that same function.</p>

Title: In plain English, what is recursion?


答:
I don't subscribe to the school of thought which says "exceptions should only be for exceptional cases!" People are scared of exceptions for some reason. If you can't do what you said you're going to do, throw an exception - even if it's a common or expected failure.

I like this for a few reasons. It's impossible for the caller to ignore (someone could easily forget to inspect the return value of a method that indicates failure by a return code.) It's simple (no special placeholder values for missing results or hierarchies which need downcasting.) It's atomic (either my change succeeded or you tell me to get lost; I'm left in no doubt as to which it is.) It's granular (you can attach as much information as you like to the exception, and throw different exceptions for different failures.)

So I'd design your method like this:

```<code>public void ChangePassword(string password)
{
    HttpResponse response = RequestPasswordChange();
    if (AuthFailed(response))
        throw new AuthorizationException();
    if (PasswordWasNotChanged(response))
        throw new InvalidNewPasswordException(
            WasPasswordLongEnough(response),
            DidPasswordContainNumbers(response)
        );
}
</code>```

"Succeed-or-throw" is a fine rule of thumb, and people are used to it, no matter how much they wave their arms. After all, Dictionary<TKey, TValue> throws KeyNotFoundException when you fail to index into it. A non-exceptional use of exceptions.

Title: What is a good design for a method that can return several logically different results?

Body:
The question title is probably too abstract, so let me provide a particular example of what I have in mind:

There is a webservice that encapsulates a process of changing passwords for users of a distributed system. The webservice accepts user's login, his old password and a new password. Based on this input, it can return one of the following three results:

In case user was not found, or his old password does not match, it will simply return with HTTP 403 Forbidden.

Otherwise, it takes a new password and makes sure that it conforms to a password policy (e.g. it is long enough, contains a proper mix of letters and numbers, etc.). If it does not, it will return an XML describing why the password does not conform to the policy.

Otherwise, it will change the password and return an XML containing an expiration date of the new password.

Now, I'd like to design a class, ideally with a single method, to encapsulate working with this webservice. My first shot was this:

```<code>public class PasswordManagementWebService
{
    public ChangePasswordResult ChangePassword(string login, string oldPassword, string newPassword)
    {
        ChangePasswordResult result;

        // send input to websevice, it's not important how; the httpResponse
        // will contain a response from webservice
        var httpResponse;
        if (HasAuthenticationFailed(httpResponse)
        {
            throw new AuthenticationException();
        }
        else if (WasPasswordSuccessfullyChanged(httpResponse))
        {
            result = new ChangePasswordSuccessfulResult(httpResponse);
        }
        else
        {
            result = new ChangePasswordUnsuccessfulResult(httpResponse);
        }

        return result;
    }
}

public abstract class ChangePasswordResult
{
    public abstract bool WasSuccessful { get; }
}

public abstract class ChangePasswordSuccessfulResult
{
    public ChangePasswordSuccessfulResult(HttpResponse  httpResponse)
    {
        // initialize the class from the httpResponse
    }

    public override bool WasSuccessful { get { return true; } }
    public DateTime ExpirationDate { get; private set; }
}

public abstract class ChangePasswordUnsuccessfulResult
{
    public ChangePasswordUnsuccessfulResult(HttpResponse  httpResponse)
    {
        // initialize the class from the httpResponse
    }

    public override bool WasSuccessful { get { return false; } }

    public bool WasPasswordLongEnough { get; private set; }
    public bool DoesPasswordHaveToContainNumbers { get; private set; }
    // ... etc.
}
</code>```

As you can see, I've decided to use separate classes for return cases #2 and #3 - I could have used a single class with a boolean, but it feels like a smell, the class would have no clear purpose. With two separate classes, an user of my PasswordManagementWebService class now has to know which classes inherit from ChangePasswordResult and to cast to a correct one based on the WasSuccessful property. While I now do have a nice, laser-focused classes, I made a life of my users more difficult than it should be.

As for the case #1, I've just decided to throw an exception. I could have created a separate exception for the case #2, too, and only return something from the method when the password was successfully changed. However, this doesn't feel right - I don't think that a new password being invalid is a state exceptional enough to warrant throwing an exception.

I am not very sure how would I design things were there more than two un-exceptional result types from the webservice. Probably, I would change a type of WasSuccessful property from boolean to an enum and rename it to ResultType, adding a dedicated class inherited from ChangePasswordResult for each possible ResultType.

Finally, to the actual question: Is this design approach (i.e. having one abstract class and forcing clients to cast to a correct result based on a property) a correct one when dealing with problems like this? If yes, is there a way to improve it (perhaps with a different strategy for when to throw exceptions vs. return results)? If no, what would you recommend?

Body:
I don't subscribe to the school of thought which says "exceptions should only be for exceptional cases!" People are scared of exceptions for some reason. If you can't do what you said you're going to do, throw an exception - even if it's a common or expected failure.

I like this for a few reasons. It's impossible for the caller to ignore (someone could easily forget to inspect the return value of a method that indicates failure by a return code.) It's simple (no special placeholder values for missing results or hierarchies which need downcasting.) It's atomic (either my change succeeded or you tell me to get lost; I'm left in no doubt as to which it is.) It's granular (you can attach as much information as you like to the exception, and throw different exceptions for different failures.)

So I'd design your method like this:

public void ChangePassword(string password)
{
    HttpResponse response = RequestPasswordChange();
    if (AuthFailed(response))
        throw new AuthorizationException();
    if (PasswordWasNotChanged(response))
        throw new InvalidNewPasswordException(
            WasPasswordLongEnough(response),
            DidPasswordContainNumbers(response)
        );
}

"Succeed-or-throw" is a fine rule of thumb, and people are used to it, no matter how much they wave their arms. After all, Dictionary<TKey, TValue> throws KeyNotFoundException when you fail to index into it. A non-exceptional use of exceptions.


问:
Why use getters only as opposed to marking things final?
I'm working in a java role after working a couple years in functional programming. Our company was bought by google and I took a java role after the acquisition.

Coming back to java as a polyglot developer, I'm generating getters for immutable objects and I'm seeing it's a total hogwash.

Are there any reasons why the 'getField' convention should be used so prolifically? To me it seems almost horrifying at this point that so many libraries expect public getter methods to work with their functionality when simply making a field public and final would have the same effect as making only a getter on a public mutable field.

Why isn't it more of a common practice to ditch the setters and just expose a final field?

答:
For flexibility -- this has to do with what happens when you change the class later.

If foo.x is a publicly accessible member (even a final one), and you decide that you no longer need that member, code which accessed that method is now broken.

If you have only provided a getter, then you can always provide a compatibility version of that getter which computes the value as needed, and code which worked before still works.

For example, suppose we are writing a Point class, and we decide to go from vector (x,y) to polar (angle, magnitude) representation to internally store the point's position.   Code which looks for a member named x is now broken -- but I can always provide a method named getX() which computes the X coordinate of the point and returns it.


答:
The first problem that comes up in such a design is "what if something isn't final anymore?"  You've decided that 'no, you really do need to change that field sometimes' and so when you remove the final, you're left with a public int field; sticking out there for anyone to fiddle with.

The next problem is, you've got to keep using it.  Its part of the public API of the class.  If you decide later that it doesn't have any meaning in some future version of the refactored class because instead of defining a rectangle as "length of short side, length of long side" with those two fields being public, you've now refactored it so the internal representation is two Points so that you can use it more easily in AWT.  But, you've got two fields there that you have to maintain, even though the internal code doesn't use them anymore.

This becomes even more 'fun' when extending the class.  Because now everyone that uses the extended class also has those two public final fields that they have to maintain now and is part of their API.

The problem behind these last two examples is that you've exposed some of the implementation of the class to other things.  This isn't so bad if the modifiers on the fields are such that they are restricted to only code you have written.  A default (package) protection on a fields so that other classes in the package can access it directly? Not so bad.  No getters on a private inner class? No problem at all.

Some tools out there use reflection and depend on getters and setters.  One that most easily springs to mind is Expression Language used in JSPs that expects a Java Bean compliant object.  If you have ${foo.total} it invokes foo.getTotal().  As soon as the code touches JSP, it becomes a bit of a pain to not have getters and setters (related SO) - decorators everywhere.

Title: Why use getters only as opposed to marking things final?

Body:
I'm working in a java role after working a couple years in functional programming. Our company was bought by google and I took a java role after the acquisition.

Coming back to java as a polyglot developer, I'm generating getters for immutable objects and I'm seeing it's a total hogwash.

Are there any reasons why the 'getField' convention should be used so prolifically? To me it seems almost horrifying at this point that so many libraries expect public getter methods to work with their functionality when simply making a field public and final would have the same effect as making only a getter on a public mutable field.

Why isn't it more of a common practice to ditch the setters and just expose a final field?


答: Your question says: "Started wrong, should I start over" while the additional text actually says "Finished project, but did it wrong, should I start over". For the question headline alone: If the amount of programming work that you have done is small compared to the total work needed, then starting all over will make sense. That happens a lot when the problem is complex and badly understood, and quite some time is spent figuring out what the problem actually is. No point continuing with a bad start, if throwing it away and starting all over, this time with good understanding of the problem, means you will actually finish quicker. </p>

Title: Project is nearly done, but procedural spaghetti code. Do I rewrite or just keep trying to ship it?

Body:
I'm a beginner web developer (one year of experience).

A couple of weeks after graduating, I got offered a job to build a web application for a company whose owner is not much of a tech guy. He recruited me to avoid theft of his idea, the high cost of development charged by a service company, and to have someone young he can trust onboard to maintain the project for the long run (I came to these conclusions by myself long after being hired).

Cocky as I was back then, with a diploma in computer science, I accepted the offer thinking I can build anything.

I was calling the shots. After some research I settled on PHP, and started with plain PHP, no objects, just ugly procedural code. Two months later, everything was getting messy, and it was hard to make any progress. The web application is huge. So I decided to check out an MVC framework that would make my life easier. That's where I stumbled upon the cool kid in the PHP community: Laravel. I loved it, it was easy to learn, and I started coding right away. My code looked cleaner, more organized. It looked very good.

But again the web application was huge. The company was pressuring me to deliver the first version, which they wanted to deploy, obviously, and start seeking customers.

Because Laravel was fun to work with, it made me remember why I chose this industry in the first place - something I forgot while stuck in the shitty education system.

So I started working on small projects at night, reading about methodologies and best practice. I revisited OOP, moved on to object-oriented design and analysis, and read Uncle Bob's book Clean Code.

This helped me realize that I really knew nothing. I did not know how to build software THE RIGHT WAY. But at this point it was too late, and now I'm almost done. My code is not clean at all, just spaghetti code, a real pain to fix a bug, all the logic is in the controllers, and there is little object oriented design.

I'm having this persistent thought that I have to rewrite the whole project. However, I can't do it... They keep asking when is it going to be all done.

I can not imagine this code deployed on a server. Plus I still know nothing about code efficiency and the web application's performance.

On one hand, the company is waiting for the product and can not wait anymore. On the other hand I can't see myself going any further with the actual code. I could finish up, wrap it up and deploy, but god only knows what might happen when people start using it.

Do I rewrite, or just keep trying to ship, or is there another option that I've missed?


问:
Preventing ip resolvers in a skype-like program
I'm currently in the process of creating a Skype-like program, that uses a hybrid peer to peer system to communicate between users (i.e. server contains all users IPs, a client that wants to connect to a friend will tell the server, that will then send each client the other's IP so they could start hole punching to establish a connection between them).

I know that with Skype, there are many websites that allow you to enter a username and easily get his IP address. My question is, what is the best way of preventing such an exploit?

Here are a few solutions I could think of:

save each and every users' friends lists on the server (so the server can just drop IP requests from users that aren't in the requested client's friends list)

whenever the server is asked for a client's IP, ask that client if the asker is on their friends list (if not, don't reply)

have each client use some secret key to communicate with the server (so only registered clients will be able to send IP requests)

Feel free to add a different solution, again, these are just solutions I could think of off the top of my head while writing this question.

In addition, a related question that I wanted to ask - what would be the best practice in such a program:

Have each client store his friends' IPs and make the server notify him whenever they are changed

-VS-

Have the client ask the server for a friend's IP whenever he wants to start a direct connection with him (keep in mind that the client anyway has to tell the server whenever he's trying to connect to someone, in order for the hole punching to work).

P.S. I've never created such a program and I'm not following any tutorial or such. If there's any better way of doing something I wrote, or if I got anything wrong, I'd be very glad if you could mention it.

答:
Peer-to-peer connections don't play well with firewalls.  Connections though an external server or proxy, play much better with firewalls.  As long as you are providing IP addresses for the connection, I believe you will risk leaking client IP address(es).

Allowing the clients to switch to a peer-to-peer connection after establishing a connection may help reduce the exposure.  I see exposures on all three options you list.  Any option that allows use of a proxy, will have an exposure.  Not allowing proxies will likely prevent usage in some cases.

End-to-end encryption using individual public-private key pairs, would help reduce the exposure.  However, it leads to issues on how to distribute public key pairs.

EDIT: You may want at existing standards.  There are people who have spent much more time than me looking at these things.  Study them to see what works and doesn't work.  For instance, RTSP has known problems working with firewalls.

For chat and additional functions, there is XMPP previously known as Jabber.

For voice and video there is SIP, RTSP, and Jingle.


问:
Where and how to reference composite MVP components?
I am learning about the MVP (Model-View-Presenter) Passive View flavour of MVC. I intend to expose events from view interfaces rather than using the observer pattern to remove explicit coupling with presenter.

Context: Windows Forms / Client-Side JavaScript.

I am led to believe that the MVP (or indeed MVC in general) pattern can be applied at various levels of a user interface ranging from the main "Window" to an embedded "Text Field". For instance, the model to the text field is probably just a string whereas the model to the "Window" contains application specific view state (like a persons name which resides within the contained text field).

Given a more complex scenario:

Documentation viewer which contains:

TOC navigation pane

Document view

Search pane

Since each of these 4 user interface items are complex and can be reused elsewhere it makes sense to design these using MVP.

Given that each of these user interface items comprises of 3 components; which component should be nested? where? who instantiates them?

Idea #1 - Embed View inside View from Parent View

```<code>public class DocumentationViewer : Form, IDocumentationViewerView {
    public DocumentationViewer() {
        ...

        // Unclear as to how model and presenter are injected...
        TocPane = new TocPaneView();
    }
    protected ITocPaneView TocPane { get; private set; }
}
</code>```

Idea #2 - Embed Presenter inside View from Parent View

```<code>public class DocumentationViewer : Form, IDocumentationViewerView {
    public DocumentationViewer() {
        ...

        // This doesn't seem like view logic...
        var tocPaneModel = new TocPaneModel();
        var tocPaneView = new TocPaneView();
        TocPane = new TocPanePresenter(tocPaneModel, tocPaneView);
    }
    protected TocPanePresenter TocPane { get; private set; }
}
</code>```

Idea #3 - Embed View inside View from Parent Presenter

```<code>public class DocumentationViewer : Form, IDocumentationViewerView {
    ...

    // Part of IDocumentationViewerView:
    public ITocPaneView TocPane { get; set; }
}

public class DocumentationViewerPresenter {
    public DocumentationViewerPresenter(DocumentationViewerModel model, IDocumentationViewerView view) {
        ...

        var tocPaneView = new TocPaneView();
        var tocPaneModel = new TocPaneModel(model.Toc);
        var tocPanePresenter = new TocPanePresenter(tocPaneModel, tocPaneView);
        view.TocPane = tocPaneView;
    }
}
</code>```

Some better idea...

答:
After some thought it seems like the following approach might be beneficial whereby each inner control is represented by a facade which constructs the presenter, view and its model and exposes the relevant methods:

I would love to know what others think about this idea...


答:
Do not, do not, DO NOT abuse your database.  A unique or primary key should be unique, without exception.  Even if you're using an archaic database system like xBase which natively supports the idea of "marking a record as deleted", it's just a bad idea.

There are two good and simple options, however.

1: Don't "delete", "mark inactive" instead.

As a SQL verb, "delete" has special meaning in any RDMS or system.  It means you're telling the system to physically remove and destroy records.  Any data that happens to be recoverable is such only as a shortcut by the RDMS, and your data model should not depend on that behavior.

With a simple "Active" or "Inactive" boolean value, it should be easy to mark your person record, and relatively simple for your DBA to recover someone they had to manually adjust for some reason.  (Not that such is good practice, but that's another topic.)  Don't muck-about with duplicate CPF's; just declare the thing unique, and train your admin staff on how to recover an inactive person.

Of course, this method while simple also prevents the ability to easily give a person a new surrogate key while maintaining past history.  If that's important, go with option #2.

2: Use a seperate table for CPF, and have "personID" be a property of the CPF instead of the inverse.

The obvious model for designing a system with people and their unique government number is to have said number be a field on the person table.

```<code>CREATE TABLE persons (
  personID int IDENTITY PRIMARY KEY,
  name varchar(250),
  CPF varchar(10)
)
</code>```

However, in an instance where your design demands that two person records may exist for the same CPF, the simple design is to have CPF's be unique, and have them point to their current person record.

```<code>CREATE TABLE persons (
  personID int IDENTITY PRIMARY KEY,
  name varchar(250)
)

CREATE TABLE cpfs (
  CPF varchar(10) NOT NULL PRIMARY KEY,
  personID int REFERENCES person(personID)
)
</code>```

Give the tables above, it is a simple matter to create a view listing only the "real" person for each CPF, along with their personID.

```<code>SELECT C.CPF, P.*
FROM cfps C
INNER JOIN persons P
  ON C.personID = P.personID
</code>```

And it likewise becomes simple to query for only active persons.

```<code>SELECT *
FROM someTable
WHERE personID IN (SELECT personID FROM cfps)
</code>```

Now, this system does introduce a second table, and includes a modest bit of complexity.  If you don't expect multiple "person" records to stick around as a regular thing and only anticipate some few exceptions, go with option #1 instead.

Title: Managing unique data correctly in SQL

Body:
Here in Brazil we have a personal identifier called CPF. This identifier has a sequence of 11 digits and is unique for each Brazilian citizen. Possibly in other countries there is something like that too.

How is a unique identifier, I chose to set it in the database like a UNIQUE KEY. And now that things get complicated. A user could be registered by an administrator and be removed by some kind of problem. However, it is not actually removed, but hidden by a deleted flag. And in another moment, he could be recreated again (there is a need to recreate it, and not re-enable it).

Because it is an individual identifier, the CPF would be reused on recreated user and would conflict in UNIQUE KEY.

In this situation, I thought of some practical solutions to solve the problem as well as its disadvantages. But I like what is the most appropriate way to solve this kind of problem.

Do not use a UNIQUE KEY. The disadvantage is that it could increase the query time, which could perhaps be solved by a KEY-only column.

Set the column to NULL on pseudo-DELETE. The disadvantage is that I lose the information, however, could solve just creating a second column to store its value before being annulled.

The UNIQUE KEY could group the column with a date removal column (NULL by default). The disadvantage is having to use two columns for each group UNIQUE KEY.

Create a second table to store data removed without UNIQUE KEY. The disadvantages here are almost incalculable!

Remove the row, rather than hide it. The disadvantage here is that I could lose the references in a user FK.

Currently I prefer the first option, and if very necessary, I would opt for the second or third option. But I wonder if there is a more correct way, following the concept more accepted by the community.

Body:
Do not, do not, DO NOT abuse your database.  A unique or primary key should be unique, without exception.  Even if you're using an archaic database system like xBase which natively supports the idea of "marking a record as deleted", it's just a bad idea.

There are two good and simple options, however.

1: Don't "delete", "mark inactive" instead.

As a SQL verb, "delete" has special meaning in any RDMS or system.  It means you're telling the system to physically remove and destroy records.  Any data that happens to be recoverable is such only as a shortcut by the RDMS, and your data model should not depend on that behavior.

With a simple "Active" or "Inactive" boolean value, it should be easy to mark your person record, and relatively simple for your DBA to recover someone they had to manually adjust for some reason.  (Not that such is good practice, but that's another topic.)  Don't muck-about with duplicate CPF's; just declare the thing unique, and train your admin staff on how to recover an inactive person.

Of course, this method while simple also prevents the ability to easily give a person a new surrogate key while maintaining past history.  If that's important, go with option #2.

2: Use a seperate table for CPF, and have "personID" be a property of the CPF instead of the inverse.

The obvious model for designing a system with people and their unique government number is to have said number be a field on the person table.

CREATE TABLE persons (
  personID int IDENTITY PRIMARY KEY,
  name varchar(250),
  CPF varchar(10)
)

However, in an instance where your design demands that two person records may exist for the same CPF, the simple design is to have CPF's be unique, and have them point to their current person record.

CREATE TABLE persons (
  personID int IDENTITY PRIMARY KEY,
  name varchar(250)
)

CREATE TABLE cpfs (
  CPF varchar(10) NOT NULL PRIMARY KEY,
  personID int REFERENCES person(personID)
)

Give the tables above, it is a simple matter to create a view listing only the "real" person for each CPF, along with their personID.

SELECT C.CPF, P.*
FROM cfps C
INNER JOIN persons P
  ON C.personID = P.personID

And it likewise becomes simple to query for only active persons.

SELECT *
FROM someTable
WHERE personID IN (SELECT personID FROM cfps)

Now, this system does introduce a second table, and includes a modest bit of complexity.  If you don't expect multiple "person" records to stick around as a regular thing and only anticipate some few exceptions, go with option #1 instead.


问:
Are there any benefits in not having referential integrity keys in database?
So Referential integrity is good, but are there scenarios where not having constraints is better?

For example when all the logic of relationships is kept in code? or when the database upgrade is simplified?

PS: I am not asking it is good not to have referential integrity, just that what scenarios would justify it

答:
Whether you keep the relation in the database or in code, it's still a relation, and since the database can do it better, you put it there.

The database is the central repository for not only the data, but also the schema.  Put it anywhere else, and you run the risk of one copy of the frontend program having a different schema than the others.

Kaboom.


答:
The main reason would be for dealing with inconsistent data.

Many systems import data from outside and have to deal with failures and exceptions. Imagine you're importing a daily sales log from a retail shop. Inevitably the shop will need to sell something that's not in the inventory, or is mis-quantified (they sell something even though quantity on hand is zero in the database). Depending on your foreign keys either or both of those may cause a violation.

I've fixed a system like this that used key enforcement, and it was very difficult for the staff to cope with it. The import would fail if the inventory records for the shop didn't exactly match the ones in the warehouse, and I implemented a whole set of rules and manual intervention options so that staff could manually cross-link items, add items on the fly, and just say "create a new inventory item for anything that doesn't have one, and I'll fix it later". That creates its own havoc, but it's not always possible to stop the world while you sort out the data.

(edit) Worse are systems I've seen staff fighting where they can't put product through the register if it's not in the system. You walk up to the counter carrying an item that has a price tag on it, they scan it but look at you helplessly because "computer says no". Retail is all about selling what you have, and your job as a programmer is to facilitate that. So one way or another there will be a legitimate business requirement to sell non-inventory items. Supermarkets often have a "manager product" which lets selected staff type in a description and a price, either on the register at point of sale or to print a special price sticker. One construction equipment "retailer" that I did some work for had "power cords, used" as an item in their inventory... and had sold quite a few of them over the years.

This applies when dealing with external systems of any sort. You need to either have a fairly loose way of matching, create necessary primary key values on demand, or reject records, or some combination of those. And good duplicate detection.

Title: Are there any benefits in not having referential integrity keys in database?

Body:
So Referential integrity is good, but are there scenarios where not having constraints is better?

For example when all the logic of relationships is kept in code? or when the database upgrade is simplified?

PS: I am not asking it is good not to have referential integrity, just that what scenarios would justify it


答:
I'm not sure how far you've got with your design. Your description of "hole-punching" does not ring exactly true.

AS I understand it, the server has no need for client IPs except when they are on-line and available for connection. Each client connects to the server, thereby providing a current IP location and NAT channel. A user wanting to call another user amounts to a search of connected users. Your server always needs to set up the connection (because both clients use outgoing NAT channels) but if the firewalls cooperate the server can stand aside and let them talk directly to each other. Magic happens, and during that magic each client learns the other's IP.

Your concern is that a rogue client could pillage connection info from your server by rapidly trying lots of connections. If this is a rogue client you cannot necessarily control it. So here are some suggestions.

Encrypt and protect the communications, so only your client can talk to your server. Certificates are good for that.

Restrict the rate of trying connections.

Monitor the rate and number of connections, and blacklist clients that exceed limits.

Only allow 'friends' to call 'friends', and exchange no IP info until the connection is accepted by the recipient.

If that's wide of the mark feel free to update your question and I'll try again.

Title: Preventing ip resolvers in a skype-like program

Body:
I'm currently in the process of creating a Skype-like program, that uses a hybrid peer to peer system to communicate between users (i.e. server contains all users IPs, a client that wants to connect to a friend will tell the server, that will then send each client the other's IP so they could start hole punching to establish a connection between them).

I know that with Skype, there are many websites that allow you to enter a username and easily get his IP address. My question is, what is the best way of preventing such an exploit?

Here are a few solutions I could think of:

save each and every users' friends lists on the server (so the server can just drop IP requests from users that aren't in the requested client's friends list)

whenever the server is asked for a client's IP, ask that client if the asker is on their friends list (if not, don't reply)

have each client use some secret key to communicate with the server (so only registered clients will be able to send IP requests)

Feel free to add a different solution, again, these are just solutions I could think of off the top of my head while writing this question.

In addition, a related question that I wanted to ask - what would be the best practice in such a program:

Have each client store his friends' IPs and make the server notify him whenever they are changed

-VS-

Have the client ask the server for a friend's IP whenever he wants to start a direct connection with him (keep in mind that the client anyway has to tell the server whenever he's trying to connect to someone, in order for the hole punching to work).

P.S. I've never created such a program and I'm not following any tutorial or such. If there's any better way of doing something I wrote, or if I got anything wrong, I'd be very glad if you could mention it.


答:
Speed.

If you're inserting a whole heap of data, the DB doesn't need to spend its time creating indexes.

Having said that don't do this. Create the foreign keys. Never rely on application logic :)


答:
I would assume there is different action when WasSuccessful is true and different action when WasSuccessful is false. Why not put this code inside of ChangePasswordSuccessfulResult and ChangePasswordUnsuccessfulResult and call it through virtual method, thus deciding based on the type. Then, you don't have to worry about casting.

```<code>public abstract class ChangePasswordResult
{
    public abstract SomeResponseData GetResponseData();
}

public class ChangePasswordSuccessfulResult
{
    public ChangePasswordSuccessfulResult(HttpResponse  httpResponse)
    {
        // initialize the class from the httpResponse
    }

    public DateTime ExpirationDate { get; private set; }

    public override SomeResponseData GetResponseData()
    {
        // return data for successful result
    }
}

public abstract class ChangePasswordUnsuccessfulResult
{
    public ChangePasswordUnsuccessfulResult(HttpResponse  httpResponse)
    {
        // initialize the class from the httpResponse
    }

    public bool WasPasswordLongEnough { get; private set; }
    public bool DoesPasswordHaveToContainNumbers { get; private set; }
    // ... etc.

    public override SomeResponseData GetResponseData()
    {
        // return data for unsuccessful result
    }
}
</code>```

Body:
I would assume there is different action when WasSuccessful is true and different action when WasSuccessful is false. Why not put this code inside of ChangePasswordSuccessfulResult and ChangePasswordUnsuccessfulResult and call it through virtual method, thus deciding based on the type. Then, you don't have to worry about casting.

public abstract class ChangePasswordResult
{
    public abstract SomeResponseData GetResponseData();
}

public class ChangePasswordSuccessfulResult
{
    public ChangePasswordSuccessfulResult(HttpResponse  httpResponse)
    {
        // initialize the class from the httpResponse
    }

    public DateTime ExpirationDate { get; private set; }

    public override SomeResponseData GetResponseData()
    {
        // return data for successful result
    }
}

public abstract class ChangePasswordUnsuccessfulResult
{
    public ChangePasswordUnsuccessfulResult(HttpResponse  httpResponse)
    {
        // initialize the class from the httpResponse
    }

    public bool WasPasswordLongEnough { get; private set; }
    public bool DoesPasswordHaveToContainNumbers { get; private set; }
    // ... etc.

    public override SomeResponseData GetResponseData()
    {
        // return data for unsuccessful result
    }
}


问:
Onion Architecture Structure
I am looking to understand and implement the Onion Architecture and have a vague idea on how  to structure everything but need help to clear up some of my confusion.

Based on different examples and articles I Have read I created the above structure. One of my main confusion comes when I look at "02-Service: Services Interfaces". Lets take the IUserService.cs. I assume this interface would contain different signatures like RegisterUser(), LoginUser(), BanUser(), ModifyUser(), ChangeAuthenticationLevel() and so on? Is this correct? If not what other examples would we find? And are these considered Domain Services or Application Services?

答:
I assume this interface would contain different signatures like RegisterUser(), LoginUser(), BanUser(), ModifyUser(), ChangeAuthenticationLevel() and so on? Is this correct?

No it is not. See, how there is User in each of those methods? That means it operates on user, and thus is part of the User entity. And as such, they should all be methods on User class and not part of service. Actually, from DDD perspective, Service is still part of the domain. It contains behavior that does not belong to any entity, but something like that should be extremely rare. For example, Repository is specific type of service.

Title: Onion Architecture Structure


答:
I think it's mostly because of legacy reasons.

Some of Java's older apis are not immutable (the Date class is a mutable object, there is probably an alternative in java 8 now). Thus an argument for using getters is to potentially return immutable instances of these older objects. This is in contrast with functional programming where everything is considered immutable by default.

Making things public and final does not necessarily make them immutable in java. As a simple example if a List was final, the object might not be mutable but the contents within the list are (functional programming would return a new immutable list in this case)

Java also has a JavaBeans specification which recommends the use of getters and setters. It supposedly aids in portability (which is probably why frameworks use this for reflection purposes, although some do inspect the fields itself)


答:
Okay i am going to try to keep this simple and concise.

Recursive function are functions that call themselves. Recursive function consist of three things:

Logic

A call to itself

When to terminate.

Best ways to write recursive methods, is to think of the method that you trying to write as a simple example only handling one loop of the process you want to iterate over, then add the call to the method itself, and add when you want to terminate. Best way to learn is to practice like all things.

Since this is programmers website I will refrain from writing code but here is a good link

if you got that joke you got what recursion means.

Title: In plain English, what is recursion?

Body: The idea of recursion is not very common in real world. So, it seems a bit confusing to the novice programmers. Though, I guess, they become used to the concept gradually. So, what can be a nice explanation for them to grasp the idea easily?</p>


答:
First: It is reasonable to use Functions instead of fields, because the syntax is different! If you have Code which ist int x = point.x and you decide to change the internal representation of Point to a lazy model which calculates x only when needed, you would have to refactor all legacy code, since a public field access and a method call are fundamentally different: So the code would have to be rewritten to int x = point.x()

So why should we call accessor-Methods to fields getX() instead of just X() ? because it is convention. The argument because everyone does it is perfectly acceptable here. Why do we write Classnames in Camel-Case? Why do we first declare Fields and then Methods in a class? Why do we call the iteration-variable in a simple for-loop i ?

Because it is idiomatic. Almost every Java-Programmer will expect it this way and can easily understand and maintain your code if you follow theses conventions. If you choose a different style and choose different names and code-style you should have a really good reason why this other style is better, because it will make your code less portable and harder to maintain!


答:
There are two important factors you did not mention.

Do you want to retain copyright for future benefit to you, or is this purely community?

Do you want to make money out of this, or will you compete with someone who does?

The basic breakdown is this. If you make no money out of it and harm no-one then just do your best, acknowledge the work of others and don't worry too much. Distribute your code any way that makes sense to you, including dependencies if you like. No-one will be harmed and the community will love you. Don't sweat it. If you need to do something different, wait until someone tells you and then talk to them.

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

The point of this answer is that you should worry far more about whether you code is valuable to others, whether you are contributing to the community and whether you are likely to upset someone than you should worry about the nuances of wording. You cannot get it exactly right without a lawyer but you don't need a lawyer to 'do the right thing'. Do your best, and get on with what you do best: writing code.

Title: How should I include jQuery in a library?

Body:
I'm writing a JavaScript graphing library using canvas which I am licensing under MIT, and I'm using jQuery, as well as a couple of other open sourced libraries, all under MIT. I'm also using bower to manage my front-end dependencies. How should I best handle these dependencies without violating the license?

Preferably, the user would not have to include multiple scripts, just one , and it would include all of the plugins.

Should I just ask the user to include jQuery and the other libraries in its own script tag, or should I concat all of the scripts together into one big file, headers included?