问:
Why do some programming languages have break statements, but not higher-order break statements?
I may have been exposed to exactly the wrong languages, but though many have loops and break statements, none of the languages I am familiar with have higher-order break statements¹. While a regular break statement terminates the innermost loop inside which it is executed, such a break(n) statement would terminate the n innermost loops.

For example using such a statement, I could write in Python:

for i in range(100):
    for j in range(100):
        if foo(i,j):
            break(2)
```

<p>As Python lacks such a statement, however, I have to do something like the following:</p>

<pre class="lang-python prettyprint-override"><code>broken = False
for i in range(100):
    for j in range(100):
        if foo(i,j):
            broken = True
            break
    if broken:
        break
</code>```

(I am aware that there are other ways to do this, such as raising exceptions. This serves just as an example.)

In another example, this is one of the prominent reasons to use a goto statement in C/C++. While goto allows for a close equivalent of a higher-order break, it introduces a new syntactical element (unless one already uses gotos). Not to forget that goto is frowned upon by many – be it justified or not.

While I see that using a higher-order break statement is not something most people use on a daily basis, this also applies to a lot of other language features. Also, a higher-order break statement does not seem difficult to implement to me and would be rather intuitive to use.

Is there a good reason why programming languages would have a break statement but not a higher-order break statement? I am thinking of things like inherent conceptual problems, broken paradigms or error vulnerability.

¹ Though, when researching for this question, I learnt that PHP has them.

答:
Because while and until provide clearer semantics. They provide higher level abstractions for expressing programmer intent. The semantics of break are imperative at the lower level of instructions to the computer. They are closer to that of machine code - like goto, break is thin syntactic sugar over JMP.

McConnell's basic advice:

When to Use a for Loop.  If you have a condition under which execution has to jump out of a loop, use a while loop
  instead....Most complicated looping tasks are better handled by a
  while loop. -- Code Complete [first edition] pp 329.

This is really just an extension of his more general advice:

Use break and continue only with caution. Use of break
  eliminates the possibility of treating a loop as a black box. Limiting
  yourself to only one statement to control a loop's exit condition is a
  powerful way to simplify your loops. Using break forces the person
  reading your code to look inside the loop for an understanding of the
  loop control. This makes the loop more difficult to understand.
  -- Code Complete [first edition] pp 337-338.

In the end his "key point" is:

Minimize the number of factors that affect the loop. Simplify!
  Simplify! Simplify! Second treat the inside of the loop as if it were
  a routine -- keep as much of the control as possible outside the loop.
  Explicitly state the conditions under which the body of the loop is to
  be executed. Don't make the reader look inside the loop to understand
  the loop control. Think of a loop as a black box: The surrounding
  program knows the control conditions but not the contents.


问:
Does ODBC require any run-time software beyond an .exe file to run against MySQL and ORACLE SQL?
I'm writing a software [under Windows] in C++ which later needs to be able to connect to both MySQL and ORACLE SQL. Now the software needs to be as simple for the user as possible.

Now I'm considering using ODBC.

If I use ODBC, does the software later need any additional drivers, or only during development? When I have the .exe file, do I need any additional software to have it run on any computer or simply the executable?

答:
I think that you are mixing a variety of requirements and concepts and need to revisit your architecture.

A simple user application is NOT a function of the drivers you have! This is more about platform, UI design and usability tricks. You need to separate these efforts in your mind.

Just because your data has MySQL and Oracle doesn't mean that your GUI will also need MySQL and Oracle. You could have (1) a pre-processing step to combine data or (2) add an API layer that will make the database agnostic.

You shouldn't have your users access your database directly anyways. So why not create an API/services layer (like REST) and have your app access it that way. From there, the API layer can access any number of databases and you won't have any worries about drivers on the GUI side. It simply makes more sense to do it this way and minimizes potential pitfalls for your end users.

ContentLicense: CC BY-SA 3.0


答:
Is there a good reason why so few programming languages have higher-order break statements?

Using SO tags as the metric, the seven most popular programming languages in use today are Java, C#, Javascript, PHP, Python, C++, and Objective C. Of these languages,

Java and Javascript have labeled break

C++, C#, and Objective C have goto, which is a more general control statement that solves the same problem. They also all have break, naturally, but no multi-level or labeled break

PHP has both nested (multi-level) break and goto

and Python is the odd man out with no goto and no labeled break.

So maybe a better question is,

Why doesn't Python have goto or labeled break? ;)

This question has an answer to that question:

Guido rejected it because "code so complicated to require this feature is very rare". The PEP does mention some workarounds, though (such as the exception technique), while Guido feels refactoring to use return will be simpler in most cases.

Personally, I think Python should have one or both, but that is opinionated so don't take it as part of this answer.

Title: Why do some programming languages have break statements, but not higher-order break statements?

Body:
I may have been exposed to exactly the wrong languages, but though many have loops and break statements, none of the languages I am familiar with have higher-order break statements¹. While a regular break statement terminates the innermost loop inside which it is executed, such a break(n) statement would terminate the n innermost loops.

For example using such a statement, I could write in Python:

for i in range(100):
    for j in range(100):
        if foo(i,j):
            break(2)
```

<p>As Python lacks such a statement, however, I have to do something like the following:</p>

<pre class="lang-python prettyprint-override"><code>broken = False
for i in range(100):
    for j in range(100):
        if foo(i,j):
            broken = True
            break
    if broken:
        break
</code>```

(I am aware that there are other ways to do this, such as raising exceptions. This serves just as an example.)

In another example, this is one of the prominent reasons to use a goto statement in C/C++. While goto allows for a close equivalent of a higher-order break, it introduces a new syntactical element (unless one already uses gotos). Not to forget that goto is frowned upon by many – be it justified or not.

While I see that using a higher-order break statement is not something most people use on a daily basis, this also applies to a lot of other language features. Also, a higher-order break statement does not seem difficult to implement to me and would be rather intuitive to use.

Is there a good reason why programming languages would have a break statement but not a higher-order break statement? I am thinking of things like inherent conceptual problems, broken paradigms or error vulnerability.

¹ Though, when researching for this question, I learnt that PHP has them.


问:
Finding out which version of a file a line was added/changed
Is it generally possible while using source code management to figure out in what version of a file a specific line was added? If so, what SCM systems support this?</p>

答:
In perforce the easiest way is to run p4v and look at the file's "Time-lapse view".

For every line of code you can see which revision it was added, and if you fiddle with the range sliders at the top you can see which lines were deleted.


问:
Is it okay to use exceptions as tools to "catch" errors early?
I use exceptions to catch problems early. For example:

```<code>public int getAverageAge(Person p1, Person p2){
    if(p1 == null || p2 == null)
        throw new IllegalArgumentException("One or more of input persons is null").
    return (p1.getAge() + p2.getAge()) / 2;
}
</code>```

My program should never pass null in this function. I never intend it to. However as we all know, unintended stuff happens in programming.

Throwing an exception if this problem occurs, allows me to spot and fix it, before it causes more problems in other places in the program. The exception stops the program and tells me "bad stuff happened here, fix it". Instead of this null moving around the program causing problems elsewhere.

Now, you're right, in this case the null would simply cause a NullPointerException right away, so it might not be the best example.

But consider a method such as this one for example:

```<code>public void registerPerson(Person person){
    persons.add(person);
    notifyRegisterObservers(person); // sends the person object to all kinds of objects.
}
</code>```

In this case, a null as the parameter would be passed around the program, and might cause errors much later, which will be hard to trace back to their origin.

Changing the function like so:

```<code>public void registerPerson(Person person){
    if(person == null) throw new IllegalArgumentException("Input person is null.");
    persons.add(person);
    notifyRegisterObservers(person); // sends the person object to all kinds of objects.
}
</code>```

Allows me to spot the problem much before it causes weird errors in other places.

Also, a null reference as a parameter is only an example. It could be many kinds of problems, from invalid arguments to anything else. It's always better to spot them early.

So my question is simply: is this good practice? Is my use of exceptions as problem-preventing tools good? Is this a legitimate application of exceptions or is it problematic?

答:
Yes, throwing exceptions is a good idea. Throw them early, throw them often, throw them eagerly.

I know there's an "exceptions vs. assertions" debate, with some kinds of exceptional behavior (specifically, the ones thought to reflect programming errors) handled by assertions that can be "compiled out" for runtime rather than debugging/testing builds. But the amount of performance consumed in a few extra correctness checks is minimal on modern hardware, and any extra cost is far outweighed by the value of having correct, uncorrupted results. I've never actually met an application codebase for which I'd want (most) checks removed at runtime.

I'm tempted to say I wouldn't want a lot of extra checking and conditionals within the tight loops of numerically intensive code...but that's actually where a lot of numerical errors are generated, and if uncaught there, will propagate outward to effect all results. So even there, checks are worth doing. In fact, some of the best, most efficient numerical algorithms are based on error evaluation.

One final place to be very conscious of extra code is very latency-sensitive code, where extra conditionals can cause pipeline stalls. So, in the middle of operating system, DBMS, and other middleware kernels, and low-level communication/protocol handling. But again, those are some of the places errors are most likely to be observed, and their (security, correctness, and data integrity) effects to be most damaging.

One improvement I have found is to not throw only base-level exceptions. IllegalArgumentException is good, but it can come from essentially anywhere. It doesn't take much in most languages to add custom exceptions. For your person-handling module, say:

