答:
The run time for the edit distance calculations is trivial, but I'd be concerned that the results will be poor. Character-by-character will be noisy; I'd be amazed if you got any exact matches. Word-by-word will be subject to the vagaries of erroneously hearing a plural, homophones, etc, etc.

That said, nothing wrong with trying the simplest possible thing first. If the results aren't good enough, though next I'd try:

Splitting the string up, run a simple stemming algorithm on the words, and then do the edit distance calculations. https://pypi.python.org/pypi/stemming/1.0 for example.

If that doesn't produce clean enough results, I'd fall back to the vector space document model which you could easily implement for your purposes, in 20-30 lines of most high level languages. (Or pull out the heavy guns and shove it into Lucene.)

Title: Algorithm for comparing hundreds of similar, but not identical documents

Body:
I have seen similar questions about text comparison, but none on such a large scale.

I have a client with two sets of recordings of speeches, 250 and 550 recordings each. Each of the recordings in each set are unique, but about 200 out of the 250 are duplicated in the set of 550, and they need to weed out the doubles. The recordings were recorded on separate devices, so you can't just compare the file length and content.

They are willing to pay to have the first 15 seconds of each recording transcribed, and then they want me to devise some system of using those transcripts to identify the doubles.

First of all, I'm assuming that I should first remove any punctuation and capitalization, because those are things that might arbitrarily change based on the transcriptionist who happens to do that file.

My first idea was to simply calculate the Levenshtein distance for each combination of recordings, but I can't imagine doing that on such a large scale (250 x 550) would be efficient. Then I thought that instead of doing a Levenshtein distance, but using words as the unit instead of characters. But this still would involve running an algorithm 250X550 times, albeit a much faster algorithm each time.

Then I was thinking that maybe I should go through each document, and make a alphabetically sorted dictionary with a count of how many times each word appears in each document. Then I could just go through the dictionary associated with each document and subtract the number of appearances of each word from each other, to produce a total number of mismatched words. This looses taking into account the order of the words, but it should be much faster.

Which of these methods, or perhaps an entirely different method, should I use?


问:
How can I map a number of points of a polygon to matching points of a larger rectangle?
Suppose I have 2D polygon image and a larger 2D rectangle image and that I have a collection of points for each that I want to align.

For Example the polygon has point collection:

[PA(a, b), PB(c, d), (PC(e, f)]

And the Rectangle has point collection:

[RA(g, h), RB(i, j), RC(k, l)]

Is there an algorithm I can use to pragmatically transform the Polygon such that the points will align to the points on the Rectangle, Scaling and Rotating such that the Polygon remains intact?

Please note: I'm using three points in the example; however, an algorithm with an arbitrary number of equal points is fine.

For clarity:

I by transform I mean: Scale and Rotate. The objective being that the polygon image is not "warped"

I think circumscribed does describe what I'm trying to accomplish; however, for all practical purposes the Rectangle will always be large enough to contain the polygon.

Images:

Given:

And:

I want:

答:
In general, no.

The two sets of three points each define a triangle.  Unless those triangles are proportional to one another, there is no 2D affine transformation (i.e., without warping) that can map one to another.

In the special case that they are proportional, a geometric approach would be:

Compute the circumscribing circles for each set of points.

Translate the polygon by the negative of the center of its circle, centering it's circle.

Scale by the ratio of the radii of the two circles.

Rotate the polygon (about the origin) to align the directions of the points.

Translate the polygon to the center of the rectangle's circle.

You may have to perform a reflection between steps 3 and 4 if the order of the two points in each set are not identical.

ContentLicense: CC BY-SA 3.0


问:
How to write a doubly linked list for multi-core use without global lock?
I'm trying to write a cyclic doubly linked list where the nodes or even the link pointers are locked individualy. Or a lock-free or even wait-free (I think that's not possible) implementation.

The list will be used in a simple kernel for the scheduler and message passing subsystems. The kernel is non-interruptible, so code will never be preempted in the middle, but it is an SMP kernel, so multiple cores can be trying to work on the list in parallel.

Needed operations:

insert node after current node

insert node at end

move current node from one list to another

delete current node

advance from current node to next node

Note: if the algorithm is so complex that it is 10 times as slow as locking the whole list then it is pointless. It would be faster to run the cores sequentially than parallel even if they try to modify the list all at the same time.

So, any pointers for an algorithm or should I just use a lock for the whole list?

答:
If you need synchronization and a copy-on-write list is not acceptable, I would place the lock granularity at the node level.

Specifically, you would lock two or three adjacent nodes and perform your operations. This relies on the fact that it is cyclic, which actually simplifies some of the logic.

insert node after current node: lock the current and next node, then do your insertion, rewiring the pointers between the two nodes to point at the new node.

insert node at end: same as above, except the next node is the first node.

move current node from one list to another: this is unlinking from one list and inserting into another. You would need to lock the node being moved, and the adjacent nodes in both lists.

delete current node: lock the current node and the two around it. Unlink the current node.

advance from current node to next node: lock nothing, but wait for the lock to release if moving to a locked node. After the lock releases, reevaluate what "next node" is.

Without measuring it my gut feeling is the performance would likely be better the larger the list is. There is a bit of overhead both in design/coding as well as in the locking. Locking the whole list is really easy, but penalizes reads unnecessarily. As the list grows, the number of nodes penalized this way increases linearly.

You did not give a language, but it may be worth seeing what existing code is in its standard library and see if that works. If the performance is unacceptable or nothing exists (e.g. C) then roll your own. Compare the two and see what works better.


问:
How to define IntsWithoutZero type in f#
Recently I saw a great video of Scott Wlaschin about patterns in functional programming. He gives an example of dividing a numbers. In f# we'd use int option for the result to handle division by zero in a nice functional way.

As another possibility he mentions creating a type that would not allow 0 as a valid value.
Let's say IntsWithoutZero. How could we define this kind of type "functionally"?

I know how I'd do it with OO approach (e.g. write a IntsWithoutZero class and disallow 0 during construction).

答:
I would use a single case union type to wrap the integer.

I would put the type in its own module and access it through factory and getter methods like so:

```<code>    module IntsWithoutZero =
        // make the type constructor private
        type T = private IntsWithoutZero of int

        // factory that can apply the constraints
        let create value =
            // do check for zero here
            match value with
                | 0 -> None
                | _ -> IntsWithoutZero(value) |> Some

        // a method to extract the private data
        let value (IntsWithoutZero v) = v

    // ================== later in the code ==================
    // create the type
    let myInt = 5 |> IntsWithoutZero.create

    // ================== later when used ==================
    let myDividedValue =
        match myInt with
            | None -> None
            | Some(v) ->
                // get value out
                let d = (v |> IntsWithoutZero.value)
                // do something zero cannot do
                Some(10 / d)
</code>```

If you wanted to avoid option, alternatively you could throw an exception in the IntsWithoutZero.create method if the user supplied zero as a parameter.

Here is a blog post by Scott that does a much better job explaining this concept:

http://fsharpforfunandprofit.com/posts/designing-with-types-single-case-dus/

I hope this helps!

Body:
I would use a single case union type to wrap the integer.

I would put the type in its own module and access it through factory and getter methods like so:

    module IntsWithoutZero =
        // make the type constructor private
        type T = private IntsWithoutZero of int

        // factory that can apply the constraints
        let create value =
            // do check for zero here
            match value with
                | 0 -> None
                | _ -> IntsWithoutZero(value) |> Some

        // a method to extract the private data
        let value (IntsWithoutZero v) = v

    // ================== later in the code ==================
    // create the type
    let myInt = 5 |> IntsWithoutZero.create

    // ================== later when used ==================
    let myDividedValue =
        match myInt with
            | None -> None
            | Some(v) ->
                // get value out
                let d = (v |> IntsWithoutZero.value)
                // do something zero cannot do
                Some(10 / d)

If you wanted to avoid option, alternatively you could throw an exception in the IntsWithoutZero.create method if the user supplied zero as a parameter.

Here is a blog post by Scott that does a much better job explaining this concept:

http://fsharpforfunandprofit.com/posts/designing-with-types-single-case-dus/

I hope this helps!


问:
Workaround for Java checked exceptions
I appreciate a lot the new Java 8 features about lambdas and default methods interfaces. Yet, I still get bored with checked exceptions. For instance, if I just want to list all the visible fields of an object I would like to simply write this:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
        f -> System.out.println(f.get(p))
    );
</code>```

Yet, since the get method might throw a checked exception, which does not agrees with the Consumer interface contract, then I must catch that exception and write the following code:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
            f -> {
                try {
                    System.out.println(f.get(p));
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    throw new RuntimeException(ex);
                }
            }
    );
</code>```

However in most cases I just want the exception to be thrown as a RuntimeException and let the program handle, or not, the exception without compilation errors.

