问:
Line intersection detection algorithm
I'm trying to detect if a line drawn by the user intersects itself. I'm using a line intersection detection algorithm that goes through each waypoint of the line and checks if intersects with any other point in the line.

This is a costly method and has started to produce performance problems. What would be the recommended algorithm for this problem? Is there a code example of it?

The line is represented with wayPoints which are coordinates that have been gathered by users movement on screen.

Thanks a lot for just reading this far! All help Appreciated!

```<code>    for i in 1 ..<(wayPoints.count-1) {
            for j in 0 ..< i-1 {
                   if let intersection = intersectionBetweenSegments(wayPoints[i], wayPoints[i+1], wayPoints[j], wayPoints[j+1]){
  ...}
   }
  }

    func intersectionBetweenSegments(p0: CGPoint, _ p1: CGPoint, _ p2: CGPoint, _ p3: CGPoint) -> CGPoint? {
        var denominator = (p3.y - p2.y) * (p1.x - p0.x) - (p3.x - p2.x) * (p1.y - p0.y)
        var ua = (p3.x - p2.x) * (p0.y - p2.y) - (p3.y - p2.y) * (p0.x - p2.x)
        var ub = (p1.x - p0.x) * (p0.y - p2.y) - (p1.y - p0.y) * (p0.x - p2.x)
        if (denominator < 0) {
            ua = -ua; ub = -ub; denominator = -denominator
        }

        if ua >= 0.0 && ua <= denominator && ub >= 0.0 && ub <= denominator && denominator != 0 {
            return CGPoint(x: p0.x + ua / denominator * (p1.x - p0.x), y: p0.y + ua / denominator * (p1.y - p0.y))
        }

        return nil
    }
</code>```

答:
This is a costly method and has started to produce performance problems. What would be the recommended algorithm for this problem? Is there a code example of it?

It depends very much on how you represent the line itself. It seems that you use a broken line, that is a juxtaposition of straight lines.

The first idea that jumps to my mind is to do a simple region check. You can pack each line in a small rectangle (its bounding box) and it is very easy to check if two bounding boxes overlap or not – you can do this by doing a few subtractions, which is much cheaper than computing a determinant!  If the region check fails, then the lines certainly do not intersect so you do not need to compute the determinant.

With this you should jump from complexity (nˆ4) to (nˆ2) where n is the number of tiny straight lines in your line.

If this is not enough, a second common technique is to divide the canvas in regions and represent this region as a binary tree. You start with the full canvas, then cut in halves, and then subdivide each half in two, again and again, until you reach a number of splitting you choose in advance. (You can do empirical tests to determine a value suitable for your data.)  Then you can attach each line segment to a region where its bounding box fits – Typically a leaf, but it can be a higher level node if a line segment cuts a region border.  Once you packed each line segment in the region tree, it is easy to retrieve neighbours of a segment line, where the intersection can take place.

Title: Line intersection detection algorithm


问:
how does test-driven development prevent us from type errors?
I heard (from Robert C. Martin) an assertion that since dynamic languages don't have static typechecking, people should write unit tests to prevent us from type errors.

I'm not sure if I'm following the thinking here. Could anyone exaplain HOW? Could you give me one concrete example?

答:
Unit tests don't actively prevent type errors, but they do provide you a mechanism to execute the code you have written before the entire application is complete.

If you try to do something silly, like mistyping calculateInterest as claculateinterest, then that will be caught early on if you use a statically typed, compiled language like Java because the compiler will complain loudly.

If you do the same in a dynamically typed language, the error will not be noticed until that line of code actually gets executed.

If you don't write unit tests, then it can be weeks before the application is finished far enough that your feature can be executed and tested in the complete application. That is a very long turn-around time for finding such silly mistakes.

On the other hand, if you do write unit tests, then it is mere minutes between writing a module and executing it. This has the huge advantage that the code is still fresh in your mind and that you are not yet fully occupied with writing other modules.

ContentLicense: CC BY-SA 3.0


问:
Good, simple reasons for having multiple environments
Throughout my career I had worked at companies that had a collection of different environments for different purposes. We always had more or less our desktop environment, a test environment, a QA environment, a staging environment and a production environment. This went for both servers/applications and any data sources we were using.

When I started at my current company I found that 90% of the apps were either developed on a desktop environment against production data sources or developed directly on the production server depending on the platform. This wasn't particularly surprising, as I was hired in part to make changes to improve the way the development team functioned, which was clear from my interview process. We slowly started to turn the philosophy and pretty soon, most of the apps could be run in either a desktop, test or production environment. Not too long after that staging came around as well.

Now most of our developers see the benefit of this methodology and defend it vigilantly. However, we have a number of legacy apps that never got migrated. We also have a number of legacy programmers who think of this as a waste of time. Unfortunately, we got lip service but never full buy-in from management. We got what we thought was a commitment to invest substantially in this about a year ago, but nothing materialized despite the considerable planning that we put into it. Now we are finding that we need more and more environments. We need help from the server/network administration teams for setup and we need participation from the business stakeholders to support the release cycle. We are at a place now where a project can function what reasonable developers would consider "normally" only if you have the right people on the project and the time to set up the proper environments.

I'd love to present a complete argument, but management really has no time and interest in hearing me out until there is a critical issue. I can't really articulate the benefits simply as it always just seemed second nature to me. I was wondering if there are any good, simple, irrefutable reasons for the separation of environments that would get managers lacking development experience to support this idea?. Are there any good resources/literature on the topic?

答:
Forget time, money, testability, quality...how about reputation.

good, simple, irrefutable reasons for the separation of environments
  that would get managers lacking development experience to support this
  idea.

Uber recently shipped code to github that contained passwords for their live environment, allowing 'hackers' to download all their customer details. Uber says it was a breach, everyone else says"don't put the keys to your locks in public view. If their developers worked entirely on a dev environment, they might have released the keys to their dev environment on github, but that's entirely harmless. That the production ones were released shows how poor this idea of performing dev on the production environment is.

Just remind your manager that mistakes happen, so the way to avoid him being hauled before the CEO who is about to get a grilling in front of journalists and laughed at by the tech public is to take simple, obvious steps to prevent those mistakes being catastrophic ones.


答:
A good example for this comes from code I have seen recently:

```<code>if foo
    bar == baz
    # should be bar = baz
</code>```

In python expressions like this work totally fine but they don't do what you intended.

Another typo in the same code:

```<code>class foo:
    ...
    def bar(self):
        ...

def foo_bar:
    ...

...

foo.bar()
# They meant to use foo_bar()
</code>```

Sure this is caused by bad naming but the bug could have been spottet using tests. Simple tests could have uncovered that the if statement simply does nothing.

Title: how does test-driven development prevent us from type errors?

Body:
I heard (from Robert C. Martin) an assertion that since dynamic languages don't have static typechecking, people should write unit tests to prevent us from type errors.

I'm not sure if I'm following the thinking here. Could anyone exaplain HOW? Could you give me one concrete example?

Body:
A good example for this comes from code I have seen recently:

if foo
    bar == baz
    # should be bar = baz

In python expressions like this work totally fine but they don't do what you intended.

Another typo in the same code:

class foo:
    ...
    def bar(self):
        ...

def foo_bar:
    ...

...

foo.bar()
# They meant to use foo_bar()

Sure this is caused by bad naming but the bug could have been spottet using tests. Simple tests could have uncovered that the if statement simply does nothing.


问:
Code formatting: is it worth to make bad code to look bad?
In Code Complete 2nd Edition, Steve McConnell wrote the following (page 732):

Techniques that make good code look good
  and bad code look bad are more useful
  than techniques that make all code look good.

I have an argue about that and Eclipse code format rules with a colleague. He said that badly looking code makes refactoring and cleaning up bad code harder, since he needs more effort to understand the code. On the other hand I've found that code that looks bad is similar to a "be careful" warning. I reminds me that I have to think it through twice before modifying anything to make sure I won't broke anything. Furthermore, it probably forces developers to restructure their code to be a little bit more beautiful and better structured.

