问:
Does decoupling trump DRY in REST?
I am building a REST API to expose most of functionality of an existing Java API.  Both APIs are for internal use within my organization; I do not have to design for external use.  I have influence over both APIs but am implementing the REST one.  The Java API will continue to be used for local applications (it's not being "retired"), but the REST API will be used for significant new development.

Some of the Java API classes are simply data (beans with properties, getters, setters).  And at least some of these make sense to transmit (in some form) over the REST API as data (which will be marshalled to XML or JSON).  For example, a class that stores info about a server machine.  I am faced with the following choice for these data classes:  Do I...

expose the original Java class (or a subclass) directly in the REST API, or

make a new data transfer class (DTO pattern) specifically for the REST API?

Either way I'll have REST data transfer classes; the question is whether to annotate the originals or create new ones (which may be near copies of the originals).  There may be other choices, but I'll focus mainly on those two.

Arguments for #1:

DRY (don't repeat yourself)

Faster to implement

Easier to upgrade REST API

Arguments for #2:

What if REST API needs to be versioned separately from Java API?  (This is somewhat likely.)

What if there are significant changes to the Java data classes such as removal of properties, adding of behavior, or changes to class hierarchy?  (This is also somewhat likely.)

Bottom line is that it seems like a tradeoff between DRY (#1) and decoupling (#2).

I'm leaning toward starting with #1 and then if problems arise moving to #2 later, following the agile guideline of not building what you can't prove you need.  Is this a bad idea; should I start with #2 if I think I may end up there anyway?

Are there major arguments/consequences missing from my lists?

答:
Your REST API does not have to follow the same structure as your data model

When implementing REST make sure that you are creating an intuitive external API, and then map this to your internal data model classes. This allows you to change each independently of the other leading to APIs that can last decades.

Therefore, decoupling is the way to go here.

Title: Does decoupling trump DRY in REST?


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答:
Marvin Minsky

Computation: Finite and Infinite Machines

Semantic Information Processing

ContentLicense: CC BY-SA 2.5


问:
Is using unit tests to tell a story a good idea?
So, I have an authentication module I wrote some time ago. Now I'm seeing the errors of my way and writing unit tests for it. While writing unit tests, I have a hard time coming up with good names and good areas to test. For instance, I have things like

RequiresLogin_should_redirect_when_not_logged_in

RequiresLogin_should_pass_through_when_logged_in

Login_should_work_when_given_proper_credentials

Personally, I think it's a bit ugly, even though it seems "proper". I also have trouble differentiating between tests by just scanning over them (I have to read the method name at least twice to know what just failed)

So, I thought that maybe instead of writing tests that purely test functionality, maybe write a set of tests that cover scenarios.

For instance, this is a test stub I came up with:

```<code>public class Authentication_Bill
{
    public void Bill_has_no_account()
    { //assert username "bill" not in UserStore
    }
    public void Bill_attempts_to_post_comment_but_is_redirected_to_login()
    { //Calls RequiredLogin and should redirect to login page
    }
    public void Bill_creates_account()
    { //pretend the login page doubled as registration and he made an account. Add the account here
    }
    public void Bill_logs_in_with_new_account()
    { //Login("bill", "password"). Assert not redirected to login page
    }
    public void Bill_can_now_post_comment()
    { //Calls RequiredLogin, but should not kill request or redirect to login page
    }
}
</code>```

Is this a heard of pattern? I've seen acceptance stories and such, but this is fundamentally different. The big difference is that I'm coming up with scenarios to "force" the tests out. Rather than manually trying to come up with possible interactions that I'll need to test. Also, I know that this encourages unit tests that don't test exactly one method and class. I think this is OK though. Also, I'm aware that this will cause problems for at least some testing frameworks, as they usually assume that tests are independent from each other and order doesn't matter(where it would in this case).

Anyway, is this an advisable pattern at all? Or, would this be a perfect fit for integration tests of my API rather than as "unit" tests? This is just in a personal project, so I'm open to experiments that may or may not go well.

答:
A problem with telling a story with unit tests is that it doesn't make explicit that unit tests should be arranged and run entirely independently of each other.

A good unit test should be completely isolated from all other dependent code, it's the smallest unit of code that can be tested.

This gives the benefit that as well as confirming the code works, if a test fails you get the diagnosis for exactly where the code is wrong for free. If a test isn't isolated you have to look at what it depends on to find out exactly what's gone wrong and miss out on a major benefit of unit testing. Having the order of execution matter can also raise a lot of false negatives, if a test fails it's possible for the following tests to fail despite the code they test working perfectly fine.

A good article in more depth is the classic on dirty hybrid tests.

To make the classes, methods and results readable the great Art of Unit testing uses the naming convention

Test Class:

ClassUnderTestTests

Test Methods:

MethodUnderTest_Condition_ExpectedResult

To copy @Doc Brown's example, rather than using [Setup] which runs before each test, I write helper methods to build isolated objects to test.

```<code>[TestFixture]
public class AuthenticationTests
{
    private Authentication GetAuthenticationUnderTest()
    {
        // create an isolated Authentication object ready for test
    }

    [Test]
    public void CreateAccount_WithValidCredentials_CreatesAccount()
    {
         //Arrange
         Authentication codeUnderTest = GetAuthenticationUnderTest();
         //Act
         Account result = codeUnderTest.CreateAccount("some", "valid", "data");
         //Assert
         //some assert
    }

    [Test]
    public void CreateAccount_WithInvalidCredentials_ThrowsException()
    {
         //Arrange
         Authentication codeUnderTest = GetAuthenticationUnderTest();
         Exception result;
         //Act
         try
         {
             codeUnderTest.CreateAccount("some", "invalid", "data");
         }
         catch(Exception e)
         {
             result = e;
         }
         //Assert
         //some assert
    }
}
</code>```

So the failing tests have a meaningful name that gives you some narrative about exactly what method failed, the condition and the expected result.

That is how I've always written unit tests, but a friend has had a lot of success with Gerkin.

ContentLicense: CC BY-SA 3.0

Body:
A problem with telling a story with unit tests is that it doesn't make explicit that unit tests should be arranged and run entirely independently of each other.

A good unit test should be completely isolated from all other dependent code, it's the smallest unit of code that can be tested.

This gives the benefit that as well as confirming the code works, if a test fails you get the diagnosis for exactly where the code is wrong for free. If a test isn't isolated you have to look at what it depends on to find out exactly what's gone wrong and miss out on a major benefit of unit testing. Having the order of execution matter can also raise a lot of false negatives, if a test fails it's possible for the following tests to fail despite the code they test working perfectly fine.

A good article in more depth is the classic on dirty hybrid tests.

To make the classes, methods and results readable the great Art of Unit testing uses the naming convention

Test Class:

ClassUnderTestTests

Test Methods:

MethodUnderTest_Condition_ExpectedResult

To copy @Doc Brown's example, rather than using [Setup] which runs before each test, I write helper methods to build isolated objects to test.

[TestFixture]
public class AuthenticationTests
{
    private Authentication GetAuthenticationUnderTest()
    {
        // create an isolated Authentication object ready for test
    }

    [Test]
    public void CreateAccount_WithValidCredentials_CreatesAccount()
    {
         //Arrange
         Authentication codeUnderTest = GetAuthenticationUnderTest();
         //Act
         Account result = codeUnderTest.CreateAccount("some", "valid", "data");
         //Assert
         //some assert
    }

    [Test]
    public void CreateAccount_WithInvalidCredentials_ThrowsException()
    {
         //Arrange
         Authentication codeUnderTest = GetAuthenticationUnderTest();
         Exception result;
         //Act
         try
         {
             codeUnderTest.CreateAccount("some", "invalid", "data");
         }
         catch(Exception e)
         {
             result = e;
         }
         //Assert
         //some assert
    }
}

So the failing tests have a meaningful name that gives you some narrative about exactly what method failed, the condition and the expected result.

That is how I've always written unit tests, but a friend has had a lot of success with Gerkin.


问:
Node.js app private modules. Where to put them?
The situation would be:

I develop 2 projects in my Node.js development environment, P1 and P2.

P1 required the development of two simple modules, mod1 and mod2, which are stored in P1/lib. Each one of this modules resolves find their external dependencies in  P1/node_modules. Necessary dependencies for P1 have been installed in this folder via npm.

Now image we want to reuse mod1 in the other proyect P2, here's were my doubts come up. I could...

Just copy mod1 to P2/lib. Replication, so I don't even consider this option.

From P2, reference mod1 from P1: require($PROJECTS_DIR + '/P1/lib/mod1'). Not a good option, this way P2 would depend on P1.

Put mod1 into a higher level directory or using NODE_PATH, so that P1 and P2 can resolve it by just doint require('mod1'). However, when deploying, I should also deploy this higher level directory which seems a bit dirty.

I would like to treat mod1 as a npm module, so it can be easily installed in any project or environment, However, in this particular case, I can't publish the module to npm cause is too project-specific. I could create a private npm repository and put mod1 inside. The gist of this would be to set it up in order to be accessed also from the production envirnoment. Is it worth it?

What about putting it all together in node_modules? (external depencencies and my own libraries).  That would be great since modules can be just required like `require('module'). But it also seems quite dirty.

Not sure how npm link would work when deploying. It creates a symbolic link, which is not followed when commiting code via Git or SVN. If I run npm install in production, will it also install the linked module?

None of the above quite  satisfies  me.
I don't know if one of these is suitable, or you guys have other suggestions, but, are there any preferred ways to structure own private libraries so that they can be easily reused in other projects?

答:
Use npm link. It allows you to have a module wherever you want, and you can then "link" it in your project (a symbolic link will be created in your node_modules/ folder), thus you can use it with require('mod1'). Your module has to be npm-compatible.

More information here: https://docs.npmjs.com/cli/link

About your private concerns, npm thought about this and provides the private option. See here: https://docs.npmjs.com/misc/registry (Go to : "I don't want my package published in the official registry. It's private.")

For each module dependency, you can simply define them in the package.json.


问:
Should I return from a function early or use an if statement?
I've often written this sort of function in both formats, and I was wondering if one format is preferred over another, and why.

public void SomeFunction(bool someCondition)
{
    if (someCondition)
    {
        // Do Something
    }
}
```

<p>or</p>

<pre class="lang-java prettyprint-override"><code>public void SomeFunction(bool someCondition)
{
    if (!someCondition)
        return;

    // Do Something
}
</code>```

I usually code with the first one since that is the way my brain works while coding, although I think I prefer the 2nd one since it takes care of any error handling right away and I find it easier to read

答:
I would prefer to write:

if(someCondition)
{
    SomeFunction();
}
```


问:
How to improve database schema with different n:m and 1:n associations between users/tasks/comments/attachments
I'm trying to build a database for an upcoming Ruby on Rails webproject.

There will be 4 tables minium: tasks, users, attachments and comments.
And 1 table to join the n:m relations (tasks <-> users).

One task has many users, many comments and many attachments.
One comment has many attachments and was created by one user.
One attachment was created by one user.

Users can have many tasks, many comments and many attachments.

A little sketch to illustrate my thougts:

The tables with 1:n relations contains the ID from the related table (e.g.: one comment contains the user id)

Do you think this scheme follows the normalization rules? Does this make sense or are there any redundancies? I think there is a little problem with the attachment table, cause this must contain a type field and a id field to differentiate between task and comment.

And all content types (tasks, comments, attachments) are assigned by many users (tasks) or created by (comments, attachments) one user.

Comments are not recursive.

I've considered the following pseudocode:

```<code>tasks = getTasks
each tasks as task

    # get task content

    users = getUsersByTaskID
    each users as user
        #get user content

    attachments = getAttachmentsByTypeAndTaskID
    each attachments as attachment
        # get attachment content
        user = getUserByID

    comments = getCommentsByTaskID
    each comments as comment
        # get comment content
        user = getUserByID
        attachments = getAttachmentsByTypeAndCommentID
        each attachments as attachment
            # get attachment content
            user = getUserByID
</code>```

I think it's still a little bit too complicated. Did i overlooked something?
Are there better ways to implement my ideas?

答:
Edit: I've reread your requirements and shifted my design a bit.

I'd contemplate orienting your models around the task where possible:

```<code>class User; end

class Task
  belongs_to :created_by,    :class_name => "User"
end

class TaskAssignment
  belongs_to :task
  belongs_to :assigned_to,   :class_name => "User"
  belongs_to :created_by,    :class_name => "User"
end

class Comment
  belongs_to :task
  belongs_to :created_by,    :class_name => "User"
end

class Attachment
  belongs_to :created_by,    :class_name => "User"

  # Consider connecting attachments to :comment (and thus indirectly to a parent task)
  # instead of directly to the :task
  #
  belongs_to :task
end
</code>```

Body:
Edit: I've reread your requirements and shifted my design a bit.

I'd contemplate orienting your models around the task where possible:

class User; end

class Task
  belongs_to :created_by,    :class_name => "User"
end

class TaskAssignment
  belongs_to :task
  belongs_to :assigned_to,   :class_name => "User"
  belongs_to :created_by,    :class_name => "User"
end

class Comment
  belongs_to :task
  belongs_to :created_by,    :class_name => "User"
end

class Attachment
  belongs_to :created_by,    :class_name => "User"

  # Consider connecting attachments to :comment (and thus indirectly to a parent task)
  # instead of directly to the :task
  #
  belongs_to :task
end


问:
How to debug through a swing based application effectively
I am trying to understand how a radio button is created in a Dynamic field by reading from an XML using Netbeans 7.0.

I know the radio button is created because of the XML being read from database, but I cannot see how the radio button is created.

Also, since I don't know where to place the break points, I can't see how I would debug the creation of components on the Dynamic Editor.

Maybe I am trying a wrong approach or something, so how do I efficiently debug an application like this?

答: All you need might be a conditional breakpoint. Both Netbeans and Eclipse allow you to edit properties of a breakpoint by right-clicking it and add a condition (a piece of code) that the debugger will evaluate every time it reaches the breakpoint, and stop only of the condition is true. In your case the condition would be some string that identifies the component being created dynamically as the one you're interested in.</p>


问:
Layered architecture using Entity Framework with different class libraries
Our business requirements required to create a layered and modular architecture. So I designed an architecture to make it as decoupled and as modular as possible. I will list my layers below

ASP .NET MVC Application (UI)

Business Logic Layer (BLL)

Data Access Layer (DAL)

I have further used IOC where each BLL module defines its Data Access requirements in terms of interfaces. So DAL has now to implement these interfaces.

It is important to note that

Both UI and DAL are dependent on the BLL

BLL is not dependent on any other solution. Using Interfaces I have done IOC so now DAL is dependent on BLL and not the other way round.

BLL is not just one project but a set of class library projects - one class library each   for each business module.

DAL is a single class library project "shared" by all the BLL projects (since Database is same and it did not make sense dividing DAL into separate projects).

I will not go into details here but let us say there was a decision to use EDMX. However now I do not see how EDMX will fit into this mix. I believe I am not the only person ever to divide the BLL into different class libraries but have a single DAL project. But can EDMX or for that matter any ORM support such "distributed" architecture ?

答:
I assume by EDMX you mean Database First or Model First rather than Code First (POCO).  You can still do code first with POCO's with an existing database if that's the reason for using EDMX.

However if you're absolutely stuck with an EDMX you can use POCO data transfer objects as a wrapper around the EDMX to isolate it from your BLL and top UI.  This question about the same subject on Stack Overflow discusses this alternative.


答:
I think your schema is clear:

I do not see redundancies

on your doubts regarding the attachment table: rails makes it relatively easy to have CommentAttachment and
TaskAttachment derive from a common Attachment model with
single table inheritance (STI). STI is pretty much a standard rails setup. It comes at a certain cost, however, see e.g. this article for some discussion on the cons.

Anyway, in your case, I would say that STI is the right choice because:

the 2 attachment-types share all attributes.

only their behaviour changes according to their type.

Title: How to improve database schema with different n:m and 1:n associations between users/tasks/comments/attachments

Body:
I'm trying to build a database for an upcoming Ruby on Rails webproject.

There will be 4 tables minium: tasks, users, attachments and comments.
And 1 table to join the n:m relations (tasks <-> users).

One task has many users, many comments and many attachments.
One comment has many attachments and was created by one user.
One attachment was created by one user.

Users can have many tasks, many comments and many attachments.

A little sketch to illustrate my thougts:

The tables with 1:n relations contains the ID from the related table (e.g.: one comment contains the user id)

Do you think this scheme follows the normalization rules? Does this make sense or are there any redundancies? I think there is a little problem with the attachment table, cause this must contain a type field and a id field to differentiate between task and comment.

And all content types (tasks, comments, attachments) are assigned by many users (tasks) or created by (comments, attachments) one user.

Comments are not recursive.

I've considered the following pseudocode:

```<code>tasks = getTasks
each tasks as task

    # get task content

    users = getUsersByTaskID
    each users as user
        #get user content

    attachments = getAttachmentsByTypeAndTaskID
    each attachments as attachment
        # get attachment content
        user = getUserByID

    comments = getCommentsByTaskID
    each comments as comment
        # get comment content
        user = getUserByID
        attachments = getAttachmentsByTypeAndCommentID
        each attachments as attachment
            # get attachment content
            user = getUserByID
</code>```

I think it's still a little bit too complicated. Did i overlooked something?
Are there better ways to implement my ideas?


答: Early returns for-the-win.  They can seem ugly, but much less ugly than big if wrappers, especially if there's multiple conditions to check.

Title: Should I return from a function early or use an if statement?

Body:
I've often written this sort of function in both formats, and I was wondering if one format is preferred over another, and why.

public void SomeFunction(bool someCondition)
{
    if (someCondition)
    {
        // Do Something
    }
}
```

<p>or</p>

<pre class="lang-java prettyprint-override"><code>public void SomeFunction(bool someCondition)
{
    if (!someCondition)
        return;

    // Do Something
}
</code>```

I usually code with the first one since that is the way my brain works while coding, although I think I prefer the 2nd one since it takes care of any error handling right away and I find it easier to read


问:
Implementing the command pattern in a RESTful API
I'm in the process of designing an HTTP API, hopefully making it as RESTful as possible.

There are some actions which functionality spreads over a few resources, and sometime needs to be undone.

I thought to myself, this sounds like a command pattern, but how can I model it into a resource?

I will introduce a new resource named XXAction, like DepositAction, which will be created through something like this

```<code>POST /card/{card-id}/account/{account-id}/Deposit
AmountToDeposit=100, different parameters...
</code>```

this will actually create a new DepositAction and activate it's Do/Execute method.
In this case, returning a 201 Created HTTP status means the action has been executed successfully.

Later if a client wishes to look at the action details he can

```<code>GET /action/{action-id}
</code>```

Update/PUT should be blocked I guess, because it is not relevant here.

And in order to Undo the action, I thought of using

```<code>DELETE /action/{action-id}
</code>```

which will actually call the Undo method of the relevant object, and change it's status.

Let's say I'm happy with only one Do-Undo, I don't need to Redo.

Is this approach ok?

Are there any pitfalls, reasons not to use it?

Is this understood from the POV of the clients?

答:
You're adding in a layer of abstraction that is confusing

Your API starts off very clean and simple. A HTTP POST creates a new Deposit resource with the given parameters. Then you go off the rails by introducing the idea of "actions" that are an implementation detail rather than a core part of the API.

As an alternative consider this HTTP conversation...

POST /card/{card-id}/account/{account-id}/Deposit

AmountToDeposit=100, different parameters...

201 CREATED

Location=/card/123/account/456/Deposit/789

Now you want to undo this operation (technically this should not be allowed in a balanced accounting system but what the hey):

DELETE /card/123/account/456/Deposit/789

204 NO CONTENT

The API consumer knows that they are dealing with a Deposit resource and is able to determine what operations are permitted on it (usually through OPTIONS in HTTP).

Although the implementation of the delete operation is conducted through "actions" today there is no guarantee that when you migrate this system from, say, C# to Haskell and maintain the front end that the secondary concept of an "action" would continue to add value, whereas the primary concept of Deposit certainly does.

Edit to cover an alternative to DELETE and Deposit

In order to avoid a delete operation, but still effectively remove the Deposit you should do the following (using a generic Transaction to allow for Deposit and Withdrawal):

POST /card/{card-id}/account/{account-id}/Transaction

Amount=-100, different parameters...

201 CREATED

Location=/card/123/account/456/Transation/790

A new Transaction resource is created which has exactly the opposite amount (-100). This has the effect of balancing the account back to 0, negating the original Transaction.

You might consider creating a "utility" endpoint like

POST /card/{card-id}/account/{account-id}/Transaction/789/Undo    <- BAD!

to get the same effect. However, this breaks the semantics of a URI as being an identifier by introducing a verb. You are better off sticking to nouns in identifiers and keeping operations constrained to the HTTP verbs. That way you can easily create a permalink from the identifier and use it for GETs and so on.


问:
Why is Today() an example of an impure function?
It seems like, when reading something like this Wikipedia article about "pure functions", they list Today() as an example of an impure function but it seems pretty pure to me. Is it because there is no formal input argument? Why is the actual time of day not treated as the "input to the function" in which case if you gave it the same input, i.e. executed today() twice at the same time, or traveled back in time to execute it again (maybe a hypothetical :) ), the output would be the same time. Today() never gives you a random number. it always gives you the time of day.

The Wikipedia article says "different times it will yield different results" but that's like saying for different x sin(x) will give you different ratios. And sin(x) is their example of a pure function.

答: sin(x) will always return the same value, as long as x stays the same. Today() could return different results over time because it depends on values outside of your control. For example, if something beyond the control of your program changes the system's internal $current_datetime while your program is running, Today() will suddenly yield different results.


答:
() => 1 would be a pure function, since it always returns 1. Today() may return "Monday" or "Tuesday" or nearly any other value.

Another way to think of it is pure functions don't depend on state. The world is typically considered state. You need to know the state of reality to know what day today is.

However you don't need to know anything special about the state of the world to know what sin(x) is. And ever call to sin(x) for a given x will return the same value.

Title: Why is Today() an example of an impure function?

Body:
It seems like, when reading something like this Wikipedia article about "pure functions", they list Today() as an example of an impure function but it seems pretty pure to me. Is it because there is no formal input argument? Why is the actual time of day not treated as the "input to the function" in which case if you gave it the same input, i.e. executed today() twice at the same time, or traveled back in time to execute it again (maybe a hypothetical :) ), the output would be the same time. Today() never gives you a random number. it always gives you the time of day.

The Wikipedia article says "different times it will yield different results" but that's like saying for different x sin(x) will give you different ratios. And sin(x) is their example of a pure function.


答:
Date(timestamp) would be a pure function. Because of its idempotency. And because there would be no side-effect.

Today() can vary its result depending on when you call it. That's what makes it impure. It's not idempotent. It has no side-effect though, but that doesn't make it pure.


答: Personally, I prefer to do pass/fail condition checks at the beginning.  That allows me to group most of the most common failures at the top of the function with the rest of the logic to follow.</p>


答:
Is it because there is no formal input argument?

It is because the output depends on something that is not an input, namely the current time.

Why is the actual time of day not treated as the "input to the function"

Because you didn't pass it as a parameter. If you did pass it in as a parameter, the function would become an identity function on dates, which is pretty useless. The entire point of a Today() function is to output something that depends on an external and constantly changing value (time).

The advantage of pure functions is that their behavior is absolutely reproducible and deterministic, making it easy to have formal proofs and hard guarantees. They always do the same thing. Today() is pretty much the opposite: it always (allowing for time granularity) does something different.


答:
It seems fairly obvious that this function fails the first test of purity given at the very start of that page:

The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any
  hidden information or state that may change as program execution
  proceeds or between different executions of the program, nor can it
  depend on any external input from I/O devices.

Note that since it takes no arguments, there is only one possible set of argument values - the empty set. And this function can and does return different results for the same 'argument value(s)'.

Furthermore, the function result value does depend on "hidden ... state that may change as program execution proceeds". So another failure.


问:
Method overload in scala
I know method overload is not allowed in Scala and I have read some posts regarding the reasons. But still, I see some functions overloaded in Scala library (example: println). I want to know how it is done and if I can use the same mechanism to some of my methods.</p>

答:
Functions cannot be overloaded in Scala, that is correct. But println is not a function, it is a method, and methods most definitely can be overloaded.

I'm not sure what you mean by "How it is done". It is done the exact same way that you do it in every other language that supports overloading. If you want two definitions of a method with different types you write two definitions with different types:

```<code>def foo(arg: Int)    { println("I am overloaded for Int.")    }
def foo(arg: String) { println("I am overloaded for String.") }

foo(42)
// I am overloaded for Int.

foo("Hello")
// I am overloaded for String.

foo(1.0)
// error: overloaded method value foo with alternatives:
//  (arg: String)Unit <and>
//  (arg: Int)Unit
// cannot be applied to (Double)
//                  foo(1.0)
//                  ^
</code>```

The reason why function overloading isn't supported is simple: technically speaking, the term doesn't even make sense, since "overloading" basically means (very broadly) "different bindings for the same name depending on context". But functions don't have a name, so the whole concept of having different implementations bind to the same name is nonsensical.

Title: Method overload in scala

Body:
Functions cannot be overloaded in Scala, that is correct. But println is not a function, it is a method, and methods most definitely can be overloaded.

I'm not sure what you mean by "How it is done". It is done the exact same way that you do it in every other language that supports overloading. If you want two definitions of a method with different types you write two definitions with different types:

def foo(arg: Int)    { println("I am overloaded for Int.")    }
def foo(arg: String) { println("I am overloaded for String.") }

foo(42)
// I am overloaded for Int.

foo("Hello")
// I am overloaded for String.

foo(1.0)
// error: overloaded method value foo with alternatives:
//  (arg: String)Unit <and>
//  (arg: Int)Unit
// cannot be applied to (Double)
//                  foo(1.0)
//                  ^

The reason why function overloading isn't supported is simple: technically speaking, the term doesn't even make sense, since "overloading" basically means (very broadly) "different bindings for the same name depending on context". But functions don't have a name, so the whole concept of having different implementations bind to the same name is nonsensical.


问:
How to make an ASP.NET MVC site modular
I'm in the planning stage for an employee intranet system to be built with ASP.NET MVC 4. We'd like the site to consist of separate "modules", each of which provides a different feature: messaging, payroll changes, etc. I'd like these modules to be able to be enabled or disabled at compile time. The homepage will display some kind of navigation that will link to each module that is loaded.

That's easy so far, but I don't want the navigation feature to have to know about the modules beforehand. In other words, I want the modules to be dynamically discoverable; I want to be able to write the code for a new module and then have a link added to the navigation bar with no code changes anywhere else in the source. Each module should have some way of registering itself with the navigation bar, and--more importantly--this should be done for each module as it's loaded.

I believe that this precludes using MVC's Areas, since those are designed for the case when the layout of the site is known beforehand. MEF seems like it might be appropriate, although people seem to have had mixed success in combining MEF with MVC. Is MEF actually the way to go here, or is there a better way to accomplish what I need?

答:
I would first have a centralized class that is used for the app to register compiled modules with a static constructor and a static member List of modules that were in the system. The modules would have a static property indicating if its a menu item or not and what order it should appear in the menu.

Each module would have its own static constructor that would note itself in the centralized class that keeps track of modules.

Think of this system more like a time clock system where employees come in and clock in. Then at payroll time, we know to pay all the employees based on who clocked in, etc.

Reflection could also be used if you have an interface contract on the modules they must inherit from that ties meta property info to it.

I worked for Warner Brothers Music and did an internal music processing system for different encoding formats. I made a generic plugin model for encoding with reflection that used inheritance so it could be typecast with reflection to get the basic meta properties of the class. I have not tried using a static centralized class though. Just kind of thought of that randomly as another way to try for fun.

I would also add that I've used MVC serving multiple clients with a baseline of requirement but with also enhanced features similar to what you are trying to do. Instead I converted the MVC into using App_Code rather than requiring a compile. Its easier to push files out this way without needing a centralized compilation.

You can leverage JIT with simple FTP or GIT push rather than needing to compile locally and push DLLs around.

Here is a link to that article on stack overflow

Title: How to make an ASP.NET MVC site modular


答: I prefer the second style.  Get invalid cases out of the way first, either simply exiting or raising exceptions as appropriate, put a blank line in there, then add the "real" body of the method.  I find it easier to read.</p>


答:
Today() is an impure function because its result is dependent upon something that you do not give it; specifically, the current system time. Therefore, its result is not deterministic when based only on the inputs provided at invocation.

A pure function would be int Add(int a, int b) {return a + b;}. The function works solely with what it is given, and uses no other external state data. The natural result of this is that you can Add(2,2) and get 4 from now until the end of time. In addition, because the function doesn't change any external state (it has no "side effects"), Add()ing 2 and 2 from now until the end of time won't change anything else in the system, unless you then assign the result of the function to a variable or otherwise use the value to update state (which is not an operation performed by the function itself). Virtually all classical mathematical operations are pure functions and can be implemented as such.

Today(), on the other hand, may produce the same value when called two times in a row, but not if called repeatedly for several days. This is because it is dependent on external state data which is not provided by you as a parameter to the function. As a result, it is impossible, within the boundaries of the program, to control the result of the Today() function. It will produce a given value on a given day, and will never produce that value on any other day, unless you change the system clock of the computer on which it is run (a change generally occurring outside the boundaries of the program).

An impure function is not necessarily a bad thing; impure functions are required, even in functional languages, to interact with anything outside the boundaries of the program, such as data stores, communication pipelines, UI displays, peripheral devices, etc. A program that does not do any of these things is a program that is sharply limited in its utility; I would even go so far as to call such a program trivial, as without any means to accept input or any avenue to inform you of its output, it might as well be doing nothing. Programs written in functional languages can have only the input provided by the runtime and produce an output reported to the runtime without any explicitly defined impure methods, but that's because the runtime is abstracting away all these impure details of working within an imperfect computer system, so that the program itself can be structured in terms of a nested set of mathematical expressions that the runtime then evaluates given initial input.

It is simply a Very Good Thing to know which of the functions you are using are pure and which ones are not, so that you can make good decisions about how they are used. Impure functions, because they do things or are dependent on things that are not apparent from their usage, may behave unpredictably given only knowledge of the usage. Further knowledge of the purpose of the function, and thus what it needs from or does to external state, is required in order to place a system that uses it in a consistent state and thus to expect a deterministic result.


问:
Is Using Locking/Unlocking in Version Control an Anti-Pattern?
Recently I've started using Git at work. Previously I've only ever used VSS (which has some problems) and so far, Git is orders of magnitude better.

The key differences here is that Git is distributed while VSS has a centralized "server" version, and that VSS uses a "checkout-lock-checkin" workflow while Git doesn't. The biggest problems we've had on working with code on our team relate to code being checked-out and unavailable to other people. This slows down work considerably, but I also know this isn't unique to VSS. Other source control systems like CVS apparently also lock files as part of their workflow.

Is there any good reason for locking to be part of a version control system? Or even a development workflow? Or perhaps locking practices should be considered bad practice and discouraged?

答:
Is there any good reason for locking to be part of a version control system?

Yes, of course! It means that you NEVER have to worry about merging, which is a serious pain in any version control environment.

However, it was learned from bitter experience that the only pain bigger than merging is being forced to lock your team out from developing a file until you're ready to commit your entire development. Which is why modern VCSes, including TFS (and later versions of VSS, although it wasn't switched on by default), favour making merges easier over making them entirely unnecessary, at any cost.