So, I would like to have your opinion about my controversial workaround for checked exceptions annoyance. To that end, I created an auxiliary interface ConsumerCheckException<T> and an utility function rethrow (updated according to the sugestion of Doval's comment) as follows:

```<code>  @FunctionalInterface
  public interface ConsumerCheckException<T>{
      void accept(T elem) throws Exception;
  }

  public class Wrappers {
      public static <T> Consumer<T> rethrow(ConsumerCheckException<T> c) {
        return elem -> {
          try {
            c.accept(elem);
          } catch (Exception ex) {
            /**
             * within sneakyThrow() we cast to the parameterized type T.
             * In this case that type is RuntimeException.
             * At runtime, however, the generic types have been erased, so
             * that there is no T type anymore to cast to, so the cast
             * disappears.
             */
            Wrappers.<RuntimeException>sneakyThrow(ex);
          }
        };
      }

      /**
       * Reinier Zwitserloot who, as far as I know, had the first mention of this
       * technique in 2009 on the java posse mailing list.
       * http://www.mail-archive.com/javaposse@googlegroups.com/msg05984.html
       */
      public static <T extends Throwable> T sneakyThrow(Throwable t) {
          throw (T) t;
      }
  }
</code>```

And now I can just write:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
            rethrow(f -> System.out.println(f.get(p)))
    );
</code>```

I am not sure that this is the best idiom to turn around the checked exceptions, but as I explained, I would like to have a more convenient way of achieving my first example without dealing with checked exceptions and this is the simpler way that I found to do it.

答:
Checked exceptions are very useful and their handling depends on the kind of product you code is part of:

a library

a desktop application

a server running within some box

an academical exercise

Usually a library must not handle checked exceptions, but declare as thrown by public API. The rare case when they could wrapped into plain RuntimeExcepton is, for example, creating inside of library code some private xml document and parsing it, creating some temporary file and then reading that.

For desktop applications you must start the development of product by creating your own exception handling framework. Using you own framework usually you will wrap a checked exception into some of two to four wrappers (your custom sub-classes of RuntimeExcepion) and handle them by a single Exception Handler.

For servers usually your code will run inside of some framework. If you don't use any (a bare server) create your own framework similar (based on Runtimes)  described above.

For academical exercises you can always wrap them directly into RuntimeExcepton. Somebody can create a tiny framework too.

Title: Workaround for Java checked exceptions


问:
How do you go about understanding others' code?
What do you do to understand some code that you didn't write? Or code that you wrote long time ago and don't remember what it does anymore.

Do you have some technique that you go about? Do you analyze the structures first, or the public methods, or do you draw flow charts, etc.? Or do you fire up the debugger and just step through it? Or do you just ad-hoc your way through until you understand it?

答:
I go through the usecases. Each use-case starts at some point and finishes at another. Start looking at the begining and follow the flow. When you've examined three or four usecases you know the structure of the code.

Preferably you should be writing tests when following the code, since it will help you keep a more active role in examining the code than reading it line by line.

The debugger is a great tool to follow the flow, you could make some quick tests that doesn't realy assert anything but start the code at the point you want to debug from, to get a quick starting point for the debugger.

Though depending on how comfortable you are with tests, tests might be faster to check expected results.

ContentLicense: CC BY-SA 2.5


问:
Clean Code comments vs class documentation
I'm having some discussions with my new colleagues regarding commenting. We both like Clean Code, and I'm perfectly fine with the fact that inline code comments should be avoided and that class and methods names should be used to express what they do.

However, I'm a big fan of adding small class summaries that tries to explain the purpose of the class and what is actually represents, primarily so that its easy to maintain the single responsibility principle pattern. I'm also used to adding one-line summaries to methods that explains what the method is supposed to do. A typical example is the simple method

```<code>public Product GetById(int productId) {...}
</code>```

I'm adding the following method summary

```<code>/// <summary>
/// Retrieves a product by its id, returns null if no product was found.
/// </summary
</code>```

I believe that the fact that the method returns null should be documented. A developer that wants to call a method should not have to open up my code in order to see if the method returns null or throws an exception. Sometimes it's part of an interface, so the developer doesn't even know which underlying code is running?

However, my colleagues think that these kinds of comments are "code smell" and that "comments are always failures" (Robert C. Martin).

Is there a way to express and communicate these types of knowledge without adding comments? Since I'm a big fan of Robert C. Martin, I'm getting a bit confused. Are summaries the same as comments and therefore always failures?

This is not a question about in-line comments.

答:
The Robert C. Martin quote is taken out of context. Here is the quote with a bit more context:

Nothing can be quite so helpful as a well-placed comment.  Nothing can
  clutter up a module more than frivolous dogmatic comments.  Nothing
  can be quite so damaging as an old crufty comment that propagates lies
  and misinformation.

Comments are not like Schindler's List.  They are not "pure good."
  Indeed, comments are, at best, a necessary evil.  If our programming
  languages were expressive enough, or if we had the talent to subtly
  wield those languages to express our intent, we would not need
  comments very much -- perhaps not at all.

The proper use of comments is to compensate for our failure to express
  ourself in code.  Note that I used the word failure.  I meant it.
  Comments are always failures.  We must have them because we cannot
  always figure out how to express ourselves without them, but their use
  is not a cause for celebration.

So when you find yourself in a position where you need to write a
  comment, think it through and see whether there isn't some way to turn
  the tables and express yourself in code.  Every time you express
  yourself in code, you should pat yourself on the back.  Every time you
  write a comment, you should grimace and feel the failure of your
  ability of expression.

(Copied from here, but the original quote is from Clean Code: A Handbook of Agile Software Craftsmanship)

How this quote is reduced into "Comments are always failures" is a good example of how some people will take a sensible quote out of context and turning it into stupid dogma.

API documentation (like javadoc) is supposed to document the API so the user can use it without having to read the source code. So in this case the documentation should explain what the method does. Now you can argue that "Retrieves a product by its id" is redundant because it is already indicated by the method name, but the information that null may be returned is definitely important to document, since this in not in any way obvious.

If you want to avoid the necessity of the comment, you have to remove the underlying problem (which is the use of null as a valid return value), by making the API more explicit. For example you could return some kind of Option<Product> type, so the type signature itself communicates clearly what will be returned in case the product is not found.

But in any case it is not realistic to document an API fully just through method names and type signatures. Use doc-comments for any additional non-obvious information which the user should know. Take say the API documentation from DateTime.AddMonths() in the BCL:

The AddMonths method calculates the resulting month and year, taking
  into account leap years and the number of days in a month, then
  adjusts the day part of the resulting DateTime object. If the
  resulting day is not a valid day in the resulting month, the last
  valid day of the resulting month is used. For example, March 31st + 1
  month = April 30th. The time-of-day part of the resulting DateTime
  object remains the same as this instance.

There is no way you could express this using just the method name and signature! Of course your class documentation might not require this level of detail, it is just an example.

Inline comments are not bad either.

Bad comments are bad. For example comments which only explains what can be trivially seen from the code, the classical example being:

```<code>// increment x by one
x++;
</code>```

Comments which explains something which could be made clear by renaming a variable or method or otherwise restructuring the code, is a code smell:

```<code>// data1 is the collection of tasks which failed during execution
var data1 = getData1();
</code>```

These are the kind of comments Martin rails against. The comment is a symptom of a failure to write clear code - in this case to use self-explanatory names for variables and methods. The comment itself is of course not the problem, the problem is we need the comment to understand the code.

But comments should be used to explain everything which is not obvious from the code, e.g. why the code is written a certain non-obvious way:

```<code>// need to reset foo before calling bar due to a bug in the foo component.
foo.reset()
foo.bar();
</code>```

Comments which explains what an overly convoluted piece of code does is also a smell, but the fix is not to outlaw comments, the fix is the fix the code! In the real word, convoluted code does happen (hopefully only temporarily until a refactor) but no ordinary developer writes perfect clean code the first time. When convoluted code happens it is much better to write a comment explaining what it does than not write a comment. This comment will also make it easier to refactor later.

Sometimes code is unavoidably complex. It may be an complicated algorithm, or it may be code sacrificing clarity for performance reasons. Again comments are necessary.

Body:
The Robert C. Martin quote is taken out of context. Here is the quote with a bit more context:

Nothing can be quite so helpful as a well-placed comment.  Nothing can
  clutter up a module more than frivolous dogmatic comments.  Nothing
  can be quite so damaging as an old crufty comment that propagates lies
  and misinformation.

Comments are not like Schindler's List.  They are not "pure good."
  Indeed, comments are, at best, a necessary evil.  If our programming
  languages were expressive enough, or if we had the talent to subtly
  wield those languages to express our intent, we would not need
  comments very much -- perhaps not at all.

The proper use of comments is to compensate for our failure to express
  ourself in code.  Note that I used the word failure.  I meant it.
  Comments are always failures.  We must have them because we cannot
  always figure out how to express ourselves without them, but their use
  is not a cause for celebration.

So when you find yourself in a position where you need to write a
  comment, think it through and see whether there isn't some way to turn
  the tables and express yourself in code.  Every time you express
  yourself in code, you should pat yourself on the back.  Every time you
  write a comment, you should grimace and feel the failure of your
  ability of expression.

(Copied from here, but the original quote is from Clean Code: A Handbook of Agile Software Craftsmanship)

How this quote is reduced into "Comments are always failures" is a good example of how some people will take a sensible quote out of context and turning it into stupid dogma.

API documentation (like javadoc) is supposed to document the API so the user can use it without having to read the source code. So in this case the documentation should explain what the method does. Now you can argue that "Retrieves a product by its id" is redundant because it is already indicated by the method name, but the information that null may be returned is definitely important to document, since this in not in any way obvious.

If you want to avoid the necessity of the comment, you have to remove the underlying problem (which is the use of null as a valid return value), by making the API more explicit. For example you could return some kind of Option<Product> type, so the type signature itself communicates clearly what will be returned in case the product is not found.

But in any case it is not realistic to document an API fully just through method names and type signatures. Use doc-comments for any additional non-obvious information which the user should know. Take say the API documentation from DateTime.AddMonths() in the BCL:

The AddMonths method calculates the resulting month and year, taking
  into account leap years and the number of days in a month, then
  adjusts the day part of the resulting DateTime object. If the
  resulting day is not a valid day in the resulting month, the last
  valid day of the resulting month is used. For example, March 31st + 1
  month = April 30th. The time-of-day part of the resulting DateTime
  object remains the same as this instance.

There is no way you could express this using just the method name and signature! Of course your class documentation might not require this level of detail, it is just an example.

Inline comments are not bad either.

Bad comments are bad. For example comments which only explains what can be trivially seen from the code, the classical example being:

// increment x by one
x++;

Comments which explains something which could be made clear by renaming a variable or method or otherwise restructuring the code, is a code smell:

// data1 is the collection of tasks which failed during execution
var data1 = getData1();

These are the kind of comments Martin rails against. The comment is a symptom of a failure to write clear code - in this case to use self-explanatory names for variables and methods. The comment itself is of course not the problem, the problem is we need the comment to understand the code.

But comments should be used to explain everything which is not obvious from the code, e.g. why the code is written a certain non-obvious way:

// need to reset foo before calling bar due to a bug in the foo component.
foo.reset()
foo.bar();

Comments which explains what an overly convoluted piece of code does is also a smell, but the fix is not to outlaw comments, the fix is the fix the code! In the real word, convoluted code does happen (hopefully only temporarily until a refactor) but no ordinary developer writes perfect clean code the first time. When convoluted code happens it is much better to write a comment explaining what it does than not write a comment. This comment will also make it easier to refactor later.

Sometimes code is unavoidably complex. It may be an complicated algorithm, or it may be code sacrificing clarity for performance reasons. Again comments are necessary.


问:
How C# protected access modifier when applied to a member variable works
I have 2 classes, Base and child class.
Base class has a protected int variable. My understanding is that any protected member of a class can only be accessed in a child class, It cannot be accessed from say creating an Instance of a class and accessing the protected member. How is this working then?</p>

```<code>  class BaseClass
        {
            protected int x = 0;

            private static void Funny(BaseClass c, ChildClass d)
            {
                d.x = 9; // How can we access x here?
                c.x = 0; // How can we access x here?
            }
        }

        class ChildClass: BaseClass
        {
            public void MyFunc()
            {
                x = 0; // This should be OK, because x is a protected member of
            }

            private static void Funny(BaseClass c,ChildClass d)
            {

                d.x = 9;
                c.x=0;// This is giving compile time error? According to me even above line should give compile time error

            }
        }