Another thing is @SuppressFBWarnings annotations for false positive FindBugs warnings which also makes the code harder to maintain since these annotations look bad, break the structure of code and they're hard to read. On the other hand I think these also save time. When a developer finds some code that smells and FindBugs has already found it the developer probably has a reason why it's OK (or why somebody thought it's OK) in the justification element of the annotation.

Are there other reasons why is it worth or not to make bad code to look bad or it is rather a psychology question and both formatting are acceptable?

答:
The quote from the same page, same paragraph, a few sentences before:

Making the code look pretty is worth something, but it's worth less than showing the code's structure. If one technique shows the structure better and another looks better, use the one that shows the structure better. [...] In practice, prioritizing logical representation usually doesn't create ugly code—unless the logic of the code is ugly.

The point is not that you should format bad code badly intentionally. The point is that in good code, you can easily see the structure, while in bad code, finding any structure (if there is any) is painful.

In this context, formatting is completely superfluous. You may spend hours improving naming conventions or adding line breaks, but bad code will still remain bad, because—once again—of the lack of structure.

In essence, this is the difference between pretty and readable. Style makes code pretty, but this doesn't mean that it becomes immediately readable. Only (relatively important and painful) refactoring can cope with that. On the other hand, readable code can be perceived as ugly because of the lack of style, but a basic tool can walk through it and reformat it in a matter of milliseconds.


答:
Not only bad formatting makes it harder to improve the code, but also, bad (or, more likely, unfamiliar) formatting may make code look as if it is logically worse than it really is.

I once caught myself troubleshooting something which I was almost sure it was a bug, only to find out that there was no bug after all, and I realized that I got the impression that there was a bug because the bad formatting of the code tempted me to believe that it was doing something wrong.

So, for the most part, no, I do not think it is a good idea to intentionally go out of your way to either make bad code look bad, or leave bad looking code looking bad.

I would be willing to make an exception in certain cases where ugly identifiers are chosen to correctly represent the ugliness of what the code does.  For example, time and again I see programmers write void-returning functions called 'checkSomething()' as if they were the most natural innocent little things in the world. Of course, these functions work entirely by side effect, so they are quite evil.  I would rename this function to 'checkSomethingAndDoThisIfSuchOrThatOtherwise()' in order to clearly indicate that this is an evil function which possibly does evil things.

Title: Code formatting: is it worth to make bad code to look bad?

Body:
In Code Complete 2nd Edition, Steve McConnell wrote the following (page 732):

Techniques that make good code look good
  and bad code look bad are more useful
  than techniques that make all code look good.

I have an argue about that and Eclipse code format rules with a colleague. He said that badly looking code makes refactoring and cleaning up bad code harder, since he needs more effort to understand the code. On the other hand I've found that code that looks bad is similar to a "be careful" warning. I reminds me that I have to think it through twice before modifying anything to make sure I won't broke anything. Furthermore, it probably forces developers to restructure their code to be a little bit more beautiful and better structured.

Another thing is @SuppressFBWarnings annotations for false positive FindBugs warnings which also makes the code harder to maintain since these annotations look bad, break the structure of code and they're hard to read. On the other hand I think these also save time. When a developer finds some code that smells and FindBugs has already found it the developer probably has a reason why it's OK (or why somebody thought it's OK) in the justification element of the annotation.

Are there other reasons why is it worth or not to make bad code to look bad or it is rather a psychology question and both formatting are acceptable?


答:
I will refer you to this question, for which properly indenting the code instantly revealed the source of the bug.  I will also refer you to the Linux kernel coding style, which explicitly uses 8-space tabs as a way of highlighting excessive nesting.

These sorts of coding standards aren't intended to place a permanent caution tape around bad areas of your code.  They are intended to give you a visual kick in the head so that badly-structured code never gets submitted in the first place.  They make certain kinds of code intentionally more difficult to read, not as some sort of punishment or permanent warning, but so you will fix it.  If you have to temporarily turn off the formatting in order to fix it, so be it, but that's no excuse to leave it disabled forever.

There are two ways to write code: write code so simple there are
  obviously no bugs in it, or write code so complex that there are no
  obvious bugs in it.
—Tony Hoare

Formatting code is one easy way of making certain kinds of bugs obvious, so they can be removed.  It doesn't help with all kinds of bugs, but any easy step you can take in that direction is a good one.


问:
If Else - Repeated Code Logic
My boss gave me a project with a particular logic. I have to develop a web page which has to lead the navigator through many cases until he/she arrives at the product.

This is the path scheme of the navigation in the site:

IMPORTANT!

In the Products page the navigator can choose which filter he wants.

If A, he/she MUST go through the B (and then C of course) or C and reach the products.

If B, he/she MUST go through the C and reach the products.

If C, he/she reaches directly the products.

Of course if I start from A I am following the longest path and when I reach my products I have 3 active filters.

Until now I developed the following code which works fine.

```<code>if filter_A
  if filter_B
     filter_C()
     .. else ..
  else
     filter_C
    .. else ..
else
   if filter_B
      filter_C()
     .. else ..
   else
     filter_C()
     .. else ..
</code>```

I'm here to ask what would a more expert programmer have done in this situation. I didn't respect the DRY principle, I don't like it and I'd like to know an alternative way to develop this kind of logic.

I thought about splitting every section of code in functions but is it a good idea in this case?

答:
I'm going to assume filterA, filterB, and filterC actually modify the list of products. Otherwise, if they are just if-checks, then filterA and filterB can be ignored since all paths lead ultimately to filterC. Your description of the requirement seems to imply that each filter will reduce product list.

So assuming the filters actually reduce the list of products, here's bit of pseudo-code...

```<code>class filter
    func check(item) returns boolean
endclass

func applyFilter(filter, productList) returns list
    newList is list
    foreach item in productList
        if filter.check(item) then
            add item to newList
        endif
    endfor
    return newList
endfunc

filterA, filterB, filterC = subclasses of filter for each condition, chosen by the user
products = list of items to be filtered

if filterA then
    products = applyFilter(filterA, products)
endif

if filterB then
    products = applyFilter(filterB, products)
endif

if filterC then
    products = applyFilter(filterC, products)
endif

# use products...
</code>```

In your requirements, filterC is not automatically applied, but in the diagram, it is. If the requirement is that at least filterC should be applied no matter what, then you would call applyFilter(filterC, products) without checking if filterC is chosen.

```<code>filterC = instance of filter, always chosen

...

# if filterC then
products = applyFilter(filterC, products)
# endif
</code>```

Title: If Else - Repeated Code Logic

Body:
I'm going to assume filterA, filterB, and filterC actually modify the list of products. Otherwise, if they are just if-checks, then filterA and filterB can be ignored since all paths lead ultimately to filterC. Your description of the requirement seems to imply that each filter will reduce product list.

So assuming the filters actually reduce the list of products, here's bit of pseudo-code...

class filter
    func check(item) returns boolean
endclass

func applyFilter(filter, productList) returns list
    newList is list
    foreach item in productList
        if filter.check(item) then
            add item to newList
        endif
    endfor
    return newList
endfunc

filterA, filterB, filterC = subclasses of filter for each condition, chosen by the user
products = list of items to be filtered

if filterA then
    products = applyFilter(filterA, products)
endif

if filterB then
    products = applyFilter(filterB, products)
endif

if filterC then
    products = applyFilter(filterC, products)
endif

# use products...

In your requirements, filterC is not automatically applied, but in the diagram, it is. If the requirement is that at least filterC should be applied no matter what, then you would call applyFilter(filterC, products) without checking if filterC is chosen.

filterC = instance of filter, always chosen

...

# if filterC then
products = applyFilter(filterC, products)
# endif


问:
Black box or white box testing - which do you do first?
On a very small team, where the black box and white box testing is done by the same person, which should the tester do first?</p>

答:
Black

Black-box testing to verify the features. White-box testing as necessary if things are broken. If all the black-box tests pass and the coverage is good, white-box testing is unnecessary.

ContentLicense: CC BY-SA 2.5


答:
In this case, it is important to separate the logic of filtering, and the control flow of how the filters run.  The filter logic should be separated out into individual functions, that can run independent of each other.

```<code>ApplyFilterA();
ApplyFilterB();
ApplyFilterC();
</code>```

In the sample code posted, there's 3 booleans filter_A, filter_B, and filter_C.  However, from the diagram, filter_C always runs, so that can be changed to an unconditional.

NOTE: I am assuming that the control flow diagram is correct.  There is a discrepancy between the posted sample code and the control flow diagram.

A separate piece of code controls which filters get run

```<code>ApplyFilters(bool filter_A, bool filter_B)
{
    listOfProducts tmp;
    if (filter_A)
        ApplyFilterA();
    if (filter_B)
        ApplyFilterB();
    ApplyFilterC();
}
</code>```

There is a distinct separation between controlling which filters run, and what the filters do.  Break those two pieces of logic apart.

Title: If Else - Repeated Code Logic

Body:
My boss gave me a project with a particular logic. I have to develop a web page which has to lead the navigator through many cases until he/she arrives at the product.

This is the path scheme of the navigation in the site:

IMPORTANT!

In the Products page the navigator can choose which filter he wants.

If A, he/she MUST go through the B (and then C of course) or C and reach the products.

If B, he/she MUST go through the C and reach the products.

If C, he/she reaches directly the products.

Of course if I start from A I am following the longest path and when I reach my products I have 3 active filters.

Until now I developed the following code which works fine.

```<code>if filter_A
  if filter_B
     filter_C()
     .. else ..
  else
     filter_C
    .. else ..
else
   if filter_B
      filter_C()
     .. else ..
   else
     filter_C()
     .. else ..
</code>```

I'm here to ask what would a more expert programmer have done in this situation. I didn't respect the DRY principle, I don't like it and I'd like to know an alternative way to develop this kind of logic.

I thought about splitting every section of code in functions but is it a good idea in this case?

Body:
In this case, it is important to separate the logic of filtering, and the control flow of how the filters run.  The filter logic should be separated out into individual functions, that can run independent of each other.

ApplyFilterA();
ApplyFilterB();
ApplyFilterC();

In the sample code posted, there's 3 booleans filter_A, filter_B, and filter_C.  However, from the diagram, filter_C always runs, so that can be changed to an unconditional.

NOTE: I am assuming that the control flow diagram is correct.  There is a discrepancy between the posted sample code and the control flow diagram.

A separate piece of code controls which filters get run

ApplyFilters(bool filter_A, bool filter_B)
{
    listOfProducts tmp;
    if (filter_A)
        ApplyFilterA();
    if (filter_B)
        ApplyFilterB();
    ApplyFilterC();
}

There is a distinct separation between controlling which filters run, and what the filters do.  Break those two pieces of logic apart.


答:
I wonder if modeling your filters to be some kind of objects in a graph would make sense. At least that's what I think of when seeing the diagram.

If you model the dependency of the filters like a object graph, then the code that handles the possible flow paths is pretty much straight forward without any hairy logic. Also, the graph (business logic) can change, while the code that interprets the graph stays the same.

Title: If Else - Repeated Code Logic


问:
Should the method describe its side effects?
I was reading Clean Code by Bob Martin and there's one particular code smell, related to naming, that looks interesting to me:

N7: Names Should Describe Side-Effects

  Names should describe everything that a function, variable, or class is or does.
  Don’t hide side effects with a name. Don’t use a simple verb to describe a function that does more than just that simple action. For example, consider this code from TestNG:

```<code>public ObjectOutputStream getOos() throws IOException {
    if (m_oos == null) {
        m_oos = new ObjectOutputStream(m_socket.getOutputStream());
    }
    return m_oos;
}
</code>```

This function does a bit more than get an “oos”; it creates the “oos” if it hasn’t been created already. Thus, a better name might be createOrReturnOos.

I think that the method name should say what the method does and not how it does it (since this would break encapsulation of the implementation).

So, for me, this method does one thing. It retrieves (gets) ObjectOutputStream object as its name says and renaming it to createOrReturnOos would be revealing implementation details to the caller. And as a caller I just want to get ObjectOutputStream and I don't care about how was it retrieved/created.

If the method was private, maybe I could agree that proposed name would me more benefitial, since the method would have class visibility and strong cohesion is desirable, but since method is public, that's one more reason to abstract the name of the method.

In this situations (which happen quite often), I always have two conflicting questions: should I abstract what the method does or say in details what the method does? But, again, since this is a public method I'd rather abstract what the method does.

Also, maybe Bob found a bad example of what he wanted to say.

Your thoughts?

答:
But you do care about it being created, because it can throw an IOException!

In fact, the only time it can throw is the first time it's called. Every other time you'll need to put a pointless try/catch block (assuming this is Java) in the calling code for something that will never happen.

I'd refactor this code to have an explicit stream creation method. Having I/O happen in a getter is generally not good if the I/O ever goes wrong.

(If the object creation didn't involve I/O, I'd agree with your assessment)


答:
You haven't said whether the filters take any parameters. For example, filter_A might be a category filter, so that it's not just a question of "do I need to apply filter_A", it could be "I need to apply filter_A and return all records in with the category field = fooCategory".

The simplest way to implement exactly what you've described (but make sure to read the second half of the answer below) is similar to the other answers, but I wouldn't have any boolean checks at all. I would define interfaces: FilterA, FilterB, FilterC. Then you can have something like (I'm a Java programmer, so this will be Java-esque syntax):

class RequestFilters {
    FilterA filterA;
    FilterB filterB;
    FilterC filterC;
}
```

<p>Then you could have something like this (using the enum singleton pattern from Effective Java):</p>

<pre class="lang-java prettyprint-override"><code>enum NoOpFilterA implements FilterA {
    INSTANCE;

    public List<Item> applyFilter(List<Item> input) {
       return input;
    }
}
</code>```

But if you actually want some items to be filtered, you can instead provide an instance of a FilterA implementation that actually does something. Your filtration method will be the very simple

List<Item> filterItems(List<Item> data, RequestFilters filters) {
    List<Item> returnedList = data;
    returnedList = filters.filterA.filter(data);
    returnedList = filters.filterB.filter(data);
    returnedList = filters.filterC.filter(data);
    return returnedList;
}
```

<hr>

<p><strong><em>But I'm just getting started.</em></strong></p>

<p>I suspect that the <code>applyFilter</code> call will actually be quite similar for all three types of filters. If that's the case, I wouldn't even do it the way described above. You can get even cleaner code by only having one interface, then doing this:</p>

<pre class="lang-java prettyprint-override"><code>class ChainedFilter implements Filter {
     List<Filter> filterList;

     void addFilter(Filter filter) {
          filterList.add(filter);
     }

     List<Item> applyFilter(List<Item> input) {
         List<Item> returnedList = input;
         for(Filter f : filterList) {
             returnedList = f.applyFilter(returnedList);
         }
         return returnedList;
     }
}
</code>```

Then, as your user navigates through the pages, you just add a new instance of whatever filter you need when appropriate. This will allow you to be able to apply multiple instances of the same filter with different arguments should you need that behavior in the future, and also add additional filters in the future without having to change your design.

Additionally, you can add either something like the NoOpFilter above or you can just not add a particular filter at all to the list, whatever is easier for your code.

Title: If Else - Repeated Code Logic

Body:
You haven't said whether the filters take any parameters. For example, filter_A might be a category filter, so that it's not just a question of "do I need to apply filter_A", it could be "I need to apply filter_A and return all records in with the category field = fooCategory".

The simplest way to implement exactly what you've described (but make sure to read the second half of the answer below) is similar to the other answers, but I wouldn't have any boolean checks at all. I would define interfaces: FilterA, FilterB, FilterC. Then you can have something like (I'm a Java programmer, so this will be Java-esque syntax):

class RequestFilters {
    FilterA filterA;
    FilterB filterB;
    FilterC filterC;
}

Then you could have something like this (using the enum singleton pattern from Effective Java):

enum NoOpFilterA implements FilterA {
    INSTANCE;

    public List<Item> applyFilter(List<Item> input) {
       return input;
    }
}

But if you actually want some items to be filtered, you can instead provide an instance of a FilterA implementation that actually does something. Your filtration method will be the very simple

List<Item> filterItems(List<Item> data, RequestFilters filters) {
    List<Item> returnedList = data;
    returnedList = filters.filterA.filter(data);
    returnedList = filters.filterB.filter(data);
    returnedList = filters.filterC.filter(data);
    return returnedList;
}

But I'm just getting started.

I suspect that the applyFilter call will actually be quite similar for all three types of filters. If that's the case, I wouldn't even do it the way described above. You can get even cleaner code by only having one interface, then doing this:

class ChainedFilter implements Filter {
     List<Filter> filterList;

     void addFilter(Filter filter) {
          filterList.add(filter);
     }

     List<Item> applyFilter(List<Item> input) {
         List<Item> returnedList = input;
         for(Filter f : filterList) {
             returnedList = f.applyFilter(returnedList);
         }
         return returnedList;
     }
}

Then, as your user navigates through the pages, you just add a new instance of whatever filter you need when appropriate. This will allow you to be able to apply multiple instances of the same filter with different arguments should you need that behavior in the future, and also add additional filters in the future without having to change your design.

Additionally, you can add either something like the NoOpFilter above or you can just not add a particular filter at all to the list, whatever is easier for your code.


答:
Step 1 is of course make it so your method doesn't have side effects.

But let's focus on the example. Yes, you should generally abstract what a function does from how it does it, but side effects are clearly still part of what the function is doing. By making them explicit in the name, you are making the code clearer about what is going on, leading to less bugs.

This sort of function that works with streams has special significance as well. The caller of this sort of function needs to know if the stream is new or not since that sort of thing indicates to the programmer if they need to clean up the stream or not. Managing that sort of resource ownership is a dicey scenario that leads to all sorts of nasty bugs (especially in non-memory managed languages). That makes clear communication of intentions all the more important.

Title: Should the method describe its side effects?

Body:
I was reading Clean Code by Bob Martin and there's one particular code smell, related to naming, that looks interesting to me:

N7: Names Should Describe Side-Effects

  Names should describe everything that a function, variable, or class is or does.
  Don’t hide side effects with a name. Don’t use a simple verb to describe a function that does more than just that simple action. For example, consider this code from TestNG:

```<code>public ObjectOutputStream getOos() throws IOException {
    if (m_oos == null) {
        m_oos = new ObjectOutputStream(m_socket.getOutputStream());
    }
    return m_oos;
}
</code>```

This function does a bit more than get an “oos”; it creates the “oos” if it hasn’t been created already. Thus, a better name might be createOrReturnOos.

I think that the method name should say what the method does and not how it does it (since this would break encapsulation of the implementation).

So, for me, this method does one thing. It retrieves (gets) ObjectOutputStream object as its name says and renaming it to createOrReturnOos would be revealing implementation details to the caller. And as a caller I just want to get ObjectOutputStream and I don't care about how was it retrieved/created.

If the method was private, maybe I could agree that proposed name would me more benefitial, since the method would have class visibility and strong cohesion is desirable, but since method is public, that's one more reason to abstract the name of the method.

In this situations (which happen quite often), I always have two conflicting questions: should I abstract what the method does or say in details what the method does? But, again, since this is a public method I'd rather abstract what the method does.

Also, maybe Bob found a bad example of what he wanted to say.

Your thoughts?


答:
Yes, I think method name should describe side effects.

For one thing, this example uses checked exception, which by itself reveals implementation details. Invocation of this method requires try/catch block anyway (for no reason, since it can be handled inside and throw NPE or return null, which wouldn't improve the situation, but at least make it cleaner on a caller's side), so a clearer method name wouldn't hurt.

I'd rather called it getSingletonOos, however, since it is what it actually does. getOos sounds like a plain old getter, and it is very misleading. Compare:

```<code>// Plain getter, no side effect.
public ObjectOutputStream getOos() {
    return m_oos;
}

// Additional side effects are described by the name.
public ObjectOutputStream getSingletonOos() throws IOException {
    if (m_oos == null) {
        m_oos = new ObjectOutputStream(m_socket.getOutputStream());
    }
    return m_oos;
}
</code>```

The second example does more than the first one, and it should be reflected in the name. How else would you tell the difference?

Body:
Yes, I think method name should describe side effects.

For one thing, this example uses checked exception, which by itself reveals implementation details. Invocation of this method requires try/catch block anyway (for no reason, since it can be handled inside and throw NPE or return null, which wouldn't improve the situation, but at least make it cleaner on a caller's side), so a clearer method name wouldn't hurt.

I'd rather called it getSingletonOos, however, since it is what it actually does. getOos sounds like a plain old getter, and it is very misleading. Compare:

// Plain getter, no side effect.
public ObjectOutputStream getOos() {
    return m_oos;
}

// Additional side effects are described by the name.
public ObjectOutputStream getSingletonOos() throws IOException {
    if (m_oos == null) {
        m_oos = new ObjectOutputStream(m_socket.getOutputStream());
    }
    return m_oos;
}

The second example does more than the first one, and it should be reflected in the name. How else would you tell the difference?


问:
Running an algorithm against a large dataset
We have a python application which does a DFS search against data in a database. Right now, that data is small so I can hold everything in a python container but the data is going to grow and there might come a time when it is impossible to hold everything in RAM. On the other hand, querying data from the database during every iteration is not a smart solution, is it?

But the question is more general. The solution is most probably in some smart caching but I don't have any experience in that.

What are the techniques of dealing with large data when you need to frequently (say you are running an algorithm) access it?

答:
There is an entire field called External Memory Algotihms, there are lots of textbooks about it.

An example of an external memory algorithm is External Sorting.

The relational database management system is not always the best solution in such cases. Some NoSQL (Not Only Structured Query Language) database management systems have been designed to perform better in some cases.

About In Memory Depth First Search there are different algorithms and implementations.


答:
As others have pointed out, your method does actually expose the fact that it is more than just a getter, since it publicizes the fact that it may throw an exception.  So, you might as well make it clear in the name of the method that it works either as a getter or as a factory, otherwise someone using at it is bound to frown upon the fact that an innocent-looking getter is capable of throwing an exception.

In alternative scenarios which are not complicated by publicly declared exceptions, it goes like this:

The question of whether to publicize the side effects of a method is answerable not by looking at that single method, but by taking into consideration the object as a whole.

The fact that a method has side effects should be publicized if these
  side effects are in any way, shape, or form visible through the public
  interface of the object to which the method belongs.

So, if your object manages to fully hide the fact that some of its methods internally performs side effects, then it is fine to not publicize this fact in the name of any public method.  However, if, by invoking other methods of the object, you can discover the fact that side effects took place, then those methods that cause these side effects should indicate so in their names.


问:
Class design and object references
Here is a very basic example of what I am trying to do.  In reallity there are more relations but not something extreme or memory heavy.

```<code>public class ClassA : ISomething
{
    public double property { get; set; }
    ...
    public ClassB classb { get; set; }
}

public class ClassB : ISomething2
{
    public double Length { get; set; }
    ...
}

public class MyProject : BaseProject
{
    public IEnumerable<ISomething> ISomethings { get; set; }
    ...
    public IEnumerable<ISomething2> ISomethings2 { get; set; }
    ...
}
</code>```

The issue here is that I have to keep a list of MyProject.ISomethings2 and then   classb property of ClassA to reference only an existing item in MyProject.ISomethings2  list. The hard thing here is that:

Removing an item from ISomething2 should remove all references to it (classb property of ClassA instances to be set to null)

Prevent other developers setting classb property to a non existing object in list or a new user created object.

Objects in MyProject.ISomethings2 could be added without having to be referenced from elsewhere.

These classes are used for project description not database stuff. Like when you open a project file for an application. So changing a property in classB should be visible to all since it is the same object reference.
Is there a pattern to achieve what I want without much coupling? Alternative designs/approaches are also welcome.

答:
Note: I'm assuming the language is C#. If it's Java, similar mechanisms should exist as well.

If you want to track changes to the properties of ClassA, you can use INotifyPropertyChanged.

If you want to track changes to the ISomethings2 sequence, instead of IEnumerable<T>, use ObservableCollection<T>.

If you just need to keep ISomethings2 sequence in sync with ISomethings, rewrite the property as:

public IEnumerable<ISomething2> ISomethings2
{
    get
    {
        return this.ISomethings.Select(c => c.classb);
    }
}
```

If this doesn't give you an answer, consider editing your question. Its actual form is very unclear because of the lack of proper terminology and cryptic names of your example. Also note that you currently cannot remove anything from ISomethings2, given its type.

Title: Class design and object references

Body:
Note: I'm assuming the language is C#. If it's Java, similar mechanisms should exist as well.

If you want to track changes to the properties of ClassA, you can use INotifyPropertyChanged.

If you want to track changes to the ISomethings2 sequence, instead of IEnumerable<T>, use ObservableCollection<T>.

If you just need to keep ISomethings2 sequence in sync with ISomethings, rewrite the property as:

public IEnumerable<ISomething2> ISomethings2
{
    get
    {
        return this.ISomethings.Select(c => c.classb);
    }
}

If this doesn't give you an answer, consider editing your question. Its actual form is very unclear because of the lack of proper terminology and cryptic names of your example. Also note that you currently cannot remove anything from ISomethings2, given its type.


答:
Is there a pattern to achieve what I want without much coupling?

Not really, since at its core what you want to do "when X happens, I want to do Y to these other things" is coupling by definition. Which also makes this a rather undesirable design for the problem at hand.

If I had to work with this, I'd start by looking to make the classes immutable (publically at least) and controlled by the project. If you can't set the classb property on the object, there's no way to set it to be invalid. Instead the project class can do that (along with validation rules, and possible optimizations like reference counting perhaps).

But honestly, I would try very hard to not work with this. Project here is a manager of the other objects. Forcing class instances to be in some external collection is gross and unweildly. Occasionally it's somewhat necessary (games especially do this), but it should be avoided where possible and used with care otherwise. Without knowing more about the problem you're trying to solve, I can't say for sure which bucket this falls in.

Title: Class design and object references

Body:
Here is a very basic example of what I am trying to do.  In reallity there are more relations but not something extreme or memory heavy.

```<code>public class ClassA : ISomething
{
    public double property { get; set; }
    ...
    public ClassB classb { get; set; }
}

public class ClassB : ISomething2
{
    public double Length { get; set; }
    ...
}

public class MyProject : BaseProject
{
    public IEnumerable<ISomething> ISomethings { get; set; }
    ...
    public IEnumerable<ISomething2> ISomethings2 { get; set; }
    ...
}
</code>```

The issue here is that I have to keep a list of MyProject.ISomethings2 and then   classb property of ClassA to reference only an existing item in MyProject.ISomethings2  list. The hard thing here is that:

Removing an item from ISomething2 should remove all references to it (classb property of ClassA instances to be set to null)

Prevent other developers setting classb property to a non existing object in list or a new user created object.

Objects in MyProject.ISomethings2 could be added without having to be referenced from elsewhere.

These classes are used for project description not database stuff. Like when you open a project file for an application. So changing a property in classB should be visible to all since it is the same object reference.
Is there a pattern to achieve what I want without much coupling? Alternative designs/approaches are also welcome.


问:
Mutation operator for genetic algorithms for solving traveling salesman problem
I need help help for defining mutation operator for traveling salesman problem.

I'm currently using this now (pseudocode):

```<code>mutate ( strand ):
    for n in random_interval ( min_gene_index, max_gene_index ):
        i := random_interval ( min_gene_index, max_gene_index );
        j := random_interval ( min_gene_index, max_gene_index );
        swap ( strand[i], strand[j] );
</code>```

So when swapping is executed two cities in the route is swapped.
The goal is that it needs to be fast and effective. I don't want it to be a performance hit in the main loop. Can I improve my implementation or is there any other alternative that is better?

答:
Unless you're doing some really nonstandard version of the TSP, I don't think you need a loop here. With a GA using a binary encoding of real-valued parameters, occasionally you might need a loop like

```<code>for each gene:
    for each bit in the gene:
        do something
</code>```

It's fairly rare even then, but occasionally you do want to observe parameter boundaries like that.

For TSP though, the canonical representation is just a permutation of integers representing the cities in the order they occur in the tour. If you want to make one swap (the smallest valid mutation), then you just do

```<code>def mutate(candidate):
    p1 = random_index()
    p2 = random_index()
    swap(candidate[p1], candidate[p2])
</code>```

You can try doing the swap trick with bitwise operators, but I don't imagine it would make a noticeable difference. Otherwise, this is about as efficient as you can get.

Body:
Unless you're doing some really nonstandard version of the TSP, I don't think you need a loop here. With a GA using a binary encoding of real-valued parameters, occasionally you might need a loop like

for each gene:
    for each bit in the gene:
        do something

It's fairly rare even then, but occasionally you do want to observe parameter boundaries like that.

For TSP though, the canonical representation is just a permutation of integers representing the cities in the order they occur in the tour. If you want to make one swap (the smallest valid mutation), then you just do

def mutate(candidate):
    p1 = random_index()
    p2 = random_index()
    swap(candidate[p1], candidate[p2])

You can try doing the swap trick with bitwise operators, but I don't imagine it would make a noticeable difference. Otherwise, this is about as efficient as you can get.


答:
I assume, that you want the simplest, clearest algorithm.

In this case, knowing that filter c is always applied, I would live it out of the if logic and apply it at the end regardless. As it looks in your flowchart, each filter before the c, is optional, because each of them can either be applied, or not. In this case, I would live ifs separate from each filter, without nesting and chaining:

```<code>if filter_a
  do_filter_a()

if filter_b
  do_filter_b()

do_filter_c()
</code>```

if you have a flowchart with a variable number of filters, before the mandatory one, I would, instead, save all the filters to an array, in an order that they should appear. Then process optional filters in the loop and apply the mandatory one at the end, outside of the loop:

```<code>optional_filters_array = (a, b, c, d, e, f, g, h, etc)

for current_filter in optional_filters_array
  do_filter(current_filter)

do_required_filter()
</code>```

or:

```<code>optional_filters_array = (a, b, c, d, e, f, g, h, etc)
required_filter = last_filter

for current_filter in optional_filters_array
  do_filter(current_filter)

do_filter(required_filter)
</code>```

of cource, you would have to define the filter processing subroutine.

Title: If Else - Repeated Code Logic

Body:
I assume, that you want the simplest, clearest algorithm.

In this case, knowing that filter c is always applied, I would live it out of the if logic and apply it at the end regardless. As it looks in your flowchart, each filter before the c, is optional, because each of them can either be applied, or not. In this case, I would live ifs separate from each filter, without nesting and chaining:

if filter_a
  do_filter_a()

if filter_b
  do_filter_b()

do_filter_c()

if you have a flowchart with a variable number of filters, before the mandatory one, I would, instead, save all the filters to an array, in an order that they should appear. Then process optional filters in the loop and apply the mandatory one at the end, outside of the loop:

optional_filters_array = (a, b, c, d, e, f, g, h, etc)

for current_filter in optional_filters_array
  do_filter(current_filter)

do_required_filter()

or:

optional_filters_array = (a, b, c, d, e, f, g, h, etc)
required_filter = last_filter

for current_filter in optional_filters_array
  do_filter(current_filter)

do_filter(required_filter)

of cource, you would have to define the filter processing subroutine.


问:
Object oriented Classes and single responsibility
I'm reading a book that explain that it is a good thing that classes have a single responsibility, that is, that they do a single thing.

I can understand how to implement this in some cases I personally faced:
- I needed an array of 6 countries returned to the model, so it can use it in the views... So I designed a class to do just that and only that. The class contained a few functions, each with a single task.

But what if I need in a game, a class "monster" that is responsible for the "monster" entity in the game. The monster can "attack", "hide" and "sleep".

That's 3 responsibilities, isn't it ? Then in this case, how to organize that monster class while still respecting the single responsibility principle ? I don't get it.

答:
You need to consider how we use the word responsibility. If you are responsible for a child, that is a single responsibility. We all know there are many tasks you'll have to perform to maintain that responsibility.

So for your example of a Monster Class. You would only have functionality and data that pertains to the Monster. A monster has health and once the monster dies, the health value is gone from the individual monster, but could be recorded in some history. If you put the history in the monster class, you would lose it. If the monster was carrying a club, that would be a separate object that was possessed by the Monster, but upon the monster's death, the club would now be without an owner in some place another object could obtain possession. There's no law that says you have to do this, but if that was something you wanted to happen in your game, you'd have to figure out a way to maintain objects possessed by people but can still be available when the possession is lost. The monster can't take it with him.

So try to think in the perspective of what behaviors you want. If you find you're making changes to the monster because you want to change the club, you are getting out of the responsibility of the Monster class managing a monster character.


问:
Need an algorithm to filter this collection format
I'm sorry the title is so vague ... I cannot think how to describe it any better.

I have a collection in this format:

```<code>var myCollection = [{id:"a"}, {id:"b",excludes:["a"]}, {id:"c",excludes:["b"]}];
</code>```

What I want after running my algorithm is to see this:

```<code>processedCollection = [{id:"a"}, {id:"c",excludes:["b"]});
</code>```

Alternatively, if "c" hadn't existed, then only "b" would be visible. I hope that makes sense. It's further complicated by the possibility that any item in the collection could exclude multiple other items (hence why it's an array).

NOTE: I do NOT have to worry about circular references, as it is reasonable in this instance to expect only good data to come into my algorithm.

I've attempted to construct an appropriate function but am coming unstuck. I'd figured I would first run through the collection and create an excludedBy parameter on each item, and to then run through again, outputting the correct result, but it's not quite so simple.

Any help would be much appreciated. I'm hoping very much that this is a known problem with defined algorithm(s) to deal with it! Thank you in advance!

答:
I would think of it as a graph:

Creating a topological sorting would give you a valid order to process the nodes in.  Note there can be multiple topological sorts.  Whether you need to worry about that depends on if you need one solution or all the solutions.

In this case, there is only one topological sort: c, b, a.  You start with c, add it to the output, and remove all its direct children from the graph.  The next non-removed node in the sorting is a, which has no children, so you just add it to the output.  No nodes remain in the topo sort, so you're done.


问:
When and how to apply application settings in .Net
I know that I can access application settings in .Net using Properties.Settings.Default.aSetting.

What is the best way to apply them:

To directly read them in the function which relies on
them. This approach eliminates some class properties or function parameters
which otherwise are used to pass the settings; the function may loose its flexibility to be used with other parameters than the settings but it has this advantage that they are applied as the user change them in the settings form.

Define and set corresponding member variables and parameters in classes or functions. Then how can I apply them after user changed a setting while the dependent object has been already initialized?

答:
The big value of application settings in .NET (called "Windows Forms Application Settings") is that they provide automatic persistence of settings, that can be configured per user.

Because of that, I only use them in the case of a rich client application, where I need the user to configure some settings that should persist when the user launches the application again. They are defined only by the application project, never by a library.

When the application is running, I will only use it twice:

At application startup, I read the Settings.Default object and put all the relevant values in my own configuration object, which is then the only one used by the application;

When I want to save the settings (at application exit, when the user changes settings, etc.), I write into the Settings.Default object the configuration values from my configuration object, and then call Save() on it;

As for your dilemma (between "using an object" and "passing configuration values), they can be solved by a custom, mutable, configuration object:

The rest of the application is passed only the configuration object (or a part of it), without knowing where it comes from (that is, no component should be coupled to the configuration by accessing it as a static property);

Changes made by the user while the application is running goes to my configuration object, and the rest of the application is able to read changes to the configuration object as they happen;

One thing that you might want to do is, instead of copying the data from your own model to your own object, is to define a configuration interface, that would then be implemented by the Properties.Settings class. However that can get more complex if you have nested complex objects in your settings.

And if you have many configuration settings, then you should define multiple types for it - there is no reason for the code that queries a HTTP server to have access to the user's window color.

Also, please note that using the static property Properties.Settings.Default directly falls under the case of the question:

Is a single config object a bad idea?


答:
Single Responsibility Principle means a class should only have a single "responsibility." This does not mean one "action" or one "attribute" however.

If I were to write down a list of what a monster in a game might need to do, I may come up with a list such as this one:

Monsters have attributes such as health and attack power. These attributes may change as the monster takes damage, or perhaps it can pick up a different weapon.

Monsters have an AI that governs its actions and differentiate dumb little monsters with tougher, smarter monsters.

Monsters need to be displayed on the screen somehow.

There are multiple responsibilities here. Clearly, "having health" and "having attack power" are not different responsibilities: they are both attributes that define what a monster is and how tough it is compared to other monsters.

The AI might be different responsibility. Perhaps a game has 200 types of monsters, and 10 different AIs. Different types of monsters might be grouped and act similarly: the AI does not need to be recoded each time, it can be shared. How the monster acts might be a responsibility of the AI, not the monster itself! For example, in the Diablo series of games, the Fallen (cowardly little imps) all act pretty much the same despite having slightly different appearances and different toughness.

Displaying a monster on the screen is a great application for an adapter object that has its own single responsibility: figuring out, for a given monster; where it is located, what state it is in (swinging its weapon, running, standing), and generally how it should look on screen.

In this example we might have a core monster object describing the current state of the monster, a pluggable AI that governs its actions, and an adapter object that knows the current visual state of the monster and can produce its graphical state to the graphics subsystem for display on screen.

Note that this analysis does not dig down to the level of individual functions or methods. I analyzed this at a higher level than that: getting bogged down in the nuts and bolts of the implementation is a bad idea when defining object responsibilities. Once those responsibilities are defined and you move on to the low level implementation details, of course you need to write the attributes and functions to support those responsibilities.

Title: Object oriented Classes and single responsibility

Body:
I'm reading a book that explain that it is a good thing that classes have a single responsibility, that is, that they do a single thing.

I can understand how to implement this in some cases I personally faced:
- I needed an array of 6 countries returned to the model, so it can use it in the views... So I designed a class to do just that and only that. The class contained a few functions, each with a single task.

But what if I need in a game, a class "monster" that is responsible for the "monster" entity in the game. The monster can "attack", "hide" and "sleep".

That's 3 responsibilities, isn't it ? Then in this case, how to organize that monster class while still respecting the single responsibility principle ? I don't get it.


问:
Name for a Function which Returns its Arguments?
A function that does nothing, takes no arguments and returns nothing is traditionally called a noop, or no-op. An example of a noop is below:

```<code>function noop(){}
</code>```

http://en.wikipedia.org/wiki/NOP

So is there a name for a function which is meant only to return its arguments, and not do anything else? An example of this kind of function:

```<code>function(a){return a}
</code>```

答: It's called the identity function and is sometimes abbreviated as id in category theory and functional programming languages.


答:
So, for me, this method does one thing. It retrieves (gets) ObjectOutputStream object as its name says

No. You can't retrieve something that doesn't exist.  Creating an object which didn't exist before and returning that object changes program state (possibly with other significant side effects).  It's not a retrieval.  Retrieval should be a safe, low-impact operation.

Creating a new object and handing it back changes program state.  At the very least, it is adding a new object to the heap, consuming a bit more memory and using whatever cpu cycles are involved in object creation.  That alone can have a significant impact on application performance if this function is called frequently.

And creating a new object may have other side effects:

Opening a file

Starting a thread

Writing to a database

Opening a network socket

Resetting the state of other objects

Do you know how many of those an Oos may trigger on creation?  If all you want (and all you are given) is a reference to the existing object, none of those need bother you.

My last point there is very important.  The code snippet implies that there is only one Oos in this context.  So the creation of a new Oos may wipe the state of related objects (caches, counters, stacks) and return them to a virginal condition.  Oops.

renaming it to createOrReturnOos would be revealing implementation details to the caller.

If the Oos object were never returned to the caller - if it were a transient, hidden thing - that would be true.  But you're returning the created object.  Its provenance and history are important.

And as a caller I just want to get ObjectOutputStream and I don't care about how was it retrieved/created.

You should.  Knowing which operations change state and which don't is very important.

Some resources (e.g. databases, clustered data caches) scale by having one node which takes writes while all the others can only be read from.  If you don't know which functions change state and which do not, your application will break unexpectedly.

Some internal resources (e.g. thread pools) can be exhausted by problems with just one function/component.  For resilience, it is good practice to segregate these resources into separate pools and assign potentially destructive components to separate pools, so that one component suddenly exhausting a resource doesn't starve the others.  But for that to work you have to know which functions consume these resources.

Security concerns often require you to know which functions change state and which just report it.  If you have that knowledge, functions which change state can be restricted so that only privileged processes can use them.

Graceful degradation (a desirable feature) means that your applications can still do much even if they have lost some of their resources (e.g. the master database, where writes can be performed).  A well designed application can still return information even if it can't change it.  But designing such code requires you to know which functions change state.

So far, I've only been talking about side effects which you may not have considered and why those are important.  But there is another significant consideration.

Dishonesty.

You're lying to the caller.

The caller should expect ObjectOutputStream to return the existing stream.  It may have significant state (a cache, a history of operations, output written to a file) which the caller expects to inherit, even if they don't have direct access.  Streams in particular tend to have a lot of state and history.  Well, you lied to them.  Here is a brand new object without that state.  They don't know that.  You shouldn't lie like that.

Maybe there should be an existing Oos in the current context.  The lack of one may mean something died or a bug elsewhere in the code deleted the old Oos.  Now you hid that error.  Debugging this is going to be fun.

You're also denying the caller the freedom to create his own control flow.  Now, I'm a FP kind of guy and I am suspicious of exceptions, but we're in Java land here.  It is a common Java idiom to do things which may or may not break and leave catch blocks to deal with those cases where it does.  Sometimes a whole code path lives only in there.  You're denying the caller that option.  And other, simpler things.

Do not automagically create things which were not there when you were not asked to.  If the caller asks for something which isn't there, tell him.  Let him decide what to do next.

Stop lying to him.

maybe Bob found a bad example of what he wanted to say

He did not.  Clean Code has some of the best writing on software development that I have ever read and there's nothing in the section you quote that I would complain about.


答:
If you are beginning a refactoring project, and the code is badly formatted, you should first mechanically reformat the entire codebase to something sensible.  You should make no other changes in that VCS commit.

You can make manual adjustments for local readability (insertion of blank lines, alignment of consecutive equals signs, removal of meaningless comments, etc.) later, as you refactor each logical unit, but the initial reformatting should be 100% mechanical and applied to 100% of the code.

There are three reasons for this:

You should not reformat bad code piece-by-piece at the same time as you refactor it semantically, because that makes it harder for code reviewers to understand what the semantic changes were.

It will be easier for you to understand the code well enough to refactor it, if it is well-formatted when you begin.

A mechanical reformatting patch is certain to be large and boring.  If it is 100% mechanical, code reviewers do not have to read through it looking for semantic changes.  It is also certain to touch nearly every file, so you may as well make it all the files, minimizing the number of times anyone has to rebuild the world.

It does not matter what mechanically enforceable code-formatting style you pick (except that you should never put spaces on the inside of parentheses, because that makes the baby Jesus cry).  Consistency of formatting across an entire project is far more important than any particular style.  (Local readability is even more important, but you don't worry about that at this stage.)

Finally, if the code is so messy that mechanically reformatting the code breaks it, you should apply corrections before the reformatting patch.  That is, your VCS history should wind up looking like

```<code>... --- [corrections so reformatting doesn't break the code] --- [reformatting] --- ...
</code>```

time advancing to the right. This is so every revision of the code in the VCS is non-broken, but the reformatting patch remains 100% mechanical.

If you do not have a VCS, a code review process, a test suite, or a continuous integration infrastructure, get yourself those things before you attempt to refactor the program.  In that order.

Body:
If you are beginning a refactoring project, and the code is badly formatted, you should first mechanically reformat the entire codebase to something sensible.  You should make no other changes in that VCS commit.

You can make manual adjustments for local readability (insertion of blank lines, alignment of consecutive equals signs, removal of meaningless comments, etc.) later, as you refactor each logical unit, but the initial reformatting should be 100% mechanical and applied to 100% of the code.

There are three reasons for this:

You should not reformat bad code piece-by-piece at the same time as you refactor it semantically, because that makes it harder for code reviewers to understand what the semantic changes were.

It will be easier for you to understand the code well enough to refactor it, if it is well-formatted when you begin.

A mechanical reformatting patch is certain to be large and boring.  If it is 100% mechanical, code reviewers do not have to read through it looking for semantic changes.  It is also certain to touch nearly every file, so you may as well make it all the files, minimizing the number of times anyone has to rebuild the world.

It does not matter what mechanically enforceable code-formatting style you pick (except that you should never put spaces on the inside of parentheses, because that makes the baby Jesus cry).  Consistency of formatting across an entire project is far more important than any particular style.  (Local readability is even more important, but you don't worry about that at this stage.)

Finally, if the code is so messy that mechanically reformatting the code breaks it, you should apply corrections before the reformatting patch.  That is, your VCS history should wind up looking like

... --- [corrections so reformatting doesn't break the code] --- [reformatting] --- ...

time advancing to the right. This is so every revision of the code in the VCS is non-broken, but the reformatting patch remains 100% mechanical.

If you do not have a VCS, a code review process, a test suite, or a continuous integration infrastructure, get yourself those things before you attempt to refactor the program.  In that order.


问:
Why doesn't v8 compile typescript instead of javascript?
Since Typescript is just a superset of javascript (every javascript program is also a typescript program), I've got this idea - why doesn't v8 support typescript? or anything statically typed compatible with JS? This way it could do some real big performance hacks and suit a much wider range of programmers who require static typing... For me it sounds like a very good idea. Why hasn't anyone done this yet?
(so the Q is: are there some visible downsides of this solution? I don't see anything but I'm sure there may be something...)</p>

答:
For starters, v8 predates (public knowledge of) TypeScript by several years, TypeScript isn't from Google, TypeScript is far from an industry standard, and Google has its own language trying to fill a similar niche (Dart). And then there's the problem that nobody deploys TypeScript to websites, it's designed to be compiled to JavaScript and that's what everyone does. But let's assume none of this matters.

I don't believe that there are any performance gains to be had. Precisely because it is interoperable with JavaScript, TypeScript's type system provides virtually no hard guarantees. Sure, it allows workable autocomplete in most circumstances, but it does not guarantee that the types are all 100% correct. With type assertions (<Type> something), you can smuggle type errors past the type checker, and it's not even a runtime error. TypeScript code can and does call into JavaScript code, which might break any guarantees in arbitrary ways. So V8 can't rely on anything the TypeScript types assert.

JIT compilers can already figure out all information they need for optimization with runtime instrumentation. TypeScript can't statically eliminate the need for those checks, so it provides no extra value.

Maybe the types could give the baseline compiler an initial guess for speculative optimizations (which would be overridden by runtime profiling data in later stages), but:

That there is a benefit at all is complete speculation at this stage.

Type checking and inference takes time, and time is precious for baseline execution. Browsers want to start executing scripts as soon as possible.

It would have to be worth the extra complexity and implementation effort.

see the first paragraph.

ContentLicense: CC BY-SA 4.0


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答: We had a product release date pushed back a week so we could get the internal company footy tipping competition system running in time for the start of season...</p>


问:
What is the idiomatic way in REST to handle field level permissions?
REST APIs conventionally expose resources addressed at the object level. While it's easy to do object level permissions using the appropriate HTTP responses, handling field level permissions is a bit less clear.

Imagine the hypothetical app which exposes the user object. Publicly, you want to show some subset of the fields, for the user themself all fields should be shown.

Should the public and private versions be different endpoints, or is it reasonable to return a different set of fields depending on permissions?

答: A resource is a resource. The resource doesn't change simply because the permissions change. What you can do with the resource or what you can know about the resource might change, but the mapping of the resource doesn't change. If it does it becomes a different resource type. So in your description, it's conceivable that various properties would exist at any access of the user resource, but there would only be certain properties available based on the accessor's permissions. The inaccessible properties would simply be null.</p>


问:
OOP - How to refactor a "pyramid architecture"
Unbeknownst to me while I was building it, I built a "pyramid" architecture. I did not realize this until I laid it out in my new Visual Studio 2013 Layer Diagrammer. Each layer depends on the layer below, and all the other layers below that.

I suspect this is the cause of some of my woes. Each higher layer violates the SRP, because it has more than one reason to change, right? It has multiple contracts with multiple foundational layers. If any of those layers changes, the component has to change.

My question is, how can I refactor this? It's 19,000 lines of code but I can refactor it given enough time as long as I have a solid refactoring strategy.

And as a side note, I also invite your speculation as to why I felt the need to create it like this in the first place. Is this an anti-pattern? Does it have a name?

EDIT

I christen this anti-pattern "The Garlic Architecture"

答:
Based on the picture you provided, this looks like Onion Architecture, but with the dependencies proceeding in reverse.

A typical onion architecture looks something like this:

Each layer presents interfaces (an API) to the layer above it, and communicates with the layer above it, and the layer below it.  The onion model has some similarities to a Model-View-Controller architecture or a three-tier architecture, though note the inclusion of a Tests layer, an Infrastructure layer, and an "Inverter."  The Domain Model communicates with a database (normally shown as a component external to this diagram).

The consultant from whom I borrowed this picture describes it like this:

For web-based enterprise applications, we espouse the benefits of a specialized hexagonal architecture known as Onion Architecture. The core principle of this architecture is to build the application around an independent object model that describes the business domain. Component coupling is unidirectional toward the center with separation between component contracts (interfaces) and implementations.

Understanding the structure of the architecture is simple. In practice, the architecture relies on the Dependency Inversion (DI) principle to assemble the components at runtime. We isolate the "Inverter" into a separate physical tier to avoid leaking responsibilities.


问:
How do you manage a complexity jump?
It seems an infrequent but common experience that sometimes you're working on a project and suddenly something turns up unexpectedly, throws a massive spanner in the works and ramps up the complexity a whole lot.

For example, I was working on an application that talked to SOAP services on various other machines. I whipped up a prototype that worked fine, then went on to develop a regular front end and generally get everything up and running in a nice, fairly simple and easy to follow fashion. It worked great until we started testing across a wider network and suddenly pages started timing out as the latency of the connections and the time required to perform calculations on remote machines resulted in timed out requests to the soap services. It turned out that we needed to change the architecture to spin requests out onto their own threads and cache the returned data so it could be updated progressively in the background rather than performing calculations on a request by request basis.

The details of that scenario are not too important - indeed it's not a great example as it was quite forseeable and people who have written a lot of apps of this type for this type of environment might have anticipated it - except that it illustrates a way that one can start with a simple premise and model and suddenly have an escalation of complexity well into the development of the project.

What strategies do you have for dealing with these types of functional changes whose need arises - often as a result of environmental factors rather than specification change - later on in the development process or as a result of testing? How do you balance between avoiding the premature optimisation/ YAGNI/ overengineering risks of designing a solution that mitigates against possible but not necessarily probable issues as opposed to developing a simpler and easier solution that is likely to be as effective but doesn't incorporate preparedness for every possible eventuality?

Edit: Crazy Eddie's answer includes "you suck it up and find the least expensive way to implement the new complexity." That made me think of something that was implicit in the question but I didn't specifically raise.

Once you hit that bump, and you incorporate the necessary changes. Do you do the thing that will keep the project as close to schedule as possible but may affect maintainability or do you go back to your architecture and rework it on a more detailed level that may be more maintainable but will push everything back during development?

答:
As with most programming problems, it depends, in my opinion.  This issue is so intrinsic to creative work, that you should not forget that failures are going to happen, and that's O.K..  Programming is a wicked problem, and you usually don't know the right solution to the problem until you've already solved it.

However, there's a host of local, specific factors that might come into play here, such as:

The goals for this system.  Is it a one-off thing?  Do you intend to keep this system working for a medium to long term?

For short term things, it might not be worth it to think about it more than enough to just get it running.  Refactoring is expensive, and it's something that doesn't create immediate end value to your user.  However, there's pretty much no case I can think of other than absolute throwaway software, where it's so short term that it's not worth improving your design. It's much more important to be able to understand what you did, and fix it quickly, than to finish right now.  If it's for the longer term, then it will very likely pay off eventually (and possibly much sooner than everyone involved thinks), or the inverse (not doing it will cause pain very soon instead of "when we have to fix it").  I am almost tempted to say "always take the time to make it better", but there's some cases where that's not possible.

The goals of the team.  Is it more of a "do it now, at any cost", or a "let's do it right" kind of thing?

This should influence your decisions enormously.  Your team will either support this decision by either giving you resources to redesign, or they will demand the quick solution to be done now.  In my opinion, if you find that the team is pushing you in the wrong direction consistently, it's a huge red flag.  I've seen this sort of thing end up in a scenario where there is constant fire-extinguishing going on, where there's never time to redesign because you're always fixing the problems your bad design creates.  There can also be a middle ground, though: "duct-tape" now, fix ASAP (but actually do it).

Your understanding of the problem.  Why did the previous solution not work?

Really important.  Think about what the error or problem is and why it's happening.  This sort of situation is a great opportunity to find flawed (or missing) assumptions, constraints and interactions.  In general, always favor understanding your problem better instead of solving the current problem.  This is probably your greatest defense against YAGNI/overengineering.  If you understand your problem well enough, then you will solve it and not other problems.

Finally, try to build things the right way.  I'm not talking about the errors and problems you face when you either understand more about the problem or your inherent human error.  I don't mean "don't make mistakes and get it perfect the first time" - that's impossible.  I mean, try manage complexity well in your everyday work, fix broken windows, keep it as simple as you can, improve your code and your thinking all the time.  That way when (not if) change knocks at your door, you can welcome it with open arms instead of a shotgun.

Title: How do you manage a complexity jump?


问:
eBook editions of programming books
(I'll get my justification for why this is on topic in early: programming books tend to have fairly specific formatting needs - code samples, tables, images and graphs - which are not common to all book types and are not necessarily well handled by eBook readers.  Similarly they're used in different ways - you often dip in and out rather than read cover to cover.)

I've just noticed that Don't Make Me Think by Steve Krug is available as an eBook edition for the Kindle (and presumably also for other readers) which set me thinking.

There are certain advantages to eBook readers for tech books - primarily that you can carry a massive library of what would be heavy physical books around very easily.  The downside is that certain eBook readers allegedly aren't particularly well equipped to cope with tables, code samples and so on and a book like Don't Make Me Think presumably makes extensive use of these sorts of things.

So, the question, what are your experiences of reading and using programming books on an eBook reader and would you recommend it? I'm specifically interested in the latest generation Kindle but happy to hear about all devices - might be useful to state which one you use in the answer.

答:
I read a lot, and since I got my iPad, I started to use Kindle. I bought a dozen of books. I also purchased +- 5 eBook instead of the paper version before I got the iPad.

After few months of intensive tests, I decided that I will stop buying electronic version in the future.

I can't give or lend them to others. I know it's also prohibited explicitly by the license. They have your name watermarked in the binary.

I can't read them in my bath!

It's not even practical on my desk.

When I have my iPad with me, I always need to watch it in case someone try to steal it. No problem with a paper book, you can leave it on the table while you go to the restrooms.

I don't know what will happens if my iPad crash. I used to buy lot of music at MSN Music (OD2 Nokia) and when they decided to shutdown, I lost all my library, and today I have no way to even know what I've purchased (site out)

The +- 5 PDF ebooks I mention earlier, I lost them somewhere on a DVD or an harddrive and can't found them anymore... I can't even remember what I purchased

I forget I purchased books. Since I don't see them unless I open Kindle. And when I open Kindle, I have to scroll down to see them all.

And more importantly... the electronic version is sometimes more expensive than the paper version! And when it's not more expensive it's not as cheap as it should be.

And probably the more important reason I will stop buy electronic books and purchase the paper version instead is:

I really need to touch them! I like their smell. The noise it makes when you fold the pages.

Title: eBook editions of programming books


问:
Should a Java Boolean be used for ternary (3-state) logic?
I'm trying to make a basic cache of a boolean value, and I did it like such:

private Boolean _valueCache = null;
private boolean getValue() {
    try {
        if (_valueCache == null) { // if cache was never filled
            return _valueCache = getReader().getMyBooleanProperty(); // fill it and return the new value
        }
        return _valueCache; // else, return the cache
    } catch (NullPointerException ex) { // getReader() returned null
        return false; // that return may not be null in the future, so set nothing
    }
}
```

Does this go against best practices? (letting a Boolean have 3 values: true, false, and null) I only want to cache this value, so I don't want to make an entire custom HashMap that mimics this behavior with a get-or-default method. That said, I've never done a cache this small so I don't know the downsides to it.

To clarify, I meant "ternary" as in "3-state", as opposed to "binary" as in "2-state". Sorry for any confusion.

答:
The  tenary logic for this should be

```<code>private Boolean _valueCache = null;
private boolean getValue() {
         Boolean readerValue = getReader() == null ? false : reader.getMyBooleanProperty();
         _valueCache = _valueCache == null  ? readerValue : _valueCache;
         return _valueCache;

   }
</code>```

By the way, what is the use of the NullPointer exception handled, Does the getReader() return null, Runtime exceptions like this are also not advisable

Body:
The  tenary logic for this should be

private Boolean _valueCache = null;
private boolean getValue() {
         Boolean readerValue = getReader() == null ? false : reader.getMyBooleanProperty();
         _valueCache = _valueCache == null  ? readerValue : _valueCache;
         return _valueCache;

   }

By the way, what is the use of the NullPointer exception handled, Does the getReader() return null, Runtime exceptions like this are also not advisable


问:
Complex Number help
OK so I have a programming assignment and I need to create a class that represents Complex Numbers (good so far), add them to a list(good so far), and then output whether each individual number is real (a+0x), imaginary (0+bx), or complex (a+bx). A Complex object is made by initializing the real portion and imaginary portion

```<code>    Complex(int _real, int _imag) { real = _real; imag = _imag; };
    Complex(int _real) {real = _real; imag = 0;};
    Complex() { real, imag = 0;}
</code>```

The problem is my professor has silly stipulations such as all of the data fields must be private and there can be no get methods to access any portion of an indivdual Complex number from outside the class.

Instead the only public methods I have to work with are plus, subtract, and multiply methods that take another Complex number and return a sum, difference and product of the two respectively and a conjugate method that returns an individual Complex's conjugate.
With only those four public methods at my disposal, what formula can I use to compute whether an individual number is real, imaginary or complex?

This is less a coding issue and more of a logic issue I know.

答:
Let c = a + bi and q be the conjugate of c.

Then c + q = 2a and c - q = 2bi. Now you've isolated twice the real and imaginary parts.

If your professor allows you to have an equals method, you can compare these to zero (i.e. Complex(0, 0)), and you have your answers.

If you literally can use only the four methods you mentioned (addition, subtraction, multiplication, and conjugation), determining your answer is provably impossible.

Title: Complex Number help


问:
Calculate different prices for different user types
I'm working on a website that, among other things, sells courses. Each course is segmented in units, to which users can subscribe but is not a requirement that they subscribe to all of them. Now the client asked me to be able to configure different prices to course's units based on the user type and membership status (they can pay an annual fee to become members and get discounts). Also, subscribing to all units of the same course gives the user a discount. An example for a course would be like this:

Website users with no membership:

Unit 1: $500

Unit 2: $500

Unit 3: $500

All Units: $1200

Website users with membership but with debt on the annual fee:

Unit 1: $450

Unit 2: $450

Unit 3: $450

All Units: $1100

Website users with membership (no debt):

Unit 1: $400

Unit 2: $400

Unit 3: $400

All Units: $900

Whether an user is member or not is easy because there is a column that defines that. But then there is another table to log the user's payments, which should be used to get the last payment and deduce if the user has a debt. Based on that combination, the correct prices should be presented to the user.

The client needs to download then a list of users who subscribed to a specific course/unit, so I can't just have three "Unit 1" rows on the database for each price because they should be treated as the same unit.

Regarding the "All Units" price, I can initially keep it simple and add it as another unit to avoid wasting time programming that because it's more important to solve the logic of the different prices.

My question is: How should I structure the database, and what is the best way (logic) to deduce which price is shown to the user?.

Initially the request was different prices for members/not-members which is easy because I can filter by the is_member column of the users table, but then they add to the request the debt status for each user, making it more complex.

I'll be using PHP & MySQL, but the question is more about the logic than the code.

One idea that came to my mind was to get from the database the user info + debt status in one query, and all the course's units and prices in another query and then use PHP to check which values should be used, but how can I implement that logic if the rules can be different for each course (another course will have a discount for users which have been members for 2+ years). Should I manually program Classes for each course (all implementing the same Interface) that do the logic and define in the courses table which Class should be used? I think it's not the best way but I can't think of another option to change the PHP logic according to the selected course.

答: The simplest option is probably to add an outstanding_debt column, and ensure all payments and subscriptions update this number in addition to wherever you're currently keeping billing information (I couldn't really understand your description of that part). Your database probably has a constraints feature you can use to ensure these numbers remain in sync. After that, dealing with the debt rule is just as trivial as the membership rule.</p>


答:
Note: This is a hack and not how "real" (ha-ha) code should be written

As Bogie said to Bergman, "We'll always have toString()".

Given the overly-restrictive parameters given by OP, the only solution I can think of is to put the information into the toString() method.  With no serious thought about good code or testing, something like:

```<code>public String toString() {
   StringBuilder sb = new StringBuilder();
   sb.append(this.real);
   sb.append( (this.imag >= 0.0) ? " +" : " ");
   sb.append(this.imag);
   if (this.real == 0.0) {
      if (this.imag != 0.0)
         sb.append("   imaginary");
   }
   else {
      sb.append( (this.imag == 0.0) ? "   real" : "   complex");
   }

   // TODO  note : not sure what 0.0, 0.0 counts as...

   return sb.toString();
}
</code>```

This is more of a "gee I'm clever Google Interview Answer".  In real life you'd ask your professor (or your stakeholder) what the heck they actually want.

p.s. Note that my direct comparisons to 0.0 are dubious, you probably want to test if the absolute value is less than a small epsilon.

Title: Complex Number help

Body:
OK so I have a programming assignment and I need to create a class that represents Complex Numbers (good so far), add them to a list(good so far), and then output whether each individual number is real (a+0x), imaginary (0+bx), or complex (a+bx). A Complex object is made by initializing the real portion and imaginary portion

```<code>    Complex(int _real, int _imag) { real = _real; imag = _imag; };
    Complex(int _real) {real = _real; imag = 0;};
    Complex() { real, imag = 0;}
</code>```

The problem is my professor has silly stipulations such as all of the data fields must be private and there can be no get methods to access any portion of an indivdual Complex number from outside the class.

Instead the only public methods I have to work with are plus, subtract, and multiply methods that take another Complex number and return a sum, difference and product of the two respectively and a conjugate method that returns an individual Complex's conjugate.
With only those four public methods at my disposal, what formula can I use to compute whether an individual number is real, imaginary or complex?

This is less a coding issue and more of a logic issue I know.

Body:
Note: This is a hack and not how "real" (ha-ha) code should be written

As Bogie said to Bergman, "We'll always have toString()".

Given the overly-restrictive parameters given by OP, the only solution I can think of is to put the information into the toString() method.  With no serious thought about good code or testing, something like:

public String toString() {
   StringBuilder sb = new StringBuilder();
   sb.append(this.real);
   sb.append( (this.imag >= 0.0) ? " +" : " ");
   sb.append(this.imag);
   if (this.real == 0.0) {
      if (this.imag != 0.0)
         sb.append("   imaginary");
   }
   else {
      sb.append( (this.imag == 0.0) ? "   real" : "   complex");
   }

   // TODO  note : not sure what 0.0, 0.0 counts as...

   return sb.toString();
}

This is more of a "gee I'm clever Google Interview Answer".  In real life you'd ask your professor (or your stakeholder) what the heck they actually want.

p.s. Note that my direct comparisons to 0.0 are dubious, you probably want to test if the absolute value is less than a small epsilon.


答:
<edit>I think you have misunderstood your professor's intent. A complex number class without any way to access internal values would be useless. I would expect getRealPart() and getImaginaryPart() would be implemented, and getMagnitude() and getAngle() as well.
As to the down-voter, what exactly is your concern? </edit>

Your professor is probably steering you towards making your Complex class immutable. Take a look at the BigDecimal class - it uses this pattern

Don't forget that in a member method like with a signature like Complex add(Complex x) you can access the fields of x directly - you don't need getters, as the access rules of Java allow access.

I'm not sure why you need to test for real, imaginary or complex. If you need an isReal() member method, just test the imaginary part for zero.

Your class will have an equals() method, as it is a method of all Java objects. You will need to override this, and you should also override hashCode() while in the area.

Title: Complex Number help


问:
Confusion regarding def function within Python
I've been learning Python for about 2 months now (Started with Learn Python The Hard Way, now reading Dive Into Python), and within both books, I still seem to be confused over this one bit of code.

Lets just take the default code that Dive Into Python uses as an example:

```<code>def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.

    Returns string."""
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

if __name__ == "__main__":
    myParams = {"server":"mpilgrim",
                "database":"master",
                "uid":"sa",
                "pwd":"secret"
               }

print buildConnectionString(myParams)
</code>```

How does the function buildConnectionString with the argument (params) know to get its data from the variable myParams?  Or params.items(), too within the return line?  Wouldn't the argument in buildConnectionString need to be set as buildConnectionString(myParams) in order for it to read properly?  How can you set the variable of your data to myParams, but have the argument of your function be params and have it read?  How does it know to read myParams as params?

And is there a reason behind not naming your variable params, or vice versa naming your argument in your function myParams?  It's just been extremely confusing seeing the argument set as one word, and then having the variable named something completely different, but having the function still be able to read your code, even when the argument name is different from your variable with the data you're printing from.

答:
You're right to wonder why this symbol doesn't seem to mean anything to the rest of the file, but its spelling isn't its only attribute. Consider its positioning.

The confusion lies in trying to equate the parameter name and the argument name. You are right, there is no connection between the names as such. But if you saw a Python error message due to a missing argument from within a parentheses, you might see the terminology "positional argument". It's the positioning of the argument in the parentheses following the call of function x that identifies the argument as corresponding to the parameter from the def statement of the same function.

You wonder why the parameter and argument don't have the same name. The two names have the same position relative to the function name, which is their only connection.

What is meaningful in this function:

```<code>print('Say anything.')
nilj = input()
def rabberd(durf):
    print(nilj + ' what?')

rabberd(nilj)
</code>```

Meaningful to Python: "def", "input" and "print".

Meaningful to the file:

rabberd is rabberd

nilj is input

relative positioning of nilj and durf equate them to each other.

durf as a word is arbitrary; only its position is meaningful.

Body:
You're right to wonder why this symbol doesn't seem to mean anything to the rest of the file, but its spelling isn't its only attribute. Consider its positioning.

The confusion lies in trying to equate the parameter name and the argument name. You are right, there is no connection between the names as such. But if you saw a Python error message due to a missing argument from within a parentheses, you might see the terminology "positional argument". It's the positioning of the argument in the parentheses following the call of function x that identifies the argument as corresponding to the parameter from the def statement of the same function.

You wonder why the parameter and argument don't have the same name. The two names have the same position relative to the function name, which is their only connection.

What is meaningful in this function:

print('Say anything.')
nilj = input()
def rabberd(durf):
    print(nilj + ' what?')

rabberd(nilj)

Meaningful to Python: "def", "input" and "print".

Meaningful to the file:

rabberd is rabberd

nilj is input

relative positioning of nilj and durf equate them to each other.

durf as a word is arbitrary; only its position is meaningful.