问:
Given that I voluntarily choose not to implement virtual memory in my kernel, how would the memory-management-unit work?
For my basic kernel I refuse to implement the dreaded confusion of virtual memory scheming, so I want only real memory addresses for everything. Some people have argued with me that since virtual memory is hardware supported, and sometimes the MMU hardware is integrated with the CPU, is that a rule that virtual memory is mandatory by hardware-design?

I have at least one good reason to not care about virtual memory at this point, being that the real memory I have is plenty (32 GB), and that I don't care to go through trouble and workarounds with virtual addressing and such(and that I honestly don't like the idea, regardless of the fact that it helps in many areas).

So if my question wasn't clear, is it possible to write a dedicated kernel and not at all implement virtual memory and use only real addresses for everything, with a MMU?

(Some of these low-level programming and hardware-concepts are mind-boggling, even after hours and hours of studying and implementing).

PS: I'm guessing the answer to some point is "yes", but hearing someone with more knowledge on the subject would definitely be a good pointer for me and others who read this.

答:
You certainly don't have to, a lot of small systems didn't.  Early versions of Windows, PalmOS and Apple's pre-OS X systems used "handles", which were basically indexes into a table of pointers to memory regions. The idea was that programs would do all their memory referencing via the handles, giving the system the ability to move the memory regions as needed (to prevent fragmentation).  It's hard to prevent memory corruption with such a scheme, and it can lead to strange bugs if you create a pointer to a region that gets relocated.