</code>```

答:
In C#, the scope of access modifiers is the class, not the instance. This means that a private member can be accessed within the class on any instance.

```<code>public class Price
{
    private int amount;

    private static void CheckAmountOf(Price price)
    {
        // The following line is possible, even if `amount` is private and we are accessing an
        // instance of the object which was passed by a parameter.
        if (price.amount < 0)
        {
            throw new InvalidValueException("The price cannot be negative.");
        }
    }
}
</code>```

This, by the way, makes it possible (and easy) to override Equals. Otherwise, you would be limited to public properties only, which may not be exactly what you want.

```<code>class Price
{
    private int amount;

    public override bool Equals(object obj)
    {
        ...
        var price = obj as Price;
        ...
        // The next line is valid, even if `amount` is private and even if the initial argument
        // was of type `object`. This way, you don't need to have a corresponding `Amount`
        // property with a public getter.
        return this.amount == price.amount;
    }
}
</code>```

Body:
In C#, the scope of access modifiers is the class, not the instance. This means that a private member can be accessed within the class on any instance.

public class Price
{
    private int amount;

    private static void CheckAmountOf(Price price)
    {
        // The following line is possible, even if `amount` is private and we are accessing an
        // instance of the object which was passed by a parameter.
        if (price.amount < 0)
        {
            throw new InvalidValueException("The price cannot be negative.");
        }
    }
}

This, by the way, makes it possible (and easy) to override Equals. Otherwise, you would be limited to public properties only, which may not be exactly what you want.

class Price
{
    private int amount;

    public override bool Equals(object obj)
    {
        ...
        var price = obj as Price;
        ...
        // The next line is valid, even if `amount` is private and even if the initial argument
        // was of type `object`. This way, you don't need to have a corresponding `Amount`
        // property with a public getter.
        return this.amount == price.amount;
    }
}


答:
Well, it seems your colleague reads books, takes in what they say, and applies what he learned without thinking and without any consideration of context.

Your comment about what the function does should be such that you can throw away the implementation code, I read the comment of the function, and I can write the replacement for the implementation, without anything going wrong.

If the comment doesn't tell me whether an exception is thrown or whether nil is returned, I can't do that. Furthermore, if the comment doesn't tell you whether an exception is thrown or whether nil is returned, then wherever you call the function, you must make sure your code works correctly whether an exception is thrown or nil is returned.

So your colleague is totally wrong. And go ahead and read all the books, but think for yourself.

PS. I saw your line "sometimes it's part of an interface, so you don't even know what code is running. " Even just with virtual functions, you don't know what code is running. Worse, if you wrote an abstract class, there isn't even any code! So if you have an abstract class with an abstract function, the comments that you add to the abstract function are the only thing that an implementor of a concrete class has to guide them. Those comments may also be the only thing that can guide a user of the class, for example if all you have is an abstract class and a factory returning a concrete implementation, but you never see any source code of the implementation. (And of course I shouldn't be looking at the source code of one implementation).

Title: Clean Code comments vs class documentation

Body:
I'm having some discussions with my new colleagues regarding commenting. We both like Clean Code, and I'm perfectly fine with the fact that inline code comments should be avoided and that class and methods names should be used to express what they do.

However, I'm a big fan of adding small class summaries that tries to explain the purpose of the class and what is actually represents, primarily so that its easy to maintain the single responsibility principle pattern. I'm also used to adding one-line summaries to methods that explains what the method is supposed to do. A typical example is the simple method

```<code>public Product GetById(int productId) {...}
</code>```

I'm adding the following method summary

```<code>/// <summary>
/// Retrieves a product by its id, returns null if no product was found.
/// </summary
</code>```

I believe that the fact that the method returns null should be documented. A developer that wants to call a method should not have to open up my code in order to see if the method returns null or throws an exception. Sometimes it's part of an interface, so the developer doesn't even know which underlying code is running?

However, my colleagues think that these kinds of comments are "code smell" and that "comments are always failures" (Robert C. Martin).

Is there a way to express and communicate these types of knowledge without adding comments? Since I'm a big fan of Robert C. Martin, I'm getting a bit confused. Are summaries the same as comments and therefore always failures?

This is not a question about in-line comments.


答:
There are two types of comments to consider - those visible to people with the code and those use to generate documentation.

The type of comment that Uncle Bob is referring to is the kind that is only visible to people with the code. What he is advocating for is a form of DRY. For a person that is looking at the source code, the source code should be the documentation that they need. Even in the case where people have access to the source code, comments aren't always bad. Sometimes, algorithms are complicated or you need to capture why you're taking a non-obvious approach so that others don't end up breaking your code if they try to fix a bug or add a new feature.

The comments that you are describing are API documentation. These are things that are visible to people using your implementation, but that may not have access to your source code. Even if they do have access to your source code, they may be working on other modules and not be looking at your source code. These people would find it useful to have this documentation available in their IDE as they are writing their code.


答:
There is a difference between commenting your code and documenting your code.

Comments are needed to maintain the code later, that is change the code itself.

Comments may indeed be perceived as problematic. The extreme point would be to say that they always indicate a problem, either within your code (code too difficult to understand) or within the language (language unable to be expressive enough; for instance, the fact that the method never returns null could be expressed through Code contracts in C#, but there is no way to express it through code in, say, PHP).

Documentation is needed to be able to use the objects (classes, interfaces) you developed. The target audience is different: it's not the persons who will maintain your code and change it that we are talking about here, but persons who barely need to use it.

Removing documentation because the code is clear enough is insane, since documentation is here specifically to make it possible to use classes and interfaces without having to read thousands of lines of code.


答:
As others have said, there's a difference between API-documenting comments and in-line comments. From my perspective, the main difference is that an in-line comment is read alongside the code, whereas a documentation comment is read alongside the signature of whatever you're commenting.

Given this, we can apply the same DRY principle. Is the comment saying the same thing as the signature? Let's look at your example:

Retrieves a product by its id

This part just repeats what we already see from the name GetById plus the return type Product. It also raises the question what the difference between "getting" and "retrieving" is, and what bearing code vs. comment has on that distinction. So it's needless and slightly confusing. If anything, it's getting in the way of the actually useful, second part of the comment:

returns null if no product was found.

Ah! That's something we definitely can't know for sure just from the signature, and provides useful information.

Now take this a step further. When people talk about comments as code smells, the question isn't whether the code as it is needs a comment, but whether the comment indicates that the code could be written better, to express the information in the comment. That's what "code smell" means- it doesn't mean "don't do this!", it means "if you're doing this, it could be a sign there's a problem".

So if your colleagues tell you this comment about null is a code smell, you should simply ask them: "Okay, how should I express this then?" If they have a feasible answer, you've learned something. If not, it'll probably kill their complaints dead.

Regarding this specific case, generally the null issue is well known to be a difficult one. There's a reason code bases are littered with guard clauses, why null checks are a popular precondition for code contracts, why the existence of null has been called a "billion-dollar mistake". There aren't that many viable options. One popular one, though, found in C# is the Try... convention:

```<code>public bool TryGetById(int productId, out Product product);
</code>```

In other languages, it may be idiomatic to use a type (often called something like Optional or Maybe) to indicate a result that may or may not be there:

```<code>public Optional<Product> GetById(int productId);
</code>```

So in a way, this anti-comment stance has gotten us somewhere: we've at least thought about whether this comment represents a smell, and what alternatives might exist for us.

Whether we should actually prefer these over the original signature is a whole other debate, but we at least have options for expressing through code rather than comments what happens when no product is found. You should discuss with your colleagues which of these options they think is better and why, and hopefully help move on beyond blanket dogmatic statements about comments.

Body:
As others have said, there's a difference between API-documenting comments and in-line comments. From my perspective, the main difference is that an in-line comment is read alongside the code, whereas a documentation comment is read alongside the signature of whatever you're commenting.

Given this, we can apply the same DRY principle. Is the comment saying the same thing as the signature? Let's look at your example:

Retrieves a product by its id

This part just repeats what we already see from the name GetById plus the return type Product. It also raises the question what the difference between "getting" and "retrieving" is, and what bearing code vs. comment has on that distinction. So it's needless and slightly confusing. If anything, it's getting in the way of the actually useful, second part of the comment:

returns null if no product was found.

Ah! That's something we definitely can't know for sure just from the signature, and provides useful information.

Now take this a step further. When people talk about comments as code smells, the question isn't whether the code as it is needs a comment, but whether the comment indicates that the code could be written better, to express the information in the comment. That's what "code smell" means- it doesn't mean "don't do this!", it means "if you're doing this, it could be a sign there's a problem".

So if your colleagues tell you this comment about null is a code smell, you should simply ask them: "Okay, how should I express this then?" If they have a feasible answer, you've learned something. If not, it'll probably kill their complaints dead.

Regarding this specific case, generally the null issue is well known to be a difficult one. There's a reason code bases are littered with guard clauses, why null checks are a popular precondition for code contracts, why the existence of null has been called a "billion-dollar mistake". There aren't that many viable options. One popular one, though, found in C# is the Try... convention:

public bool TryGetById(int productId, out Product product);

In other languages, it may be idiomatic to use a type (often called something like Optional or Maybe) to indicate a result that may or may not be there:

public Optional<Product> GetById(int productId);

So in a way, this anti-comment stance has gotten us somewhere: we've at least thought about whether this comment represents a smell, and what alternatives might exist for us.

Whether we should actually prefer these over the original signature is a whole other debate, but we at least have options for expressing through code rather than comments what happens when no product is found. You should discuss with your colleagues which of these options they think is better and why, and hopefully help move on beyond blanket dogmatic statements about comments.


问:
How to extract the active code path from a complex algorithm
I have been puzzled lately by an intruiging idea.

I wonder if there is a (known) method to extract the executed source code from a large complex algorithm. I will try to elaborate this question:

Scenario: There is this complex algorithm where a large amount of people have worked on for many years. The algorithm creates measurement descriptions for a complex measurement device.

The input for the algorithm is a large set of input parameters, lets call this the recipe. Based on this recipe, the algorithm is executed, and the recipe determines which functions, loops and if-then-else constructions are followed within the algorithm. When the algorithm is finished, a set of calculated measurement parameters will form the output. And with these output measurement parameters the device can perform it's measurement.

Now, there is a problem. Since the algorithm has become so complex and large over time, it is very very difficult to find your way in the algorithm when you want to add new functionality for the recipes. Basically a person wants to modify only the functions and code blocks that are affected by its recipe, but he/she has to dig in the whole algorithm and analyze the code to see which code is relevant for his or her recipe, and only after that process new functionality can be added in the right place. Even for simple additions, people tend to get lost in the huge amount of complex code.

Solution: Extract the active code path? I have been brainstorming on this problem, and I think it would be great if there was a way to process the algorithm with the input parameters (the recipe), and to only extract the active functions and codeblocks into a new set of source files or code structure. I'm actually talking about extracting real source code here.

When the active code is extracted and isolated, this will result in a subset of source code that is only a fraction of the original source code structure, and it will be much easier for the person to analyze the code, understand the code, and make his or her modifications. Eventually the changes could be merged back to the original source code of the algorithm, or maybe the modified extracted source code can also be executed on it's own, as if it is a 'lite' version of the original algorithm.

Extra information: We are talking about an algorithm with C and C++ code, about 200 files, and maybe 100K lines of code. The code is compiled and build with a custom Visual Studio based build environment.

So...: I really don't know if this idea is just naive and stupid, or if it is feasible with the right amount of software engineering. I can imagine that there have been more similar situations in the world of software engineering, but I just don't know.

I have quite some experience with software engineering, but definitely not on the level of designing large and complex systems.

I would appreciate any kind of answer, suggestion or comment.

Thanks in advance!

答:
I think it depends on what you want to achieve... Do you want to improve the code? parallelize the code? clean it? just understand it?

Besides the great comment given by @Calphool, what I've done in similar cases (but not with 100K lines code to be honest) is this:

Look for whoever wrote the code. Or has use it. Asked them what I needed to know, that saves you a lot of time. This may seem stupid, but is not.

I made a graph of the dependencies. Take a look at this for an example.

Depending on what you need to do, you could measure the execution time of some (or all) function.

Start playing with it... but with modern tools, like git. If possible, started to add some tests.

If you want to see what functions get called, you could just print the functions that are called (take a look at this question). You could add a printf at each function using a script, but I don't think that is a good idea. Also, you have to think how are you going to go through the generated output.

After you know what you want, and before making my implementations, I try to isolate the part I need to work on. Meaning, I cleanup the code a little, put in a different file if needed, compile it and test it. Only then I proceed to actually modify the code adding functionality or whatever needs to be done. This may also include port the code to use modern building tools if needed.

My two cents.


问:
Maintaining State without assignment
I am learning functional programming and I have trouble understanding how some particular scenarios are implemented without the use of assignment. The following simple problem pretty much sums up my confusion.

Write a program that receives events about changes in a given data structure and      emits events when this data structure reaches a certain state.

So I have a copy of the datastructure that I maintain

```<code>datastructure_copy::DataStructure
</code>```

I have the stream of events which are fired when it changes:

```<code>datastructure_changes::Stream Change
</code>```

I have a function that applies a change to a data structure and returns a new copy it:

```<code>apply_change::Change -> DataStructure -> DataStructure
</code>```

And I have a predicate which checks if the data state has reached the desired state.

```<code>is_ready::DataStructure ->Boolean
</code>```

In other words I need something like 'reduce' that works on streams.

I know that one way to implement this is to recompute the state each time a change arrives, however this seems impractical. I played a bit with the State monad, but it looks to me like it is meant to solve a different problem.

So is there another way to do that?

Note that my question is purely conceptual and I am not deeply familiar with Haskell.

答:
You say you have 2 functions:

```<code>apply_change::Change -> DataStructure -> DataStructure
is_ready::DataStructure ->Boolean
</code>```

and if I understand you right then is_ready is rather expensive so you don't want to do that for every change event over and over.

What you need is a function takes an initial DataStructure and condenses it into a simple state and a function that takes a condensed state, a Change and outputs a new condensed state.

Say DataStructure is a triplet x,y,z and you are waiting for x, y and z to be prime numbers. Your condensed state could then be a set of which of x,y,z are not prime. A Change that makes x prime removes x from the set. A Change that makes x not prime adds x to the set (if not present). The DataStructure is ready then the set is empty.

The idea would be that updating the condensed state is a lot cheaper than updating DataStructure and computing is_ready from scratch.

Note: An even better approach could be to keep track of which of x,y,z where checked for being prime and if they where. For every Change you flag the relevant field as not checked. Then when is_ready is called you check and remember. This is better if you do not check is_ready after every Change since x might change multiple times and you only check for prime once.

Title: Maintaining State without assignment

Body:
You say you have 2 functions:

apply_change::Change -> DataStructure -> DataStructure
is_ready::DataStructure ->Boolean

and if I understand you right then is_ready is rather expensive so you don't want to do that for every change event over and over.

What you need is a function takes an initial DataStructure and condenses it into a simple state and a function that takes a condensed state, a Change and outputs a new condensed state.

Say DataStructure is a triplet x,y,z and you are waiting for x, y and z to be prime numbers. Your condensed state could then be a set of which of x,y,z are not prime. A Change that makes x prime removes x from the set. A Change that makes x not prime adds x to the set (if not present). The DataStructure is ready then the set is empty.

The idea would be that updating the condensed state is a lot cheaper than updating DataStructure and computing is_ready from scratch.

Note: An even better approach could be to keep track of which of x,y,z where checked for being prime and if they where. For every Change you flag the relevant field as not checked. Then when is_ready is called you check and remember. This is better if you do not check is_ready after every Change since x might change multiple times and you only check for prime once.


问:
When is the time right to bring a project to the alpha/beta/public phase?
When should a project be released to alpha, beta and to the public?

Is it a good idea to extend the alpha and beta phases when it is needed?

When in a later phase (eg. beta), is it wise to go back to an early phase (eg. alpha) if it didn't work out?

答:
The right time is when the product is ready for each stage.

It's up to you and the customer to define "ready". This might be when a certain number of bugs have been found and fixed or how much documentation has been completed. It all depends on the application and what the customer is expecting.

I'll ignore the alpha phase for now.

A beta phase is usually when you think you're feature complete for this release and require feedback on the fine details of your application. This is often seen as public testing, but that depends on your application. A small scale application will be beta tested by a few select users, a large application (like Visual Studio, or Stack Overflow) will be beta tested by anybody and everybody willing to help.

The official release is when you (and your customers/users) are confident that your product can do the job it's designed for. It might not have all it's features, but those you implemented for this release will be.

Alpha testing is more nebulous. It means different things to different people. You might release an early version that not feature complete because you need more user feedback on one particular aspect. You might also need to get something "out there" to meet a specific demand and can't afford to wait.


答:
refactoring

the code, thus making it clearer, and in standard that ah-hock established.

Title: How do you go about understanding others' code?

Body:
What do you do to understand some code that you didn't write? Or code that you wrote long time ago and don't remember what it does anymore.

Do you have some technique that you go about? Do you analyze the structures first, or the public methods, or do you draw flow charts, etc.? Or do you fire up the debugger and just step through it? Or do you just ad-hoc your way through until you understand it?


问:
Does the Head(start) pointer of Doubly Linked list points previously to the tail(last) node
I have one question in my mind that in case of circular doubly linked list the head pointer of the doubly linked list also logically point to the next pointer of the tail node of the linked list and tail's next pointer also point to the previous pointer of head.

Please Answer me this question I am a bit confused.

答:
I've used a circular doubly linked list like this:

```<code>typedef struct List {
  struct List *next;
  struct List *prev;
  void *data;
} List;
</code>```

I decided to define the head of a List as one that has data == NULL. So an empty List is one where next and prev point to itself and data == NULL. You can then insert before or after the head at will. You can iterate the list by starting at head->next and going till you hit head again.

And here is the fun part: You can have multiple heads. Nothing prevents you from inserting a second List with data == NULL. Now there are two ways to iterate over the list: You can iterate till you hit the next head (data == NULL) or skip over heads and keep going till you hit the original head again.

Body:
I've used a circular doubly linked list like this:

typedef struct List {
  struct List *next;
  struct List *prev;
  void *data;
} List;

I decided to define the head of a List as one that has data == NULL. So an empty List is one where next and prev point to itself and data == NULL. You can then insert before or after the head at will. You can iterate the list by starting at head->next and going till you hit head again.

And here is the fun part: You can have multiple heads. Nothing prevents you from inserting a second List with data == NULL. Now there are two ways to iterate over the list: You can iterate till you hit the next head (data == NULL) or skip over heads and keep going till you hit the original head again.


问:
Events in WCF Service Architecture (Server Side)
Problem:
 Now, I have some events that will take place when the client submits a request to the server. These events will arise on the server and they will  be subscribed by the services themselves (the services on the server interact with one another not through a channel but as simple objects i.e instantiating a class) who will do some work and the return the result to client if need be.

In the event aggregator pattern the subscribers and publishers are unaware of each other.

Now I was looking at the options that I have to implement this problem and event aggregators got my attention. Plus, I want to have a way to notify multiple services when an event has occurred without explicitly calling them.

Edit:

Example:
In my current setup say I have three services X(publisher), Y(subscriber) and Z(subscriber). I have an incoming request for service Y before X. Since It was a registered subscriber (I have subscribed to the event in ctor) it gets instantiated and thus it is a live subscriber. Now a request comes for X and it gets instantiated and publishes the event. Y is alive to listen and handles the event. But, though Z was also a subscriber but had no alive instance when X published the event the call goes unheard. For this below I have given a possible solution but don't know if its a viable one. This is happening at the server.

Edit 2:

```<code>// Service X and Service Y and Service Z are not linked through a channel
// All services are WCF services and client call them through a channel
public class ServiceX{

publi void DoSomeWork(){

MyEventAggregator<MyEvent>.Instance.Publish(Payload);  //Some event is triggered and the subscribers will be notified

//if event aggregator is not used normal call would go like

ServiceY obj=new SerivceY();  // no channel creation

obj.CallSomeMethod(Payload);
}

}

