问:
Advantage of Tagging a Release in SVN versus Only Leaving a Comment for the Commit
In my company, we have had a policy of tagging every release. Someone new joined, and he suggested that instead of formally using a Tag, we could just leave a comment for the release build when it is checked in. I like using a Tag, but, obviously, we can also get to the source code for a build also by looking for the comment. The only advantage I see is that because our product spans multiple technologies, we can group the source code for both in the same directory with a folder for each. Is there some other advantage of tagging releases that I'm missing? BTW, we are using SVN.

答: Some customer who cannot upgrade to a newer version ask you for support for version x.y.z. A tag with that release will help you identify the code you need to inspect. Ask the new guy to search the release using commit comments. Please, do it!</p>


答:
A tag in subversion is technically the same as a branch. It is only convention that keeps you from modifying a tag after it was created.

Last year I had a situation where we were very happy that we use tags in subversion.

We had created a release and tagged that release. In parallel to the acceptance tests on the release, normal development continued on the trunk of the repository.
The problem was that late in the acceptance tests, a critical issue was found that absolutely had to be solved, but the new stuff that was being developed could absolutely not be included in the release, because it was far from being stable enough.

We resolved that finally by making use of the fact that under the hood a tag is the same as a branch, so we made the change directly on the tag. If we had used check-in comments to 'tag' our releases, that would not have been as easy to do.

Besides that, if your project consists of multiple projects that evolve at a different rate but are always released together, then a subversion tag ensures that you have a correct snapshot of all the projects at the time of the release, even if some of them haven't changed since the last release. If you use check-in comments to mark a release, you must make a check-in on each project, even if nothing has changed.

ContentLicense: CC BY-SA 3.0

Title: Advantage of Tagging a Release in SVN versus Only Leaving a Comment for the Commit

Body: In my company, we have had a policy of tagging every release. Someone new joined, and he suggested that instead of formally using a Tag, we could just leave a comment for the release build when it is checked in. I like using a Tag, but, obviously, we can also get to the source code for a build also by looking for the comment. The only advantage I see is that because our product spans multiple technologies, we can group the source code for both in the same directory with a folder for each. Is there some other advantage of tagging releases that I'm missing? BTW, we are using SVN.


问:
Is this the correct understanding of tight coupling and loose coupling
Coupling mean "dependency". It is the case of "Class A" dependent on "Class B" to get the job done.

Tight Coupling is when "Class A" Use the implementation of "Class B".
Loose Coupling is when "Class A" Use the abstraction on "Class B".

Is this the correct understanding or is it oversimplify ?

答:
Tight Coupling is when "Class A" directly calls "Class B" or an object of "Class B" to done a job. in loose coupling "Class A" calls  an abstract class or an object of an abstract class to done a job; so if "Class B" implements mentioned abstract then "Class A" indirectly called the "Class B" without depending on "class B"

as an example think "Class B" is Data layer that provide you services to run queries on SQLServer Db. what will happen if you want to run same application with for example an Oracle DB or MySQL or XML etc. If "Class A" instead of depending on "Class B" just depent on an abstract class like IDBProvider. then you can use "Class A" with any Class that just Implement IDBProvider. this is loosely coupled.


答:
Consider the following example:

```<code>// Let's say this method lives in a class MyClass
public void doSomething(Foo foo, Bar bar) {
    foo.prepareProcessing();
    Worker work = foo.createWorker();
    work.dispatchTask(new Task(bar), 12);
    work.start();
    foo.waitForWorker(work);
    foo.finishProcessing();
}
</code>```

Contrast it to the following:

```<code>public void doSomething(Foo foo, Bar bar) {
    foo.runTaskAtPriority(bar, 12);
}
</code>```

In the first example, classes Foo and MyClass are tightly coupled: MyClass not only depends on Foo, but also on Foo's dependencies, like the Worker and Task classes. Furthermore, MyClass depends on very specific internals of Foo: It has to call several methods in a certain order. It's much more likely that changing something in Foo will also require changing MyClass.

The second example only depends on Foo itself. So if Foo stops using a Worker internally, MyClass doesn't have to care. MyClass and Foo are loosely coupled.

In the end, it's all about knowledge: The more you need to know about a certain class/method in order to use it, the tighter the coupling.

"Depending on abstractions instead of concretions" is a common way to achieve low coupling. But introducing abstract classes/interfaces doesn't automatically reduce coupling - you rather need to think about ways to reduce the possible interactions (knowledge) one class has with another one.

Title: Is this the correct understanding of tight coupling and loose coupling

Body:
Coupling mean "dependency". It is the case of "Class A" dependent on "Class B" to get the job done.

Tight Coupling is when "Class A" Use the implementation of "Class B".
Loose Coupling is when "Class A" Use the abstraction on "Class B".

Is this the correct understanding or is it oversimplify ?

Body:
Consider the following example:

// Let's say this method lives in a class MyClass
public void doSomething(Foo foo, Bar bar) {
    foo.prepareProcessing();
    Worker work = foo.createWorker();
    work.dispatchTask(new Task(bar), 12);
    work.start();
    foo.waitForWorker(work);
    foo.finishProcessing();
}

Contrast it to the following:

public void doSomething(Foo foo, Bar bar) {
    foo.runTaskAtPriority(bar, 12);
}

In the first example, classes Foo and MyClass are tightly coupled: MyClass not only depends on Foo, but also on Foo's dependencies, like the Worker and Task classes. Furthermore, MyClass depends on very specific internals of Foo: It has to call several methods in a certain order. It's much more likely that changing something in Foo will also require changing MyClass.

The second example only depends on Foo itself. So if Foo stops using a Worker internally, MyClass doesn't have to care. MyClass and Foo are loosely coupled.

In the end, it's all about knowledge: The more you need to know about a certain class/method in order to use it, the tighter the coupling.

"Depending on abstractions instead of concretions" is a common way to achieve low coupling. But introducing abstract classes/interfaces doesn't automatically reduce coupling - you rather need to think about ways to reduce the possible interactions (knowledge) one class has with another one.


问:
NVI for virtual function implemented in every layer of a deep hierarchy
Suppose we have the following class hierarchy:

```<code>class Object {
public:
    virtual void update() {
        // Update position
    }
};

class Rocket : public Object {
public:
    virtual void update() {
        Object::update();
        // Orientate towards target
    }
};

class SparklingRocket : public Rocket {
public:
    virtual void update() {
        Rocket::update();
        // Create sparkling particles
    }
};
</code>```

For obvious reason this is no good idea. For instance an inheritor of any of the classes might forget to call Base::update() and the behaviour of the program would be incomplete.
As I see it, functions that implement important behaviour shouldn't be made virtual, that's something better reserved for replaceable behaviour.

So, we would probably change the architecture like that:

```<code>class Object {
public:
    void update() {
        // Update position
        afterObjectUpdate();
    }

protected:
    virtual void afterObjectUpdate() {}
};

class Rocket : public Object {
protected:
    virtual final void afterObjectUpdate() override {
        // Orientate towards target
        afterRocketUpdate()
    }

    virtual void afterRocketUpdate() {}
};

class SparklingRocket : public Rocket {
protected:
    virtual final void afterRocketUpdate() {
        // Create sparkling particles
        afterSparklingRocketUpdate();
    }
    virtual void afterSparklingRocketUpdate() {}
};
</code>```

This is pretty much what I want:

The public interface of all classes is only the non-virtual update() - method

When that method is called it is ensured that every update()-"submethod" is called

Even if the one inheritor forgets to call a afterUpdate() - method, the hierarchy is stable from the base class down. This way a API could ensure its own integrity whilst in the first codeexample it would have to rely on the user to call the Base::update() method

I dislike one thing though: The name of each class is part of the after...Update() methodname. That seems like codesmell to me.

I think the general goal of keeping virtual call hierarchies stable can't be that uncommon. What is the commonly applied solution that I didn't come across yet?

答:
Having such virtual call hierarchies in the first place is quite rare. Having an inheritance tree that is more than three levels deep is often already considered a code smell and having a method that can be extended in each level of the hierarchy is rare.

Those two combined makes your scenario extremely rare.

On the other hand, the architecture you came up with has many similarities to a repeated application of the Template Method pattern. In the Template Method pattern, the base class implements an algorithm for which some steps are implemented by a derived class.

As you are having trouble coming up with good names for the afterXXXUpdate method, it could also be that inheritance isn't the right tool here. Call chains, such as between your update methods are also a hallmark of the Decorator pattern. It might be worth to have a look at.


答:
A tag is precisely made to be able to get the exact snapshot of the sources at the moment you created it. It is 1000000 times more convenient than looking at the submit comments....especially if your release requiered several commits (or more).

Furthermore, the case where a important bug is dicovered in acceptance or in production while the development is ongoing and not stable enough is quite common!
In that case you have to create a branch. As others mentioned, a tag is beyond the scene a branch in SVN so you are saved in that case but tagging can also save your life with other tools because many tools allow you to create a branch from tag (CVS, TFS and certainly others).
Just try it with comments only!


问:
How do Traits in Scala avoid the "diamond error"?
(Note: I used 'error' instead of 'problem' in the title for obvious reasons.. ;) ).

I did some basic reading on Traits in Scala. They're similar to Interfaces in Java or C#, but they do allow for default implementation of a method.

I was wondering: can't this cause a case of the "diamond problem", which is why many languages avoid multiple inheritance in the first place?

If so, how does Scala handle this?

答:
Scala avoids the diamond problem by something called "trait linearization". Basically, it looks up the method implementation in the traits you extend from right to left. Simple example:

```<code>trait Base {
   def op: String
}

trait Foo extends Base {
   override def op = "foo"
}

trait Bar extends Base {
   override def op = "bar"
}

class A extends Foo with Bar
class B extends Bar with Foo

(new A).op
// res0: String = bar

(new B).op
// res1: String = foo
</code>```

Having said that, the list of traits it looks up might contain more than the ones you explicitly gave, since they might extend other traits. A detailed explanation is given here:
Traits as stackable modifications
and a more complete example of the linearization here:
Why not multiple inheritance?

I believe in other programming languages this behavior is sometimes referred to as "Method resolution order" or "MRO".

Body:
Scala avoids the diamond problem by something called "trait linearization". Basically, it looks up the method implementation in the traits you extend from right to left. Simple example:

trait Base {
   def op: String
}

trait Foo extends Base {
   override def op = "foo"
}

trait Bar extends Base {
   override def op = "bar"
}

class A extends Foo with Bar
class B extends Bar with Foo

(new A).op
// res0: String = bar

(new B).op
// res1: String = foo

Having said that, the list of traits it looks up might contain more than the ones you explicitly gave, since they might extend other traits. A detailed explanation is given here:
Traits as stackable modifications
and a more complete example of the linearization here:
Why not multiple inheritance?

I believe in other programming languages this behavior is sometimes referred to as "Method resolution order" or "MRO".


问:
How are negative signed values stored?
I was watching this video on the maximum and minimum values  of signed integers.

Take an example of a positive signed value - 0000 0001
The first bit denotes that the number is positive and the last 7 bits are the number itself. So it is easily interpreted as +1.

Now take an example of a negative signed value - 1000 0000
which comes out to be -8. Okay, the computer can understand that it is a negative value because of the first bit but how the hell does it understand that 000 0000 means -8?

In general, how are negative signed values stored/interpreted in a computer?

答:
The signed integers are stored using http://en.wikipedia.org/wiki/Two%27s%20complement

Then you get :

```<code>000   0
001   1
010   2
011   3
100   -4
101   -3
110   -2
111   -1
</code>```

Basically it's very easy counting, you count till half the max of the signed integer. Do a +1, make it negative and start counting down.

Title: How are negative signed values stored?

Body:
The signed integers are stored using http://en.wikipedia.org/wiki/Two%27s%20complement

Then you get :

000   0
001   1
010   2
011   3
100   -4
101   -3
110   -2
111   -1

Basically it's very easy counting, you count till half the max of the signed integer. Do a +1, make it negative and start counting down.


答:
The C standard doesn't mandate any particular way of representing negative signed numbers.

In most implementations that you are likely to encounter, negative signed integers are stored in what is called two's complement. The other major way of storing negative signed numbers is called one's complement.

The two's complement of an N-bit number x is defined as 2^N - x. For example, the two's complement of 8-bit 1 is 2^8 - 1, or 1111 1111. The two's complement of 8-bit 8 is 2^8 - 8, which in binary is 1111 1000. This can also be calculated by flipping the bits of x and adding one. For example:

```<code> 1      = 0000 0001
~1      = 1111 1110 (1's complement)
~1 + 1  = 1111 1111 (2's complement)
-1      = 1111 1111

 21     = 0001 0101
~21     = 1110 1010
~21 + 1 = 1110 1011
-21     = 1110 1011
</code>```

The one's complement of an N-bit number x is defined as x with all its bits flipped, basically.

```<code> 1      = 0000 0001
-1      = 1111 1110

 21     = 0001 0101
-21     = 1110 1010
</code>```

Two's complement has several advantages over one's complement. For example, it doesn't have the concept of 'negative zero', which for good reason is confusing to many people. Addition, multiplication and subtraction work the same with signed integers implemented with two's complemented as they do with unsigned integers as well.

Title: How are negative signed values stored?

Body:
I was watching this video on the maximum and minimum values  of signed integers.

Take an example of a positive signed value - 0000 0001
The first bit denotes that the number is positive and the last 7 bits are the number itself. So it is easily interpreted as +1.

Now take an example of a negative signed value - 1000 0000
which comes out to be -8. Okay, the computer can understand that it is a negative value because of the first bit but how the hell does it understand that 000 0000 means -8?

In general, how are negative signed values stored/interpreted in a computer?

Body:
The C standard doesn't mandate any particular way of representing negative signed numbers.

In most implementations that you are likely to encounter, negative signed integers are stored in what is called two's complement. The other major way of storing negative signed numbers is called one's complement.

The two's complement of an N-bit number x is defined as 2^N - x. For example, the two's complement of 8-bit 1 is 2^8 - 1, or 1111 1111. The two's complement of 8-bit 8 is 2^8 - 8, which in binary is 1111 1000. This can also be calculated by flipping the bits of x and adding one. For example:

 1      = 0000 0001