I believe IBM's OS/MFT (going wayyy back) simply partitioned memory into fixed-size regions (defined at 'system generation' time), then loaded a single program into each region.  Each program was only supposed to use the memory in its region, so all programs had to know their memory requirements.  Depending on the tasks you'll be running, maybe something simple like this could work.


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答:
How to read other people's code.

Code doesn't exist if it is not checked in Version Control System.


问:
What does "recursive" mean for a program which processes files and directories?
I know what recursion is in programming.  I do understand the basics of version control systems (have used svn that is).  But I have often wondered what the meaning of "recursion" or "recursive" is with respect to version control systems.

What does a function calling itself have to do with working with files and directories in a version control system?

答:
The specific meaning of "recursive" in this context is "operating on a directory and its contents, including the contents of any subdirectories".

The word "recursive" is used here, because at least conceptually, this is easily implemented by a recursive algorithm:

```<code>procedure check_in_directory (d : directory)
    for each entry e in d             <== recursive exit after last entry in directory
        if e is a file
            check_in_file(f)
        if e is a directory
            check_in_directory(e)     <== recursive call
</code>```

The recursive structure of this procedure matches the recursive definition of a directory:

A directory contains zero or more directory entries

A directory entry is either a file or a directory

This approach -- writing a function whose structure matches the definition of the data type you are processing is often referred to as structural recursion.