public class ServiceY(){

public ServiceY(){
//subscribers register for event
MyEventAggregator<MyEvent>.Instance.Subscribe(MyHandler,true);  //true is a flag that keeps subscriber ref alive

}

MyHandler(dynamic obj){
//Do work

}

}

public class ServiceZ{
public ServiceZ(){
//subscribers register for event
MyEventAggregator<MyEvent>.Instance.Subscribe(MyHandlerZ,true);  //true is a flag that keeps subscriber ref alive

}

MyHandlerZ(dynamic obj){
//Do work

}

}
public class MyEvent:PubSubEvents<dynamic>{
//from prism library
//My Event
}

public class MyEventAggregator{

//implements singleton that returns the event aggregator instance.

}
//By using event aggregators the there can be multiple subscribers to an event without them knowing about each other
</code>```

Possible Solution:
I could use the Prism Event Aggregators to publish and subscribe to events but that in itself will give rise to a problem i.e though I will have my subscribers registered they will only function if they are instantiated before the event is triggered (published).

So now I will have to make sure that my subscribers are alive when
       the event is published which could be handled with an infrastructure module together with the unity application block(don't know if it will be required though) that deals   with subscriptions though instantiating a ton of objects will have its overhead

Now what I wanted to know is am I thinking in the right direction because I haven't seen a lot of people using WCF and Prism Event Aggregators together (Prism is mostly considered to be client side framework as far as I know).

Edit 3:

Solution Code (to instantiate subscriber before publisher):
I could use unity to resolve this dependency say in the global.asax.cs file's application_start method I could do something like this:

```<code>IUnityContainer uContainer = new UnityContainer()
   .RegisterType<ISubscriber, ServiceY>("Abc")
   .RegisterType<ISubscriber, ServiceZ>("Xyz");