~1      = 1111 1110 (1's complement)
~1 + 1  = 1111 1111 (2's complement)
-1      = 1111 1111

 21     = 0001 0101
~21     = 1110 1010
~21 + 1 = 1110 1011
-21     = 1110 1011

The one's complement of an N-bit number x is defined as x with all its bits flipped, basically.

 1      = 0000 0001
-1      = 1111 1110

 21     = 0001 0101
-21     = 1110 1010

Two's complement has several advantages over one's complement. For example, it doesn't have the concept of 'negative zero', which for good reason is confusing to many people. Addition, multiplication and subtraction work the same with signed integers implemented with two's complemented as they do with unsigned integers as well.

ContentLicense: CC BY-SA 4.0


答:
There are three well known methods for representing negative values in binary:

Signed magnitude. This is the easiest to understand, because it works the same as we are used to when dealing with negative decimal values: The first position (bit) represents the sign (0 for positive, 1 for negative), and the other bits represent the number. Although it is easy for us to understand, it is hard for computers to work with, especially when doing arithmetic with negative numbers.

In 8-bit signed magnitude, the value 8 is represented as 0 0001000 and -8 as 1 0001000.

One's complement. In this representation, negative numbers are created from the corresponding positive number by flipping all the bits and not just the sign bit. This makes it easier to work with negative numbers for a computer, but has the complication that there are two distinct representations for +0 and -0. The flipping of all the bits makes this harder to understand for humans.

In 8-bit one's complement, the value 8 is represented as 00001000 and -8 as 11110111.

Two's complement. This is the most common representation used nowadays for negative integers because it is the easiest to work with for computers, but it is also the hardest to understand for humans. When comparing the bit patterns used for negative values between one's complement and two's complement, it can be observed that the same bit pattern in two's complement encodes for the next lower number. For example 11111111 stands for -0 in one's complement and for -1 in two's complement, and similarly for 10000000 (-127 vs -128).

In 8-bit two's complement, the value 8 is represented as 00001000 and -8 as 11111000.

Title: How are negative signed values stored?


问:
What's so bad about creative coding?
I was watching Bob Ross paint some "happy trees" tonight, and I've figured out what's been stressing me out about my code lately.

The community of folks here and on Stack Overflow seem to reject any whiff of imperfection.  My goal is to write respectable (and therefore maintainable and functioning) code, by improving my skills.  Yet, I code creatively.

Let me explain what I mean by "coding creatively":

My first steps in a project are often to sit down and bash out some code.  For bigger things, I plan a bit out here and there, but mostly I just dive in.

I don't diagram any of my classes, unless I'm working with others who are creating other pieces in the project.  Even then, it certainly isn't the first thing I do.  I don't typically work on huge projects, and I don't find the visual very useful.

The first round of code I write will get rewritten many, many times as I test, simplify, redo, and transform the original hack into something reusable, logical, and efficient.

During this process, I am always cleaning.  I remove unused code, and comment anything that isn't obvious.  I test constantly.

My process seems to go against the grain of what is acceptable in the professional developer community, and I would like to understand why.

I know that most of the griping about bad code is that someone got stuck with a former employee's mess, and it cost a lot of time and money to fix.  That I understand.  What I don't understand is how my process is wrong, given that the end result is similar to what you would get with planning everything from the start.  (Or at least, that's what I have found.)

My anxiety over the issue has been so bad lately that I have stopped coding until I know everything there is about every method for solving the particular problem I am working on.  In other words, I have mostly stopped coding altogether.

I sincerely appreciate your input, no matter what your opinions are on the issue.

Edit:  Thank you all for your answers.  I have learned something from each of them.  You have all been most helpful.

答:
I code pretty much the same way. I'll just start writing and as I see patterns emerging, I refactor. You can paint yourself into a corner that way, you have to know when to sit back and think a problem through, but sometimes you just to take a stab at it to really understand the problem.

But I'm curious about this:

The community of folks here and on Stack Overflow seem to reject any whiff of imperfection. [..] My process seems to go against the grain of what is acceptable in the professional developer community, and I would like to understand why.

How would anybody at Stack Overflow know your process? And what do you mean by "reject"? Naturally, code posted to a programming community is going to be critically examined. But if someone spots areas where your code can be improved, that can only be a good thing, right?

Hopefully, when posting a question to Stackframe, you cleanup up your code and try to reduce it to the simplest form possible, out of respect for your readers (you sometimes solve your own problem just trying to make it presentable to others), in which case any feedback is good. If you post code that you know is bad, and you know why it's bad before you post it, you shouldn't take it personally if people notice that it's bad.

ContentLicense: CC BY-SA 2.5

Title: What's so bad about creative coding?


问:
c# naming - What are common conventions for a suffix to distinguish between read-only and writable interfaces
Assume an interface that allows queries on a spatial tree

```<code>public ISpatialTree
{
    int FindChildIndex(Vector point);
    bool IsLeaf { get; }
    ICollection<ISpatialTree> Children { get; }
}
</code>```

and another one that allows changing the tree:

```<code>public ISpatialTreeWriter : ISpatialTree
{
    void Add(Vector point);
    bool Remove(Vector point);
    void Clear();
}
</code>```

I am looking for a name to denote the writeable interface. Ideally it would be reasonably short and readable word. It's not only for this example, but I would like to use a convention for all code in the project because this is a common case.

Does anyone know of a good convention for this problem? What conventions are used in other projects?

Words that were discussed include Writer (ambiguous, often used in other contexts), Mutator (confusing), Rw (unreadable, not a word).

A good solution would be a single word, not longer than 6-8 letters and that makes it obvious that this is the writer interface.

答:
I would suggest that you specify a read-only interface style, such as:

```<code>interface IReadOnlySpatialTree
{
}
</code>```

and then the writeable interface extends this with its name only, ie.:

```<code>interface ISpatialTree : IReadOnlySpatialTree
{
}
</code>```

You will rarely use a writeable interface without also needing the readonly part.  If you're not careful you'll end up with at least 3 interfaces for every type (readonly/ writeonly and readwrite), which isn't particularly useful and is a waste of energy to maintain.

Having a readonly interface is useful, as these methods are presumably pure, which simplifies caching and other aspects.  It also means one can ensure that writes do not happen unintentionally.  However, for a writeable interface, being also to read also doesn't really matter- the readonly interface doesn't have side-effects.

There is the rather weird method List<T>.AsReadOnly in the .NET framework, as MS didn't consider readonly in the first place.

Body:
I would suggest that you specify a read-only interface style, such as:

interface IReadOnlySpatialTree
{
}

and then the writeable interface extends this with its name only, ie.:

interface ISpatialTree : IReadOnlySpatialTree
{
}

You will rarely use a writeable interface without also needing the readonly part.  If you're not careful you'll end up with at least 3 interfaces for every type (readonly/ writeonly and readwrite), which isn't particularly useful and is a waste of energy to maintain.

Having a readonly interface is useful, as these methods are presumably pure, which simplifies caching and other aspects.  It also means one can ensure that writes do not happen unintentionally.  However, for a writeable interface, being also to read also doesn't really matter- the readonly interface doesn't have side-effects.

There is the rather weird method List<T>.AsReadOnly in the .NET framework, as MS didn't consider readonly in the first place.


答:
Writer and Mutator are a bad choice because they imply mutating something else. If you change the object itself, the proper forms are Writable and Mutable.

If you have a readonly interface but the underlying object can be changed through another interface, that object isn't immutable. This implies that mutability vs. immutability is not the distinction you want to make here.

So only ReadOnly, ReadWrite or Writable remain. Since you don't have WriteOnly access at all you don't need to distinguish ReadWrite from WriteOnly. ReadWrite isn't a proper word, so I'd rather go with the simpler Writable.

Following the convention of the existing collections in .NET, the appropriate choices would be IReadOnlySpatialTree and ISpatialTree, where the latter is writable.

If most of your code is only reading and write access is the exception, you could deviate from this convention and use ISpacialTree as the readonly interface and IWritableSpacialTree as the writable interface.

Title: c# naming - What are common conventions for a suffix to distinguish between read-only and writable interfaces

Body:
Assume an interface that allows queries on a spatial tree

```<code>public ISpatialTree
{
    int FindChildIndex(Vector point);
    bool IsLeaf { get; }
    ICollection<ISpatialTree> Children { get; }
}
</code>```

and another one that allows changing the tree:

```<code>public ISpatialTreeWriter : ISpatialTree
{
    void Add(Vector point);
    bool Remove(Vector point);
    void Clear();
}
</code>```

I am looking for a name to denote the writeable interface. Ideally it would be reasonably short and readable word. It's not only for this example, but I would like to use a convention for all code in the project because this is a common case.

Does anyone know of a good convention for this problem? What conventions are used in other projects?

Words that were discussed include Writer (ambiguous, often used in other contexts), Mutator (confusing), Rw (unreadable, not a word).

A good solution would be a single word, not longer than 6-8 letters and that makes it obvious that this is the writer interface.


问:
How exactly to use the MVC design pattern
I have read the documentation on the apple's developer website which refer following guidelines

A view class shouldn't depend on a model class (although this may be unavoidable with some custom views).

A view class shouldn't have to depend on a mediating controller class.

A model class shouldn't depend on anything other than other model classes.

A mediating controller class shouldn’t depend on a model class (although, like views, this may be necessary if it's a custom controller class).

A mediating controller class shouldn't depend on view classes or on coordinating controller classes.

A coordinating controller class depends on classes of all MVC role types.

Consider this scenario:

I have a view controller class called EmployeeViewController.
I have some minor components of which are some are programmatically created and some are created through xib.

What exactly I am doing is creating all the subviews inside the EmployeeViewController class and adding them to the EmployeeViewController's view, e.g. [self.view addSubView:…]

Is it a better option for me to create a seperate UIView Subclass which consists of all the components and initialize it once and add it in the EmployeeViewController?

What exactly is the correct way to implement MVC? Am I supposed to create separate components for view and controller or should I stack subviews inside the EmployeeViewController?

答:
The basic concept of MVC is to decouple the components (i.e. the model, view and controller).

The advantages of this approach are: less dependencies between the components; more flexibility; and when the design of your application changes, you only need to change the code in one location, not multiple.

For example, in Struts, all the configuration will be written in struts.xml
and mapping will be done in such a way that for every action there will be a result (JSP defined).

If you want to change the design or flow, you only have to change struts.xml.


问:
Lexer/Parser for multidimensional Languages
How does Lexer/Parser work in a 2D programming language like Funciton in order to transform such an unusual source-code to the correct AST?

答:
Layout sensitive languages are an unusual occurrence because they are a bit more difficult to parse. A token produced by a lexer will not only contain a type and a value, but also a position and maybe a size. It is possible that the lexer will not proceed linearly line by line, but will first read the whole file into memory and then traverse it as a 2D map.

Layout-sensitive parsing or indentation-sensitive parsing is a small but still active field of research; investigating these terms will provide you with a number of papers. In easy cases like Python, we can use a stateful lexer that hides the indentation from a parser, and instead emits phantom tokens like INDENT and DEDENT which would be the equivalent to curly braces in C. In more complex cases, we need to annotate the parser's grammar with requirements on the indentation, e.g. the enhanced context free grammar

```<code>DoExpression{n} ::= "do"{n} DoExpressionInner{m: m > n}
DoExpressionInner{n} ::= Expression{n}+
</code>```

might allow

```<code>do expr1
   expr2
   expr3
</code>```

but not

```<code>do expr1
     expr2
expr3
</code>```

In the above grammar, the expression in curly braces puts a condition on the position of the left edge of the rule or token. Most parser generators do not support such layout parsing.

In the most general case, a lexer would have to recognize shapes in the textual input. A parser would then likely use bottom-up techniques to group the primitive shapes into a usable data structure, likely a non-hierarchical graph. For example, the image

```<code>  012345678901234567890123456789
0 +---+
1 | A |-----------.
2 +---+           |        +---+
3                 '------->| B |
4                          +---+
</code>```

could be lexed as:

```<code>BOX "A" at ( 0, 0) to ( 4, 2)
BOX "B" at (25, 2) to (29, 4)
ARROW   at ( 5, 1) to (24, 3)
</code>```

These tokens could then be stored in a manner supporting spatial lookup. Starting with the A box, we can look at the surrounding fields and will find the start of the arrow. At the end of the arrow, we find the B box and can therefore add this connection between A and B to the Abstract Syntax Graph. After that, the arrow can be removed from the set of unused tokens. As no other tokens are in the A  box's immediate neighborhood, it too can be removed, ditto for B. As the set of uninspected tokens is empty, the parse has succeeded.

Parsing Funciton is easier than parsing such ASCII art, as the used symbols directly show connections. It might therefore be possible to parse the source in a single pass: once any element is found, we can follow the connections and add the appropriate connections to our Abstract Syntax Graph.

Most languages that use graphs to represent data or a program do not use a 2D textual representations. Instead, they will provide IDEs that represent render the structure as a graph, but store it as a more easily processed form. Likely, the connections would be stored by IDs rather than by spatial locations, although the layout would be part of the stored information. LabView is probably one of the best-known visual programming languages that use graphs to represent control/data flow, but do not offer a textual representation of the program.

Body:
Layout sensitive languages are an unusual occurrence because they are a bit more difficult to parse. A token produced by a lexer will not only contain a type and a value, but also a position and maybe a size. It is possible that the lexer will not proceed linearly line by line, but will first read the whole file into memory and then traverse it as a 2D map.

Layout-sensitive parsing or indentation-sensitive parsing is a small but still active field of research; investigating these terms will provide you with a number of papers. In easy cases like Python, we can use a stateful lexer that hides the indentation from a parser, and instead emits phantom tokens like INDENT and DEDENT which would be the equivalent to curly braces in C. In more complex cases, we need to annotate the parser's grammar with requirements on the indentation, e.g. the enhanced context free grammar

DoExpression{n} ::= "do"{n} DoExpressionInner{m: m > n}
DoExpressionInner{n} ::= Expression{n}+

might allow

do expr1
   expr2
   expr3

but not

do expr1
     expr2
expr3

In the above grammar, the expression in curly braces puts a condition on the position of the left edge of the rule or token. Most parser generators do not support such layout parsing.

In the most general case, a lexer would have to recognize shapes in the textual input. A parser would then likely use bottom-up techniques to group the primitive shapes into a usable data structure, likely a non-hierarchical graph. For example, the image

  012345678901234567890123456789
0 +---+
1 | A |-----------.
2 +---+           |        +---+
3                 '------->| B |
4                          +---+

could be lexed as:

BOX "A" at ( 0, 0) to ( 4, 2)
BOX "B" at (25, 2) to (29, 4)
ARROW   at ( 5, 1) to (24, 3)

These tokens could then be stored in a manner supporting spatial lookup. Starting with the A box, we can look at the surrounding fields and will find the start of the arrow. At the end of the arrow, we find the B box and can therefore add this connection between A and B to the Abstract Syntax Graph. After that, the arrow can be removed from the set of unused tokens. As no other tokens are in the A  box's immediate neighborhood, it too can be removed, ditto for B. As the set of uninspected tokens is empty, the parse has succeeded.

Parsing Funciton is easier than parsing such ASCII art, as the used symbols directly show connections. It might therefore be possible to parse the source in a single pass: once any element is found, we can follow the connections and add the appropriate connections to our Abstract Syntax Graph.

Most languages that use graphs to represent data or a program do not use a 2D textual representations. Instead, they will provide IDEs that represent render the structure as a graph, but store it as a more easily processed form. Likely, the connections would be stored by IDs rather than by spatial locations, although the layout would be part of the stored information. LabView is probably one of the best-known visual programming languages that use graphs to represent control/data flow, but do not offer a textual representation of the program.


问:
Release management with Azure and Visual Studio Online (Cloud TFS)
What strategy would you use to manage the releasing of versioned software to Azure cloud services (web and worker roles)?  We are not looking for continuous integration.  We are using Visual Studio 2013 and Visual Studio Online (Cloud TFS).

At one point, we were releasing straight from Visual Studio using the Azure Cloud Project Publish tool.  This is really bad practice in my opinion as you can never be sure what you are really releasing.  Additionally, there is no automated control on the labeling or branching of code, or the running of unit tests and code analysis checks.

Next, we employed Release builds on Visual Studio Online.  Before deployment, one would edit the appropriate Build Definition (whether it be for Test or Production by and filling in the code label (under the "Get Version" build property) that is to be released.  This would then get the appropriate code (by the label specified), build it, and release it to whatever cloud service is specified in the targeted Cloud Project profile (this is using the AzureContinuousDeployment.11.xaml template).

There is still a degree of manual intervention involved.  Also, the fact that a version of code is built every time before it is released is not ideal (as far as I understand it would be better if it was packaged once).

Microsoft Release Management tools look ideal for the job, but are not supported with Visual Studio Online.

Is there a better way of handling our releases?

答:
/waves hand.. These are not the tools you seek. You are looking for continuous integration.

Although CI has the word continuous in there, it does not mean "all the time, every checkin". It can easily refer only to those bits you want to release - -and the way to tell the system which bits you want released is to merge them to a Releases branch.

If you do this, not only do you get all the joy of controlled CI, but you guarantee what you release is exactly what is controlled in your SCM - under the Releases branch, preferably tagged or otherwise noted as a particular release. That means you can also rollback to a previous release by simply reverting to a previous release in your SCM!

Of course you don't have to let it happen automatically, you can set it up to build 'continually' and then remove the check on the SCM to see if any changes have been committed. You can replace this with the manual build button.


答:
Yes, you can use the revision number to uniquely identify a snapshot in time.

But... where do you record which revnum matches which release? Will you keep a spreadsheet that says "release 4.2.1" is Revnum 18345? Not recommended.

However, creating a Tag 'branch' does exactly this without the need for spreadsheets or external tooling - if you remember a branch in SVN is just a copy of the repository state (like a symlink) then you realise that a Tag is not much more than a pointer to the revision you want to remember. You get all the benefit of a snapshot in time, but with the advantage of being able to name it something meaningful.

You also get other benefits, as its a branch, you can make patch fixes to it. Code made to trunk can be merged into it when necessary. You can create a new branch from that branch so you can make a forked product if you need to. You can switch your working copy to the Tagged release with a single command. All of this can also be done by recording the revnum, but its much easier to use a Tag, and as it doesn't cost anything you might as well go with the easy option.


答:
It seems you are:

Trying stuff out to find the best approach (experimenting, incremental design)

Rewriting code to get it cleaner (refactoring)

Constantly writing tests (test driven development)

What you are doing is awesome! It looks like you are doing it perfectly right, especially if you've figured it out by yourself and not learned it from an (agile) programming book. There is obviously more to this but you've got the values nailed. Just remember to refactor and improve the design while you are adding code and there should be no need for a BDUF.

Have you considered focusing on one small feature at a time, and release after each feature is completed? That might help you get unstuck from any analysis problem you are struggling with and demonstrates real progress to you employer.

Also, I don't know what "professional development community" you are talking about, but if were you, I'd tell them to go back to their ivory towers so you can get on with your work!

Title: What's so bad about creative coding?

Body:
I was watching Bob Ross paint some "happy trees" tonight, and I've figured out what's been stressing me out about my code lately.

The community of folks here and on Stack Overflow seem to reject any whiff of imperfection.  My goal is to write respectable (and therefore maintainable and functioning) code, by improving my skills.  Yet, I code creatively.

Let me explain what I mean by "coding creatively":

My first steps in a project are often to sit down and bash out some code.  For bigger things, I plan a bit out here and there, but mostly I just dive in.

I don't diagram any of my classes, unless I'm working with others who are creating other pieces in the project.  Even then, it certainly isn't the first thing I do.  I don't typically work on huge projects, and I don't find the visual very useful.

The first round of code I write will get rewritten many, many times as I test, simplify, redo, and transform the original hack into something reusable, logical, and efficient.

During this process, I am always cleaning.  I remove unused code, and comment anything that isn't obvious.  I test constantly.

My process seems to go against the grain of what is acceptable in the professional developer community, and I would like to understand why.

I know that most of the griping about bad code is that someone got stuck with a former employee's mess, and it cost a lot of time and money to fix.  That I understand.  What I don't understand is how my process is wrong, given that the end result is similar to what you would get with planning everything from the start.  (Or at least, that's what I have found.)

My anxiety over the issue has been so bad lately that I have stopped coding until I know everything there is about every method for solving the particular problem I am working on.  In other words, I have mostly stopped coding altogether.

I sincerely appreciate your input, no matter what your opinions are on the issue.

Edit:  Thank you all for your answers.  I have learned something from each of them.  You have all been most helpful.


问:
What is the relationship between data structures and algorithms?
I have been searching for a good online course in data structures but have found that Google also returns results for algorithms courses, which say stuff like:

In this course you will learn several fundamental principles of
  algorithm design: divide-and-conquer methods, graph algorithms,
  practical data structures (heaps, hash tables, search trees),
  randomized algorithms, and more. [source]

and

By the end of this class you will understand key concepts needed to
  devise new algorithms for graphs and other important data structures
  and to evaluate the efficiency of these algorithms. [source]

and

This course provides an introduction to mathematical modeling of
  computational problems. It covers the common algorithms, algorithmic
  paradigms, and data structures used to solve these problems. [source]

My question is: are algorithms and data structures intimately linked, meaning that they must be understood together or is one topic more foundational than the other?

EDIT: For those voting to close this question, can you please tell me why and maybe how to improve this one? Learning to ask the right questions is part of the educational process.

答:
All sorts of mixtures do exist. You have data structures, which are not associated with algorithms, algorithms, which require no (real) data structures, but most often the two come in one package.

Edit: as @Doval correctly pointed out, data structures per se do not have any operations associated with them. The act of combining data structure and algorithm forms an abstract data type.

Data structures without algorithms

Consider for example a data structure for storing 2-dimensional coordinates, appropriately called Point. There is nothing much in terms of algorithms to be done for a point and it really is just a container for an x and y value. Of course, giving this data structure, you can now add all sorts of algorithms on top of it (distance calculation, convex hulls, what-have-you).

You can think of a lot of data structures, which are simply an accumulation of individual data. While these do occur frequently in practice, they do not make for good teaching material, because there is nothing to be learned from it, once you have understood, that single data items can be accumulated into a new data structure (like what do you learn after the above Point example, if I provide you with that awesome data structure called Point3D, which can do the same thing for 3-dimensional space?)

Algorithms without (real) data structures

"Real", because obviously every interesting algorithm needs primitive data types like integers or booleans, and we do not want to consider those as data structures in this context. Similarly to above, these algorithms are typically rather simple ones. In particular, they do not come with a complicated state of any sort, because that usually goes into a data structure (see next section).

An example for such an algorithm would be calculating the greatest common divisor of two numbers. Euklid's algorithms for the gcd really only needs to hold two integers and manipulates them.

Once things start to get more interesting, you very soon enter the world of abstract data types though. For example, the sieve of Eratosthenes is based on an array. We could have a discussion now, whether an array is still primitive, or in fact, you could discuss if an integer isn't already a data structure. Either way, algorithms that exist completely without data structures are rather boring, even if you accept their isolated existence.

Algorithms combined with data structures, aka abstract data types

Now these are the interesting ones, but for two very different reasons. Typically, you can approach these from two directions: data structure first, or algorithm first.

While an abstract data type is defined by the combination of data structure + algorithms/operations, we often view them with a focus on either one of those and consider the other one as enablers.

Data structure, then algorithm

You will encounter abstract data types, which are rather simple to use, but involve more or less complicated algorithms to make them work internally. For example, a HashMap is trivial to use, but involves a nifty hash function and dealing with the hash collisions on the inside. Yet, from your point of view as a user you care about it as something that holds data for you, not something that does something for you.

In contrast to the last group below, these data structures do not expose their users to these algorithms. You do not need to know, nor care, about a HashMaps internal hash function in order to be able to use it. (To use it effectively though, you may want to know these things ;)

Algorithm, then data structure

The other direction means you have an algorithm, which you want to be able to simply use, but which needs data structures internally to make it work as intended. An example would be a binary space partitioning (BSP) algorithm, that you can simply ask for the 2-dimensional Point from a large set of points that is closest to a given query point. However, you need a tree structure (and even additional algorithms like distance calculations) on the inside to actually write the algorithm.

In general, one can say that algorithms in this group use involved data structures for their internal state representation. I would argue, that this group of algorithms is the most diverse and you will find many many different ones that fit this general scheme. Regarding the point of view, we see these as interesting, because they do something (f.ex. sorting) for us, and do not care as much about the data holding part.

Closely related data structures and algorithms

Finally, you have data structures, which are very close related to algorithms that directly correspond with them. A typical example is a binary tree, which, when you want to do anything meaningful with it, forces the topic of tree-walking algorithms on you (depth-first, breadth-first, whatever).

For these cases, we change the focus of our view of the resulting abstract data types every so often. Sometimes you care about the structure of your tree, a few minutes later you care about being able to run a find operation on it, then you wonder about deleting a node, and right-away about how the structure looks afterwards. While all of this holds true for the other sections above as well, it is not something that is the primary focus in your mind, for example, when you store/retrieve data to/from a Map, or when you sort a linked list.


答:
Data structures often influence the details of an algorithm. Because of this the two often go hand in hand.

Consider for example an algorithm for cutting your lawn. How you go about cutting your lawn is likely to be influenced by the actual structure of your lawn. If you live in a small house in a densely packed suburb and your lawn is just a small rectangle a few meters squared in area, you would probably prefer to cut your lawn with a push-mower instead of a tractor/riding mower. If your lawn involves many acres of flat meadow land, your preference may be for the riding mower as opposed to the push-mower (though either mower may eventually get the job done). If your lawn involves acres of land with large flat areas, but a few small hills and a number of trees, you may develop a more interesting algorithm for cutting the lawn that involves both a riding mower and a push-mower, or some other grass cutting techniques.

Ultimately though, the structure of your data may have a significant impact on your decisions for how to develop your algorithm (or which algorithms to use). For this reason, the two topics often go hand in hand.

And vice versa: sometimes the algorithm we want to use influences (at least at the onset of computing) the data structures you develop to support the algorithm. For example going from an array list to the idea of a linked list and eventually to a BST for storing an ordered list that will allow for quick find.

Title: What is the relationship between data structures and algorithms?

Body:
I have been searching for a good online course in data structures but have found that Google also returns results for algorithms courses, which say stuff like:

In this course you will learn several fundamental principles of
  algorithm design: divide-and-conquer methods, graph algorithms,
  practical data structures (heaps, hash tables, search trees),
  randomized algorithms, and more. [source]

and

By the end of this class you will understand key concepts needed to
  devise new algorithms for graphs and other important data structures
  and to evaluate the efficiency of these algorithms. [source]

and

This course provides an introduction to mathematical modeling of
  computational problems. It covers the common algorithms, algorithmic
  paradigms, and data structures used to solve these problems. [source]

My question is: are algorithms and data structures intimately linked, meaning that they must be understood together or is one topic more foundational than the other?

EDIT: For those voting to close this question, can you please tell me why and maybe how to improve this one? Learning to ask the right questions is part of the educational process.


答: Another reason to use tags instead of revision numbers to track what you released is it's easier to keep links/references to tags than to revisions of trunk (or branches). References to particular paths at some old revision can break if you reorganize your trunk (or branch) folder layout in the future. Tags don't change (by convention), so they don't have that problem.</p>


问:
What was the worst piece of code you fixed that you are proud of?
I have had a few that I am proud of and some of them were written by myself few years ago. It doesn't have to be necessarily buggy, just bad code. </p>

答: My first programming job was writing installers in InstallShield. I inherited a script that was thousands lines with no functions, only gotos. It was mind boggling. I rewrote it, made it all pretty and modular and data driven, so that I could be given binaries/art/etc. and turn out a new installer in under an hour, rather than the week+ it took the previous guy. I was very proud of myself.


问:
Go-like interfaces + multi-methods make sense?
Thinking about the design of a potential new language, I wonder how related are the concepts of built a OO similar to GO interfaces and multi-methods (I get this from http://docs.julialang.org/en/latest/manual/methods/).

If I understand this right, the interfaces are simply a group of methods that must be implemented by each descendant, and multi-methods provide a nice way to specialize them without do a lot of boilerplate or casting.

However, Is my intuition that both could work well together, but wonder if is correct. For example, if a interface declare:

```<code>type Animal interface {
    Speak() string
}

func (d Dog) Speak() string {
    return "Woof!"
}
</code>```

but in julia is more like:

```<code>speak(x::Dog) = return "Woof!";
</code>```

So this feel like that both do the same, but different. Will be a mess to do both? When could that make sense?

Also, what make a "better" path, if only one must be used?

答:
I really want to encourage you to do this. It sounds interesting and maybe new (I did not research).

I can tell you two reasons why:

Go-like interfaces over Java-like interfaces?

Suppose I create a new interface for all object that can "read". Objects of the standard library comply to it. But in Java, this interface has to be know to the standard library. Two equal interfaces can be equal but not the same. To comply to an others interface you need to adapt the code of the standard library. This may be hindering if you have a very decentralized development process. Example

Multimethods with Interfaces

An interface is not a type. You will get troubles (good troubles) with identity.

```<code>Interface Dog {bark()};
Interface Wolf {bark(); pack()};

multimethod a(Dog);
multimethod a(Wolf);

// calling a
a(aWolf) // a wolf has the same ablilities as a dog. Which method to choose?
</code>```

I would like to see a solution that is understandable.

Body:
I really want to encourage you to do this. It sounds interesting and maybe new (I did not research).

I can tell you two reasons why:

Go-like interfaces over Java-like interfaces?

Suppose I create a new interface for all object that can "read". Objects of the standard library comply to it. But in Java, this interface has to be know to the standard library. Two equal interfaces can be equal but not the same. To comply to an others interface you need to adapt the code of the standard library. This may be hindering if you have a very decentralized development process. Example

Multimethods with Interfaces

An interface is not a type. You will get troubles (good troubles) with identity.

Interface Dog {bark()};
Interface Wolf {bark(); pack()};

multimethod a(Dog);
multimethod a(Wolf);

// calling a
a(aWolf) // a wolf has the same ablilities as a dog. Which method to choose?

I would like to see a solution that is understandable.


问:
Why can't a server continue to act on a request after sending the response?
Say for example I've got a RESTful webservice, and I need to support creating a widget via a POSTed http request. I need to

Deserialize the POSTed widget.

Validate the deserialized widget.

Persist the widget to a backing service.

Send a success response back to the client.

Now, the problem is that my SLA does not allow 3 to block 4--persistence in this case takes too long and the client needs to know right away that the request has succeeded (this is the standard use case for the 202 http status code).

Almost everywhere I look, the assumption is that the way to solve this is to "background" the expensive persistence part. This is typically an awkward process with many moving parts and often its own latency (e.g. making a blocking call to a separate queuing service).

Simply parallelizing 3 and 4 using native constructs is generally out of the question, as is switching the order so that 4 blocks 3. As near as I can tell, this is mainly because the web and app servers are built with the fundamental assumption that a process (and any children it's forked off) is free to be killed/reused as soon as it's sent its response. Or, equivalently, that the response can't be sent until the app has finished doing everything it's going to do.

This is intensely frustrating to me! In any other context, I can do what I like with the program's control flow. But when I'm running a Phusion Passenger -> Ruby on Rails setup, and I want to do a thing after I send the response, I'm left with a wide variety of baroque options that all seem to consider it perfectly natural and acceptable to, say, serialize the application state, post it to Amazon SQS, have basically separate web service that polls SQS, deserializes the old application state, then do the thing. I had application state all set up the way I wanted it after sending the response! Why isn't anything written so I can just do

```<code>def create
  widget = Widget.new(params[:widget])
  if widget.valid?
    respond_with(widget)
    widget.save
  else
    respond_with(widget.errors)
  end
end
</code>```

Why is there a pervasive assumption that web service stacks will never support this kind of flow? Is there a hidden drawback, or tradeoff, to making it possible to do this?

答:
I think you need something similar to JMS (but in Ruby or whatever you are using, the question was not completely clear).

The idea here is that your front-end web service can quickly pass a message off to another service that says "persist this data." That service will save the message to a persistent queue and return immediately. The web service can return right away without chewing up more server resources.

Then, in the background, a queue processor picks up messages in the queue and dispatches them. In this case, it would dispatch to a persistence service which would take the the raw message and take whatever steps are necessary to save it to its destination.

The difference between saving to a queue and saving to your application's database is this. The queue might use JSON or XML or another interchange format, and it does not care much about the payload. It cares about what service or services need the message and when it was put in the queue. Your persistence service gets the message and cracks open the payload to do whatever domain-specific processing is necessary.


问:
How to unit test without mocks and not be tied to a concrete implementations of an interface
I consider myself to be a 'mockist' on the 'mockist' vs 'classicist' debate, but I am trying to understand the other point of view.

Imagine I have this class, where a concrete instance of IDependency is injected by an IoC container.

IDependency does not access a remote resource like a database or web service (in which case I would definately mock it), it is just another class containing some business logic.

```<code>public class UnitUnderTest
{
    public UnitUnderTest ( IDependency dependency )
    {
    }
}
</code>```

Using this pattern, I am free to change the concrete implementation of IDependency by changing the class injected by the IoC container. I am not tied to any particular implementation.

If I was to test this class without mocking IDependency, wouldn't I have to instantiate my real IDependency to pass in to the constructor?

```<code>public class My_Unit_Test()
{
    IDependency concreteDependency = new ConcreteDependency();
    var unitUnderTest = new UnitUnderTest(concreteDependency);
}
</code>```

In this example, if I write a replacement to ConcreteDependency, I would have to not only change my IoC container configuration, but all of my unit tests that use ConcreteDependency.

Or.. do I use the same IoC container within my unit tests (which seems like it goes against the idea of testing things in isolation)?

答:
You only need an IoC container if you want to centralize your dependency declarations.  For everything else, there's ordinary constructor injection.

To put it another way, you don't need an IoC container in your unit tests.  You're not testing the IoC container, after all.

To put it still another way, if you're stitching together a bunch of mock dependencies in your unit tests using an IoC container, they're no longer unit tests; they're integration tests (mock integration tests, if there is such a thing).


答:
If I was to test this class without mocking IDependency, wouldn't I have to instantiate my real IDependency to pass in to the constructor?

No, you could create a fake IDependency for your specific needs. You may even make your "real" IDependency but parameterize it specifically to your needs. Though depending on who you talk to, these are considered mock objects since they're not used in production.

This is the common argument against mocking everything: you already have objects to do this stuff that are robust, flexible and trustworthy. You don't mock IList in your tests because List is a dependency do you?

Like most arguments, the best approach is often a balance of the two.

In this example, if I write a replacement to ConcreteDependency, I would have to not only change my IoC container configuration, but all of my unit tests that use ConcreteDependency.

Yes, just like you'd have to change all of your mocks should you replace your mock objects.

How to unit test without mocks and not be tied to a concrete implementations of an interface

You literally can not.

You need to create a concrete implementation of that interface somewhere. You could share that instance between tests, but that is against best practice (tests are not isolated). You could have a factory to generate the object, but then you have added complexity and it's uncommon that a single type of instance can be used for every test. But in the end, the test needs a concrete implementation to work, no matter how much indirection you put between the test and the thing.

Body:
I consider myself to be a 'mockist' on the 'mockist' vs 'classicist' debate, but I am trying to understand the other point of view.

Imagine I have this class, where a concrete instance of IDependency is injected by an IoC container.

IDependency does not access a remote resource like a database or web service (in which case I would definately mock it), it is just another class containing some business logic.

```<code>public class UnitUnderTest
{
    public UnitUnderTest ( IDependency dependency )
    {
    }
}
</code>```

Using this pattern, I am free to change the concrete implementation of IDependency by changing the class injected by the IoC container. I am not tied to any particular implementation.

If I was to test this class without mocking IDependency, wouldn't I have to instantiate my real IDependency to pass in to the constructor?

```<code>public class My_Unit_Test()
{
    IDependency concreteDependency = new ConcreteDependency();
    var unitUnderTest = new UnitUnderTest(concreteDependency);
}
</code>```

In this example, if I write a replacement to ConcreteDependency, I would have to not only change my IoC container configuration, but all of my unit tests that use ConcreteDependency.

Or.. do I use the same IoC container within my unit tests (which seems like it goes against the idea of testing things in isolation)?


问:
Merging around 15 small Git repos of non-optional centralized web service components to a single large repo
In a centralized web service we break down the components into various small Git repos by software modules, e.g. authentication module, authorization module, data access module etc. (around 15 repos at the moment)

The good thing is it is easy to manage the smaller code base, however, our productivity has decreased a lot since quite a lot of changes need to be update several repos at once.

Also, deployment is more difficult as there are multiple versions of module involved, we always need to think about the dependency.

I am considering to merge all the modules back to a single repo, because

our services must require all the modules to exists, they are not optional for our service

we are not a big team (3 people actually) and the overhead in maintaining too many repos does not worth it, they all need to have knowledge on all the code bases

What do you think? Any pros and cons if we merge into a giant repo?

答:
This really depends on the modules. You are saying the service require all the modules to exist - but do the modules require the service(or other modules) to exist?

If you have a module that's an integral part of the project, but you have it as it's own module for organization reasons(example - models, views and controllers modules in MVC architecture), then it's a good idea to have them in same repository as the main project, because chances are they'll be updated together.

On the other hand, if you have a module that acts more like a library, and you could easily work on it as a standalone module and use it's functionality in other projects, it's better to keep it in it's own repository.

With 15 modules it's a safe bet that you have both kinds. You don't have to convert everything to a single repository. Maybe the main repository will consist of 10 modules, and another module will have it's own repository because it's a standalone library, and the other 4 modules are also a library, but need to be together to make sense so you put them all in a third repository. Of course, the distribution should not be arbitrary - it should be based on the logical coupling between the modules(not the current coupling - the one you think is the right design) - but at any rate you'll probably get a lower, more maintainable amount of modules.

Also, if you are having trouble keeping track of all the modules, you should consider using Git Submodules. Submodules allow you to keep the correct version of modules that reside in other repository, and you can commit and push directly from the submodule(be careful with this!). This should make working with many modules easier.


问:
How can we use Tine 2.0 in our closed source software product, without violating the AGPL?
We develop a closed source product and customers want to add two parts:

Calendar

Contacts

Tine 2.0 would provide this, but we want to use it as a library.

Since Tine 2.0 uses the AGPL licence, we need to open source our code, if we would use some kind of linking.

How can we use Tine 2.0 in our closed source software product, without violating the AGPL?

The solution I have in mind is this: Our product and Tine 2.0 could communicate over the database. All HTML views get done by our code, and mobile sync stuff gets handled by tine20.

(I would like to open source our product, but my boss does not).

答:
You will need to talk to a lawyer to get a detailed legal opinion on the letter of the law.

That said, using AGPL or GPL code in a closed source application goes against the spirit (if not the letter) of the GPL.  The intent is that if you build something that substantially depends on GPL code your code is a derived work and must be distributed under the GPL.

Given that there is a commercial entity behind Tine 2.0 I think they will take narrow view of how it can be integrated with a closed source product. So be prepared for your interpretation to be challenged by them.


问:
How to present domain model exceptions thrown through validation
In domain model of my web application I've an entity Foo which can be created only by a pojo FooBean: Foo.newInstance(FooBean fooBean) (Might have been better a Builder-pattern.)

In the factory methode newInstance() the pojo FooBean is validated and throws NullPointerExceptions and IllegalArgumentExceptions if needed. The fields of the pojo are filled by a form on the presentation layer. That form does some validation on the user input and shows user friendly messages if needed.

The exception message of the NullPointerExceptions and IllegalArgumentExceptions thrown in the newInstance() method are rather technical and shouldn't be displayed to the end user.

What is a proper way to show user friendly error messages that are originated by the NullPointerException or the IllegalArgumentException?

答:
Be specific, throw early, and catch late.

I think you are missing both the "be specific" as well as the "catch" parts.

You should be throwing descriptive exceptions and handling them as appropriate, where appropriate.


问:
Why do we must declare a public API when using semantic versionning?
from semver.org:

Software using Semantic Versioning MUST declare a public API. This API could be declared in the code itself or exist strictly in documentation. However it is done, it should be precise and comprehensive.

Why are we forced to declare a public API? Why can't I use it for my own website that has no API?

Perhaps I am wrong with the definition. For me it is a part of the site desigedn for other developers (i.e.: api.example.com) that allow them to query my website and get the result into structured data (json, xml...).

答:
It requires a public API in order to effectively apply it's versioning pattern.

For example:

Bug fixes not affecting the API increment the patch version

Backwards compatible API additions/changes increment the minor version, and...

Backwards incompatible API changes increment the major version.

What represents your API is subjective, as they even state in the SemVer doc:

This may consist of documentation or be enforced by the code itself.

I think that is where your misunderstanding is.  An API is not necessarily...

a part of the site designed for other developers that allow them to query my website and get the result into structured data

It could be that.  Who knows. It could also be a set of documented UX rules.

If you can't effectively outline what your website's API is, then maybe SemVer isn't appropriate.


问:
When one thread out of four is executing first line in run() then at the same time what will remaining three threads do?
I have four thread instances and they are executing run() code given below:

```<code>public void run (){
   System.out.println("1st line :"+Thread.CurrentThread().getName());
   System.out.println("2nd line :"+Thread.CurrentThread().getName());
   System.out.println("3rd line :"+Thread.CurrentThread().getName());
   System.out.println("4th line :"+Thread.CurrentThread().getName());
   System.out.println("5th line :"+Thread.CurrentThread().getName());
   System.out.println("6th line :"+Thread.CurrentThread().getName());
}
</code>```

When one thread out of four is executing first line then at the same time what will remaining three threads do?

Either they are waiting for executing first line or will they proceed other lines of code?

答:
Since all the threads run the same method, they'll all print all the lines.

This is like calling run() 4 times, except that instead of waiting for one call to finish before starting the next all the calls are executed at the same time. The order is different, but all the lines are still executed 4 times.

If you want to execute run() only once but in 4 different threads, you'll need to use more complex methods and inevitably restructure it into multiple methods.


问:
Using 2 Constructors: one that injects dependencies and one that instantiates them
I started using TDD for the first time on a project I started recently.

I have a few objects with dependencies and structures that look something like this:

```<code>public class MyClass
{
    private readonly IDependency1 _dependency1;
    private readonly IDependency2 _dependency2;

    public MyClass(IDependency1 d1, IDependency2 d2)
    {
        _dependency1 = d1;
        _dependency2 = d2;
    }

    public MyClass()
    {
        _dependency1 = new Dependency1();
        _dependency2 = new Dependency2();
    }
}
</code>```

For tests I use Mock objects for the dependencies but in the implementation I sometimes let the constructor new up a concrete object.

It feels like I am cheating by doing this but I'm not sure why it is bad in practice.

Is this considered bad practice? If so why?

答:
First, it's better to chain constructors, so that you're using only one piece of code.

```<code>public MyClass() : this(new Dependency1(), new Dependency2()) { }
</code>```

This is much more maintainable over time, specifically if you ever want to do something else in both constructors.

As to whether this is good practice ... it's not the best practice, but it's perfectly acceptable, when you can't or don't want to use Dependency Injection. It's particularly useful when you're adding tests to a new module in legacy code and want to avoid reengineering the entire project.

And when I say Dependency Injection, I don't necessarily mean an IOC container or service locator. I mean that if you CAN pass the dependencies from the calling code to the constructor then do so, even if it means a little more code.

Much better to decouple your implementation from the calling code as much as possible. You might want to reuse it later with an entirely different implementation.

For more information, look at the Dependency Inversion Principle.

Body:
First, it's better to chain constructors, so that you're using only one piece of code.

public MyClass() : this(new Dependency1(), new Dependency2()) { }

This is much more maintainable over time, specifically if you ever want to do something else in both constructors.

As to whether this is good practice ... it's not the best practice, but it's perfectly acceptable, when you can't or don't want to use Dependency Injection. It's particularly useful when you're adding tests to a new module in legacy code and want to avoid reengineering the entire project.

And when I say Dependency Injection, I don't necessarily mean an IOC container or service locator. I mean that if you CAN pass the dependencies from the calling code to the constructor then do so, even if it means a little more code.

Much better to decouple your implementation from the calling code as much as possible. You might want to reuse it later with an entirely different implementation.

For more information, look at the Dependency Inversion Principle.


答:
Your second constructor should call the first one. Otherwise it looks fine for me.

```<code>public MyClass() : this(new Dependency1(), new Dependency2())
{
    // should be empty here
}
</code>```

In the test suite

test MyClass works with mock objects (with constructor MyClass(IDependency1, IDependency2))

test default constructor MyClass() call MyClass(IDependency1, IDependency2) with correct concrete type

and you are good to go

Title: Using 2 Constructors: one that injects dependencies and one that instantiates them

Body:
I started using TDD for the first time on a project I started recently.

I have a few objects with dependencies and structures that look something like this:

```<code>public class MyClass
{
    private readonly IDependency1 _dependency1;
    private readonly IDependency2 _dependency2;

    public MyClass(IDependency1 d1, IDependency2 d2)
    {
        _dependency1 = d1;
        _dependency2 = d2;
    }

    public MyClass()
    {
        _dependency1 = new Dependency1();
        _dependency2 = new Dependency2();
    }
}
</code>```

For tests I use Mock objects for the dependencies but in the implementation I sometimes let the constructor new up a concrete object.

It feels like I am cheating by doing this but I'm not sure why it is bad in practice.

Is this considered bad practice? If so why?

Body:
Your second constructor should call the first one. Otherwise it looks fine for me.

public MyClass() : this(new Dependency1(), new Dependency2())
{
    // should be empty here
}

In the test suite

test MyClass works with mock objects (with constructor MyClass(IDependency1, IDependency2))

test default constructor MyClass() call MyClass(IDependency1, IDependency2) with correct concrete type

and you are good to go


问:
Many-to-many in OOP: Class A instantiates Class B, which instantiates Class A, which
I am mapping Field1 to Field2. The map object instantiates the field object and vice versa, creating an infinite loop.

This is in PHP.

```<code>class field {
  protected $maps; // mapCollection object. all the mappings of this field to others

}

class map {
  protected $field1; // field object
  protected $field2; // field object
}

class mapCollection {
  protected $maps; // array of map objects
}
</code>```

The mappings and fieldsets are stored in a database where they each have a unique ID. So I decided to allow fetching them using their ids in the constructors.

```<code>class field {
  protected $maps; // map object
  public __construct($id = 0 ) {
    if(!empty($id) ) {
      $this->maps = // get mapsCollection. data from db
    }
  }

}

class map {
  protected $field1; // field object
  protected $field2; // field object
  public __construct($id = 0 ) {
    if(!empty($id) ) {
      $this->field1 = // get field1 data from db
      $this->field2 = // get field2 data from db
    }
  }
}

class mapCollection {
  protected $maps; // array of map objects
  public __construct($field_id) {
    // get maps from db by field id
    foreach($dbdata as $map_id) {
      $this->maps[] = new map($map_id); // instantiates new map, which instantiates new field, etc
    }
  }
}
</code>```

How should I be doing this?

答:
It is called a circular dependency.  Typically the way you resolve them is you have an unbiased third party create both A and B then introduce them to one another.  This should break the infinite loop and allow things to progress.

Another option is give both your field and map class a constructor that takes the other object as a parameter.  Now only load from the database if you don't get what you are looking for passed in.


答:
Ya don't do this. By putting new in the 2nd constructor, you're doing a few things that will make your life harder over time:

creating a hard, compile-time dependency between your class and the implementation classes you're instantiating.

making decisions at coding time about which implementation classes to bake into the class, which goes against the idea of dependency injection

creating more code that you have to test and maintain

breaking "do not repeat yourself" in a subtle way, because the 2nd constructor does in code what your bean factory is doing through configuration

So you won't be smitten by the God of Dependency Injection, but you're creating extra work for you and your team.

Even if you're not using mocks, you'd be better off letting the client instantiate & inject the concrete classes to use. Or else write up a Builder or Factory, and let it make those decisions about concrete classes.

...the acid test is, how much smaller, and therefore more maintainable, is your code without that second constructor?

(full disclosure: sometimes I find it makes sense to do this, but I would reserve it as a special case rather than a general practice.)


问:
Benefits of caching the count of items in a data structure versus on-demand calculation?
Given a data structure, I want to provide an API method Size which returns the number of items.

I am vacillating between 2 approaches:

Maintain a count and increment/decrement it in response to Add/Delete calls respectively

Perform a traversal to calculate the count when Size is called.

Approach #2 will take O(n) vs O(1) for approach #1. Other than performance, any other benefits of #1 over #2 ?

答:
By maintaining a separate count, you are running the risk of bugs causing the count to get out of sync with the actual number of items in your data structure. Now, if your code is bug-free then this won't be a problem, but you can't guarantee that it will remain bug-free forever (if somebody else comes along and changes something).

I would nearly always choose option #2 unless measurements prove you need to optimise the performance.


问:
_variable - why that underscore at the beginning?
Sometimes I see people writing variable names like this:

int _variable;

IMO That's really ugly. What's that about?

答:
Let's say you want to make the difference between two types of variables (such as private and public) very visual, so that anyone could tell which one is which just by glancing at the name of the variable.

You may go with privatePrice and publicQuantity. This is hardly usable and requires more typing, wastes more screen space, etc.

You may use an abbreviation or a convention, such as rPrice and uQuantity. This looks like Hungarian notation, is misleading and is not easily discoverable. Putting just the first letter won't help neither: which one is private, pPrice or pQuantity?

Finally, you can use a symbol. Which symbols can be used in most languages and are available on most keyboards?

Letters,

Digits (but some languages forbid starting a variable name by a digit,

Underscore.

Dashes, dots, commas and brackets usually have different purposes. Unicode symbols are supported in many languages, but are difficult to use when typing source code. Accented letters such as "à" are easy to type on my French layout keyboard, but may be much more difficult to enter on a Chinese or Russian keyboard.

Looks like underscore becomes an obvious choice.

About its ugliness...

Ugly is subjective. Let's concentrate on more objective notions. Design and UX principles, for example, are somehow much more objective than the terms such as "pretty" or "ugly", so let's talk design/UX. What word do you notice in the following text?

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nec laoreet elit. Nullam egestas eros vel luctus bibendum. Pellentesque habitant morbi tristique senectus et netus et _malesuada fames ac turpis egestas. Sed nec leo sem. Maecenas vitae augue non odio lacinia ornare a eget dolor.

That's because the underscore prefix is visually distinctive. In the same way, underscore improves the readability of code by being visually distinctive as a prefix: if you search the source code for a private member, your eye will catch identifiers starting by "_", but much less the ones which simply contain an underscore:

```<code>private Price computePrice(Product product)
{
    Price result = calculator.ComputePrice(product, Path_Default);

    if (_ruleset.isEnabled)
    {
        result.applyRuleset(_ruleset);
    }

    return result;
}
</code>```

By glancing at this piece of code, you easily notice both _ruleset, but don't visually recognize Path_Default as a potential match.

About its benefits...

While this improves readability, the usage of underscore character as a prefix is not always a good idea. Some standards and style guides, such as the official C# style guide, forbid using underscore as a prefix for private variables, in the same way as it is forbidden to use Hungarian notation. The reason for that is that:

First, the cases where you need to know the visibility of a variable is pretty rare, and in those cases, the IDE helps you to find this information in less than three seconds.

Second, all those notations add visual clutter. Since it is not essential, it should be removed.

Third, it is not unusual to end up with code like this:

```<code>public string _Title { get; set; }
</code>```

and the sole fact that such convention may lead to misleading code and easily avoidable bugs, while the IDE will never lie is a good reason to avoid such conventions.

This being said, other communities using other languages find underscore prefix useful enough to communicate information. They may take a risk for the underscore prefix to become misleading (if the variable changes from private to public or from public to private but is not renamed properly), the risk similar to one that each developer takes when he writes a comment which may not be updated by the successive maintainers of the piece of code.

Body:
Let's say you want to make the difference between two types of variables (such as private and public) very visual, so that anyone could tell which one is which just by glancing at the name of the variable.

You may go with privatePrice and publicQuantity. This is hardly usable and requires more typing, wastes more screen space, etc.

You may use an abbreviation or a convention, such as rPrice and uQuantity. This looks like Hungarian notation, is misleading and is not easily discoverable. Putting just the first letter won't help neither: which one is private, pPrice or pQuantity?

Finally, you can use a symbol. Which symbols can be used in most languages and are available on most keyboards?

Letters,

Digits (but some languages forbid starting a variable name by a digit,

Underscore.

Dashes, dots, commas and brackets usually have different purposes. Unicode symbols are supported in many languages, but are difficult to use when typing source code. Accented letters such as "à" are easy to type on my French layout keyboard, but may be much more difficult to enter on a Chinese or Russian keyboard.

Looks like underscore becomes an obvious choice.

About its ugliness...

Ugly is subjective. Let's concentrate on more objective notions. Design and UX principles, for example, are somehow much more objective than the terms such as "pretty" or "ugly", so let's talk design/UX. What word do you notice in the following text?

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nec laoreet elit. Nullam egestas eros vel luctus bibendum. Pellentesque habitant morbi tristique senectus et netus et _malesuada fames ac turpis egestas. Sed nec leo sem. Maecenas vitae augue non odio lacinia ornare a eget dolor.

That's because the underscore prefix is visually distinctive. In the same way, underscore improves the readability of code by being visually distinctive as a prefix: if you search the source code for a private member, your eye will catch identifiers starting by "_", but much less the ones which simply contain an underscore:

private Price computePrice(Product product)
{
    Price result = calculator.ComputePrice(product, Path_Default);

    if (_ruleset.isEnabled)
    {
        result.applyRuleset(_ruleset);
    }

    return result;
}

By glancing at this piece of code, you easily notice both _ruleset, but don't visually recognize Path_Default as a potential match.

About its benefits...

While this improves readability, the usage of underscore character as a prefix is not always a good idea. Some standards and style guides, such as the official C# style guide, forbid using underscore as a prefix for private variables, in the same way as it is forbidden to use Hungarian notation. The reason for that is that:

First, the cases where you need to know the visibility of a variable is pretty rare, and in those cases, the IDE helps you to find this information in less than three seconds.

Second, all those notations add visual clutter. Since it is not essential, it should be removed.

Third, it is not unusual to end up with code like this:

public string _Title { get; set; }

and the sole fact that such convention may lead to misleading code and easily avoidable bugs, while the IDE will never lie is a good reason to avoid such conventions.

This being said, other communities using other languages find underscore prefix useful enough to communicate information. They may take a risk for the underscore prefix to become misleading (if the variable changes from private to public or from public to private but is not renamed properly), the risk similar to one that each developer takes when he writes a comment which may not be updated by the successive maintainers of the piece of code.


问:
Ideal data structure for storing map data?
I was asked this in an interview test. I did okay on the test but didn't know enough to answer this question. I am curious to know what data structures I can use to query the data quickly.

Basically the idea is there would be road sections (lines, made up of points) stored in some kind of data structure. It should be quick to query which road sections (or points) are within a certain distance from a point (radius).

答:
Different kinds of operations upon map data will require different storage formats for optimal results.  Consider, for example, the following three tasks:

Given a point, find the road nearest that point

Given a geographical area of a certain size, find all the roads which are within that area.

Given two roads, find the shortest route between them.

The differences in requirements are sufficiently great that unless one will need to accommodate "live" changes to the map, one will likely be better off with storing three separate copies of the data--each optimized for one of the above tasks--than trying to come up with a format which can handle all three tasks well.


问:
Collaboration between a Graphic Designer and Expression Blend developer?
I'm new to the programming world and also a little bit confused. My brother would like to work with me on some program. I'm a graphic designer so he asked me for UI and all it's elements. I would really help him as much as it's possible so I have found Expression Blend for Visual Studio. At first it looked great but after few minutes I've started to understand that I totally don't know What to do with my project.

Lets assume that I have already made an Interface. Even made in Blend. Now, how can I give it to him so he could implement the UI? How to export and how to give it to him. For example, He works on separate PC and I need to export the project and give it to him for implementation. I know everything about Graphic Design but nothing about coding. I know that he uses Visual Studio :)

I have been working in a web company so my workflow was very easy. It was only to send well prepared PSD file. With Blend I don't know what's next after the design part is finished.

答:
Typically the designer will work with Blend (in addition to whatever other tools) and the developer will work with a combination of Blend and/or Visual Studio. You'd hand him your Blend project files and XAML. He'd load them up in Visual Studio (or Blend; developers use both) and begin hooking up the interface you developed to the program's business logic.

Note that you can open a Blend project file in Visual Studio and certain Visual Studio project types (WPF, etc.) in Blend. That's what enables the above workflow.

More info: MSDN: Collaboration with Expression Blend


问:
How to find out if a tile is being covered by a polygon?
Given a (intersecting) polygon, I'd like find out which tiles are being covered by the polygon.

Example:

Details:

Tiles are square, 1 unit wide/high

The grid begins in (0,0)

The corners of the polygon can have floating point coordinates (i.e. 3.433, 5.234)

In general, an edge of the polygon might be as long as 1000 - 10000 tiles

I tried to iterate over all tiles and check whether they are in the polygon, however as I have to iterate over 10000² tiles it takes a quite a long time.

I'm interested in a solution which allows me to quickly answer "Is tile (x,y) covered by the polygon?" without recomputing everything from scratch for each question.

Any solution/approach/pseudo-code/hint which leads me to a correct solution will be accepted.

答:
It seems that you want to do polygon rasterization, where your "pixels" are your grid elements.

An approach I would try (as chances are you will find ready-to-use algorithms to do that), is to use an in-memory rasterizer (e.g. Cairo), adjusting the filtering (and of course the coordinates of your polygons so they are expressed in grid units).

You could alternatively roll your own using existing algorithms.
For instance:

split the polygon into its convex parts

draw each polygon's outline (more precise: each convex part's outline) with Bresenham's line algorithm

fill the holes (which should be easy since you are working with convex polygons)

For step 2, if you want to cover all pixels, see this SO question.


问:
Do you have a metaphor for cache/data latencies?
From this answer about latencies, we have some numbers (yes, caveat caveat) for latencies when coding (slightly edited):

L1 cache reference 0.5 ns

Branch mispredict 5 ns

L2 cache reference 7 ns

Main memory reference 100 ns

Send 2K bytes over 1 Gbps network 20,000 ns

Read 1 MB sequentially from memory 250,000 ns

Disk seek 10,000,000 ns

Read 1 MB sequentially from network 10,000,000 ns

Read 1 MB sequentially from disk 30,000,000 ns

Send packet CA->Netherlands->CA 150,000,000 ns

Do you have a metaphor that puts this in human terms? For example, a human might find a value in a table on their desk (L1) in 15s, so the equivalent time to go find the same thing if the page is still in the book on the shelf (L2) would be 14x longer, or 3.5 minutes.

I know this seems like an ELI5, but I think most programmers (including me) lack a real grasp of how the orders of magnitude vary, making it hard to reason about whether to memoize some function or pre-cache some data. I'll expand the example in an answer.

If you have a handle on CPU pipelining and cycles instead, that would be a great boon for understanding CPUs. Also mutex performance, SIMD paralellism, multi-threading, multi-core...

答:
Expanding the example:

You need the result of a log calculation, log(7.2), but you have only a slide rule and no computer. It takes you:

15s [1x] to look up the value for 7.2 in a table on your desk (L1), because you have the page of 7.1 to 7.2 photocopied.

3.5 mins [14x] for your secretary to go find the same thing from a book on the office shelf (L2), though this is shared with your colleagues (cores) so you might have to wait.

50 mins [200x] for your secretary's assistant to go find the appropriate book from the campus library (Main memory) if you don't have a copy on the office shelf.

9.5 years [2e7 x] for your value to be found in the national archive which involves setting up a human chain all the way to a remote mountain village (disk seek).

143 years [3e8 x] for your value to be found by sending a rocket to neighbouring star system and back again (packet request with 150ms round trip).

As it goes, the galactic gods are ok to wait about 250 years if you just have the 1 answer to get, but they expect to see some sign of progress (user expects a response in 250ms).

If you had been doing a few of these and thought the result was going to come out below 0.85 (allowing you to carry on with your work on that basis), when you realise it's actually 0.857 it will take you 2.5 minutes to erase all the stuff you wrote since that mistake (branch mispredict).

Should you need more than 1 value, say a lot of values from the same book:

43 days [5e5 x] to receive a million or so of these from your campus library sequentially; that works out to about 7.5s each, compared to 50 minutes for getting 1.

3.5 days to send a large request for a load of values internationally (local network request).

9.5 years [2e7 x] to receive a million or so of these (local network receive), assuming they have them all to hand and don't need to look in their own national archive (disk seek), which works out to about 5 minutes each.

29 years [6e7 x] to receive a million or so of these from the national archive sequentially; that works out to about 15 minutes each, compared to 9.5 years for getting 1.

If it seems odd that the national archive takes longer than an international request, then yes it is odd. But that's how slow hard disks are; it is quicker to ask the next machine if it has the values to hand (i.e. cached) than to scan the head to the appropriate bit of disk ready to start receiving values.

Hopefully if the metaphor isn't too tortuous, you can start to see how you might use caching, pre-fetching and so on to avoid having to ask the national archive (disk), or heaven forbid make a network request (Proxima centauri, prepare for a generational ship in several decades time). For example, if someone said 'why don't I just pre-calculate all the log results and put them on disk so I can find one if I need it', it should be pretty apparent why it might be quicker to just calculate it every time (hint: 9.5 years!), but also why sometimes it's still quicker to cache stuff for a big sequential batch (7.5s each on average from RAM (campus library) instead of say 30s to calculate).