Body:
The specific meaning of "recursive" in this context is "operating on a directory and its contents, including the contents of any subdirectories".

The word "recursive" is used here, because at least conceptually, this is easily implemented by a recursive algorithm:

procedure check_in_directory (d : directory)
    for each entry e in d             <== recursive exit after last entry in directory
        if e is a file
            check_in_file(f)
        if e is a directory
            check_in_directory(e)     <== recursive call

The recursive structure of this procedure matches the recursive definition of a directory:

A directory contains zero or more directory entries

A directory entry is either a file or a directory

This approach -- writing a function whose structure matches the definition of the data type you are processing is often referred to as structural recursion.


问:
Devising test of Haskell's value/reference semantics
In imperative languages, it is trivial to devise a programming test of language's use of "value semantics" or "reference semantics". One could do the following and check the value of a (where Vertex  {one, two, three :: Integer}):

```<code>a := Vertex 3 4 5
b := a
one b   :=  6
two b   :=  8
three b := 10
</code>```

However, since variables are immutable in functional languages, this test won't work in such languages.

I know very little about Haskell (and functional programming in general), but my understanding is that it uses value semantics. Is it possible to devise a programming experiment that would distinguish between a "ref record" and a "val record" in Haskell?

答: There is no such test, because, without mutability, the distinction isn't meaningful (as you demonstrated).</p>


问:
success:/failure: blocks vs completion: block
I see two common patterns for blocks in Objective-C. One is a pair of success:/failure: blocks, the other is a single completion: block.

For example, lets say I have a task that will return an object asynchronously and that task might fail. The first pattern is -taskWithSuccess:(void (^)(id object))success failure:(void (^)(NSError *error))failure. The second pattern is -taskWithCompletion:(void (^)(id object, NSError *error))completion.

success:/failure:

```<code>[target taskWithSuccess:^(id object) {
    // W00t! I've got my object
} failure:^(NSError *error) {
    // Oh noes! report the failure.
}];
</code>```

completion:

```<code>[target taskWithCompletion:^(id object, NSError *error) {
    if (object) {
        // W00t! I've got my object
    } else {
        // Oh noes! report the failure.
    }
}];
</code>```

Which is the preferred pattern? What are the strengths and weaknesses? When would you use one over the other?

答:
I suspect it's going to end up being personal preference...

But I prefer the separate success/failure blocks. I like separating the success/failure logic. If you had nested success/failures, you'd end up with something that would be more readable (in my opinion at least).

As a relatively extreme example of such nesting, here's some Ruby showing this pattern.


答: Completion callback (opposed to success/failure pair) is more generic. If you need to prepare some context before dealing with return status, you can do it just before "if (object)" clause. In success/failure case you have to duplicate this code. This depends on callback semantics, of course.</p>

Title: success:/failure: blocks vs completion: block

Body:
I see two common patterns for blocks in Objective-C. One is a pair of success:/failure: blocks, the other is a single completion: block.

For example, lets say I have a task that will return an object asynchronously and that task might fail. The first pattern is -taskWithSuccess:(void (^)(id object))success failure:(void (^)(NSError *error))failure. The second pattern is -taskWithCompletion:(void (^)(id object, NSError *error))completion.

success:/failure:

```<code>[target taskWithSuccess:^(id object) {
    // W00t! I've got my object
} failure:^(NSError *error) {
    // Oh noes! report the failure.
}];
</code>```

completion:

```<code>[target taskWithCompletion:^(id object, NSError *error) {
    if (object) {
        // W00t! I've got my object
    } else {
        // Oh noes! report the failure.
    }
}];
</code>```

Which is the preferred pattern? What are the strengths and weaknesses? When would you use one over the other?


问:
Java memory management (thunks/lazyness)
If I want to create an infinite list of integers in Java like so:

```<code>ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0;;i++){
    list.add(i);
}
</code>```

I run out of memory. My understanding is that we allocate some memory for i, list, and every time we add i to the list, we allocate more memory for it.