ISubscriber myInstance = uContainer.Resolve<ISubscriber>("Abc");
ISubscriber myInstance = uContainer.Resolve<ISubscriber>("Xyz");
</code>```

where all subscribers will extend and ISubscriber interface like:

```<code>ServiceY:ISubscriber{}
</code>```

This would ensure that the subscriber instance is alive when an event is published.

How would you go about dealing with events in WCF?

Are there any other options that I have??

答:
I posted this question on codeplex forum and got the answer from Bryan Noyes. It is:

I'm afraid you are cleanly outside what Prism pub-sub events were designed for. They were designed for loosely coupled components that are all in memory at the same time on the client side but you don't want to introduce coupling between those client components for them to communicate. For the kind of scenario you are talking about server side queues of some sort are the right answer, whether they are MSMQ-based, RabbitMQ, or Service Bus queues for Service Bus for Windows Server (or many other options along those lines depending on whether you want the queue to be on premise or in the cloud).

So in short prism pubsubevents aren't a good idea when it comes to server side events.


问:
Designing a REST api by URI vs query string
Let's say I have three resources that are related like so:

```<code>Grandparent (collection) -> Parent (collection) -> and Child (collection)
</code>```

The above depicts the relationship among these resources like so: Each grandparent can map to one or several parents. Each parent can map to one or several children. I want the ability to support searching against the child resource but with the filter criteria:

If my clients pass me an id reference to a grandparent, I want to only search against children who are direct descendants of that grandparent.

If my clients pass me an id reference to a parent, I want to only search against children who are direct descendants of my parent.

I have thought of something like so:

```<code>GET /myservice/api/v1/grandparents/{grandparentID}/parents/children?search={text}
</code>```

and

```<code>GET /myservice/api/v1/parents/{parentID}/children?search={text}
</code>```

for the above requirements, respectively.

But I could also do something like this:

```<code>GET /myservice/api/v1/children?search={text}&grandparentID={id}&parentID=${id}
</code>```

In this design, I could allow my client to pass me one or the other in the query string: either grandparentID or parentID, but not both.

My questions are:

1) Which API design is more RESTful, and why? Semantically, they mean and behave the same way. The last resource in the URI is "children", effectively implying that the client is operating on the children resource.

2) What are the pros and cons to each in terms of understandability from a client's perspective, and maintainability from the designer's perspective.

3) What are query strings really used for, besides "filtering" on your resource? If you go with the first approach, the filter parameter is embedded in the URI itself as a path parameter instead of a query string parameter.

Thanks!

答:
A lot of people have allready talked about what REST means, etc etc. But none seem to address the real issue: your design.

Why is grandparent different from a father? they both have children that can possibly have children that can ...

Eventually, they are all 'human'. You probably have that in your code as well. So use that:

```<code>GET /<api-endpoint>/humans/<ID>
</code>```

Will return some usefull info about the human. (Name, and stuff)

```<code>GET /<api-endpoint>/humans/<ID>/children
</code>```

will obviously return an array of children. If no children exist, an empty array is probably the way to go.

To make it easy, you could for instance add a flag 'hasChildren'. or 'hasGrandChildren'.

Think smarter not harder

Body:
A lot of people have allready talked about what REST means, etc etc. But none seem to address the real issue: your design.

Why is grandparent different from a father? they both have children that can possibly have children that can ...

Eventually, they are all 'human'. You probably have that in your code as well. So use that:

GET /<api-endpoint>/humans/<ID>

Will return some usefull info about the human. (Name, and stuff)

GET /<api-endpoint>/humans/<ID>/children

will obviously return an array of children. If no children exist, an empty array is probably the way to go.

To make it easy, you could for instance add a flag 'hasChildren'. or 'hasGrandChildren'.

Think smarter not harder


答:
Uncommented code is bad code.  It is a widespread (if not universal) myth that code can be read in much the same way as, say, English.  It must be interpreted, and for any but the most trivial code that takes time and effort.  Plus, everybody has a different level of capability in both reading and writing any given language.  Differences between the author and the reader's coding styles and capabilities are strong barriers to accurate interpretation.  It is also a myth that you can derive the intention of the author from the implementation of the code.  In my experience, it is rarely wrong to add extra comments.

Robert Martin et al. consider it a "bad smell" because it may be that the code is changed and the comments not.  I say it is a good thing (in exactly the same way that a "bad smell" is added to domestic gas to alert the user to leaks).  Reading comments give you a useful starting point to interpreting the actual code.  If they match then you will have increased confidence in the code.  If they differ then you have detected a warning smell and need to investigate further.  The cure to a "bad smell" is not to remove the smell but to seal the leak.


问:
How do you judge if you're paid enough?
How do you evaluate how much you feel you ought to be paid as a junior programmer?</p>

答:
Ask yourself how much added value you are providing to your company

Edit: Downvoters - skip to the end...

Simple formula:

How much you earn or save the company
  per year / 3 = Gross salary

This takes into account the fact that your employer will want to exploit you (you will always be underpaid), and allows for the overheads of having an employee on the books (training, heating the office, health and safety, equipment purchase etc).

How to work out your added value

Here are some scenarios that may help with your application of the above formula. These have been left in as an illustration of thought processes, you may want to simply skip to the end.

Internal software

Let's assume you do some work on an internal software product that helps to automate a previously manual process. Instead of that process taking an admin worker in Accounts all day to complete, they can now do it with a click of a mouse. The admin worker is now freed up to do other work and the Accounts department don't have to hire a new person to handle that manual process.

This is why they stumped up the cash from their budget to pay for you to develop this code for them in the first place.

You have saved the company the employer cost of a permanent admin worker - say $30,000. Therefore, you have justified your salary up to $10,000. In order to earn more, you need to provide more solutions that reduce the companies outgoings. As the company grows your contribution may affect a larger group of people, and as such your salary may increase (or you may be exploited more).

External software

Let's say you've just written a killer feature for your company's new commercial product. It retails at $3000, and the feature has caused an extra 100 units to be sold. (Your company is remarkable in that the sales force and developers get to chat freely by the water cooler). From that you deduce that your contribution was worth $300,000 to the company.

But... you didn't do it alone, did you?

The entire company exists to sell this product and everyone has made some kind of input -  from the person who came up with the idea of the feature you implemented to you doing the coding to the marketing and the salesmanship that neatly cleaved the cash from the customer.

For argument's sake, let's assume that 10 other people were principal in making this feature a success. Therefore, by the formula above you justify $10,000 of your gross salary.

Open-source software

You work for free, don't you?

Only joking.

Assuming that you mean that your company provides free and open-source software (e.g. Ubuntu) then your company's income is dependent on alternative revenue streams (service contracts, advertising, philanthropist funding etc). As a result, matching your contribution to your salary is going to be hard.

The final word (read first)

From this article (provided by @Macneil)

Using a labour theory of value is just
  a red herring

which essentially states that you will never be able to work out directly what you are worth because you need to take into account a large number of contributing factors that are not available to you.

Realistically, you will have to compare yourself to others doing similar programming jobs in the same country. The problem there is that you are averaging out your individual contributions over the entire country which means that you won't be reaching your maximum earnings potential.

Title: How do you judge if you're paid enough?


答:
MainMa's answer explains why most of the accesses work. However, to understand why the final one doesn't work, let's see what we could do if it was allowed:

```<code>class SiblingClass: BaseClass
{
}

    //...And then, inside some other code:
    var sibling = new SiblingClass();
    var child = new ChildClass();
    ChildClass.Funny(sibling, child);