```<code>public class PersonArgumentException extends IllegalArgumentException {
    public MyException(String message) {
        super(message);
    }
}
</code>```

Then when someone sees a PersonArgumentException, it's clear where it's coming from. There's a balancing act about how many custom exceptions you want to add, because you don't want to multiply entities unnecessarily (Occam's Razor). Often just a few custom exceptions are enough to signal "this module isn't getting the right data!" or "this module can't do what it's supposed to do!" in a way that is specific and tailored, but not so over-precise that you have to re-implement the entire exception hierarchy. I often come to that small set of custom exceptions by starting with stock exceptions, then scanning the code and realizing that "these N places are raising stock exceptions, but they boil down to the higher-level idea that they're not getting the data they need; let's replace those stock exceptions with a higher-level exception that more clearly communicates what's really going on."

Body:
Yes, throwing exceptions is a good idea. Throw them early, throw them often, throw them eagerly.

I know there's an "exceptions vs. assertions" debate, with some kinds of exceptional behavior (specifically, the ones thought to reflect programming errors) handled by assertions that can be "compiled out" for runtime rather than debugging/testing builds. But the amount of performance consumed in a few extra correctness checks is minimal on modern hardware, and any extra cost is far outweighed by the value of having correct, uncorrupted results. I've never actually met an application codebase for which I'd want (most) checks removed at runtime.

I'm tempted to say I wouldn't want a lot of extra checking and conditionals within the tight loops of numerically intensive code...but that's actually where a lot of numerical errors are generated, and if uncaught there, will propagate outward to effect all results. So even there, checks are worth doing. In fact, some of the best, most efficient numerical algorithms are based on error evaluation.

One final place to be very conscious of extra code is very latency-sensitive code, where extra conditionals can cause pipeline stalls. So, in the middle of operating system, DBMS, and other middleware kernels, and low-level communication/protocol handling. But again, those are some of the places errors are most likely to be observed, and their (security, correctness, and data integrity) effects to be most damaging.

One improvement I have found is to not throw only base-level exceptions. IllegalArgumentException is good, but it can come from essentially anywhere. It doesn't take much in most languages to add custom exceptions. For your person-handling module, say:

public class PersonArgumentException extends IllegalArgumentException {
    public MyException(String message) {
        super(message);
    }
}

Then when someone sees a PersonArgumentException, it's clear where it's coming from. There's a balancing act about how many custom exceptions you want to add, because you don't want to multiply entities unnecessarily (Occam's Razor). Often just a few custom exceptions are enough to signal "this module isn't getting the right data!" or "this module can't do what it's supposed to do!" in a way that is specific and tailored, but not so over-precise that you have to re-implement the entire exception hierarchy. I often come to that small set of custom exceptions by starting with stock exceptions, then scanning the code and realizing that "these N places are raising stock exceptions, but they boil down to the higher-level idea that they're not getting the data they need; let's replace those stock exceptions with a higher-level exception that more clearly communicates what's really going on."


问:
What does the => symbol do in haskell?
I'm fairly new to learning haskell, so I don't really understand the typing system when it comes to constraints. There's this weird => symbol that doesn't make sense to me. Is it actually just syntax? Or is it a type constructor? I'm not sure. Below are my thoughts about it. Can someone clarify what exactly => means in haskell?

In haskell, (->) is a type constructor, with kind * -> * -> *. This is nice, because it makes it clear why, for example, Double -> Bool has kind *. But then I wondered about types like (Integral a) => a -> a. Clearly, this has kind *, and a -> a has kind * (I think). Since Integral has kind * -> Constraint, Integral a must have kind Constraint. Then, I conclude that (=>) has kind Constraint -> * -> *. However, when I type :k (=>) in GHCi, I get an error ("parse error on input =>")! This seems to indicate that (=>) is not a type constructor. Then what is it?

GHCi also tells me that (Show List, Read List) has kind Constraint, but that (,) has kind * -> * -> *, which makes me very confused. Does (,) have two definitions? Are constraints some magical hocus-pocus that I just don't understand?

Any help is greatly appreciated.

答:
The => is just there as a delimiter between context and type when you write a type signature. They aren't even saved after compilation. You can see it here:
http://www.haskell.org/onlinereport/syntax-iso.html</p>

Title: What does the => symbol do in haskell?


问:
Local Updates in Persistent/Immutable Data Structures
I'm getting into ReactJS and am intrigued but also confused about persistent data structures. I love the idea, but I'm not sure how to take my MV*, Mutable, Observable Bindings experience in designing view components and apply it in a sane way.

For example, suppose I have a deeply nested structure:

```<code>Foo
  Bar
     Baz
      someValue
  Qux
  Quxx
</code>```

In my UI, I have a component that is an editor for someValue. In a mutate-observe paradigm I would do something like:

```<code>Baz.setSomeValue(newValue)  // trigger observers, etc...
</code>```

As near as I can tell, though, the equivalent with persistent data structures is something like:

```<code>Foo = extend(Foo, { Bar:{ Baz:{ someValue: newValue } } });
// recompute with new value of Foo
</code>```

What is the normal pattern for encapsulating a component that deals with Baz so that it doesn't have to know the entire structure?

答:
Part of your trouble is that you're using JavaScript and not a functional programming language like ClojureScript.  In ClojureScript you'd have the aid of atoms and update-in and assoc-in to help with these nested structural updates.  Languages that don't emphasize doing everything with persistent data structures aren't optimized for this use case.

However, that said, there is another way.  One thing I've taken to is modeling complex objects (anything made up of key/value pairs) as entities.  Each object upon creation would be assigned an immutable ID (I used BSON IDs but GUIDs will do).  Then in this manner you're able to eliminate all nesting:

```<code>function Entities(state){
  this.state = state || {}; //never mutated
}
Entities.prototype.update = function(id, immutableData){...};
Entities.prototype.get = function(id){...};

function Ref(id){
  this.id = id; //never mutated
}

var entities = new Entities();
entities = entities.update(1, {id: 1, name: 'Foo'});
entities = entities.update(2, {id: 2, name: 'Bar', children: [new Ref(1)]});
entities = entities.udpate(3, {id: 3, name: 'Baz', children: [new Ref(2)]});
entities = entities.update(3, entities.get(3).set('name', "Bazooka"))
</code>```

The update method doesn't mutate, but rather returns a new representation of the modified entity state object;

By using Reference objects, you've effectually eliminated the nesting altogether.  You could use the actual integers instead of Refs; however, that doesn't make it clear that what you have in your children array is actually a reference to some other entity.  Wrapping it effectively transforms the integer into a Ref type.  It's up to you to interpret the ref type as a pointer to the entity.

Body:
Part of your trouble is that you're using JavaScript and not a functional programming language like ClojureScript.  In ClojureScript you'd have the aid of atoms and update-in and assoc-in to help with these nested structural updates.  Languages that don't emphasize doing everything with persistent data structures aren't optimized for this use case.

However, that said, there is another way.  One thing I've taken to is modeling complex objects (anything made up of key/value pairs) as entities.  Each object upon creation would be assigned an immutable ID (I used BSON IDs but GUIDs will do).  Then in this manner you're able to eliminate all nesting:

function Entities(state){
  this.state = state || {}; //never mutated
}
Entities.prototype.update = function(id, immutableData){...};
Entities.prototype.get = function(id){...};

function Ref(id){
  this.id = id; //never mutated
}

var entities = new Entities();
entities = entities.update(1, {id: 1, name: 'Foo'});
entities = entities.update(2, {id: 2, name: 'Bar', children: [new Ref(1)]});
entities = entities.udpate(3, {id: 3, name: 'Baz', children: [new Ref(2)]});
entities = entities.update(3, entities.get(3).set('name', "Bazooka"))

The update method doesn't mutate, but rather returns a new representation of the modified entity state object;

By using Reference objects, you've effectually eliminated the nesting altogether.  You could use the actual integers instead of Refs; however, that doesn't make it clear that what you have in your children array is actually a reference to some other entity.  Wrapping it effectively transforms the integer into a Ref type.  It's up to you to interpret the ref type as a pointer to the entity.


问:
Unit testing classes that have online functionality
When unit testing functions of a class that has private functions that require online functionality. How would one go about testing it?

For example:

```<code>public class Foo
{
    public int methodA()
    {
         int val = goOnlineToGetVal();

         return val;
    }

    private int goOnlineToGetVal()
    {
        CloudService c = new CloudService();
        int oval = c.getValueFromService();
        return oval;
    }
}
</code>```

If I were to test function: 'methodA()' it would attempt to use 'goOnlineToGetVal()' which would in turn try to go online however, if this test was done without functionality. How would I go about 100% Class coverage without going online?

答:
new CloudService()

And there's your problem.

Modern OO design recommends that this sort of dependency be passed in rather than constructed directly. This can be passed into the function itself, or to the class at construction time. It could also be grabbed or aggregated by an Inversion of Control container if that sort of complexity is warranted.

At that point, it becomes fairly trivial to pass in a mock/fake service to provide you with your "online" data during testing. Better yet, it allows your software to be sufficiently flexible, so that you can quickly adapt should some (governmental?) client comes along and doesn't want to use the cloud for their values. Or you want to dump one cloud provider for another. Or...


答:
I would implement it like this:

```<code>public class Foo
{
    private ICloudService cloudService;

    public Foo(ICloudService s)
    {
       cloudService=s;
    }

    public int methodA()
    {
         int val = goOnlineToGetVal();

         return val;
    }

    private int goOnlineToGetVal()
    {
        int oval = cloudService.getValueFromService();
        return oval;
    }
}
</code>```

The interface ICloudService can be either implemented with a mock for testing, or with the "real" cloudservice. When the instantiation new CloudService() is mandatory for every call of getValueFromService, or CloudServiceis from a 3rd party API which cannot be changed, implement a wrapper, deriving from ICloudService and making the appropriate calls.

Title: Unit testing classes that have online functionality

Body:
When unit testing functions of a class that has private functions that require online functionality. How would one go about testing it?

For example:

```<code>public class Foo
{
    public int methodA()
    {
         int val = goOnlineToGetVal();

         return val;
    }

    private int goOnlineToGetVal()
    {
        CloudService c = new CloudService();
        int oval = c.getValueFromService();
        return oval;
    }
}
</code>```

If I were to test function: 'methodA()' it would attempt to use 'goOnlineToGetVal()' which would in turn try to go online however, if this test was done without functionality. How would I go about 100% Class coverage without going online?

Body:
I would implement it like this:

public class Foo
{
    private ICloudService cloudService;

    public Foo(ICloudService s)
    {
       cloudService=s;
    }

    public int methodA()
    {
         int val = goOnlineToGetVal();

         return val;
    }

    private int goOnlineToGetVal()
    {
        int oval = cloudService.getValueFromService();
        return oval;
    }
}

The interface ICloudService can be either implemented with a mock for testing, or with the "real" cloudservice. When the instantiation new CloudService() is mandatory for every call of getValueFromService, or CloudServiceis from a 3rd party API which cannot be changed, implement a wrapper, deriving from ICloudService and making the appropriate calls.


问:
Runtime analysis of functions that call other functions
If you have a function being called in another function, do you figure out the runtime for the being called and then "add" that to function you wish to analyze the runtime for?

Function to be analyzed:

```<code>for (i = 0, i > n, ++i)
{
    if (function.call() > 0)
    {
        \\something
    }
}
</code>```

Function called:

```<code>Call
{
   for (i = 0, i > n, ++i)
    {
        \\return something
    }
}
</code>```

答:
@Rufflewind had it right in the comments, you have to substitute the function call - think closer to copy/pasting the subfunction into the main function. This can get a bit nasty when you have recursive calls, as you might guess.

One important thing to keep in mind is the "what" of your analysis. Usually big-O style runtime analysis picks a certain number of operations to measure - swaps, additions, multiplications, etc. You may have cases where the subfunction does work, but none of the operations being measured, in which case it should drop out of analysis.

So it looks like in your example that the outer loop would be O(N) if the subfunction did "no work", but when you substitute it, you'll end up with some O(N^2) type of operation.


问:
To subclass or to wrap for "default" implementation?
I'm creating a toolset in Java consisting of many Natural Language Processing (NLP) tools, such as Tokenizer, POS tagger, Lemmatizer, Sentence parsing, etc.

I want to put all good and publicly available tools into my toolset, all sharing the same interface, so that I can change library easily without change of API.

The project structure is something like this:

tokenizer/
    Tokenizer.java (an interface)
    LibraryFooTokenizer.java (from first library)
    LibraryBarTokenizer.java (from second library)
    DefaultTokenizer.java (a default tokenizer)
lemmatizer/
    Lemmatizer.java
    LibraryFooLemmatizer.java
    LibraryBarLemmatizer.java
    DefaultLemmatizer.java
```
</blockquote>

<p>The <code>Library*Tokenizer.java</code> are implementing <code>Tokenizer.java</code>, so I can directly use <code>Tokenizer</code> in my applications without needing to know the implementation details. So far so good.</p>

<p>My question is regarding the implementation of <code>DefaultTokenizer.java</code>. It's supposed to be for someone who just want to use a Tokenizer, who perhaps doesn't really know from the list of available Tokenizer which one is the best.</p>

<p><strong>Should it be a subclass of the currently best library, or should it implement the interface and has the best library as a member, or else?</strong></p>

<p>Currently I use the second approach as follows:</p>

<pre class="lang-java prettyprint-override"><code>package tokenizer;

public class DefaultTokenizer implements Tokenizer{
    public Tokenizer tokenizer;

    public DefaultTokenizer(){
        tokenizer = new LibraryFooTokenizer();
    }

    @Override
    public String[] tokenizer(String text){
        return tokenizer.tokenize(text);
    }
}
</code>```

Is it better than this one?

package tokenizer;

public class DefaultTokenizer extends LibraryFooTokenizer{}
```

The points that I'm considering are the ease of modification, in case later LibraryBarTokenizer is updated and becomes better, I want to update to that one.

You can also review this in term of ease of debugging, is it nice with common IDE (I'm currently using Eclipse)?

I'm currently using this as internal research toolset, to compare various implementations. There are some use cases why DefaultTokenizer might be required:

Sometimes we might decide that we want to change the library for Tokenizer (an update makes it better, change of license makes it (in)appropriate). Now, on codes that doesn't care about which Tokenizer is used, but only requiring the best one, using Default makes change easier, since we just need to change which library is the default.

It might be the case that there will be someone trying to use a Tokenizer component while developing new component. While it's true that in research one is supposed to know the details of each component, sometimes we want to test something for which the Tokenizer is not that crucial to the result, but is required. In that case, taking the default might be good (and if the result changes if the Tokenizer is changed, then there is something wrong with how the Tokenizer is used).

Those reasons might not be too compelling, but we decided to use such default implementation, and currently I'm looking for ways to improve how we implement the default, hence this question.

It might be the case that using default is that bad for reasons I haven't considered. In that case, that also qualifies as an answer.

But I will be glad if someone can offer more insights on how this can be improved, or whether it doesn't matter much which way I choose.

答:
You are missing option 3 (and more).

Don't have a DefaultTokenizer.

There is no value, and it leads people to make choices that reduce maintainability later. Additionally, the problem can be solved with sensible documentation.

Reasons not to have the Default:

you actually can't change it later, because people expect the default to be a specific representation, and they just use default because it was convenient.

you will need to continuously maintain option 1, where you wrap the instance.

you have an ugly empty implementation for option 2.

So, just don't do it. Do you see a 'DefaultList' class, or a 'DefaultMap' class? Do you see a 'DefaultInputStream', or 'DefaultNumber'? no.

Default class implementations are bad. Let people read your JavaDoc, and tell them which one is expected to be used in common cases. If the differences were not important, then you would not have the two implementations, so document the differences, and explain when to use which one.

OwnerDisplayName: justhalf

OwnerDisplayName: rolfl


问:
What kinds of non-source artifacts are vital to your development process?
The "classic" development artifacts are requirements documents and design specifications. But the development process includes many other non-source code artifacts: bug tracking databases, emails, wikis.

What kinds of non-source code artifacts do you think are most vital to your development process? And how do you keep these documents up to date?

Also, are there any artifacts that you don't necessarily find useful, but have to use because it's required by the contractor or management?

答:
Use Case

Use Case is most vital for development process.
For each new use case we simply update them and relate them to the case number.
At the backend there is of course a versioning tool.

ContentLicense: CC BY-SA 2.5


问:
Use and manage Front End Assets for Web
I am  a beginner and am currently developing a kind of cms using PHP. The number of libraries that we can potentially use in the front end is large.  I have a question about properly selecting, managing and using front end asset libraries.

I don't think just including a bunch of front end libraries like this is the best approach:

```<code><script src="library1" /></script>
<script src="library2" /></script>
<script src="library3" /></script>
// and soon..
</code>```

What if we use, let's say 20 ? Is that good practice, declaring the script tags 20 times ?

What I do currently is use Assetic, a php library for managing assets. I create a dump file (and cache it) for each request to my application before loading a template. My controller (I use MVC) could be something like this:

```<code>function indexAction()
{
    // some logic

    $assetManager = $this->get('assetic'); // get assetic service
    $css = $assetManager->createAsset(array(
            '@bootstrap',
            '@jquery_ui'
             // and many other library
    ));

     $assetContent = $css->dump();

     // create asset url, dont mind about this
     $data['stylesheet'] = $this->createAssetUrl($assetContent);

    return $this->render('index-template', $data);
}
</code>```

And in the template (index-template), I could put kind of:

```<code><link href="<?php echo $stylesheet ?>" rel="stylesheet" type="text/css">
</code>```

I do that in almost every controller to include a bunch of assets to view. But I am not sure if this is the best method. Are there any better practical method that I don't know ?

答: First of all, using too many

Title: Use and manage Front End Assets for Web

Body:
First of all, using too many <script> tags that link to or refer to any other file is a bad practice. Because the more the number of link to external resources, the more will be your http request which will slow your website down.

When a site is launched to production environment, generally all the different css files are merged into one (keep in mind that, this is done only when everything is complete and you don't have to make that many changes to these files) and so is with the js files.

About the management of assets, I guess Laravel has the best assets manager at present.


问:
The importance of duplicate code removal
I tried to explain to a coworker the gravity of having duplicate code in a project, on this piece of code:

```<code>+ (void)createIapInParse:(SKPaymentTransaction *)transaction {
    Reachability *reach = [Reachability reachabilityWithHostname:@"www.facebook.com"];
    if ([Social getFBUser]) {
        NSString *iapId = [Util getBundleNameFromIdentifier:transaction.payment.productIdentifier];
        PFObject *iap = [PFObject objectWithClassName:@"Iap"];
        iap[@"iapId"] = iapId == nil ? [NSNull null] : iapId;
        iap[@"userId"] = [Social getFBUser].objectID == nil ? [NSNull null] : [Social getFBUser].objectID;
        iap[@"email"] = [Social getFBUser][@"email"] == nil ? [NSNull null] : [Social getFBUser][@"email"];
        iap[@"country"] = [Util getDeviceCountry];
        iap[@"installationId"] = [Util getInstallationId];
        iap[@"score"] = [NSNumber numberWithLong:[GameScore getTotalScore]];
        NSTimeInterval interval = [[NSUserDefaults standardUserDefaults] doubleForKey:@"timeSpentInApp"];
        iap[@"timeSpentInApp"] = [NSNumber numberWithDouble:interval];
        iap[@"retries"] = @0;
        iap[@"transactionIdentifier"] = transaction.transactionIdentifier;
        iap[@"transactionDate"] = transaction.transactionDate;
        iap[@"transactionSource3G"] = [NSNumber numberWithBool:[reach isReachableViaWWAN]];
        [iap saveInBackgroundWithBlock:^(BOOL succeded, NSError *error) {
            NSString *query =[NSString stringWithFormat: @"...", iap.objectId, transaction.payment.productIdentifier];
            [ZeeSQLiteHelper executeQuery:query];
        }];
        NSLog(@"Save in parse: %@", iap);
    } else {
        NSString *iapId = [Util getBundleNameFromIdentifier:transaction.payment.productIdentifier];
        PFObject *iap = [PFObject objectWithClassName:@"Iap"];
        iap[@"iapId"] = iapId == nil ? [NSNull null] : iapId;
        iap[@"userId"] = @"-";
        iap[@"email"] = @"-";
        iap[@"country"] = [Util getDeviceCountry];
        iap[@"installationId"] = [Util getInstallationId];
        iap[@"score"] = [NSNumber numberWithLong:[GameScore getTotalScore]];
        NSTimeInterval interval = [[NSUserDefaults standardUserDefaults] doubleForKey:@"timeSpentInApp"];
        iap[@"timeSpentInApp"] = [NSNumber numberWithDouble:interval];
        iap[@"retries"] = @0;
        iap[@"transactionIdentifier"] = transaction.transactionIdentifier;
        iap[@"transactionDate"] = transaction.transactionDate;
        iap[@"transactionSource3G"] = [NSNumber numberWithBool:[reach isReachableViaWWAN]];
        [iap saveInBackgroundWithBlock:^(BOOL succeded, NSError *error) {
            NSString *query =[NSString stringWithFormat: @"...", iap.objectId, transaction.payment.productIdentifier];
            [ZeeSQLiteHelper executeQuery:query];
        }];
        NSLog(@"Save in parse: %@", iap);
    }
}
</code>```

I refactored it to:

```<code> + (void)createIapInParse:(SKPaymentTransaction *)transaction {

    Reachability *reach = [Reachability reachabilityWithHostname:@"www.facebook.com"];
    NSString *iapId = [Util getBundleNameFromIdentifier:transaction.payment.productIdentifier];
    PFObject *iap = [PFObject objectWithClassName:@"Iap"];
    NSTimeInterval interval = [[NSUserDefaults standardUserDefaults] doubleForKey:@"timeSpentInApp"];

    iap[@"iapId"] = iapId == nil ? [NSNull null] : iapId;
    iap[@"country"] = [Util getDeviceCountry];
    iap[@"installationId"] = [Util getInstallationId];
    iap[@"score"] = [NSNumber numberWithLong:[GameScore getTotalScore]];
    iap[@"timeSpentInApp"] = [NSNumber numberWithDouble:interval];
    iap[@"retries"] = @0;
    iap[@"transactionIdentifier"] = transaction.transactionIdentifier;
    iap[@"transactionDate"] = transaction.transactionDate;
    iap[@"transactionSource3G"] = [NSNumber numberWithBool:[reach isReachableViaWWAN]];

    if ([Social getFBUser]) {
        iap[@"userId"] = [Social getFBUser].objectID == nil ? [NSNull null] : [Social getFBUser].objectID;
        iap[@"email"] = [Social getFBUser][@"email"] == nil ? [NSNull null] : [Social getFBUser][@"email"];
    } else {
        iap[@"userId"] = @"-";
        iap[@"email"] = @"-";
    }

    [iap saveInBackgroundWithBlock:^(BOOL succeded, NSError *error) {
        NSString *query =[NSString stringWithFormat: @"...", iap.objectId, transaction.payment.productIdentifier];
        [ZeeSQLiteHelper executeQuery:query];
    }];

    NSLog(@"Saved in parse: %@", iap);
}
</code>```

and he kept arguing with me that it's the same thing.

His primary argument was that "he's a good programmer and he can understand and read even the first version fast enough" so he doesn't care if it's written like that or not.

The question is, am I really wrong? Is this not so important for everyone? It's a subjective matter or he doesn't understand that's not the same thing?

答:
You're right.

"So, what happens if somebody other than you needs to add a field to iap? Will they remember to add it to both branches?"

Essentially, this is a question of the bus factor - if there's only one person who can effectively maintain the code, then you have a problem because they won't necessarily be around for ever, whether that be because they do actually get hit by a bus, because they decide to move on for pastures new, because management decides that one employee should no longer be employed by the company, or just because there's a critical bug that needs to be fixed while the employee is on holiday. Ideally, code should be maintainable by any developer reasonably familiar with the code, not just by the one particular expert on that bit of code.


答:
You're not wrong. It's just psychologically very difficult to convince people of their own limitations.

The reason we have invented maxims, guidelines etc. that restrict what we should do is that we have found, over time, that behaving in a particular way leads to more success. Importantly, it will lead to more success even if it doesn't seem so to us at the moment.

If you think about it for a while, you'll realize that this is so for most if not all maxims. Correct things that are obviously correct are easy to get right. There are no maxims about not using 500-letter variable names because virtually everybody can see immediately that they would be really hard to use. But duplicated code doesn't seem to have any negative effect at first; it's easy to paste the thing, and saves time over factoring it away. What's not to like?

Once you've encountered this kind of situation, it becomes pretty obvious that refactoring will save time overall, because you've been down this road and know what will happen eventually. Someone who hasn't is not so easily convinced. It is extremely easy to fool yourself into thinking "This is so obvious, I'm not going to forget to attend to it, ever". (In fact, attributing perfect ability to itself may be the main function of the mind, according to some theories.)

Therefore the only way of convincing someone else to observe good practices is either to earn their trust, or to accompany them through the same roads that convinced you. The former is a matter of interpersonal skill, and is unfortunately too complex to answer in this format. The latter involves stepping through code where exactly this problem happens; in my experience this is a lot more convincing when done with existing code where cut-and-paste actually did lead to errors (the more serious the better) than with purely hypothetical future scenarios.

Above all, avoid attacking someone's sense of self-worth directly. Almost every young coder thinks they can do what no one else can do, and don't need the safety devices that others need. Telling them "yes, you do!" rarely works; it is marginally better to show them proof of how many people have screwed up for precisely this reason and ask them to show regard for whoever will be required to maintain their code in the future. (You may be surprised that human-factor issues play such a big role in productive coding, but I've come to realize more and more how decisive they are, and that this is one reason why building complex systems is so deceptively hard.)

Title: The importance of duplicate code removal

Body:
I tried to explain to a coworker the gravity of having duplicate code in a project, on this piece of code:

```<code>+ (void)createIapInParse:(SKPaymentTransaction *)transaction {
    Reachability *reach = [Reachability reachabilityWithHostname:@"www.facebook.com"];
    if ([Social getFBUser]) {
        NSString *iapId = [Util getBundleNameFromIdentifier:transaction.payment.productIdentifier];
        PFObject *iap = [PFObject objectWithClassName:@"Iap"];
        iap[@"iapId"] = iapId == nil ? [NSNull null] : iapId;
        iap[@"userId"] = [Social getFBUser].objectID == nil ? [NSNull null] : [Social getFBUser].objectID;
        iap[@"email"] = [Social getFBUser][@"email"] == nil ? [NSNull null] : [Social getFBUser][@"email"];
        iap[@"country"] = [Util getDeviceCountry];
        iap[@"installationId"] = [Util getInstallationId];
        iap[@"score"] = [NSNumber numberWithLong:[GameScore getTotalScore]];
        NSTimeInterval interval = [[NSUserDefaults standardUserDefaults] doubleForKey:@"timeSpentInApp"];
        iap[@"timeSpentInApp"] = [NSNumber numberWithDouble:interval];
        iap[@"retries"] = @0;
        iap[@"transactionIdentifier"] = transaction.transactionIdentifier;
        iap[@"transactionDate"] = transaction.transactionDate;
        iap[@"transactionSource3G"] = [NSNumber numberWithBool:[reach isReachableViaWWAN]];
        [iap saveInBackgroundWithBlock:^(BOOL succeded, NSError *error) {
            NSString *query =[NSString stringWithFormat: @"...", iap.objectId, transaction.payment.productIdentifier];
            [ZeeSQLiteHelper executeQuery:query];
        }];
        NSLog(@"Save in parse: %@", iap);
    } else {
        NSString *iapId = [Util getBundleNameFromIdentifier:transaction.payment.productIdentifier];
        PFObject *iap = [PFObject objectWithClassName:@"Iap"];
        iap[@"iapId"] = iapId == nil ? [NSNull null] : iapId;
        iap[@"userId"] = @"-";
        iap[@"email"] = @"-";
        iap[@"country"] = [Util getDeviceCountry];
        iap[@"installationId"] = [Util getInstallationId];
        iap[@"score"] = [NSNumber numberWithLong:[GameScore getTotalScore]];
        NSTimeInterval interval = [[NSUserDefaults standardUserDefaults] doubleForKey:@"timeSpentInApp"];
        iap[@"timeSpentInApp"] = [NSNumber numberWithDouble:interval];
        iap[@"retries"] = @0;
        iap[@"transactionIdentifier"] = transaction.transactionIdentifier;
        iap[@"transactionDate"] = transaction.transactionDate;
        iap[@"transactionSource3G"] = [NSNumber numberWithBool:[reach isReachableViaWWAN]];
        [iap saveInBackgroundWithBlock:^(BOOL succeded, NSError *error) {
            NSString *query =[NSString stringWithFormat: @"...", iap.objectId, transaction.payment.productIdentifier];
            [ZeeSQLiteHelper executeQuery:query];
        }];
        NSLog(@"Save in parse: %@", iap);
    }
}
</code>```

I refactored it to:

```<code> + (void)createIapInParse:(SKPaymentTransaction *)transaction {

    Reachability *reach = [Reachability reachabilityWithHostname:@"www.facebook.com"];
    NSString *iapId = [Util getBundleNameFromIdentifier:transaction.payment.productIdentifier];
    PFObject *iap = [PFObject objectWithClassName:@"Iap"];
    NSTimeInterval interval = [[NSUserDefaults standardUserDefaults] doubleForKey:@"timeSpentInApp"];

    iap[@"iapId"] = iapId == nil ? [NSNull null] : iapId;
    iap[@"country"] = [Util getDeviceCountry];
    iap[@"installationId"] = [Util getInstallationId];
    iap[@"score"] = [NSNumber numberWithLong:[GameScore getTotalScore]];
    iap[@"timeSpentInApp"] = [NSNumber numberWithDouble:interval];
    iap[@"retries"] = @0;
    iap[@"transactionIdentifier"] = transaction.transactionIdentifier;
    iap[@"transactionDate"] = transaction.transactionDate;
    iap[@"transactionSource3G"] = [NSNumber numberWithBool:[reach isReachableViaWWAN]];

    if ([Social getFBUser]) {
        iap[@"userId"] = [Social getFBUser].objectID == nil ? [NSNull null] : [Social getFBUser].objectID;
        iap[@"email"] = [Social getFBUser][@"email"] == nil ? [NSNull null] : [Social getFBUser][@"email"];
    } else {
        iap[@"userId"] = @"-";
        iap[@"email"] = @"-";
    }

    [iap saveInBackgroundWithBlock:^(BOOL succeded, NSError *error) {
        NSString *query =[NSString stringWithFormat: @"...", iap.objectId, transaction.payment.productIdentifier];
        [ZeeSQLiteHelper executeQuery:query];
    }];

    NSLog(@"Saved in parse: %@", iap);
}
</code>```

and he kept arguing with me that it's the same thing.

His primary argument was that "he's a good programmer and he can understand and read even the first version fast enough" so he doesn't care if it's written like that or not.

The question is, am I really wrong? Is this not so important for everyone? It's a subjective matter or he doesn't understand that's not the same thing?


问:
What are guidelines for a Win/Mac/Linux C++ source tree?
I'm learning C++ (C++11), specifically for cross platform game development using SDL.

on Windows, I use Visual Studio 2012 (Considering buying '14' once it's out), on Mac OS X and iOS I'll be using whatever the latest XCode is (right now 5.1) and I haven't looked into options for Linux yet.

However, since I'm still trying to understand how C++ applications are structured, I'm not sure how the project should be organized. I assume that 95% of the .cpp/.h files will be shared between all platforms (actual game logic), with some extra .cpp/.h files for platform specific stuff, and then there's the project files, e.g. the .xcodeproj/.plist files for XCode, the .vcxproj for Visual Studio and whatever Linux needs.

Are there guidelines or examples on how should be structuring things? Should I be using some independent format like CMake or SCons? I don't want to compicate my steep learning curve by bringing in an independent build system, I still want to be able to just hit "Run" in the IDE and have the app launch with the debugger and profiling tools.

Should I just do this:

```<code>+ root
+-- Code (shared .cpp/.h)
+-- Win (.vcxproj and Windows Specific .cpp/.h)
+-- Max (.xcodeproj and Mac specific .cpp/h)
+-- Linux/iOS/Android/etc... (Other platforms)
</code>```

I guess to a degre it's personal taste, but I do wonder if there are best practices.

答:
However, since I'm still trying to understand how C++ applications are structured, I'm not sure how the project should be organized.

This depends greatly on what tools and process you will use. You mention Visual Studio and XCode. Each has it's quircs and both optimize the sources for their own interractions with them (which makes the sources poorly organized for the other IDE).

If you wish to do cross-platform development you should create a source tree that makes sense to you (i.e. not to an IDE). This means you will probably create at least parts of it, manually.

For example, I usually have a project root directory, with something like this inside:

src (C++ source files)

include (C++ include files)

docs (documentation, todo list(s), user stories, etc)

tools (build tools, custom python scripts for the sources, etc)

build (for build artifacts and binaries)

test (for test source code)

I mostly work with command-line tools.

If I want to (for example) integrate the project with Visual Studio, I would create a new directory (e.g. vstudio-2013) and create in there the solution and other specific files. This ensures that when you use an IDE, you don't see specific files from the other IDE (i.e. you don't have to look at Visual Studio solution file from XCode).

These days, I tend to maintain a CMakeLists.txt file and use that to generate a CLI build configuration or IDE-specific configurations (it can generate Visual Studio, Netbeans and XCode projects, and it can also generate a Makefile-based build configuration).

Should I just do this? root/Code (shared .cpp/.h), root/Win, root/Mac, ...

Probably not. You can consider centralizing all items of a single type in a directory, and then specialize it by type, category, module, etc.

Example:

root/src (src - all sources)

root/src/os/win (windows specific)

root/src/os/linux (linux specific)

root/src/os.h (header hiding os-specific implementation behind abstract OS interface)

root/src/gamelogic (or whatever)

root/src/unittest (you should probably have one directory per library/module)

root/build/tmp (temporary build artifacts)

root/build/bin (binary outputs)

This will allow you to treat all files of a single type in a unified way (e.g. add all windows-specific sources to a library, by providing the directory only).

I guess to a degre it's personal taste, but I do wonder if there are best practices.

More like guidelines for things that work (and these are not universal). The "best practices" that apply to a linux&mac project will probably have to be altered a bit to fit Windows as well (and similar in the other cases).

on Windows, I use Visual Studio 2012 (Considering buying '14' once it's out), on Mac OS X and iOS I'll be using whatever the latest XCode is (right now 5.1) and I haven't looked into options for Linux yet.

I use NetBeans (C++) on Linux and OSX. I also use a terminal and CLI on both (doing mostly editing in NetBeans, and compilation, SCM, running, and tests in the CLI. Also, because I use unit tests, I rarely need to use a debugger (when feasible, prefering unit tests to debugging, can be considered a "best practice").


答:
His primary argument was that "he's a good programmer and he can understand and read even the first version fast enough" so he doesn't care if it's written like that or not.

If that is his primary argument it may be a sign that he is primarily afraid with being not called a good programmer, or even a bad programmer. IMHO the crucial point here is to make clear to him that it is not about a personal affront.

Next, good programmers stay good programmers by learning new tricks. I would try to relate to that, maybe by telling a story from your own experiences showing him, that good programmers can become even better by learning something or getting some specific insight. We all had such moments, I'm pretty sure.

Re the "reading" argument: It surely takes less time to read only half of the code, does it? So if it only were for this one, one easily can increase efficiency by halving the amount of code to read! Is that cool or what?

Last not least, it's not really about reading, but maintaining code duplicates, which is by definition prone to error. Code duplicates tend to "drift" (or wither, if you want) away from each other over time. It's not by intention, but people tend to overlook things, change only one of the duplicates, etc.

The question is, am I really wrong? Is this not so important for everyone? It's a subjective matter or he doesn't understand that's not the same thing?

You're right. The one who is subjective is he, not you. His primary argument primarily only refers to himself, you are (hopefully) do have the project success in mind.


问:
How should I make progress further as a programmer?
I have just left my college after doing graduation in computer engineering,during my college life I tried to do some freelancing in local market.I succeeded in the last year and earned some small amounts based on joomla,wordpress and visual basic based job.I had some small projects on php,mysql also.
After finishing my undergrad life,I sat for an written test for post of python programmer and luckily I got the job and is working there(Its a small software firm do most of the  task in python).Day by day I have gained some experience with core python.

Meanwhile an USA based web service firm called me for the interview and after finishing three steps(oral+mini coding project+final oral)they selected me(i was wondered!).And I am going to join their with in few days.There I have to work in python(based on Django framework,I know only basic of this framework).

My problem is when I started to work with python simultaneously I worked in Odesk as a wordpress,joomla,drupal,php developer.
Now a days I am feeling that I am getting "Jack of all trades master of none".

My current situation is i am familiar with several popular web technologies but not an expert.I want to make myself skilled.
How should I organize myself to be a skilled web programmer?

答: In My opinion you should focus on one technology first for atleast couple of years gain some grip on it then if you want to learn a new technology go for it by this you will explore new things and you expand your horizon and this will help you when you are thinking of any solution or developing a new project</p>


答:
I refactored it to [...] and he kept arguing with me that it's the same thing.

Well ... as far as the compiler is concerned, it probably is. As far as maintenance effort is concerned, it is not.

His primary argument was that "he's a good programmer and he can understand and read even the first version fast enough" so he doesn't care if it's written like that or not.

This is true (understanding the code is not that hard). It also makes two assumptions: that the most effort required in the future on this code is to understand it (it's not), and that the written code is correct and will not need major changes (it will).

The most effort in the future, will probably be required to implement changes accross the code base.

Currently, I am working on a medium-sized conversion project (adapt ~100 Visual Studio projects to Win64). When I find an error in code, I usually find it in 20+ to 40+ places (so fixing one error takes hours of searching through the code base, reading code, applying the same fix over and over and recompiling). This makes commits bigger

The code is not only duplicated, it is proliferated (because this one time excuse of "it's easier to paste the code than refactor it" was judiciously applied for the last 20 years).

This makes it very difficult to:

cover all code paths for a fix

estimate the effort to fix something

determine what to test to verify a code change

It also increases drastically the time/complexity of all operations performed on the code (due to the high degree of duplication, source files are bigger, compilation takes longer, search/replace takes longer, reading the code takes longer and so on).

Another disadvantage is that it is difficult (to the point of being impractical at this point) to implement unit tests, and document or formalize interfaces and responsibilities (because instead of having dependencies between five distinct, testable APIs, we have twenty five APIs that perform roughly the same operations with copied code from one to another and slight variations).

This point (on difficulty of increasing the code quality now) keeps the entire team playing catch-up on deadlines, working reactively and in an impossibility to set long term goals in the project.


答:
Add another field to PFObject.

Set value to that field only in the then clause of the original version.

Run the application in a way that'll make createIapInParse enter the else clause.

Fill a bug report that your new field is left unset.

Assign that bug report to your coworker.


答: The composition approach (including another Tokenizer in DefaultTokenizer) will be easier to modify in the future. If possible, you shouldn't allow the Library*Tokenizers to be subclassable at all. That said, as long as the rest of the code can only reference a DefaultTokenizer through the Tokenizer interface you'll be able to change how it's implemented without breaking anyone's code.

Title: To subclass or to wrap for "default" implementation?

Body:
I'm creating a toolset in Java consisting of many Natural Language Processing (NLP) tools, such as Tokenizer, POS tagger, Lemmatizer, Sentence parsing, etc.

I want to put all good and publicly available tools into my toolset, all sharing the same interface, so that I can change library easily without change of API.

The project structure is something like this:

tokenizer/
    Tokenizer.java (an interface)
    LibraryFooTokenizer.java (from first library)
    LibraryBarTokenizer.java (from second library)
    DefaultTokenizer.java (a default tokenizer)
lemmatizer/
    Lemmatizer.java
    LibraryFooLemmatizer.java
    LibraryBarLemmatizer.java
    DefaultLemmatizer.java
```
</blockquote>

<p>The <code>Library*Tokenizer.java</code> are implementing <code>Tokenizer.java</code>, so I can directly use <code>Tokenizer</code> in my applications without needing to know the implementation details. So far so good.</p>

<p>My question is regarding the implementation of <code>DefaultTokenizer.java</code>. It's supposed to be for someone who just want to use a Tokenizer, who perhaps doesn't really know from the list of available Tokenizer which one is the best.</p>

<p><strong>Should it be a subclass of the currently best library, or should it implement the interface and has the best library as a member, or else?</strong></p>

<p>Currently I use the second approach as follows:</p>

<pre class="lang-java prettyprint-override"><code>package tokenizer;

public class DefaultTokenizer implements Tokenizer{
    public Tokenizer tokenizer;

    public DefaultTokenizer(){
        tokenizer = new LibraryFooTokenizer();
    }

    @Override
    public String[] tokenizer(String text){
        return tokenizer.tokenize(text);
    }
}
</code>```

Is it better than this one?

package tokenizer;

public class DefaultTokenizer extends LibraryFooTokenizer{}
```

The points that I'm considering are the ease of modification, in case later LibraryBarTokenizer is updated and becomes better, I want to update to that one.

You can also review this in term of ease of debugging, is it nice with common IDE (I'm currently using Eclipse)?

I'm currently using this as internal research toolset, to compare various implementations. There are some use cases why DefaultTokenizer might be required:

Sometimes we might decide that we want to change the library for Tokenizer (an update makes it better, change of license makes it (in)appropriate). Now, on codes that doesn't care about which Tokenizer is used, but only requiring the best one, using Default makes change easier, since we just need to change which library is the default.

It might be the case that there will be someone trying to use a Tokenizer component while developing new component. While it's true that in research one is supposed to know the details of each component, sometimes we want to test something for which the Tokenizer is not that crucial to the result, but is required. In that case, taking the default might be good (and if the result changes if the Tokenizer is changed, then there is something wrong with how the Tokenizer is used).

Those reasons might not be too compelling, but we decided to use such default implementation, and currently I'm looking for ways to improve how we implement the default, hence this question.

It might be the case that using default is that bad for reasons I haven't considered. In that case, that also qualifies as an answer.

But I will be glad if someone can offer more insights on how this can be improved, or whether it doesn't matter much which way I choose.


问:
Who is the copyright owner of a contribution (commit) to a GPL-licensed project?
Suppose, that Alice started a GPL-licensed project. Later, Bob married Alice, joined the project and made a 50% contribution to it.

Then they broke up, Alice sued Bob and by court decision took his house, car etc. :( Moreover, she decided to close the source code of the project and sell it for money. As a copyright holder, does she own the whole project, including Bob's commits, or only her own commits?

答:
Absent any agreement of copyright assignment, Alice and Bob individually hold copyright over each piece of their own code.

If Alice decides to sell the work under the terms of the GPL, it's no different from a third party attempting to sell a GPL-covered work -- it's completely allowed. Both authors offered the code under the GPL, so anyone can use it and redistribute it (for free or at cost) under the terms of the GPL.

If Alice doesn't want to redistribute the project under the GPL, she can only distribute the code that she personally wrote. As the copyright holder of her own work, she's fully entitled to redistribute it under a different license:

The GNU GPL does not give users permission to attach other licenses to the program. But the copyright holder for a program can release it under several different licenses in parallel... If you are the copyright holder for the code, you can release it under various different non-exclusive licenses at various times.

However, as she is not the copyright holder of Bob's work, she only has legal access to that code under the terms of the GPL. Ultimately, this might mean she can't usefully distribute her own code outside the GPL, if it requires Bob's GPL-licensed components to work correctly. One notable exception to this is that she can distribute the complete project as it existed before Bob made any contributions (i.e., before they were "married").

For reasons such as this, many major projects require contributors to assign copyright to the project so that the legal entity of "the project" can change licenses or undertake legal action as the sole copyright holder without consulting every author who ever contributed.


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: Any programming environment with a visual designer of some sort will make it so that business users can "write" the program and actual programmers aren't needed.</p>


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

答: I really like the Scala library's more granular types.  It seems like the new collections library was well thought-out.  I also like how it reduces the amount of code required for simple classes, and the functional concepts it adds.  Its type inference is also very helpful.  It feels like Java without the training wheels.  After using C# for a while, Scala actually feels like a competitor, with Java still useful but being left behind.</p>

Title: What do Java developers think of Scala?


问:
BDD/TDD - exhaustively testing details which are low-level, but still behaviour
We're looking to concentrate more on testing behaviour (as opposed to every class/method individually) in all our automated tests, as espoused by various high-profile online discussions recently.  I like the idea of thinking about only what goes in and out of certain logical well-defined boundaries between components, but I'm having a hard time imagining how that relates to quite low-level detail of behaviour, that is only a small part of the overall requirement but still important to be correct.

As an example:

We have a component which accepts a customer order and takes some kind of significant action with it, let's say accepts it and starts processing manufacture.  The main thrust of the requirement is about accepting and manufacturing, but there are many small things which need to be correct, and which if incorrect should cause an exception, for example that the order date needs to be valid.  If we assume that I don't implicitly trust whatever date validation routine is being used, then there are loads of things I need to test there: basic format, leap years, not in the future, etc etc.  In "non-behavioural" TDD I would definitely test those at the class/method level, and then never worry in my other tests about whether they'll work. But if I'm only testing behaviour, do I need to take all those success/fail cases and test them on the component boundary, for every situation where I'm interested in the date?

I can see a few options:

Massively tedious repetition of millions of tests, as on the low-level methods, but higher up.

As above, but condense "is the date valid" down into a separate method which I reuse in my behaviour tests, so although I do check that the date is valid, it's only one line per test.  This is much more likely than the first option...

Test only broad behaviour higher-up, and do have a low level set of tests just to ensure the validation routines work.  This seems sensible, but the importance of behaviour tests not relying on implementation details has been stressed - the actual validation routine being used is an implementation detail, invisible at the component boundary, so even if I test that routine, can I officially then not test it elsewhere as well somehow?

I'm leaning towards the middle option, but I'm quite new to this, and would be interested what you think about it!

Higher-level tests also exercise the interactions between components.
  Were your premise true, we could simply dispense with unit tests
  altogether and just use higher-level tests.

I think that's true (if taken to extremes), and there are people who would try to achieve exactly that.  Understanding the reasons not to do that are partly the driver for my question.

I think potentially the difference between certain situations is to what extent these low-level behaviours are perceptible at the component boundary - in the case of date validation they are, I can feed lots of different values that I know should be valid or invalid in different ways into the interface and see differences in response; in other cases the unit in question does its work invisibly, at least from a behaviour perspective (I could test loads of stuff in a unit test, but perhaps the way it's being used in the larger component being tested doesn't give it much scope for variation).

Repetition vs Refactoring

The main reason I included the hyperbolic "millions of tests" option is another (unstated) principle that I also understand is good to aim for: "don't do too much in any one test, test one thing only".  If you're also trying to follow that as much as possible, and think of the various validation failure cases as separate "things", it seems to conflict a bit with normal DRY/refactoring approaches - you can't squish the validation into one method and use it over and over, because then when it goes wrong you haven't got such specific feedback about what to fix (although you do at least have a valuable works/doesn't work response).

If this bothers you, follow the practice of TDD'ers everywhere, and only test public methods. Naturally, this doesn't preclude you making your "is the date valid" method a public method

I don't think I like the sounds of making something arbitrarily public (without changing anything else) just so I can test it - I'm happy enough changing my APIs when I need to change them, rather than so they fit my testing approach.  Maybe bundling it off into another class (with public methods) if it might be useful, that makes more sense to me (and I've heard people suggest exactly that in TDD conversations).  But the question is not really concerned with getting access to the low-level detail, it's about whether testing at that level at all is a good idea.

At the end of the day, common sense rules. If a piece of internal functionality is complex enough that you believe it needs to be covered by its own tests, then by all means, write tests for it. Conversely, I seldom write tests for trivial getter/setter methods, or methods that are prima facie correct.

No argument from me about that!  Depsite what else I've written I'm sure we'll end up with a pragmatic mixture of approaches that we've chosen to give us the confidence in our code we need.  This is helping me decide what that might be!

So far I'm erring towards accepting slightly coarser tests at the API level (for e.g. things like our date validation example), while also setting up comprehensive unit tests for certain underlying classes - that way you get the full behaviour coverage, and nothing can slip through the net at the level which truly matters, but also you can have good confidence in and ease of maintenance for the complex low-level units.

答:
Something like a date validation function would be a genuinely reusable component, and so should;

have tests written against it's api

already exist, probably as part of your language standard library

already be tested, otherwise use a different language/library

Then you just document somewhere 'we accept dates in (e.g.) ISO format'. Then for any kind of normal 'I want my website to work' testing, there are at most two possible test cases: legal date and non-legal date.

If you have some over-enthusiastic customer that has somehow specified their own date format, then it would become part of the behavioural tests. Try to find a better customer.

Of course, if you are certifying your code as suitable for use in the flight control system of a nuclear-powered passenger aeroplane, different levels of testing will apply. But that is well outside the scope in which any advice on cost-effective testing from people building consumer-facing websites is going to be useful.


问:
Security in an iOS game?
I'm part of a team building an iOS game which has multiplayer elements.

A concern right now is how to make the game more secure, from user manipulation. I know there's a lot of multiplayer games out there, and so there must be techniques they use to make their games more secure.

An example of a scenario is if the saved game is being stored on the local device. Is there some method we can use - perhaps encryption or something else, that can stop the user from being able to just generate their own saves?

Or when making a call to a method, similar to 'createItem:', they could add something to their game that they shouldn't be able to. I'm wondering how other iOS games prevent such activity?

答:
Short answer: No.

It helps to have an appropriate mental model of the problem you're facing. Imagine that your app is a filing clerk (program binary) working in a rented office (the user's phone). He's got his own computer, desk and phone (process running on the user's phone), but the filing system (file system) is controlled by the landlord of the office building (the user). You can trust the landlord to keep providing your office equipment, but you know they have an agenda of their own, which may include messing with the work you're doing.

The important point to see is that the clerk can work unimpeded, but he goes home every night (when the app is closed), and the next day he'll only be able to remember where he was and what to do by reading instructions from the filing system - which may be compromised by the hostile landlord.

This explains why it is ultimately impossible to guarantee a secure workflow while completely depending on a hostile persistence provider. You can leave yourself notes, but the landlord might intercept and alter them. You can encrypt the notes so that others can't read them, but the landlord can apply cryptanalysis. You can sign the notes so that they can't be altered, but cryptanalysis can be applied to that problem as well. Worse, the landlord is able to scan the clerk's brain (program binary) while he sleeps and analyse its workings, including the part where he stores the secret encryption key. The landlord can even simulate running the program in a secret environment and observe how it does the encryption (here the metaphor breaks down).

Therefore, all you can do to make your workflow secure is to try and make countermeasures more expensive. Encryption can help with this, but it depends on the situation whether you can make it expensive enough to actually prevent what you want prevented. Probably no one will employ virtualization and cryptanalysis just to generate a fake online high score in a small casual game. But you never know - maybe your app will go go viral, and high-level profiles become worth a lot of money. All you can do is estimate how much effort someone would expend to subvert your program, and plan for this amount of countermeasures.

Title: Security in an iOS game?


问:
Having unwanted bits in version control history
Consider having a project which you would want to release as open-source.

There are parts which you have removed, but still remain in version control
history. License of those parts is not compatible with the license you intend
to use to release the project.

How to solve this?

Just release source tree as is. Possibly illegal option.

Strip changes/modify history to remove unwanted parts. Breaks
compatibility with existing copies of repos. Old versions no longer compile, because important part is missing.

Create new repo without unwanted parts. Same problems as above.

I have a Mercurial in mind, but I think this applies to any DVCS.

答:
Create a new repo, probably with no old revision history in it.

No "old versions fail to compile" because there are no old versions (and old versions make no sense as you're deleted half of their source code!)

This doesn't preclude you from using the old repo yourself, though migrating changes from OSS devs into your copy will require you to manually make a new branch, populate with a copy of their code, and merge rather than simply merge.

You could keep the old repo for the historical versions, while they're still needed, and close it to new development.

The last idea is still to create a new repo, and populate it with all but the copyright parts. Put those into a different repo that only you have access to.


答:
Well this indeed requires another approach. Normally with https you would like to get unknown attackers away from the user. But this time you need application to protect the user from attacking. Hacking games requires different levels of hacking

Well first of all you should protect that the game could run in an emulator mode (or something  like that). With an application like bit slicer you can easily lookup current amount of money (or any other property) and search again when the value has changed. Then they change the value in your memory to whatever value they like. Solution to this is an algorithm can be used to store a value and have an checksum stored in memory somewhere else. This way you prevent users trying to hack locally on the iOS device itself running your game on jailbreaked devices as well.

The second security that's needed is to avoid using a proxy hack, again not to protect the application from outside hackers but inside again. https doesn't provide this protection at all. What happens is that a user download an application like Charles on they Mac. Then on their iOS device they go to network settings and set the proxy settings so every request goes to the Mac. Then they startup the game and look on the mac for all communication between the iOS device and internet. An app like Charles can changes values of headers and body of HTTP requests and responses using regular expressions in real time. So even when the server replies that someone has 100 gold, a simply regular expression in Charles could make the device receive an reply from the server as the user would have 100k gold for example.

The best way to protect against proxy hacks is that you code sign everything. That means that all values, or group/array of values does have a certain checksum that only applies for that device. The algorithm depends on certain keys, liek device id, session id and type of property. So when a value of 100 gold is send to the client, a code sign value is send with it as well. The same keys are on the device which makes that when he encrypts the value of 100 it would have the same code sign value as send from the server. When someone would change the value 100 using a proxy hack, the outcome of the encryption would be different from the server and you'll notice that the user is trying to hack or is being hacked by someone else. At least, the device shouldn't accept the value.

Title: Security in an iOS game?

Body:
I'm part of a team building an iOS game which has multiplayer elements.

A concern right now is how to make the game more secure, from user manipulation. I know there's a lot of multiplayer games out there, and so there must be techniques they use to make their games more secure.

An example of a scenario is if the saved game is being stored on the local device. Is there some method we can use - perhaps encryption or something else, that can stop the user from being able to just generate their own saves?

Or when making a call to a method, similar to 'createItem:', they could add something to their game that they shouldn't be able to. I'm wondering how other iOS games prevent such activity?


答:
A very important, but subtle, issue when trying to write and maintain correctness is recognizing the difference between things which happen to match, versus things which are "the same".  This frequently arises in object oriented programming (99% of questions relating to deep cloning and deep equality stem from a failure to distinguish when it's appropriate to have separate things that match, versus having two references to the same thing), but the concept extends to source code as well.

Code duplication is good in cases where it should be possible for one piece of code to change without affecting the other.  It's bad in cases where the two pieces of code might change, but should always do the same thing.  Note that it doesn't really matter whether the code in question is long or short.  Unfortunately, there are many cases where language constructs do not permit common pieces of code to be factored out efficiently, since the only way to define a method which has access to a scope's variables is to create a closure; even if no reference to the closure should never escape the context where it's created, many languages have no way to specify that.

Thus, it's necessary to invoke another principle which is applicable to source code just as to run-time objects: the distinctions between identity and matching is relevant only when things are mutable or encapsulate mutable state.  The decision of whether to duplicate "immutable" code segments--unlike those which might change--is dependent upon length.  Of course, code segments which are long and might change are prime candidates for factorization for two reasons.


问:
How to design RESTful Web Api to represent Resources
I'm developing an ASP.NET Web Api 2 RESTful web api with .NET Framework 4.5.1 and C# and I'm trying to understand how to expose resources through a Web Api:

Imagine that I'm a group owner and I am the only one that can add new users to that group (I'm trying to simulate a WhatsApp group).

This is my C# class for user:

```<code>public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }

    public List<Group> Groups { get; set; }
    public List<Group> GroupsOwned { get; set; }
}
</code>```

And Group class:

```<code>public class Group
{
    public int GroupId { get; set; }
    public string GroupName { get; set; }

    public User Owner { get; set; }

    public List<User> Members { get; set; }
}
</code>```

How do I have to expose user's groups owned members in a RESTful Web Api?

I think I have to expose it this way:

```<code>"api/users/{ownerId}/groupsOwned/{groupId}/members/"
</code>```

I will allow PUT to modify the Group to add a new member, and probably GET to get all members.

Any advice?

答:
Why do you want to add the owner (which more seems like an attribute of a group) into the url? It can make sense but I don't see an argument for it. /api/groups/{groupId}/members seems to make more sense? Then you can add another path: /api/users/1/groups and /api/users/1/groupsOwned where you show a collection of links to the normal groups urls.

Because I need to pass the ID for the user that is modifying the group. If the user is the owner, he can add more members to the group.

In general that sounds as security and should be fixed by headers (like basic Auth, OAuth etcetera). It does not change which resource you show. Even better: When the owner of a group changes all urls would be invalid which is not restful. So I would suggest to leave them away and make it an attribute.

Interesting to read when you try to work restful is the concept the author of it has: Roy Fielding is the inventor of the REST concept and you can find some basics about the real concept here:

http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven


答:
The web is too fragmented! There is no true answer to what is best to learn.
Do market research and look at what the market is demanding where you do your work.

Title: How should I make progress further as a programmer?

Body:
I have just left my college after doing graduation in computer engineering,during my college life I tried to do some freelancing in local market.I succeeded in the last year and earned some small amounts based on joomla,wordpress and visual basic based job.I had some small projects on php,mysql also.
After finishing my undergrad life,I sat for an written test for post of python programmer and luckily I got the job and is working there(Its a small software firm do most of the  task in python).Day by day I have gained some experience with core python.

Meanwhile an USA based web service firm called me for the interview and after finishing three steps(oral+mini coding project+final oral)they selected me(i was wondered!).And I am going to join their with in few days.There I have to work in python(based on Django framework,I know only basic of this framework).

My problem is when I started to work with python simultaneously I worked in Odesk as a wordpress,joomla,drupal,php developer.
Now a days I am feeling that I am getting "Jack of all trades master of none".

My current situation is i am familiar with several popular web technologies but not an expert.I want to make myself skilled.
How should I organize myself to be a skilled web programmer?


问:
Is my understanding of the license for JQuery.xmleditor correct?
Please correct me if I'm wrong, but I recently found myself in a pretty confusing situation and now I am unsure how to continue.

I found the jQuery.xmleditor plugin from the UNC libraries and thought it would be useful for one of our commercial products. That's where I typically first check how a library is licensed (in this case it was Apache License 2.0, which allows redistribution under certain preconditions). I started playing around with the plugin and realized that the actual text-based editor (the part I am interested in most) was a derivative of Cloud9, which is licensed under GPLv3. That made me suspicious, because typially GPL requires GPL on derivative projects. So I started a quick web search and found out that there is indeed an incompatibility.

This licensing incompatibility applies only when some Apache project software becomes a derivative work of some GPLv3 software, because then the Apache software would have to be distributed under GPLv3. This would be incompatible with ASF's requirement that all Apache software must be distributed under the Apache License 2.0.

For my current understanding the jQuery.xmleditor plugin is licensed wrong. However, I am not quite sure whether my current understanding is right. Can anybody perhaps enlighten me?

答:
The Apache 2.0 license is compatible with the GPL v3 (but not v2): http://www.gnu.org/licenses/license-list.html#apache2

You are getting confused by the requirement that all software of the Apache Software Foundation (ASF) be licensed Apache 2.0, but that is a "company policy". That incompatibility you are thinking about is due to the policy mandate that all ASF software is licensed per Apache 2.0, regardless of whether the licenses are compatible or not.

For other projects, where no such policy is in place, only the terms of the licenses matter, and for those situations, you can use an Apache 2.0 licensed project in your GPL v3 project, though it has to keep its Apache 2.0 license.


问:
What is the alternative to an enterprise portal strategy in the Java space?
Disillusionment with the Portal Space

I'm seeing a disturbing number of large, enterprise clients who have become disillusioned with their enterprise Portal experience, especially those in the WebSphere Portal Server (WPS) space. Millions have been invested, yet the promise of personalized content with aggregation and integrated collaborative tools has never come to fruition. The move to WPS 7.x is a big rip and replace move, and clients are wondering if they should move somewhere else completely.

Portal Software: A horrible option, but what's the alternative

There are loads of Portal haters out there, and sometimes a portal solution is indeed overkill, but when you're talking about large, multi-national corporations, how would one recommend they architect a global solution without a portal server?

Portals aren't always as fun to work with as Tomcat or JBoss AS, but when it comes to integrating multiple applications, managing content, updating individual applications that are deployed as individual war files, managing security down to the portlet level, proving a certain amount of personalization to users, and help with the overwhelming task of managing the thousands of pages large scale enterprises have as part of their internal and external websites, is there a better technology out there?

Garnering community insight and feedback

I've been trying to garner as much insight as possible. I wrote a little article on TSS about the issue:

Which other alternatives to portal exists on market?

I'm also resurrecting a thread at the CodeRanch to see if I can get any insight from that handsome crew.

Updated Thread Asking for an Alternative to a Portal Software Stragety. Circa 2012

I'm also looking for some insight from the twitterati (@potemcam).

It's not so much a cross-posting as much as it is an attempt to really gather some keen insight from the community. If I can get some solid responses and experiences, I'd like to aggregate them into an advice article over at TSS.

What is the right alternative to an enterprise Portal in the Java space?

By the way, I'll be cross-linking to this question from the other sites as well so people with the same questions will be able to bounce back and forth and see what the community is saying on this topic.

答:
I have recently been deeply involved in the Java portal server scene. It was chosen as an inexpensive alternative to SharePoint, as we were able to find a portal provider carrying comparable features. We went with eXo Platform and though it is primarily advertised for social features, it is fully compliant as a JSR286 portal server.

A Java portal can be incredibly powerful, but it naturally comes at the cost of seeming over-engineered and unnecessarily complex. The general customer response we've received has been that the basic configuration and overhead of a server can be too much. I have yet to find a portal platform or alternative that can offer a verbose feature set, yet remain acceptably slim for a set of operational requirements. Years of feature bloat between competing portal platforms have seriously cludged the market.

Growth in the Java portal world has been agonizingly slow. You will find dated interfaces, archaic UX, and every action will leave a bad taste in your mouth. There are few innovators here, eXo Platform being one of the very few that we found to be making a concerted effort at modernization.

Given all of that, you can still create a reasonable product in the JSR268 world with a measure of success. We were able to do this by leveraging JAX-RS services for each portlet, basically cherry-picking portlet features and functionality. All database access runs from the web server separate RESTful services for optimized CRUD operations. It takes an imposing diligence with an excess of effort that not many are willing to commit.

You can also go completely ground-up and build yourself a 'portal' with servlets and JAX-RS.  This can be done much more rapidly than standard portal development. However, you will fall short when it comes to supporting the full set of configuration features found on a standard web portal.

Simply, there is a serious entrapment cycle of excessive feature sets stifling innovation that does not appear to be changing soon. Game-changing breakthroughs are unlikely to occur because the heavy hitters don't see the meta evolving. But your only alternative option is to re-invent only the features you want.


问:
Finding metrics for development time in different languages
I'm trying to determine if a language I'm investigating (Groovy) is better for developing enterprise applications than our current language (Java).  Specifically I'm trying to figure out if it will save significant time in coding, re-factoring and maintenance.

But, I'm not actually asking that question here as it's waaaaay too broad, I'm just setting up my actual question:

What's the best approach to gathering metrics to compare the productivity of two languages?  I mean, it's easy to look at example code that says "see, this is easier to write in Groovy than Java" or "this functionality is missing in the tools available for Groovy, but exists with Java tools."  But it's much harder to figure out how that translates into time gained/lost in the real world.

I've been combing Google, but I'm honestly not even sure what I'm looking for.  I know the question is still a tad broad, but if anyone has some answers I would appreciate it...

答:
I'd set up an experiment:

Find a bunch of interns with strictly Microsoft experience.  Train them on your Java tools and the language then give them a small project.

Find some more interns (same number) also with strictly Microsoft experience.  Train them on the Groovy tools and language then give them the same small project.

You want as many interns as possible but equal numbers on both teams.  'Strictly Microsoft experience' is so everyone is starting from roughly the same background (no head starts in Java or Groovy).

Try to pick "average" interns - not superstars that will skew the results or people you already know you won't try to hire when they graduate.  If you have enough of them you can hopefully average out their skill and experience levels.

All of the interns get a great learning experience, and you get the benefit of seeing how they tackle the projects and how steep the learning curve is.  The internship experience can be an excellent way to find great new hires, and what better test than to give them an unfamiliar language and a solvable but nontrivial problem?

There should be an item #3 in the list above as a control, but I'm not sure what it is.