But, by using a thunk, I can create an infinite list which will not eat all of my memory:

```<code>infList(final int start){
    return new InfiniteList (
    start,
    return new InfiniteList.LazyTail(){eval(){return infList(start+1);}}
    );
}
</code>```

(I adapted source from here). How does this work? I know I am delaying the evaluation of the expressions : start+1, start+1, start+1 ... but do I end up with a list of something like this:

[start, eval(){start+1}, eval(){start+1}, eval(){start+1} ... ]

Are the 'eval(){...}' object references? Do they take up space in memory? Will I eventually run out of memory with this implementation (I tried, but memory allocation was not budging)?

Do I only start using memory, say, if I wanted to system.out.print integers, then they would have to be evaluated, and some memory allocated?

答:
The classic example of the infinite sequence is that of a lazy sequence from a functional programing.

From Wikibooks Clojure Programming: Lazy Fibonacci there are a number of lazy sequences for calculating the Fibonacci sequence.  One example:

```<code>(def fib-seq
  ((fn rfib [a b]
     (lazy-seq (cons a (rfib b (+ a b)))))
   0 1))
user> (take 20 fib-seq)
(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181)
</code>```

In this, the sequence is not evaluated until one asks for it and can keep being queried to get the next value in the sequence.

Note that this is a sequence and not an array.

The idea of a structure that is hiding calculation behind it is certainly not unique to pure functional languages.

In perl one example of an array where one asks for $primes[199] returning the 200th prime can be found at Math::Prime::TiedArray.  Similarly, in Python, this stack overflow question creates a iterator/generator (I'm not a pythonian, I'm not exactly sure of the termonology) that will generate an infinite stream of primes.

Note that with the primes it still allocates memory as it is generates the numbers to make the sieve more optimal.  If you request more objects than can fit in memory, you will fill up memory.  However, it doesn't calculate the value until you ask for it.

Specifically for Java, one could do what is desired in clojure and then call the clojure code from Java -- they are both jvm languages.  Its an option, though I don't recommend it.

For Java, iterator is an interface for something that moves in one direction.  The key point being that this is an interface - you can implement it.

Consider:

```<code>package com.michaelt.se;

import java.util.Iterator;

public class EvenIter implements Iterator<Integer>
{
    private int value = 0;

    @Override
    public boolean hasNext() {
        return true;
    }

    @Override
    public Integer next() {
        return (value++ * 2);
    }

    @Override
    public void remove() { }
}
</code>```

and the demo to run it

```<code>package com.michaelt.se;

public class IterDemo
{
    public static void main(String[] args)
    {
        EvenIter evens = new EvenIter();
        for(int i = 0; i < 10; i++) {
            System.out.println(i + ": " + evens.next());
        }
    }
}
</code>```

This is an infinite "list" of numbers that takes a small, constant amount of memory.  I did this with the iterable, it could be done with other interfaces too.  The slides from the presentation on infinite streams does it as a stream.

The thunk specifically is a closure to be invoked later when needed.  Closures are something that are in Java 7.

Again, one can do similar things in Java as code by creating an object with a getter that has an associated method that is then memoized.  The idea being "yea, I'll calculate this value when you actually want it, but until that time, hang on to this."

The question of the infinite list of integers integers (be they natural numbers, primes, Fibonacci, or some other sequence) can be implemented lazy in a variety of ways in Java.  It really boils down to what one wants to do with it beyond the "it should be lazy and not eat all memory as I get big numbers".

Body:
The classic example of the infinite sequence is that of a lazy sequence from a functional programing.

From Wikibooks Clojure Programming: Lazy Fibonacci there are a number of lazy sequences for calculating the Fibonacci sequence.  One example:

(def fib-seq
  ((fn rfib [a b]
     (lazy-seq (cons a (rfib b (+ a b)))))
   0 1))
user> (take 20 fib-seq)
(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181)

In this, the sequence is not evaluated until one asks for it and can keep being queried to get the next value in the sequence.

Note that this is a sequence and not an array.

The idea of a structure that is hiding calculation behind it is certainly not unique to pure functional languages.

In perl one example of an array where one asks for $primes[199] returning the 200th prime can be found at Math::Prime::TiedArray.  Similarly, in Python, this stack overflow question creates a iterator/generator (I'm not a pythonian, I'm not exactly sure of the termonology) that will generate an infinite stream of primes.

Note that with the primes it still allocates memory as it is generates the numbers to make the sieve more optimal.  If you request more objects than can fit in memory, you will fill up memory.  However, it doesn't calculate the value until you ask for it.

Specifically for Java, one could do what is desired in clojure and then call the clojure code from Java -- they are both jvm languages.  Its an option, though I don't recommend it.

For Java, iterator is an interface for something that moves in one direction.  The key point being that this is an interface - you can implement it.

Consider:

package com.michaelt.se;

import java.util.Iterator;

public class EvenIter implements Iterator<Integer>
{
    private int value = 0;

    @Override
    public boolean hasNext() {
        return true;
    }

    @Override
    public Integer next() {
        return (value++ * 2);
    }

    @Override
    public void remove() { }
}

and the demo to run it

package com.michaelt.se;

public class IterDemo
{
    public static void main(String[] args)
    {
        EvenIter evens = new EvenIter();
        for(int i = 0; i < 10; i++) {
            System.out.println(i + ": " + evens.next());
        }
    }
}

This is an infinite "list" of numbers that takes a small, constant amount of memory.  I did this with the iterable, it could be done with other interfaces too.  The slides from the presentation on infinite streams does it as a stream.

The thunk specifically is a closure to be invoked later when needed.  Closures are something that are in Java 7.

Again, one can do similar things in Java as code by creating an object with a getter that has an associated method that is then memoized.  The idea being "yea, I'll calculate this value when you actually want it, but until that time, hang on to this."

The question of the infinite list of integers integers (be they natural numbers, primes, Fibonacci, or some other sequence) can be implemented lazy in a variety of ways in Java.  It really boils down to what one wants to do with it beyond the "it should be lazy and not eat all memory as I get big numbers".


问:
Implementing a sort of navigation system
So I am undertaking a project which does navigation sort of thing. So here is how the problem statement looks like.

Say, given a map of a floor, with different rooms, now somehow, this information is provided to the program and what the program does is, it takes two more inputs,

The starting location.
The final location.
Now having had these two locations, the program draws out the best possible route from starting to ending location. I will be using C language for the implementation of code.

Now, the problems:

How do I provide the information about the floor, i.e. whether there's a wall or a door or just empty space, to my program. Here's my take on it. I will have a 2-D matrix, where in the 1 in the matrix shows an empty space, and a 0 signifies a wall. But now I am not sure, how to mark a cell as 0. i.e how the dimensions of the matrix shall be chosen? For example, say my floor is 8 by 8 (length units). Now shall my matrix be 8 by 8 or 16 by 16 or what? And what if, having chosen the dimension of a single cell, if some part of the cell is wall and the other is empty space, shall it be a 0 or a 1? But I guess, it would be a manual input after all? But I dont expect someone to create this kind of matrix for me manually? So, some help in this direction will be appreciated? Is this way of representing the data allright, or shall I go about in a different direction?

Say, If I go by the above way of data representation, what do I do next? I was thinking, somehow, I will have to convert that matrix of data into a graph and after that it will be an easy problem to deal with. I am not quite sure, how I will do it but I will appreciate some sources, wherein I can read about something similar.

Are there any other tips, that I shall go by, for this project?

PS : By Navigation I mean, given the starting and end point, and considering the starting point to be the same as the current location of the device, it shall move to the final location on its own.

Thanks.

答: For built environments you would probably store the walls as lines (ie. store the end point coordinates). Then finding a collision is just finding if the line of your path crosses any of the lines of the walls.  Algorithms to check if/where 2d lines cross are very fast and easy</p>


答:
It depends - In general I am not going to go out of my way to try and move a bunch of code around to break out of the function early - the compiler will generally take care of that for me. That said though, if there are some basic parameters at the top that I need and can't continue otherwise, I will breakout early. Likewise, if a condition generates a giant if block in function I will have it breakout early as a result of that as well.

That said though, if a function requires some data when it is called, I'm usually going to be throwing an exception (see example) as opposed to just returning.