</code>```

(This also requires ChildClass.Funny to be made public)

This would all compile- sibling inherits from BaseClass so it could be passed in for a parameter of type BaseClass. But now a ChildClass can access a member on a SiblingClass. That's not what we expect from the protected keyword- we expect that to give access only to things it inherits from its parent, not to all other classes which also inherit from its parent.

So to prevent this unexpected access happening, it's made illegal.

Title: How C# protected access modifier when applied to a member variable works

Body:
I have 2 classes, Base and child class.
Base class has a protected int variable. My understanding is that any protected member of a class can only be accessed in a child class, It cannot be accessed from say creating an Instance of a class and accessing the protected member. How is this working then?</p>

```<code>  class BaseClass
        {
            protected int x = 0;

            private static void Funny(BaseClass c, ChildClass d)
            {
                d.x = 9; // How can we access x here?
                c.x = 0; // How can we access x here?
            }
        }

        class ChildClass: BaseClass
        {
            public void MyFunc()
            {
                x = 0; // This should be OK, because x is a protected member of
            }

            private static void Funny(BaseClass c,ChildClass d)
            {

                d.x = 9;
                c.x=0;// This is giving compile time error? According to me even above line should give compile time error

            }
        }
</code>```

Body:
MainMa's answer explains why most of the accesses work. However, to understand why the final one doesn't work, let's see what we could do if it was allowed:

class SiblingClass: BaseClass
{
}

    //...And then, inside some other code:
    var sibling = new SiblingClass();
    var child = new ChildClass();
    ChildClass.Funny(sibling, child);

(This also requires ChildClass.Funny to be made public)

This would all compile- sibling inherits from BaseClass so it could be passed in for a parameter of type BaseClass. But now a ChildClass can access a member on a SiblingClass. That's not what we expect from the protected keyword- we expect that to give access only to things it inherits from its parent, not to all other classes which also inherit from its parent.

So to prevent this unexpected access happening, it's made illegal.


问:
Round amounts internationalized
Rounding amounts in Germany we must use Math.round instead of Math.floor.

The rule is called "Kaufmännisches Runden"

Is there any rounding-function for amounts who accepts the Locale in Java?

This is not improbably since toUpperCase respects the Locale too.

答:
"Kaufmännisches Runden" seem to just be the German name for "Bankers rounding". It is not something culture specific.

See the various rounding modes supported here: http://docs.oracle.com/javase/7/docs/api/java/math/RoundingMode.html

Title: Round amounts internationalized


答:
Working at three different places in one state within the US, I've encountered three different ways of rounding numbers in different applications. This isn't locale dependent - its industry dependent (finance, retail, science all round differently for different reasons).

Reporting to the finance department (from my retail experience) wanted things rounded up (HALF_UP) always. Makes it consistent and easy to explain.

Retail wanted it rounded always in the customer's favor (this is not a default rounding mode). You may lose a penny here or there, but it reduced the likelihood of a person arguing with the front end manager about an incorrect receipt (which would cost much more than a penny)

Science used HALF_EVEN to avoid systematic biasing of the data (half the time x.5 gets rounded up, half the time it gets rounded down - so 1.5 gets rounded to 2, and 2.5 also gets rounded to 2 (more on this on Wikipedia which points out this is sometimes known as "bankers' rounding")).

A Locale object represents a specific geographical, political, or cultural region.

(From the javadocs for java.util.Locale)

So no.  There is no local association for rounding. Not everyone in a given locale always rounds the same way. It depends on the application - not the geographical, political or cultural grouping.

Title: Round amounts internationalized

Body:
Rounding amounts in Germany we must use Math.round instead of Math.floor.

The rule is called "Kaufmännisches Runden"

Is there any rounding-function for amounts who accepts the Locale in Java?

This is not improbably since toUpperCase respects the Locale too.


答:
In some languages (F# for instance) this entire comment/documentation can actually be expressed in the method signature. This is because in F#, null is generally not an allowed value unless specifically allowed.

What is common in F# (and also several other functional languages) is that instead of null you use an option type Option<T> which could either be None or Some(T). The language would then understand this and force you to (or warn you if you don't) match on both cases when you try to use it.

So for example in F# you could have a signature that looks like this

```<code>val GetProductById: int -> Option<Product>
</code>```

And then this would be a function that takes one parameter (an int) and then either returns a product, or the value None.

And then you could use it like this

```<code>let product = GetProduct 42
match product with
| None -> printfn "No product found!"
| Some p -> DoThingWithProduct p
</code>```

And you would get compiler warnings if you do  not match both possible cases. So there's no possible way to get null reference exceptions there (unless you ignore the compiler warnings of course), and you know everything you need just by looking at the function signature.

Of course, this requires that your language is designed in this way - which many common languages such as C#, Java, C++ etc are not. So this may not be helpful to you in your current situation. But it's (hopefully) nice to know that there are languages out there that lets you express this kind of information in a statically typed way without resorting to comments etc. :)

Body:
In some languages (F# for instance) this entire comment/documentation can actually be expressed in the method signature. This is because in F#, null is generally not an allowed value unless specifically allowed.

What is common in F# (and also several other functional languages) is that instead of null you use an option type Option<T> which could either be None or Some(T). The language would then understand this and force you to (or warn you if you don't) match on both cases when you try to use it.

So for example in F# you could have a signature that looks like this

val GetProductById: int -> Option<Product>

And then this would be a function that takes one parameter (an int) and then either returns a product, or the value None.

And then you could use it like this

let product = GetProduct 42
match product with
| None -> printfn "No product found!"
| Some p -> DoThingWithProduct p

And you would get compiler warnings if you do  not match both possible cases. So there's no possible way to get null reference exceptions there (unless you ignore the compiler warnings of course), and you know everything you need just by looking at the function signature.

Of course, this requires that your language is designed in this way - which many common languages such as C#, Java, C++ etc are not. So this may not be helpful to you in your current situation. But it's (hopefully) nice to know that there are languages out there that lets you express this kind of information in a statically typed way without resorting to comments etc. :)


问:
In Java, why does (unsorted) Set implement Iterable, but SortedMap does not?
There are two aspects to this question that I felt were too closely related to ask as separate questions.

Why doesn't SortedMap implement Iterable<Map.Entry<K,V>>?

If you need to perform an action on every key-value pair in a map, iterating over the entrySet() seems like the way to go.  So why not provide a direct iterator() method on SortedMap?  Unless you are worried about iteration order being inconsistent in a HashMap.  Which leads me to:

Does implementing Iterable imply a stable ordering?

Iterating over an ordered collection (List, SortedMap, SortedSet) is a great way to reliably implement equals() (see Note 1) and do other things that have to produce the same result every time.  Iterating over an unsorted set or map could yield different ordering if you call it multiple times, so is unsuitable for these purposes.  Especially if you are comparing HashSets or HashMaps - two of them could contain the same objects, but the order of their iterators would be different.

I guess there are 2 aspects to those questions:

What are the historical reasons for these design decisions?

If doing it again today, are there correct answers to these questions?  Maybe OrderedIterable should extend Iterable to guarantee order?

Notes:

I had originally suggested that you needed a reliable ordering to implement hashCode(), but if you sum all the hashcodes, it turns out that you don't need a reliable ordering if your hashing algorithm is commutative.  Addition is commonly used for hashCodes and it is commutative: a + b = b + a and B. even with overflow, addition is still commutative so that a + Integer.MAX_VALUE = Integer.MAX_VALUE + a.  You do still need a reliable ordering to implement equals() so that you can compare the first item of one to the first item of the other, etc.

P.S.

This question is about the interfaces Iterable, Set, SortedSet, Map, and SortedMap.  It's fine to bring up other interfaces as examples, but
I do not think the Collection interface is relevant to this question.  It's quirky and has the potential to be a distraction.

答:
Although it is correct from a narrowly technical point of view to say that Set implements Iterable, but SortedMap does not, it is not a very useful question to ask.  A more useful question to ask is whether both classes offer the Iterable interface, and they certainly both do.

As you know, there are three ways to offer an interface:

By explicitly implementing it using the implements keyword.

By implementing an interface which extends the interface in question.

By exposing a function which returns the interface in question.

Set is declared as follows: public interface Set<E> extends Collection<E> {... so, as you can see, Set does not directly implement Iterable, it only implements it indirectly, by virtue of implementing Collection, which extends Iterable.

Now, SortedMap would also be implementing Iterable indirectly, just as Set does, if it was implementing Collection, but it does not even do that.  Instead, it exposes an entrySet() function, which returns a Collection, which extends Iterable.

So, you can have your much desired Iterable in both cases.

If you would like to insist on the narrowly technical question of why Set (indirectly) implements Iterable, but SortedMap offers it via a function instead, the answer is that the designers of the java language runtime made the decision a long time ago to refrain from making extensive use of  interfaces extending other interfaces. That's why Map<K,V> does not extend Collection<Map.Entry<K,V>>, offering an entrySet() method instead.

They could have done the opposite, and as a matter of fact the designers of the C# language runtime did choose to go the other way, so IDictionary<K,V> extends ICollection<KeyValuePair<K,V>>.

I have experimented with both ways, and I still have not arrived at a conclusive decision as to which one is better.  They simply appear to be two different ways of accomplishing the same thing.

The implementation of Iterator does not imply a stable ordering, as you seem to understand (and therefore it is not clear to me where your question is in that respect.)  You may iterate over an unsorted map, in which case nobody can tell what the order of the items will be, and you may insert an element to the map and re-iterate, in which case the order of the items may be completely different from the previous time.  (Not just different by one item: all items may appear to be re-arranged.)

There is no need for an OrderedIterable interface because its signature would be identical to Iterable.  (And don't get me started on the choice of the java people to introduce a Set besides Collection.)  You can just invoke OrderedMap.entrySet(), which the documentation promises will return an ordered set, which means that the Iterator of that set will always yield items in order.


答:
Try to fix a bug

Best possible way to get to know the code! :)


答:
Dynamic program slicing is a possible way, though not necessarly practical with 100k lines of codes.

For example, if your original code is:

```<code>if (recipe.has_option_x) {
   foo();
} else {
   bar();
}
</code>```

And you slice your program assuming that recipe.has_option_x is false, you can reduce the size of the code being effectively called to bar(). As usual, theoritical limits will prevent a tool to always know with certainty whether a branch of your program can be safely removed.

The wikipedia page has some links to existing tools. See also Dynamic slicing in C/C++.

Title: How to extract the active code path from a complex algorithm

Body:
I have been puzzled lately by an intruiging idea.

I wonder if there is a (known) method to extract the executed source code from a large complex algorithm. I will try to elaborate this question:

Scenario: There is this complex algorithm where a large amount of people have worked on for many years. The algorithm creates measurement descriptions for a complex measurement device.

The input for the algorithm is a large set of input parameters, lets call this the recipe. Based on this recipe, the algorithm is executed, and the recipe determines which functions, loops and if-then-else constructions are followed within the algorithm. When the algorithm is finished, a set of calculated measurement parameters will form the output. And with these output measurement parameters the device can perform it's measurement.

Now, there is a problem. Since the algorithm has become so complex and large over time, it is very very difficult to find your way in the algorithm when you want to add new functionality for the recipes. Basically a person wants to modify only the functions and code blocks that are affected by its recipe, but he/she has to dig in the whole algorithm and analyze the code to see which code is relevant for his or her recipe, and only after that process new functionality can be added in the right place. Even for simple additions, people tend to get lost in the huge amount of complex code.

Solution: Extract the active code path? I have been brainstorming on this problem, and I think it would be great if there was a way to process the algorithm with the input parameters (the recipe), and to only extract the active functions and codeblocks into a new set of source files or code structure. I'm actually talking about extracting real source code here.

When the active code is extracted and isolated, this will result in a subset of source code that is only a fraction of the original source code structure, and it will be much easier for the person to analyze the code, understand the code, and make his or her modifications. Eventually the changes could be merged back to the original source code of the algorithm, or maybe the modified extracted source code can also be executed on it's own, as if it is a 'lite' version of the original algorithm.

Extra information: We are talking about an algorithm with C and C++ code, about 200 files, and maybe 100K lines of code. The code is compiled and build with a custom Visual Studio based build environment.

So...: I really don't know if this idea is just naive and stupid, or if it is feasible with the right amount of software engineering. I can imagine that there have been more similar situations in the world of software engineering, but I just don't know.

I have quite some experience with software engineering, but definitely not on the level of designing large and complex systems.

I would appreciate any kind of answer, suggestion or comment.

Thanks in advance!

Body:
Dynamic program slicing is a possible way, though not necessarly practical with 100k lines of codes.

For example, if your original code is:

if (recipe.has_option_x) {
   foo();
} else {
   bar();
}

And you slice your program assuming that recipe.has_option_x is false, you can reduce the size of the code being effectively called to bar(). As usual, theoritical limits will prevent a tool to always know with certainty whether a branch of your program can be safely removed.

The wikipedia page has some links to existing tools. See also Dynamic slicing in C/C++.


问:
How can I setup custom license for my github repository?
During creation of new Github repository I could choose license under which my project will be hosted on Github. I didn't do that because Github suggested only few licenses to choose (and WTFPL wasn't on the list). However, after repository was created I cannot find any option to indicate either WTFPL license or any other.

Is it possible to setup license for my repo after it was created on GitHub?

答:
Absolutely. Create a new file called LICENSE and put your terms in there. For quick adding of the license you can use addalicense.com or manually push the file to GitHub using various tools. (or quickly via the GUI)

License file names are normally; LICENSE, LICENSE.txt, LICENSE.md


问:
Accidentally including unrelated changes in commits
My personal approach to a git commit is that every commit should include a unit of change, in its completness.

When I develop, I usually focus on such units. But sometimes, my attention strays someplace else and I work for a while on a different unit. This is probably not optimal, but I have learned to commit carefully (git add --interactive is a good friend of mine).

However, it could happen that I forget to selectively stage my changes and instead commit the whole file, believing that all the changes I see in the diff are indeed related to the same unit, even though there might be a change or two completely unrelated.

Then I git push.

Is this dangerous? Should I make effort to amend the commit so that it only includes the intended changes? My primary concern is that whoever else looks at the history will see the change and will probably scratch their heads for several minutes before realising it is most likely a mistake. Worse still, I can imagine that the change will even look related and the programmer might not recognise the error.

The problem is, since I have already pushed, I cannot safely rewrite the server's history, so I would probably have to first revert the commit, split it properly and commit again. Alternatively, I could just amend the commit with a better commit message, but I would have to be really really fast since it also requires rewriting history. As a last resort, I might simply commit the unit I was working on as next, leaving a note that there is a related change in previous commit (but this feels wrong).

I understand that in a multi-developer setups with proper code-review workflow this would likely not happen. I also understand that if I am the sole developer on a project, then rewriting history is the best solution for this.

答:
Commit history is vitally important, but for 3 reasons:

merging to somewhere else. You need to pick the pieces out of a branch and stick them elsewhere, its important to have all the pieces you want in there and nothing you don't want. So if your 'messy' commit contains changes intended for the feature you're working on (and not, say an accidental commit of something else) then you're good.

Auditing what happened sometime afterwards - usually to determine when a particular bug or feature was introduced. In this case, it doesn't matter what is in the commits as long as you can pinpoint the change you're interested in.

Code review. Good peer reviews are committed and then reviewed (don't hold up the dev/commit process by waiting for a reviewer!) and in these cases the reviewer will want to understand what changes were made. However, generally a reviewer will be more interested in the overall changes - trying to review commits that were made, reverted, re-made is an exercise in time-wasting compared to reviewing all 3 commits at once.

So, although unit-of-work commits sound ideal, they're not anything to be insisting on in practical terms. I would attempt to keep commits sensible, and unit-of-work is a good way to keep commits sane, but don't bother trying to fiddle with the commit history just to keep the commits tidy. That's like updating a code file to make all the brackets line up the way you prefer - nice, but useless.

Now, if you have committed a bit of work intended for a different branch, revert it and commit it properly to the right branch. That's important, but if you've updated a bit of server code when you've been working on the GUI.. there's no need to worry about it.


问:
Why doesn't Java 8 include immutable collections?
The Java team has done a ton of great work removing barriers to functional programming in Java 8.  In particular, the changes to the java.util Collections do a great job of chaining transformations into very fast streamed operations.  Considering how good a job they have done adding first class functions and functional methods on collections, why have they completely failed to provide immutable collections or even immutable collection interfaces?

Without changing any existing code, the Java team could at any time add immutable interfaces that are the same as the mutable ones, minus the setter methods and make the existing interfaces extend from them, like this:

```<code>                  ImmutableIterable
     ____________/       |
    /                    |