public int myFunction(string parameterOne, string parameterTwo) {
  // Can't work without a value
  if (string.IsNullOrEmpty(parameterOne)) {
    throw new ArgumentNullException("parameterOne");
  }
  if (string.IsNullOrEmpty(parameterTwo)) {
    throw new ArgumentNullException("parameterTwo");
  }

  // ...
  // Do some work
  // ...

  return value;
}
```


答:
It's not an anti-pattern because not everyone gets to work with text files.  As this person points out, you might be using an application that creates binary files in some undocumented proprietary format that you can't easily merge afterwards.

A simpler case of that is images, it only ever makes sense for one person to work on it at a time.  Without locking you need good team communication so everyone knows what everyone else is working on and avoid stepping on each other's toes.  Communication is important in every team, but relying on it to avoid work collisions can scale poorly for large teams.

Even if you do get to work with text files, it may still be inconvenient because of context (thank you @mike).  For example, take a look at this question: Git merging within a line, specifically:

With a LaTeX document this is particularly annoying, as the common habit when writing LeTeX is to write a full paragraph per line and just let your text editor handle word wrapping when displaying for you.

There is a workable solution proposed to that question, but when you work with human languages, things often get tricky.

Title: Is Using Locking/Unlocking in Version Control an Anti-Pattern?

Body:
Recently I've started using Git at work. Previously I've only ever used VSS (which has some problems) and so far, Git is orders of magnitude better.

The key differences here is that Git is distributed while VSS has a centralized "server" version, and that VSS uses a "checkout-lock-checkin" workflow while Git doesn't. The biggest problems we've had on working with code on our team relate to code being checked-out and unavailable to other people. This slows down work considerably, but I also know this isn't unique to VSS. Other source control systems like CVS apparently also lock files as part of their workflow.

Is there any good reason for locking to be part of a version control system? Or even a development workflow? Or perhaps locking practices should be considered bad practice and discouraged?


答:
Most binary file formats can't be merged by source control.  If it is changed by two people at the same time, the last one to check it in "wins."  Locking can be useful in that situation, although a lot of teams use some other means of communication (like assigning owners) to prevent such a problem.

Outside of binary files, most people would agree that VCS locking is an anti-pattern, although it obviously has its advocates.  It often leads to people doing merges outside of version control, or making local changes "just for debugging purposes" in a file someone else has locked, then neglecting to check it in.  Merging can be annoying, but dealing with locks is usually more annoying.  That's why most centralized VCS nowadays allows you to selectively lock certain files and not others.


问:
Temporary variables vs line length requirements
I've been reading Martin Fowler's Refactoring. It is generally excellent but one of Fowler's recommendations seems to be causing a little trouble.

Fowler recommends that you replace temporary variables with a query, so instead of this:

```<code>double getPrice() {
    final int basePrice = _quantity * _itemPrice;
    final double discountFactor;
    if (basePrice > 1000) discountFactor = 0.95;
    else discountFactor = 0.98;
    return basePrice * discountFactor;
}
</code>```

you pull out into a helper method:

```<code>double basePrice() {
    return _quantity * _itemPrice;
}

double getPrice() {
    final double discountFactor;
    if (basePrice() > 1000) discountFactor = 0.95;
    else discountFactor = 0.98;
    return basePrice() * discountFactor;
}
</code>```

In general I agree except that one reason I use temporary variables is when a line is too long. For example:

```<code>$host = 'https://api.twilio.com';
$uri = "$host/2010-04-01/Accounts/$accountSid/Usage/Records/AllTime";
$response = Api::makeRequest($uri);
</code>```

If I tried inlining that, the line would go longer than 80 characters.

Alternately I end up with chains of code, which are themselves not that much easier to read:

```<code>$params = MustacheOptions::build(self::flattenParams($bagcheck->getParams()));
</code>```

What are some strategies for reconciling the two?

答:
Actually, I disagree with the eminent Mr. Fowler on this in the general case.

The advantage of extracting a method from formerly inlined code is code reuse; the code in the method is now severed from its initial usage, and can now be used in other places in code without being copied and pasted (which would necessitate making changes in multiple places if the general logic of the copied code ever had to change).

However, of equal, often greater conceptual value is "value reuse". Mr. Fowler calls these extracted methods to replace temp variables "queries". Well, what's more efficient; querying a database each of the multiple times you need a particular value, or querying once and storing the result (assuming that the value is static enough that you wouldn't expect it to change)?

For almost any calculation beyond the relatively trivial one in your example, in most languages it's cheaper to store the result of one calculation than to keep calculating it. Therefore, the general recommendation to recompute on-demand is disingenuous; it costs more developer time and more CPU time, and saves a trivial amount of memory, which in most modern systems is the cheapest resource of those three.

Now, the helper method, in conjunction with other code, could be made "lazy". It would, when first run, initialize a variable. All further calls would return that variable until the method were told explicitly to recompute. This could be a parameter to the method, or a flag set by other code that changes any value this method's computation depends on:

```<code>double? _basePrice; //not sure if Java has C#'s "nullable" concept
double basePrice(bool forceCalc)
{
   if(forceCalc || !_basePrice.HasValue)
      return _basePrice = _quantity * _itemPrice;
   return _basePrice.Value;
}
</code>```

Now, for this trivial calculation that's even more work performed than saved, and so I'd generally recommend sticking with the temp variable; however, for more complex calculations that you would generally want to avoid running multiple times, and that you need in multiple places in code, this is the way you'd do it.

Body:
Actually, I disagree with the eminent Mr. Fowler on this in the general case.

The advantage of extracting a method from formerly inlined code is code reuse; the code in the method is now severed from its initial usage, and can now be used in other places in code without being copied and pasted (which would necessitate making changes in multiple places if the general logic of the copied code ever had to change).

However, of equal, often greater conceptual value is "value reuse". Mr. Fowler calls these extracted methods to replace temp variables "queries". Well, what's more efficient; querying a database each of the multiple times you need a particular value, or querying once and storing the result (assuming that the value is static enough that you wouldn't expect it to change)?

For almost any calculation beyond the relatively trivial one in your example, in most languages it's cheaper to store the result of one calculation than to keep calculating it. Therefore, the general recommendation to recompute on-demand is disingenuous; it costs more developer time and more CPU time, and saves a trivial amount of memory, which in most modern systems is the cheapest resource of those three.

Now, the helper method, in conjunction with other code, could be made "lazy". It would, when first run, initialize a variable. All further calls would return that variable until the method were told explicitly to recompute. This could be a parameter to the method, or a flag set by other code that changes any value this method's computation depends on:

double? _basePrice; //not sure if Java has C#'s "nullable" concept
double basePrice(bool forceCalc)
{
   if(forceCalc || !_basePrice.HasValue)
      return _basePrice = _quantity * _itemPrice;
   return _basePrice.Value;
}

Now, for this trivial calculation that's even more work performed than saved, and so I'd generally recommend sticking with the temp variable; however, for more complex calculations that you would generally want to avoid running multiple times, and that you need in multiple places in code, this is the way you'd do it.


答:
It is impossible to distinguish between them. What this means is that the compiler is free to choose to use whatever semantics it sees fit for optimum performance.

In particular, functional languages are typically described as having value semantics, because that matches our conceptual model of them, but they are often implemented using reference semantics because that's more efficient. (No need to copy something that can't be changed!)

Title: Devising test of Haskell's value/reference semantics

Body:
In imperative languages, it is trivial to devise a programming test of language's use of "value semantics" or "reference semantics". One could do the following and check the value of a (where Vertex  {one, two, three :: Integer}):

```<code>a := Vertex 3 4 5
b := a
one b   :=  6
two b   :=  8
three b := 10
</code>```

However, since variables are immutable in functional languages, this test won't work in such languages.

I know very little about Haskell (and functional programming in general), but my understanding is that it uses value semantics. Is it possible to devise a programming experiment that would distinguish between a "ref record" and a "val record" in Haskell?


问:
Blocking IP address for web-scraping service

Background

Consider the following scenario:

Link. User provides a link to some poorly formatted website (e.g., creative commons content).

Scrape. Server downloads the content (web scrape), always throttled.

Format. Server formats the content (e.g., performs natural language processing).

Return. Server posts formatted results back to user.

Problem

The server hosting the poorly-formatted website (host) can block the server that pulls down the content (scraper). If this happens, the user can no longer use the service to automatically change the format.

Assume that the terms of service do not forbid scraping, nor is there an API available to pull the data directly.

Comments Regarding Copyright

The content is not subject to copyright: it is either creative commons content or already in the public domain.

The content would be from whitelisted domains that have been vetted (e.g., U.S. federal government works).

For what it's worth, I don't even know if the sites will block the requests (especially given how infrequent the requests will be and I will likely do some pre-caching). It's mostly academic at this point

Question

What strategies would you employ (such as using a virtual network, or cloud service) such that the IP address of the scraper can easily (potentially dynamically) change to avoid being blocked by the host?

答:
What strategies would you employ ... to avoid being blocked by the host?

I wouldn't.  Any (potentially thorny) legal questions aside, if a site administrator makes it clear that you aren't wanted, you really should abide by that.  If you don't like the way the admin runs things, stop using that site, or even try playing "name and shame" and telling other people why this isn't a good site to use.  But playing whack-a-mole with the admin's security policies is never a good move.  It wastes your time, it wastes the administrator's time, and it could easily end up exposing you to legal liability.


答:
Here's a little pseudo code that I think of when discussing pure functions

```<code>newValue = Function();
while(true)
{
   oldValue = newValue;
   newValue = Function();
   assert( newValue == oldValue );
}
</code>```

If that runs indefinitely and the can never trigger the assert, it's a pure function. More so, if you have a function that uses args, then a little modification....

```<code>oldValue = Function( importantVariableToYourApp );
newValue = Function( importantVariableToYourApp );
assert( newValue == oldValue );
</code>```

If you can use that after every variable assignment in your app, and it doesn't change results in your app, and it can never fail the assert, then it is a pure function.

Body:
Here's a little pseudo code that I think of when discussing pure functions

newValue = Function();
while(true)
{
   oldValue = newValue;
   newValue = Function();
   assert( newValue == oldValue );
}

If that runs indefinitely and the can never trigger the assert, it's a pure function. More so, if you have a function that uses args, then a little modification....

oldValue = Function( importantVariableToYourApp );
newValue = Function( importantVariableToYourApp );
assert( newValue == oldValue );

If you can use that after every variable assignment in your app, and it doesn't change results in your app, and it can never fail the assert, then it is a pure function.


问:
hginit - #ifdefs ridiculous
I was reading Joel Spolsky's mercurial introduction when it struck me:

"And now what they do is this: each new feature is in a big #ifdef block. So they can work in one single trunk, while customers never see the new code until it’s debugged, and frankly, that’s ridiculous."

Why is this so ridiculous anyway, isn't this, if nothing else, simply simpler to handle? It's nothing fancy but does the trick - at least if you are already "married" with subversion.

What is the downside? I kind of don't get the argument.

答:
I think the answer is given in the subsequent sentence:

Keeping stable and dev code separate is precisely what source code control is supposed to let you do.

By using #ifdef blocks, you are emulating functionality of a source control system with a C preprocessor. It's the wrong tool for the job.

The downside is that you probably either end up duplicating a lot of code (think of whole function definitions once inside, once outside the #ifdef) or have unreadable code (think of the #ifdef enclosing single lines within a function - possibly repeatedly).

In the first variant you end up fixing bugs twice (which wouldn't be necessary if you could just merge bugfixes from the stable branch to the dev branch), whereas in the second the original goal of separating stable and dev branches was not really achieved.

Title: hginit - #ifdefs ridiculous


问:
Learning a new language and framework, should I spike a project, or first ground myself in the language fundamentals?
I've got substantial J2EE experience, have worked with Grails, and am comfortable with several languages (Perl, PHP, Smalltalk). I've decided to try a new project using Ruby on Rails. For those who've decided to migrate to a new technology stack, how do you make the transition? Do you learn the details of Ruby first (I've done a few tutorials, and feel like I've got a decent enough grasp of the language to start doing some basic work) or do you do a full Ruby on Rails tutorial, and expand your knowledge from there. I'm leaning towards the latter approach because I feel like I can delve into details of the language as I encounter them. For those who work in Ruby on Rails, how did you learn, and which resources do you recommend?</p>

答:
A crucial part of any project is the purpose it is aimed to satisfy. If you are just reading about a language or copying some program, the purpose isn't there, and it's just like painting by numbers.

Choose a project of your own initiative (though you can get ideas from others), not a big one, and tackle that. That way all parts of your brain will be engaged, you'll have fun, and everything you learn will be grounded in a purpose.


答:
It assumes all new code can be written without touching existing code. Often the only way to do that is to repeat your self a lot. (a new method for one that is similar but not exactly the same for example).

One of the major advantages of distributed VCS is that encourages the team to work on their own feature branch and not be worried about your work conflicting with others. This strategy negates that advantage.

To me it seems ridiculous since they seem to be deliberately misusing the tools. If your going to make the switch surely its worth learning how to use them.

Title: hginit - #ifdefs ridiculous

Body:
I was reading Joel Spolsky's mercurial introduction when it struck me:

"And now what they do is this: each new feature is in a big #ifdef block. So they can work in one single trunk, while customers never see the new code until it’s debugged, and frankly, that’s ridiculous."

Why is this so ridiculous anyway, isn't this, if nothing else, simply simpler to handle? It's nothing fancy but does the trick - at least if you are already "married" with subversion.

What is the downside? I kind of don't get the argument.


答:
First let me say that I completely agree with Mason Wheeler's answer.

If the user has legitimate browser access (possibly including some sort of authentication), then one approach is to use a plugin/extension in the browser to capture the page, send it to your clean-up server, and then redirect the browser to the cleaned up page. This completely obviates any need to perform involved recreations of the authentication dance.

Both Firefox and Chrome can be extended to do this. Browse the extension libraries and you'll probably find several that are already doing about 80%+ of what you need.

Title: Blocking IP address for web-scraping service

Body:
Background

Consider the following scenario:

Link. User provides a link to some poorly formatted website (e.g., creative commons content).

Scrape. Server downloads the content (web scrape), always throttled.

Format. Server formats the content (e.g., performs natural language processing).

Return. Server posts formatted results back to user.

Problem

The server hosting the poorly-formatted website (host) can block the server that pulls down the content (scraper). If this happens, the user can no longer use the service to automatically change the format.

Assume that the terms of service do not forbid scraping, nor is there an API available to pull the data directly.

Comments Regarding Copyright

The content is not subject to copyright: it is either creative commons content or already in the public domain.

The content would be from whitelisted domains that have been vetted (e.g., U.S. federal government works).

For what it's worth, I don't even know if the sites will block the requests (especially given how infrequent the requests will be and I will likely do some pre-caching). It's mostly academic at this point

Question

What strategies would you employ (such as using a virtual network, or cloud service) such that the IP address of the scraper can easily (potentially dynamically) change to avoid being blocked by the host?


答:
I would highly recommend reading Version Control by Example: http://www.ericsink.com/vcbe/
It explains very clearly the concepts of various systems, including when locking works and when it doesn't (which is indeed for non-text files and when merging can't be resolved.) True locking isn't possible (due to offline access) but some kind of lock concept can be useful to prevent overwriting someone elses work. </p>

<p>(It also points out you can still use a central server in a git-setup, and it might make sense to do so. Distributed doesn't mean one of the repositories can't have a special meaning.) </p>

Body:
I would highly recommend reading Version Control by Example: http://www.ericsink.com/vcbe/
It explains very clearly the concepts of various systems, including when locking works and when it doesn't (which is indeed for non-text files and when merging can't be resolved.) True locking isn't possible (due to offline access) but some kind of lock concept can be useful to prevent overwriting someone elses work.

(It also points out you can still use a central server in a git-setup, and it might make sense to do so. Distributed doesn't mean one of the repositories can't have a special meaning.)


问:
How does authentication work with ASP.NET (using Live ID and\or Windows Authentication)
I'm primarily a .NET desktop app programmer. Coming into the web world has been difficult. I'm trying to convert one of my Silverlight apps into HTML. But I'm having a hard time figuring out the authentication system. I'm trying to read up on Live ID authentication and Windows Authentication but I'm having a hard time putting it all together in my head. Perhaps you can help?

My App Framework

My client application is a TypeScript (javascript) HTML page (or pages). And the server is a WCF Data Services REST API hosted in ASP.NET. The service works with a SQL database.

The Problems (Claims Based)

When I look at something like Live ID authentication, it's known as claims-based authentication, right? So if I had this implemented correctly, someone comes to the website, I need to verify that they are logged in. How do I do that from a client-side HTML page? Do I have a recurring timer that is validating the login every 30 seconds or something? Or is that done server-side on each call to the service?

I know that if they aren't logged in, I need to send them to the live login page, once they log in, the live page will redirect them to my server with the authorization token in the query string (or something like this). At this point though, what do I do 5 minutes down the line when they make a call to the webservice for data? Is that token sent on every call to the server some how? How do I validate that when they call the service, it is actually them? Do I have to wrap every service call in a ValidateUser() method or something? I have a user ID in the database that I would have to match with their user token somehow.

The Problems (Windows Authentication)

The previous problem still exists here. How do I know that every call from the client is still them? Additionally though, I need to understand what do I do from the HTML side to the server side to authenticate them and then continue the authentication.

Conclusion

I cannot really find any sort of explanation that conceptually explains all of this information and gives me the big picture of how it all works. I'm really hoping someone here can fill in these gaps and give me a better idea on how to implement the client and server authentication.

Thanks!

Update

I found a great book that really explains a lot of this. It's entitled "A Guide to Claims-Based Identity and Access Control". It's part of the patterns & practices series.

Thanks to all for your answers and put me on the right track.

答:
I would use sessions.  You can store the information you need after they've logged in, be it a token given by the login service or even just an isLoggedIn boolean value.

Then, you can check in pages that need it (Inheriting from a base page class is great for this) that the information is there.  If not, kick them back out.

So, in your code that processes the response from the claims-based auth (I do a lot of work with CAS and Shibboleth, two claims-based systems in heavy use in academia), you'd do something like :

```<code>if(isSuccessfulLogin)
{
    Session.Add("isLoggedIn",true);
    Session.Add("userId", userIDfromService);
}
</code>```

Then, in your Page_Load method, you'd just do something like:

```<code>if(Session["isLoggedIn"])
{
    // do whatever
}
else
{
    // redirect somewhere
}
</code>```

These are very simplified, and leave out the details.

Body:
I would use sessions.  You can store the information you need after they've logged in, be it a token given by the login service or even just an isLoggedIn boolean value.

Then, you can check in pages that need it (Inheriting from a base page class is great for this) that the information is there.  If not, kick them back out.

So, in your code that processes the response from the claims-based auth (I do a lot of work with CAS and Shibboleth, two claims-based systems in heavy use in academia), you'd do something like :

if(isSuccessfulLogin)
{
    Session.Add("isLoggedIn",true);
    Session.Add("userId", userIDfromService);
}

Then, in your Page_Load method, you'd just do something like:

if(Session["isLoggedIn"])
{
    // do whatever
}
else
{
    // redirect somewhere
}

These are very simplified, and leave out the details.


答:
I'm taking you at your word regarding the legality of the site you're proposing.  Ad blocking or content archival are two uses that come to mind. I can see where going into the details of that aspect would push the question into TL;DR territory or obscure the question at hand.

Your comment about pulling public documents from government sites adds a third legit use case.  Gov't sites are often horribly formatted and don't cross-link related information well, so I can see the benefits of such a service.

You are likely going to need two servers.  One will have a fixed address, the other will have the variable address.  I presume you need at least one fixed address so the users can find the service you are providing.

The fixed address will present your main site where the ad-blocking scrape requests come in.  That server will queue up the requests that it receives; I'm thinking a message queue will handle this nicely.  The fixed IP server will forward the messages and receive the replies when the variable address server is available.  Consider having a "pending" queue in addition to the "requested" and "received" queues.  That way you can retry a message in case the variable IP server went down before the request was received.

The variable IP server will have a couple of requirements:

Receive messages to scrape sites of ads

Return the formatted sites in a reply message

Detect when the server appears blocked by the target site

Request a new IP address from the hosting cloud

Notify fixed IP server of new address

If a reboot is required, have some sort of persistence layer to keep track of what it's working on.

Take a look into various cloud providers in order to find a server that can easily / quickly change IP addresses.  To my knowledge, many of the larger providers automatically provide a new IP address on each reboot of the machine.  As an added bonus, you may not even need to keep the variable IP server up and running all the time.  It could simply be invoked by the fixed IP server as needed, although there is some delay for a virtual server to spin up like that.

I'm not sure any other technology would provide the potential range of IP addresses that you may need.  A virtual network still requires an external IP address to request content, and that external IP is the one that will get blocked.  I doubt an ISP would be willing / want you to be cycling through IP addresses like that even if they have a large block available.


答:
Non-technical solution: Have you considered contacting the content owner(s)?

If the content is PD or CC then perhaps the content owner would be willing to provide you with an archive of the content, so that you don't need to bother with scraping.

If the site owner is not the original content owner then try to find the original source where he obtained it from.


答:
Take a look at http://www.asp.net/web-forms/videos/authentication.  It seems like its geared towards a newcomer audience.  (Yes, it says web-forms, but the information is applicable to a broader scope).

Asp.net already has libraries built in for the basics.  You should look into RoleProvider and MembershipProvider.

Basically, you should authenticate each HTTP request.  How you perform authentication and how you persist it is up to you.  It's possible to store a cookie on the client, use a session, etc...

The definitive guide to forms based website authentication is a nice cross-platform list of do's and don'ts.  Tons of info there, and once you're up and running, this will have a bunch of gotchas you may have missed.

Title: How does authentication work with ASP.NET (using Live ID and\or Windows Authentication)

Body:
I'm primarily a .NET desktop app programmer. Coming into the web world has been difficult. I'm trying to convert one of my Silverlight apps into HTML. But I'm having a hard time figuring out the authentication system. I'm trying to read up on Live ID authentication and Windows Authentication but I'm having a hard time putting it all together in my head. Perhaps you can help?

My App Framework

My client application is a TypeScript (javascript) HTML page (or pages). And the server is a WCF Data Services REST API hosted in ASP.NET. The service works with a SQL database.

The Problems (Claims Based)

When I look at something like Live ID authentication, it's known as claims-based authentication, right? So if I had this implemented correctly, someone comes to the website, I need to verify that they are logged in. How do I do that from a client-side HTML page? Do I have a recurring timer that is validating the login every 30 seconds or something? Or is that done server-side on each call to the service?

I know that if they aren't logged in, I need to send them to the live login page, once they log in, the live page will redirect them to my server with the authorization token in the query string (or something like this). At this point though, what do I do 5 minutes down the line when they make a call to the webservice for data? Is that token sent on every call to the server some how? How do I validate that when they call the service, it is actually them? Do I have to wrap every service call in a ValidateUser() method or something? I have a user ID in the database that I would have to match with their user token somehow.

The Problems (Windows Authentication)

The previous problem still exists here. How do I know that every call from the client is still them? Additionally though, I need to understand what do I do from the HTML side to the server side to authenticate them and then continue the authentication.

Conclusion

I cannot really find any sort of explanation that conceptually explains all of this information and gives me the big picture of how it all works. I'm really hoping someone here can fill in these gaps and give me a better idea on how to implement the client and server authentication.

Thanks!

Update

I found a great book that really explains a lot of this. It's entitled "A Guide to Claims-Based Identity and Access Control". It's part of the patterns & practices series.

Thanks to all for your answers and put me on the right track.


问:
Refactoring: Two big chunks within a function
I am designing an API which mostly involves refactoring the original code.

So Right now I have a method which has two big chunks which are seperated by an If-else condition, which in my opinion is not exactly the best idea.

The code looks like

```<code>do_something():
     if (isTrue):
         #Large block of statements.
     else:
         #another large block of statements.