Iterable        ImmutableCollection
   |    _______/    /          \   \___________
   |   /           /            \              \
 Collection  ImmutableList  ImmutableSet  ImmutableMap  ...
    \  \  \_________|______________|__________   |
     \  \___________|____________  |          \  |
      \___________  |            \ |           \ |
                  List            Set           Map ...
</code>```

Sure, operations like List.add() and Map.put() currently return a boolean or previous value for the given key to indicate whether the operation succeeded or failed.  Immutable collections would have to treat such methods as factories and return a new collection containing the added element - which is incompatible with the current signature.  But that could be worked-around by using a different method name like ImmutableList.append() or .addAt() and ImmutableMap.putEntry().  The resulting verbosity would be more than outweighed by the benefits of working with immutable collections, and the type system would prevent errors of calling the wrong method.  Over time, the old methods could be deprecated.

Wins of immutable collections:

Simplicity — reasoning about code is simpler when the underlying data does not change.

Documentation — if a method takes an immutable collection interface, you know it isn't going to modify that collection.  If a method returns an immutable collection, you know you can't modify it.

Concurrency — immutable collections can be shared safely across threads.

As someone who has tasted languages which assume immutability, it is very hard to go back to the Wild West of rampant mutation.  Clojure's collections (sequence abstraction) already have everything that Java 8 collections provide, plus immutability (though maybe using extra memory and time due to synchronized linked-lists instead of streams).  Scala has both mutable and immutable collections with a full set of operations, and though those operations are eager, calling .iterator gives a lazy view (and there are other ways of lazily evaluating them).  I don't see how Java can continue to compete without immutable collections.

Can someone point me to the history or discussion about this? Surely it's public somewhere.

答:
This is a very good question. I enjoy entertaining the idea that of all the code written in java and running on millions of computers all over the world, every day, around the clock, about half the total clock cycles must be wasted doing nothing but making safety copies of collections returned by functions, which are garbage-collected milliseconds later.

A percentage of java programmers are aware of the existence of the unmodifiableCollection() family of methods of the Collections class, but most don't bother with it, and I can't blame them: an interface which pretends to be read-write but will slap you in the face with an UnsupportedOperationException if you make the mistake of invoking any of its 'write' methods is quite an evil thing to have!

Now, an interface like Collection which would be missing the add(), remove() and clear() methods would not be an "ImmutableCollection" interface; it would be an "UnmodifiableCollection" interface. As a matter of fact, there could never be an "ImmutableCollection" interface, because immutability is a nature of an implementation, not a characteristic of an interface. I know, that's not very clear; let me explain.

Suppose someone hands you such a read-only collection interface; is it safe to pass it to another thread? If you knew for sure that it represents a truly immutable collection, then the answer would be "yes"; unfortunately, since it is an interface, you do not know how it is implemented, so the answer has to be a no: for all you know, it may be an unmodifiable (to you) view of a collection which is in fact mutable, (like what you get with Collections.unmodifiableCollection(),) so attempting to read from it while another thread is modifying it would result in reading corrupt data.

So, what you have essentially described is a set of not "Immutable", but "Unmodifiable" collection interfaces. It is important to understand that "Unmodifiable" simply means that whoever has a reference to such an interface is prevented from modifying the underlying collection not because the underlying collection is necessarily immutable, but simply because the interface lacks any modification methods.

Now, I happened to be present at Devoxx Belgium 2017 where several people from Oracle gave talks, and one of them was Brian Goetz. I went to him after his talk and asked him precisely this: why are there no unmodifiable interfaces in Java? I must say that the answer he gave me was not particularly convincing: he said that they are not doing it due to a security concern: if you have a mutable collection class implementing a mutable collection interface which extends an unmodifiable collection interface, and you hand out the unmodifiable interface, whoever holds that interface can up-cast it to the mutable interface and modify the original collection.

This is not convincing because it describes a very simplistic scenario which can very easily be taken care of with some simple extra measures: If you have a security concern you can instantiate and hand-out an unmodifiable collection adaptor which wraps (delegates to) your mutable collection without implementing the mutable collection interface. As a matter of fact, you are already doing this structurally when you use the unmodifiableCollecton() family of methods, the only problem is that the interface you are handing out is secretly unmodifiable, meaning that it obtusely exposes mutation methods, but invoke any of them and you die. Thus, unmodifiable interfaces could eliminate this existing obtuseness while keeping everything else structurally the same if need be.

But of course, things would not have to be kept the same. The next step would be to add immutable collection classes, which implement the unmodifiable collection interfaces. When there is a need to guarantee immutability, (such as the case is, for example, when passing a collection from one thread to another,) such collections would be passed around as immutable classes, not as unmodifiable interfaces, so that the receiver knows for sure that what they have in their hands is immutable.

So, in order to have a complete set of collections in java, (or any other declarative imperative language,) we would need the following:

A set of unmodifiable collection interfaces.

A set of mutable collection interfaces, extending the unmodifiable ones.

A set of mutable collection classes implementing the mutable interfaces, and by extension also the unmodifiable interfaces.

A set of immutable collection classes, implementing the unmodifiable interfaces, but mostly passed around as classes, so as to guarantee immutability.

I have implemented all of the above for fun, and I am using them in projects, and they work like a charm.

The reason why they are not part of the java runtime is probably because it was thought that this would be too much / too complex / too difficult to understand.

Personally, I think that what I described above is not even enough; one more thing that appears to be needed is a set of mutable interfaces & classes for structural immutability. (Which may simply be called "Rigid" because the prefix "StructurallyImmutable" is too damn long.)

ContentLicense: CC BY-SA 4.0