</code>```

The reason I have them both under a single function is because both the chunks do the same thing but with some slight variations, which introduces the ugly if-else block.

I wanted to know what would be the best idea to refactor this code in a better way, if it is possible to do that using OOP, that would be even better.

I am not going with the obvious defining two methods way because at the moment both the chunks are doing the same thing.

答: You're saying the two chunks "do the same thing but with some slight variations". Are the variations small enough that you could replace each of the chunks with the same function, controlled by slightly different arguments? Don't do this if it would create even uglier code with lots of if/then tests, of course; but if the two chunks "do the same thing", think about what they have in common and try to factor it out into a single function.


问:
Java or C++ for university CS courses?
I'm in the throes of getting myself enrolled in school to get a CS degree. The school I am looking at actually offers both Java- and C++-based for the introductory software development courses (object-oriented programming, design patterns, that sort of thing). It is student's choice which track to follow, but there is only time to follow one.

Knowing what you know now, if you had the choice, would you lay down your CS curriculum foundation in Java or C++?

My current debate currently looks like this:

A good friend (who has a PhD in AI) is touting Java as the better choice regardless of what I do, if only to open up more job opportunities later, though he might be biased since all of his work has been in Java (he loves it). I live in the Boston, MA, USA area and I see an equal amount of Java and C work.

On the flip side, although I haven't entirely yet settled on what I want to do with the degree when I'm done, my preference would be to develop for the Mac, which I am doing now albeit in a limited capacity. To that end, I'm getting some limited exposure to C++ already, but I've had none with Java, and looking at my projects at my day job I don't see a need to use it anytime soon, "soon" measured by at least two years.

I probably should note that I'm an adult going back to school after 20 years (I currently have no degree of any kind) so I'm looking to maximize the opportunity and time spent as best I can. I'm kind of leaning towards C++ but I'm still ambivalent, and some outside, objective advice would help here.

Or I could just be thinking too hard about it.

UPDATE: It turns out the language selection wasn't so clear cut as I originally surmised. While a couple of core courses focused on Java, some of the other core courses work in primarily C and Java, but also a few others thrown in for good measure. In fact, my rest of my semester is going to be in Objective-C after spending time in Java and Javascript. Last semester was C, Javascript, and PHP, plus a few others thrown in as assignments required. Since things were pretty much split down the middle overall, and I am still getting answers to this, I am now trying to work my curriculum such that I meet all of the requirements for the degree but to absorb as many languages as I can reasonably handle. So far, my grades have not suffered trying to do this.

答:
C++ is the more flexible and offers a deeper of understanding. Unquestionably, you will gain more from C++ than from Java. C++ is also harder, because it's more complex.

That said, C++ jobs are not nearly as common as Java jobs.

Java and its descendant, C#, are the standard solutions for the enterprise/corporate big-iron coding space. I strongly recommend learning one of the two in your second year and being very comfortable with that one by the time you finish your degree. It will let you get jobs much easier. That does not mean I think those jobs have significant intellectual interest on average. I made a pass through craigslist software jobs in the Rocky Mountains recently and most of the jobs were C#/Java and related to what is termed "CRUD" software; IMO that's very boring.

Title: Java or C++ for university CS courses?


答:
Haskell does not have references (a reference is a mutable object, and Haskell does not have (directly-accessible) mutable objects). Therefore function calls use value semantics, kind of by default. This is in fact an important property of pure functional languages: a function cannot modify its argument.

Value semantics does not imply that copying happens under the hood. You only need to copy the part of a value that the function modifies, which in a pure language means you never need to copy anything.

However, this isn't the whole story. In a sense, Haskell has reference semantics.

While it is meaningless to test whether a function modifies its argument (it never does), you can test whether a function uses (part of) its argument. Supply it with an argument that does not terminate. If the function call terminates, you know the function didn't use its argument.

```<code>let bottom = bottom
let ignore x = 1
ignore bottom
</code>```

If you evaluate bottom, it does not terminate: bottom expands to itself, ad nauseam. The term bottom cannot have a value. But if you evaluate ignore bottom, the value is 1. This shows that calling the function ignore does not require to calculating the value of its argument. In this sense, Haskell has a reference semantics: what a function receives is not a value but something that allows this value to be found. The technical term is call by name (as opposed to call by value).

(More precisely, Haskell implementations use call by need. In call by value, the argument of a function is evaluated exactly once, just before calling the function. In call by name, the argument is evaluated each time it is used, which can range from never to as many times as the function wants. In call by need, the argument is evaluated at most once: it is evaluated the first time it is used, or never if it isn't used.)

Body:
Haskell does not have references (a reference is a mutable object, and Haskell does not have (directly-accessible) mutable objects). Therefore function calls use value semantics, kind of by default. This is in fact an important property of pure functional languages: a function cannot modify its argument.

Value semantics does not imply that copying happens under the hood. You only need to copy the part of a value that the function modifies, which in a pure language means you never need to copy anything.

However, this isn't the whole story. In a sense, Haskell has reference semantics.

While it is meaningless to test whether a function modifies its argument (it never does), you can test whether a function uses (part of) its argument. Supply it with an argument that does not terminate. If the function call terminates, you know the function didn't use its argument.

let bottom = bottom
let ignore x = 1
ignore bottom

If you evaluate bottom, it does not terminate: bottom expands to itself, ad nauseam. The term bottom cannot have a value. But if you evaluate ignore bottom, the value is 1. This shows that calling the function ignore does not require to calculating the value of its argument. In this sense, Haskell has a reference semantics: what a function receives is not a value but something that allows this value to be found. The technical term is call by name (as opposed to call by value).

(More precisely, Haskell implementations use call by need. In call by value, the argument of a function is evaluated exactly once, just before calling the function. In call by name, the argument is evaluated each time it is used, which can range from never to as many times as the function wants. In call by need, the argument is evaluated at most once: it is evaluated the first time it is used, or never if it isn't used.)


答: Having maintained code that was a rat's nest of #ifdefs (although for different reasons), it is ridiculous; it makes code much more difficult to read and much more difficult to maintain, especially when testing against multiple conditions.

Title: hginit - #ifdefs ridiculous