问:
Multiple classes in a single .cs file - good or bad?
Is it advisable to create multiple classes within a .cs file or should each .cs file have an individual class?

For example:

```<code>public class Items
{
    public class Animal
    {
    }

    public class Person
    {
    }

    public class Object
    {
    }
}
</code>```

Dodging the fact for a minute that this is a poor example of good architecture, is having more than a single class in a .cs file a code smell?

答: Basically, if you only need to use this class from within the "parent" class (in terms of scope), then it is usually appropiate to define it as a nested class.</p>

OwnerDisplayName: Sergio


问:
Designing a REST API: setting business logic error codes in http headers or within the response payload
I am designing a REST api backend that is meant to be consumed by a javascript front-end.

I am not sure how to communicate server-side business logic errors (e.g. a user trying to retrieve his password with an unknown email, etc.) to the front-end.

After setting a 40x status code on the response, I need to add further detail about the error and I am hesitating between two options:

Setting custom HTTP headers in the response (e.g. X-Unknow-Email)

Setting a JSON in the HTTP response payload with the corresponding error code

Can anyone having already being exposed to designing REST APIs please tell me what the pros and cons are for the two solutions being considered above?

答:
The best way to do this, in my experience, is to describe a universal error structure for your API. Something like this might suffice:

```<code>{
  "errorCategory": "Authentication/Authorization",
  "errorMessage": "Unknown email provided as part of authentication",
  "errorDetailURL": "http://api.company.com/documentation/email_auth_error.html",
  "errorId": "some-kind-of-identifer"
}
</code>```

This allows you to provide a category (which is not going to change, and thus is useful for client code), a message (which may change, and is best for manual auditing and testing), a more detailed URL (which can be used to provide documentation on how to address specific errors, without wasting bandwidth), and an ID for this instance of the error, which can be provided to your support team if the client believes it is a bogus error.

This can be used in both 40x and 50x errors, and must be consistent.

ContentLicense: CC BY-SA 3.0

Body:
The best way to do this, in my experience, is to describe a universal error structure for your API. Something like this might suffice:

{
  "errorCategory": "Authentication/Authorization",
  "errorMessage": "Unknown email provided as part of authentication",
  "errorDetailURL": "http://api.company.com/documentation/email_auth_error.html",
  "errorId": "some-kind-of-identifer"
}

This allows you to provide a category (which is not going to change, and thus is useful for client code), a message (which may change, and is best for manual auditing and testing), a more detailed URL (which can be used to provide documentation on how to address specific errors, without wasting bandwidth), and an ID for this instance of the error, which can be provided to your support team if the client believes it is a bogus error.

This can be used in both 40x and 50x errors, and must be consistent.


问:
Foreach loop and variable initialization
Is there a difference between these two versions of code?

```<code>foreach (var thing in things)
{
    int i = thing.number;
    // code using 'i'
    // pay no attention to the uselessness of 'i'
}
</code>```

```<code>int i;
foreach (var thing in things)
{
    i = thing.number;
    // code using 'i'
}
</code>```

Or does the compiler not care? When I'm speaking of difference I mean in terms of performance and memory usage. ..Or basically just any difference or do the two end up being the same code after compilation?

答:
Depending on what compiler you use (I don't even know if C# has more than one), your code will be optimised before being turned into a program. A good compiler will see that you're re-initialising the same variable each time with a different value and manage the memory space for it efficiently.

If you were initialising the same variable to a constant each time, the compiler would likewise initialise it before the loop and reference it.

It all depends how well your compiler is written, but as far as coding standards are concerned variables should always have the least possible scope. So declaring inside the loop is what I've always been taught.


答: I would say that option 2 makes it easier to understand what happened.  The client can know to look in the body for a message, which is the usual place information is found. In your option 1, not only would the client need to know to look at the headers (which is more work in many rest client libraries), it would also have to know which headers to look for.  In option 2, if need be, you can pass the string message to the user and let them figure out what it means.  I think it is safe to assume that if you return an error code (non-2XX), then the client will not expect an entity in the response body, so it is ok to replace that with the message.

Title: Designing a REST API: setting business logic error codes in http headers or within the response payload

Body:
I am designing a REST api backend that is meant to be consumed by a javascript front-end.

I am not sure how to communicate server-side business logic errors (e.g. a user trying to retrieve his password with an unknown email, etc.) to the front-end.

After setting a 40x status code on the response, I need to add further detail about the error and I am hesitating between two options:

Setting custom HTTP headers in the response (e.g. X-Unknow-Email)

Setting a JSON in the HTTP response payload with the corresponding error code

Can anyone having already being exposed to designing REST APIs please tell me what the pros and cons are for the two solutions being considered above?


问:
Is remote agile sustainable?
This is somewhat related to another question i just asked, but I'm freelancing solo and remotely for a contractor who is to project management, what big ball of mud is to code, so to speak.

I've been thinking a lot about working on a proposition to deal with his projects in a truly agile way. As I see it, this would involve several client-friendly and web-based apps :

basecamp for communication

github as a repository

pivotal tracker for user-stories and as a display of work in progress

some tool to gather acceptance tests (will upvote suggestions !)

I've done a fair bit of reading on agile, and all good resources put much emphasis on the importance of communication in the team, to the point they are discouraging agile for non-colocated teams.
Being the only programmer this seemed less of an issue, but as I'll rarely meet the client (if at all), I'm worried the communication may not be effective enough to enable this kind of management.

Edit : Other people on the team would include :

- customers (business people)

- product manager (my client's client)

- project manager (my client)

- ui designer

答:
I've worked on a few projects that used a remote agile development strategy, with varying results.

The experience level of the team is the key factor, if everyone involved is competent with this strategy and the tools (or can become competent quickly) Then it's a sustainable.

The problems of remote work are often due to lack of communication, both 'face-to-face' and poor use of project tracking tools and SCM/VCS.  The most successful agile projects I've worked on remotely involved the following.

Daily face-to-face / VOIP morning scrum style meetings.

Clear iteration plans (this is heavily reliant on a good project manager, plus good, communicative developers.)

Automation tools such as continuous integration / build servers.

Diligent use of project tracking tools (and the quality thereof.)

Cohesive use of VCS/SCM with a well understood team strategy for commit and branching.

Good project tracking tools I'd recommend are Redmine, TargetProcess and Jira. My experiences with TargetProcess were particularly effective, mostly due to the competency level of the PM on those projects.

A great team is without doubt the fundamental key to success on remote (and frankly any) projects, in close second are the tools used to facilitate the project management and development.

One other point, if pairs of developers can work colocal then there is a definite benefit over solo developers, in terms of motivation and of course, continuous code-review.

ContentLicense: CC BY-SA 2.5

Title: Is remote agile sustainable?


答:
TL;DR - they're equivalent examples at the IL layer.

DotNetFiddle makes this pretty to answer as it allows you to see the resulting IL.

I used a slightly different variation of your loop construct in order to make my testing quicker.  I used:

Variation 1:

```<code>using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        int x;
        int i;

        for(x=0; x<=2; x++)
        {
            i = x;
            Console.WriteLine(i);
        }
    }
}
</code>```

Variation 2:

```<code>        Console.WriteLine("Hello World");
        int x;

        for(x=0; x<=2; x++)
        {
            int i = x;
            Console.WriteLine(i);
        }
</code>```

In both cases, the compiled IL output rendered the same.

```<code>.class public auto ansi beforefieldinit Program
       extends [mscorlib]System.Object
{
  .method public hidebysig static void  Main() cil managed
  {
    //
    .maxstack  2
    .locals init (int32 V_0,
             int32 V_1,
             bool V_2)
    IL_0000:  nop
    IL_0001:  ldstr      "Hello World"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ldc.i4.0
    IL_000d:  stloc.0
    IL_000e:  br.s       IL_001f

    IL_0010:  nop
    IL_0011:  ldloc.0
    IL_0012:  stloc.1
    IL_0013:  ldloc.1
    IL_0014:  call       void [mscorlib]System.Console::WriteLine(int32)
    IL_0019:  nop
    IL_001a:  nop
    IL_001b:  ldloc.0
    IL_001c:  ldc.i4.1
    IL_001d:  add
    IL_001e:  stloc.0
    IL_001f:  ldloc.0
    IL_0020:  ldc.i4.2
    IL_0021:  cgt
    IL_0023:  ldc.i4.0
    IL_0024:  ceq
    IL_0026:  stloc.2
    IL_0027:  ldloc.2
    IL_0028:  brtrue.s   IL_0010

    IL_002a:  ret
  } // end of method Program::Main
</code>```

So to answer your question: the compiler optimizes out the declaration of the variable, and renders the two variations equivalent.

To my understanding, the .NET IL compiler moves all variable declarations to the beginning of the function but I couldn't find a good source that clearly stated that2. In this particular example, you see that it moved them up with this statement:

```<code>    .locals init (int32 V_0,
             int32 V_1,
             bool V_2)
</code>```

Wherein we get a bit too obsessive in making comparisons....

Case A, do all variables get moved up?

To dig into this a bit further, I tested the following function:

```<code>public static void Main()
{
    Console.WriteLine("Hello World");
    int x=5;

    if (x % 2==0)
    {
        int i = x;
        Console.WriteLine(i);
    }
    else
    {
        string j = x.ToString();
        Console.WriteLine(j);
    }
}
</code>```

The difference here is that we declare either an int i or a string j based upon the comparison.  Again, the compiler moves all the local variables to the top of the function2 with:

```<code>.locals init (int32 V_0,
         int32 V_1,
         string V_2,
         bool V_3)
</code>```

I found it interesting to note that even though int i won't be declared in this example, the code to support it is still generated.

Case B: What about foreach instead of for?

It was pointed out that foreach has different behavior than for and that I wasn't checking the same thing that had been asked about.  So I put in these two sections of code to compare the resulting IL.

int declaration outside of the loop:

```<code>    Console.WriteLine("Hello World");
    List<int> things = new List<int>(){1, 2, 3, 4, 5};
    int i;

    foreach(var thing in things)
    {
        i = thing;
        Console.WriteLine(i);
    }
</code>```

int declaration inside of the loop:

```<code>    Console.WriteLine("Hello World");
    List<int> things = new List<int>(){1, 2, 3, 4, 5};

    foreach(var thing in things)
    {
        int i = thing;
        Console.WriteLine(i);
    }
</code>```

The resulting IL with the foreach loop was indeed different from the IL generated using the for loop.  Specifically, the init block and the loop section changed.

```<code>.locals init (class [mscorlib]System.Collections.Generic.List`1<int32> V_0,
         int32 V_1,
         int32 V_2,
         class [mscorlib]System.Collections.Generic.List`1<int32> V_3,
         valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32> V_4,
         bool V_5)
...
.try
{
  IL_0045:  br.s       IL_005a

  IL_0047:  ldloca.s   V_4
  IL_0049:  call       instance !0 valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32>::get_Current()
  IL_004e:  stloc.1
  IL_004f:  nop
  IL_0050:  ldloc.1
  IL_0051:  stloc.2
  IL_0052:  ldloc.2
  IL_0053:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_0058:  nop
  IL_0059:  nop
  IL_005a:  ldloca.s   V_4
  IL_005c:  call       instance bool valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32>::MoveNext()
  IL_0061:  stloc.s    V_5
  IL_0063:  ldloc.s    V_5
  IL_0065:  brtrue.s   IL_0047

  IL_0067:  leave.s    IL_0078

}  // end .try
finally
{
  IL_0069:  ldloca.s   V_4
  IL_006b:  constrained. valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32>
  IL_0071:  callvirt   instance void [mscorlib]System.IDisposable::Dispose()
  IL_0076:  nop
  IL_0077:  endfinally
}  // end handler
</code>```

The foreach approach generated more local variables and required some additional branching.  Essentially, on the first time in it jumps to the end of the loop to get the first iteration of the enumeration and then jumps back to almost the top of the loop to execute the loop code.  It then continues to loop through as you'd expect.

But beyond the branching differences caused by using the for and foreach constructs, there was no difference in the IL based upon where the int i declaration was placed.  So we're still at the two approaches being equivalent.

Case C: What about different compiler versions?

In a comment that was left1, there was a link to an SO question regarding a warning about variable access with foreach and using closure.  The part that really caught my eye in that question was that there may have been differences in how the .NET 4.5 compiler worked versus earlier versions of the compiler.

And that's where the DotNetFiddler site let me down - all they had available was .NET 4.5 and a version of the Roslyn compiler.  So I brought up a local instance of Visual Studio and started testing out the code.  To make sure I was comparing the same things, I compared locally built code at .NET 4.5 to the DotNetFiddler code.

The only difference that I noted was with the local init block and variable declaration.  The local compiler was a bit more specific in naming the variables.

```<code>  .locals init ([0] class [mscorlib]System.Collections.Generic.List`1<int32> things,
           [1] int32 thing,
           [2] int32 i,
           [3] class [mscorlib]System.Collections.Generic.List`1<int32> '<>g__initLocal0',
           [4] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32> CS$5$0000,
           [5] bool CS$4$0001)
</code>```

But with that minor difference, it was so far, so good.  I had equivalent IL output between the DotNetFiddler compiler and what my local VS instance was producing.

So I then rebuilt the project targeting .NET 4, .NET 3.5, and for good measure .NET 3.5 Release mode.

And in all three of those additional cases, the generated IL was equivalent.  The targeted .NET version had no effect on the IL that was generated in these samples.

To summarize this adventure:  I think we can confidently say that the compiler does not care where you declare the primitive type and that there is no effect upon memory or performance with either declaration method.  And that holds true regardless of using a for or foreach loop.

I considered running yet another case that incorporated a closure inside of the foreach loop.  But you had asked about the effects of where a primitive type variable was declared, so I figured I was delving too far beyond what you were interested in asking about.  The SO question I mentioned earlier has a great answer that provides a good overview about closure effects on foreach iteration variables.

1 Thank you to Andy for providing the original link to the SO question addressing closures within foreach loops.

2 It's worth noting that the ECMA-335 spec addresses this with section I.12.3.2.2 'Local variables and arguments'. I had to see the resulting IL and then read the section for it to be clear regarding what was going on.  Thanks to ratchet freak for pointing that out in chat.

Title: Foreach loop and variable initialization

Body:
Is there a difference between these two versions of code?

```<code>foreach (var thing in things)
{
    int i = thing.number;
    // code using 'i'
    // pay no attention to the uselessness of 'i'
}
</code>```

```<code>int i;
foreach (var thing in things)
{
    i = thing.number;
    // code using 'i'
}
</code>```

Or does the compiler not care? When I'm speaking of difference I mean in terms of performance and memory usage. ..Or basically just any difference or do the two end up being the same code after compilation?

Body:
TL;DR - they're equivalent examples at the IL layer.

DotNetFiddle makes this pretty to answer as it allows you to see the resulting IL.

I used a slightly different variation of your loop construct in order to make my testing quicker.  I used:

Variation 1:

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        int x;
        int i;

        for(x=0; x<=2; x++)
        {
            i = x;
            Console.WriteLine(i);
        }
    }
}

Variation 2:

        Console.WriteLine("Hello World");
        int x;

        for(x=0; x<=2; x++)
        {
            int i = x;
            Console.WriteLine(i);
        }

In both cases, the compiled IL output rendered the same.

.class public auto ansi beforefieldinit Program
       extends [mscorlib]System.Object
{
  .method public hidebysig static void  Main() cil managed
  {
    //
    .maxstack  2
    .locals init (int32 V_0,
             int32 V_1,
             bool V_2)
    IL_0000:  nop
    IL_0001:  ldstr      "Hello World"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ldc.i4.0
    IL_000d:  stloc.0
    IL_000e:  br.s       IL_001f

    IL_0010:  nop
    IL_0011:  ldloc.0
    IL_0012:  stloc.1
    IL_0013:  ldloc.1
    IL_0014:  call       void [mscorlib]System.Console::WriteLine(int32)
    IL_0019:  nop
    IL_001a:  nop
    IL_001b:  ldloc.0
    IL_001c:  ldc.i4.1
    IL_001d:  add
    IL_001e:  stloc.0
    IL_001f:  ldloc.0
    IL_0020:  ldc.i4.2
    IL_0021:  cgt
    IL_0023:  ldc.i4.0
    IL_0024:  ceq
    IL_0026:  stloc.2
    IL_0027:  ldloc.2
    IL_0028:  brtrue.s   IL_0010

    IL_002a:  ret
  } // end of method Program::Main

So to answer your question: the compiler optimizes out the declaration of the variable, and renders the two variations equivalent.

To my understanding, the .NET IL compiler moves all variable declarations to the beginning of the function but I couldn't find a good source that clearly stated that2. In this particular example, you see that it moved them up with this statement:

    .locals init (int32 V_0,
             int32 V_1,
             bool V_2)

Wherein we get a bit too obsessive in making comparisons....

Case A, do all variables get moved up?

To dig into this a bit further, I tested the following function:

public static void Main()
{
    Console.WriteLine("Hello World");
    int x=5;

    if (x % 2==0)
    {
        int i = x;
        Console.WriteLine(i);
    }
    else
    {
        string j = x.ToString();
        Console.WriteLine(j);
    }
}

The difference here is that we declare either an int i or a string j based upon the comparison.  Again, the compiler moves all the local variables to the top of the function2 with:

.locals init (int32 V_0,
         int32 V_1,
         string V_2,
         bool V_3)

I found it interesting to note that even though int i won't be declared in this example, the code to support it is still generated.

Case B: What about foreach instead of for?

It was pointed out that foreach has different behavior than for and that I wasn't checking the same thing that had been asked about.  So I put in these two sections of code to compare the resulting IL.

int declaration outside of the loop:

    Console.WriteLine("Hello World");
    List<int> things = new List<int>(){1, 2, 3, 4, 5};
    int i;

    foreach(var thing in things)
    {
        i = thing;
        Console.WriteLine(i);
    }

int declaration inside of the loop:

    Console.WriteLine("Hello World");
    List<int> things = new List<int>(){1, 2, 3, 4, 5};

    foreach(var thing in things)
    {
        int i = thing;
        Console.WriteLine(i);
    }

The resulting IL with the foreach loop was indeed different from the IL generated using the for loop.  Specifically, the init block and the loop section changed.

.locals init (class [mscorlib]System.Collections.Generic.List`1<int32> V_0,
         int32 V_1,
         int32 V_2,
         class [mscorlib]System.Collections.Generic.List`1<int32> V_3,
         valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32> V_4,
         bool V_5)
...
.try
{
  IL_0045:  br.s       IL_005a

  IL_0047:  ldloca.s   V_4
  IL_0049:  call       instance !0 valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32>::get_Current()
  IL_004e:  stloc.1
  IL_004f:  nop
  IL_0050:  ldloc.1
  IL_0051:  stloc.2
  IL_0052:  ldloc.2
  IL_0053:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_0058:  nop
  IL_0059:  nop
  IL_005a:  ldloca.s   V_4
  IL_005c:  call       instance bool valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32>::MoveNext()
  IL_0061:  stloc.s    V_5
  IL_0063:  ldloc.s    V_5
  IL_0065:  brtrue.s   IL_0047

  IL_0067:  leave.s    IL_0078

}  // end .try
finally
{
  IL_0069:  ldloca.s   V_4
  IL_006b:  constrained. valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32>
  IL_0071:  callvirt   instance void [mscorlib]System.IDisposable::Dispose()
  IL_0076:  nop
  IL_0077:  endfinally
}  // end handler

The foreach approach generated more local variables and required some additional branching.  Essentially, on the first time in it jumps to the end of the loop to get the first iteration of the enumeration and then jumps back to almost the top of the loop to execute the loop code.  It then continues to loop through as you'd expect.

But beyond the branching differences caused by using the for and foreach constructs, there was no difference in the IL based upon where the int i declaration was placed.  So we're still at the two approaches being equivalent.

Case C: What about different compiler versions?

In a comment that was left1, there was a link to an SO question regarding a warning about variable access with foreach and using closure.  The part that really caught my eye in that question was that there may have been differences in how the .NET 4.5 compiler worked versus earlier versions of the compiler.

And that's where the DotNetFiddler site let me down - all they had available was .NET 4.5 and a version of the Roslyn compiler.  So I brought up a local instance of Visual Studio and started testing out the code.  To make sure I was comparing the same things, I compared locally built code at .NET 4.5 to the DotNetFiddler code.

The only difference that I noted was with the local init block and variable declaration.  The local compiler was a bit more specific in naming the variables.

  .locals init ([0] class [mscorlib]System.Collections.Generic.List`1<int32> things,
           [1] int32 thing,
           [2] int32 i,
           [3] class [mscorlib]System.Collections.Generic.List`1<int32> '<>g__initLocal0',
           [4] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32> CS$5$0000,
           [5] bool CS$4$0001)

But with that minor difference, it was so far, so good.  I had equivalent IL output between the DotNetFiddler compiler and what my local VS instance was producing.

So I then rebuilt the project targeting .NET 4, .NET 3.5, and for good measure .NET 3.5 Release mode.

And in all three of those additional cases, the generated IL was equivalent.  The targeted .NET version had no effect on the IL that was generated in these samples.

To summarize this adventure:  I think we can confidently say that the compiler does not care where you declare the primitive type and that there is no effect upon memory or performance with either declaration method.  And that holds true regardless of using a for or foreach loop.

I considered running yet another case that incorporated a closure inside of the foreach loop.  But you had asked about the effects of where a primitive type variable was declared, so I figured I was delving too far beyond what you were interested in asking about.  The SO question I mentioned earlier has a great answer that provides a good overview about closure effects on foreach iteration variables.

1 Thank you to Andy for providing the original link to the SO question addressing closures within foreach loops.

2 It's worth noting that the ECMA-335 spec addresses this with section I.12.3.2.2 'Local variables and arguments'. I had to see the resulting IL and then read the section for it to be clear regarding what was going on.  Thanks to ratchet freak for pointing that out in chat.


问:
Best way to unit test methods that call other methods inside same class
I was recently discussing with some friends which of the following 2 methods is best to stub return results or calls to methods inside same class from methods inside same class.

This is a very simplified example. In reality the functions are much more complex.

Example:

```<code>public class MyClass
{
     public bool FunctionA()
     {
         return FunctionB() % 2 == 0;
     }

     protected int FunctionB()
     {
         return new Random().Next();
     }
}
</code>```

So to test this we have 2 methods.

Method 1:
Use Functions and Actions to replace functionality of the methods.
Example:

```<code>public class MyClass
{
     public Func<int> FunctionB { get; set; }

     public MyClass()
     {
         FunctionB = FunctionBImpl;
     }

     public bool FunctionA()
     {
         return FunctionB() % 2 == 0;
     }

     protected int FunctionBImpl()
     {
         return new Random().Next();
     }
}

[TestClass]
public class MyClassTests
{
    private MyClass _subject;

    [TestInitialize]
    public void Initialize()
    {
        _subject = new MyClass();
    }

    [TestMethod]
    public void FunctionA_WhenNumberIsOdd_ReturnsTrue()
    {
        _subject.FunctionB = () => 1;

        var result = _subject.FunctionA();

        Assert.IsFalse(result);
    }
}
</code>```

Method 2:
Make members virtual, derive class and in derived class use Functions and Actions to replace functionality
Example:

```<code>public class MyClass
{
     public bool FunctionA()
     {
         return FunctionB() % 2 == 0;
     }

     protected virtual int FunctionB()
     {
         return new Random().Next();
     }
}

public class TestableMyClass
{
     public Func<int> FunctionBFunc { get; set; }

     public MyClass()
     {
         FunctionBFunc = base.FunctionB;
     }

     protected override int FunctionB()
     {
         return FunctionBFunc();
     }
}

[TestClass]
public class MyClassTests
{
    private TestableMyClass _subject;

    [TestInitialize]
    public void Initialize()
    {
        _subject = new TestableMyClass();
    }

    [TestMethod]
    public void FunctionA_WhenNumberIsOdd_ReturnsTrue()
    {
        _subject.FunctionBFunc = () => 1;

        var result = _subject.FunctionA();

        Assert.IsFalse(result);
    }
}
</code>```

I want to know wich is better and also WHY ?

Update:
NOTE: FunctionB can also be public

答:
I personally use Method1 i.e. making all methods into Actions or Funcs as this has hugely improved code testability for me. As with any solution there are pros and cons with this approach:

Pros

Allows for simple code structure where using Code Patterns just for Unit Testing might add additional complexity.

Allows classes to be sealed and for the elimination of virtual methods that are required by popular mocking frameworks like Moq. Sealing classes and eliminating virtual methods makes them candidates for inlining and other compiler optimizations. (https://msdn.microsoft.com/en-us/library/ff647802.aspx)

Simplifies testability as replacing the Func/Action implementation in a Unit test is as simple as just assigning a new value to the Func/Action

Also allows for testing if a static Func was called from another method since static methods can not be mocked.

Easy to refactor existing methods to Funcs/Actions since the syntax
for calling a method on the call site remains the same. (For times
when you can't refactor a method into a Func/Action see cons)

Cons

Funcs/Actions can't be used if your class can be derived as Funcs/Actions have no inheritance paths like Methods

Can't use default parameters. Creating a Func with default parameters entails creating a new delegate which might make the code confusing depending on the use case

Can't use the named parameter syntax for calling methods like something(firstName: "S", lastName: "K")

The biggest Con is that you don't have access to the 'this' reference in Funcs and Actions, and so any dependencies on the class must be explicitly passed in as parameters. Its good as you know all dependencies but bad if you have many properties that your Func will depend on. Your mileage will vary based on your use case.

So to sum up, using Funcs and Actions for Unit test is great if you know that your classes are never going to be overridden.

Also, I usually don't create properties for Funcs but inline them directly as such

```<code>public class MyClass
{
     public Func<int> FunctionB = () => new Random().Next();

     public bool FunctionA()
     {
         return FunctionB() % 2 == 0;
     }
}
</code>```

Hope this helps!

Body:
I personally use Method1 i.e. making all methods into Actions or Funcs as this has hugely improved code testability for me. As with any solution there are pros and cons with this approach:

Pros

Allows for simple code structure where using Code Patterns just for Unit Testing might add additional complexity.

Allows classes to be sealed and for the elimination of virtual methods that are required by popular mocking frameworks like Moq. Sealing classes and eliminating virtual methods makes them candidates for inlining and other compiler optimizations. (https://msdn.microsoft.com/en-us/library/ff647802.aspx)

Simplifies testability as replacing the Func/Action implementation in a Unit test is as simple as just assigning a new value to the Func/Action

Also allows for testing if a static Func was called from another method since static methods can not be mocked.

Easy to refactor existing methods to Funcs/Actions since the syntax
for calling a method on the call site remains the same. (For times
when you can't refactor a method into a Func/Action see cons)

Cons

Funcs/Actions can't be used if your class can be derived as Funcs/Actions have no inheritance paths like Methods

Can't use default parameters. Creating a Func with default parameters entails creating a new delegate which might make the code confusing depending on the use case

Can't use the named parameter syntax for calling methods like something(firstName: "S", lastName: "K")

The biggest Con is that you don't have access to the 'this' reference in Funcs and Actions, and so any dependencies on the class must be explicitly passed in as parameters. Its good as you know all dependencies but bad if you have many properties that your Func will depend on. Your mileage will vary based on your use case.

So to sum up, using Funcs and Actions for Unit test is great if you know that your classes are never going to be overridden.

Also, I usually don't create properties for Funcs but inline them directly as such

public class MyClass
{
     public Func<int> FunctionB = () => new Random().Next();

     public bool FunctionA()
     {
         return FunctionB() % 2 == 0;
     }
}

Hope this helps!


问:
Version control of a website : dev/production front-end files
I'm trying to think of a better way to version control our website projects. Keep in mind I'm only a front-end dev so I don't have a profound knowledge of VCS.

Workflows are changing, and past version control habits become obsolete.
The main problem is there are 2 arrays of front-end files for each website.

The dev environment (less files, uncompressed js, images, etc). The build environment, "gulpified" (everything compressed and not readable by humans).

But you can't sell a website with its source files. Well, it feels not quite right.

There's the solution of having 2 repos : one build, one dev, with gulp sending dev files to build directory. But its a hassle to maintain, with small companies I don't think it's that great. It creates a lot of repos, and people have to manage with several repos, sometimes even with one svn repo, problems arise.

So there's also the solution of having 1 repo : the source files and the prod files in the same svn. But then it is needed to remove the source files when the website goes from local dev server to production server (so there are different files in a single repository, based on its location, dev or production..). From what I heard, it's not good

What is the correct way of managing a gulp front-end workflow in regard to version control system ?

答:
One basic rule of source control is that you need only to put manual written artifacts into the repo (the original source files), everything which can be "compiled" or "generated" does not need to be stored there, because it will produce redundancy. One can (optionally) store intermediate outputs/parts of a build process in a repo (sometimes also called artifacts), when the steps to reproduce them are not fully automatic, or for caching purposes, when the build steps to reproduce the output is slow.

So if you have a fully automated process to generate the production files from your dev source files, you only need put the dev files into source control (together with the scripts for creating the production files). If not, establish such a process. Make sure noone has to fiddle around with the production files manually after they have been generated from the source.  If you want to deploy "directly" from your VCS, make sure you have a deploy script which pulls the dev source files out of source control, does the "gulpification" and transfers the resulting files over to production in one step.

Of course, if you want to use source control also as a "poor mans backup" or as a cache for your production files, you can set up a second repo for this purpose and put there a copy of the production file structure after generation. This repo will not serve for development, and after it is set up, you should not have to maintain it manually. So make sure there will be no manual steps involved for making backups into this "prod repo" - include the necessary steps into the deploy script which makes the backup automatically. Think about adding a separate backup script if you cannot prohibit manual changes to production after deployment. That way, you can keep the process maintainable even if you have limited resources.

And yes, this should be a strictly separated, second repo, because it has a completely different purpose and a different life cycle than you dev repo. You use it only for backups, not for source control, which is a different process.


问:
How can I transition to a job using the Microsoft stack?
I graduated from university with a computer science degree (BSc), having done some C, C++, Java, Python, and Oracle along the way. I did some freelancing while I was at university and carried this into a full time job when I graduated, and I've been working full time for a year now.

PHP isn't really what I want to do, and I think it's limiting my opportunities the longer I stay along this path. It's not a language I like to use on a daily basis, and I would like to work in a larger organization, where it doesn't seem PHP has much use.

I want to stay in web development, and there seems to be plenty of jobs for the Microsoft stack: C#, SQL Server, and ASP.NET MVC. But beyond a half semester writing common-line C++ in Visual Studio, I have no experience with Microsoft technology.

Where do I start to make the transition to landing a job in a Microsoft shop? Are there any specific certifications I should be focusing on, or university courses I should be taking? What are employers or recruiters looking for?

What can I do besides creating a pet project in my spare time?

答:
You don't like PHP, so avoiding jobs in that area is pretty easy. Lot's of jobs in the web/Microsoft area, but are these the types of companies you want to work for?

There are three types of jobs:

Software / Web Service Company

Consultancy

Company in some other industry that want to hire in-house programmers.

Not sure #1 does a lot of C#, but you'll have to find that out for yourself. Have you considered Python or Ruby?

You have a job, so you shouldn't be too desperate. Pick a company you want to work for and see what they require. With your education and experience, self-study is the best option. Shouldn't be too hard convincing employers you know what you're doing and are capable of picking up new languages. There are no definitive paths; be prepared to sell your skills.


问:
call function once again after failure, without duplicate lines?
I have what is probably an over-engineering question. I have some PHP code that logs messages to a file. We've been having a problem with the file having the wrong perms from time to time. While we're troubleshooting that, I am writing a work-around for that in the logging function, changing the unix perms and owners on the log file.

So my code looks like this:

```<code>function log($message) {
  if ( FALSE === file_put_contents(log_path(), $message) ) {
    chown(log_path(), 'apache');
    chgrp(log_path(), 'www-data');
    chown(log_path(), 0770);

    // now I'm repeating this line
    if ( FALSE === file_put_contents(log_path(), $message) ) {
      // log error to database
      db_log($message);
    }
  }
}
</code>```

In the interest of DRY, can I somehow change the code to avoid repeating the line if ( FALSE === file_put_contents(log_path(), $message) ) {? Of course, I can't use recursion, because that would go on forever.

答:
It's unnecessary, but if you want to dry this up:</p>

```<code>function and_($now, $then) {
    return function($seed) use($now, $then) {
        return $now($seed) && $then($seed);
    };
}

function or_($now, $else) {
    return function($seed) use($now, $else) {
        return $now($seed) || $else($seed);
    };
}

function write_message($message) {
  return file_put_contents(log_path(), $message);
}

function fix_file($message) {
  chown(log_path(), 'apache');
  chgrp(log_path(), 'www-data');
  chown(log_path(), 0770);
  return TRUE;
}

function log_($message) {
    $log = or_('write_message', and_('fix_file', or_('write_message', 'db_log')));
    $log($message);
}
</code>```

Body:
It's unnecessary, but if you want to dry this up:

function and_($now, $then) {
    return function($seed) use($now, $then) {
        return $now($seed) && $then($seed);
    };
}

function or_($now, $else) {
    return function($seed) use($now, $else) {
        return $now($seed) || $else($seed);
    };
}

function write_message($message) {
  return file_put_contents(log_path(), $message);
}

function fix_file($message) {
  chown(log_path(), 'apache');
  chgrp(log_path(), 'www-data');
  chown(log_path(), 0770);
  return TRUE;
}

function log_($message) {
    $log = or_('write_message', and_('fix_file', or_('write_message', 'db_log')));
    $log($message);
}


问:
Is there a benefit to unit testing code whose sole purpose is to generate non-human-readable code in another language?
A significant portion of the application I work on every day consists of Javascript that outputs a lot of (what might as well be) Excel spreadsheet formulas. Yes, Excel is barely a Turing-complete language, but the formulas are more than complex enough to qualify as "code". They're not meant to be human-readable or human-editable. The users never see these formulas at all, only the values which those formulas evaluate to.

The main problem with our codebase right now is a lack of automated testing, and thus far I've focused my efforts on integration tests which run both the Javascript and the formulas, then assert on the final values. After all, we don't care what formulas were used to create those values, so I don't really see the point in a unit test that asserts on the formulas produced by each piece of Javascript. I'd also expect such unit tests to be exceedingly brittle, as most of our changes to the Javascript code are intended to change the formulas in some way (albeit in a way that shouldn't affect most of the final values).

Note that the code which evaluates the formulas is owned by a different team, and they have loads of unit tests on it. I'm interested in tests for our code, the part that generates the formulas.

Also note that speed is a non-issue; the integration tests I've written so far are so fast they feel more like unit tests.

For the reasons given above I'm convinced that improving our integration test coverage is the higher priority, at least for now, but I honestly can't see any benefit at all to unit testing this code, which feels like a sign that I might be missing something important.

So, is there any purpose to having unit tests as well as integration tests for this particular kind of code, where the sole objective is to generate "code" in some other language, and nobody cares what "intermediate code" is used to achieve the final result?

答:
I would generally argue that there are uses. Those uses might not apply to you in this specific scenario, but they might.

What happens when your integration tests fail?

Now you get to dig into the code to narrow down what the actual root cause was. If you had unit tests for just the formula generation, it would provide clear evidence (without any work or guessing on your part) if it was the formula generation that broke or the execution bits.

What happens when you move to a new execution framework?

Presumably, your company will still need to calculate all of these values. If your execution framework changes, you're going to need to change your output syntax. Ideally you have some implementation agnostic form for your formulae. Unit tests help unsure that part of the code is right so that when you change your target syntax you can have confidence that you're not changing the semantics as well.

What happens when the execution framework is updated? Does it break your tests? How do you know that is what broke the tests?

Decoupling makes for less impact of changes, even in tests.

How long does it take?

Maybe not a problem for you, but integration tests tend to be more complex. That means slower to run, slower to write, slower to maintain. If unit tests are 95% as effective as the integration tests, but take half the time to make, they may be the better option (at least in part).

Again, these may not apply to you in this situation, but they would be my default arguments for unit testing even in an environment where integration tests seem abundantly sufficient.


问:
Should security restrictions cause a service to return null or throw an exception?
I'm in a bit of a disagreement with a more experienced developer on this issue, and wondering what others think about it; our environment is Java, EJB 3, services, etc.

The code I wrote calls a service to get things and to create things. The problem I ran into was that I got null pointer exceptions that didn't make sense. For example, when I ask the service to create an object, I get null back; when I try to look up an object with a known valid ID, I get null back. I spent some time trying to figure out what was wrong in my code; since I'm less experienced I usually assume I've done something wrong, but it turns out the reason for the null returns was security. If the user principal using my service didn't have the right permissions for the target service, then it simply returns null. Most other services here aren't documented very well either, so apparently this is just something you have to know.

This is rather confusing as a developer writing code that interacts with the service. It would make much more sense to me if the service thew an exception that would tell me that the user didn't have the proper permissions to load this thing or to create that thing; I would then immediately know why my service wasn't working as expected.

The more experienced developer who wrote the service argued that asking for the data is not an error condition, and that exceptions should only be thrown in an error condition, not when the user doesn't have access to the data. This data is often looked up in a GUI, and for those users without the right permissions, these things simply "do not exist". So, in short: asking is not wrong, hence no exception. Get methods return null because to those users those things "don't exist". Create methods return null when the user wasn't allowed to create that thing.

Is this normal and/or good practice? I prefer using exceptions because I find it much easier to know what's going on. So I would for example also prefer to throw a NotFoundException if you asked for an object with an invalid ID, rather than returning null.

答:
The more experienced developer who wrote the service argued that asking for the data is not an error condition, and that exceptions should only be thrown in an error condition, not when the user doesn't have access to the data.

From my point of view, this makes no sense.

Querying for data without permission should result in an exception, because it is an unexpected result - to get no result - without proper access.

Analogy: The responsecode for a GET without authorization is not 200 ok with no data, it's actually 401 Unauthorized.


问:
How to handle singular and plural parameters for functions
Often when I'm writing a set of utility functions, I find myself wanting a function that applies some logic to multiple items, as well as a function that does the same with just a single item. There are a lot of potential solutions to this, but I always find myself flipping back and forth.

I could write an exclusively singular version of the function (modify_item(item)) and use map, comprehension, or a foreach externally. I don't want to do this every danged time I call it with multiple items though.

I could write an exclusively explicitly plural version of the function (modify_items(items)) that does the iteration inside. But I don't want to call it with a list every time either. Better than always singular, but still awkward to call. This would also support bulk operations better.

I could write an agnostic function that checks the input's type (modify_item(item)). If it's not iterable, it'll wrap it in a list and then iterate. This seems to be the best option, but the lure of star operators always gets me...

I could write an agnostic function that takes a variable number of inputs (modify_item(*items)) and iterates over them. This gives me a good calling syntax and automatically packs the items into an iterable for me. The problem I always run into here is that adding subsequent arguments or keyword arguments is awkward.

Finally, I could just throw up my hands and write a plural function as above, and a singular one that would wrap the parameter in a list and pass it to the plural one. Then I'd have to write double the functions, which is silly.

It seems like javascript libraries usually do the type checking option (#3), and that's the one I like best. In that case, you have the question of naming conventions. I think I favor singular, but I'm not sure about that.

Examples are in python, but this question could be applied to most languages.

答:
A friend of mine convinced me of option number three, with the addition that he uses a helper function called ensure_plural to ensure that the input is plural before continuing. This keeps it nice and declarative. The helper function could take a few different forms:

As a decorator, it would just modify the inputs before even getting to the main function. The problem is that it would have to assume some stuff.

It could just be called on the value that needs to be plural when necessary.

I've also come up with a version called if_plural, which would take a value and a function and return the result of applying the function directly to the value if singular, or of mapping the function over the value if plural.

OwnerDisplayName: JStaab


问:
Mapping different XML and CSV feeds
Not sure if this is the right venue to be asking this but here goes.

A little background.

I'm trying to build an ecommerce app that would allow sellers from other venues--like, amazon and newegg--to import their products using their export/import files.

An example would be a user having an XML feed that looks somewhat like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<products>
    <product>
        <sku>12345</sku>
        <name>Dell Computer</name>
        <description>This is a very nice Dell computer. Much quality. Very speed. Great wow.</description>
    </product>
    <product>
        <sku>123456</sku>
        <name>Dell Laptop</name>
        <description>This is a Dell laptop. Much quality as well.</description>
    </product>
</products>
</code>```

I'd like to be able to map the headers to columns in my database.

ie. sku -> product_sku, name -> product_name, description -> description.

What I'm doing right now is since not all feeds have the same structure, I developed a "mapping tool" that basically just parses the file, takes the headers and shows it in a UI that allows the user to "map" these to the list of my database columns.

The problem I'm encountering now is that since the feeds are not the same, I have a hard time getting that list of headers.

My question is what's a good way to approach this problem? Maybe I'm doing this all wrong.

I'm doing this in nodejs/javascript if that's at all relevant.

答:
Look for product not headers.

Product is the basic unit you are working with. First identify that. In your example, you can see that <product> is the only tag that has siblings of the same name. Although the same would be true for things like <category>, and <colorOption>.

Work with XML paths, not just tag names.

Let a human do the hard bit: get your sellers to pick the "headers" straight from the XML.

Display the XML (maybe as a menu tree) and ask the seller the selected the tag for a Product. Then highlight that fragment and ask the seller to select the tag for ProductName and so on.

Title: Mapping different XML and CSV feeds


问:
process large dataset c#
I have an application that process portfolios. I must aggregate 8 years of returns of aproximatelly 8K securities. (about 2016 doubles (8 years of data) for 2 dates (for comparison) 4032 for 8K securities.)

This is consuming aproximatelly 2GB of memory. I wonder if there is a better way of processing this other than holding this in memory.

I use Dictionaries to hold this data.

答:
It sounds like what you are doing is better done by a good database than directly in C#.  Using MS SQL Server you can store all of the data and use queries/stored procedures to transform the data however you like.

Database engines are designed exactly for this purpose.  They have optimisations in place to cut down on memory usage and improve speed.  Theoretically you could write code which outperformed a database engine for your specific data, but it would be hard and time consuming and generally not worth doing.

Title: process large dataset c#


问:
Isormophic javascript, request processing
I was wondering why isomorphic JS, like using reactjs in both client and server side increase first page load ?

What is different from simple SPA applications ?

In both cases we are loading the full content of the applications (in build.js or bundle.js for example). So what is different in both cases ?

答:
That shouldn't be the case, or rather, one of the main motivations for writing isomorphic JavaScript applications is to improve initial page loads (reuse being another important factor).

Previously, the user would receive a static HTML document which was only an  initial, minimally required representation of the full document, requiring the client to perform additional network I/O for completeness.

With an isomorphic architecture, the user immediately receives the full document without the need for any subsequent requests.


答:
If you absolutely wanted to, you could do this:

function log($message)
{
  for($i = 0; $i < 2; ++$i)
  {
    if ( FALSE !== file_put_contents(log_path(), $message) )
    {
      return;
    }
    if($i == 0)
    {
      chown(log_path(), 'apache');
      chgrp(log_path(), 'www-data');
      chown(log_path(), 0770);
    }
    else
    {
      // log error to database
      db_log($message);
    }
  }
}
```

I don't like it, however... Just a simple function call? Well, it is OK. If it was a more complex code you had to execute before being able to make a decision, I'd write a separate function for this, returning true or false, and have it called twice, right as you did with the file_put_contents function.

Title: call function once again after failure, without duplicate lines?

Body:
I have what is probably an over-engineering question. I have some PHP code that logs messages to a file. We've been having a problem with the file having the wrong perms from time to time. While we're troubleshooting that, I am writing a work-around for that in the logging function, changing the unix perms and owners on the log file.

So my code looks like this:

```<code>function log($message) {
  if ( FALSE === file_put_contents(log_path(), $message) ) {
    chown(log_path(), 'apache');
    chgrp(log_path(), 'www-data');
    chown(log_path(), 0770);

    // now I'm repeating this line
    if ( FALSE === file_put_contents(log_path(), $message) ) {
      // log error to database
      db_log($message);
    }
  }
}
</code>```

In the interest of DRY, can I somehow change the code to avoid repeating the line if ( FALSE === file_put_contents(log_path(), $message) ) {? Of course, I can't use recursion, because that would go on forever.

Body:
If you absolutely wanted to, you could do this:

function log($message)
{
  for($i = 0; $i < 2; ++$i)
  {
    if ( FALSE !== file_put_contents(log_path(), $message) )
    {
      return;
    }
    if($i == 0)
    {
      chown(log_path(), 'apache');
      chgrp(log_path(), 'www-data');
      chown(log_path(), 0770);
    }
    else
    {
      // log error to database
      db_log($message);
    }
  }
}

I don't like it, however... Just a simple function call? Well, it is OK. If it was a more complex code you had to execute before being able to make a decision, I'd write a separate function for this, returning true or false, and have it called twice, right as you did with the file_put_contents function.


问:
TDD Duplicate Testing on Related Classes
In following the principle of testing only the exported functions on a package (using Go - or for others languages, the public functions on a class), I'm running into a scenario where related packages are causing the code base to be tested multiple times.

For example, I have a Preprocessor, which calls a Parser package, which calls a Scanner package which calls a Lexer package.

Preprocessor -> Parser -> Scanner -> Lexer

The results bubble up to the previous package and the final results are compiled in the Preprocessor.  No package below the Preprocessor is called by any other part of the app.

Each package has tests, which means the lexer is tested 4x, the scanner 3x, the parser 2x and the preprocessor 1x.

I believe each feature should be its own separate package because if I combined them all into a single Preprocessor package, the parser, scanner and lexer don't need a public API, yet the functionality is too complex not to test individually as it would be difficult to track down where bugs were occurring.

Is this type of duplicate testing recommended or is it a sign that the packages are too related to be separated? Or, is it a sign that the lower level packages are doing too much and I should extract more business logic into the Preprocessor package such that it could call each of the lower level packages, instead of having their requests chained together?

答: A technique to avoid this - if it is in fact a problem for your project - is to use mocks.  The Scanner, for instance, would be tested with a mock Lexer; the Parser with a mock Scanner, etc.  In this way your actual Lexer is only exercised by the Lexer tests.</p>


问:
C++: Should class own or observe its dependencies?
Say I have a class Foobar that uses (depends on) class Widget. In good ol' days, Widget wolud be declared as a field in Foobar, or maybe as a smart pointer if polymorphic behavior was needed, and it would be initialized in constructor:

```<code>class Foobar {
    Widget widget;
    public:
    Foobar() : widget(blah blah blah) {}
    // or
    std::unique_ptr<Widget> widget;
    public:
    Foobar() : widget(std::make_unique<Widget>(blah blah blah)) {}
    (…)
};
</code>```

And we'd be all set and done. Unfortunately, today, Java kids will laugh at us once they see it, and rightfully, as it couples Foobar and Widget together. The solution is seemingly simple: apply Dependency Injection to take construction of dependencies out of Foobar class. But then, C++ forces us to think about ownership of dependencies. Three solutions come to mind:

Unique pointer

```<code>class Foobar {
    std::unique_ptr<Widget> widget;
    public:
    Foobar(std::unique_ptr<Widget> &&w) : widget(w) {}
    (…)
}
</code>```

Foobar claims sole ownership of Widget that is passed to it. This has following advantages:

Impact on performance is negligible.

It's safe, as Foobar controls lifetime od its Widget, so it makes sure that Widget doesn't suddenly disappear.

It's safe that Widget won't leak and will be properly destructed when no longer needed.

However, this comes at a cost:

It places restrictions on how Widget instances can be used, e.g. no stack-allocated Widgets can be used, no Widget can be shared.

Shared pointer

```<code>class Foobar {
    std::shared_ptr<Widget> widget;
    public:
    Foobar(const std::shared_ptr<Widget> &w) : widget(w) {}
    (…)
}
</code>```

This is probably closest equivalent ot Java and other garbage collected languages. Advantages:

More universal, as it allows sharing dependencies.

Maintains safety (points 2 and 3) of unique_ptr solution.

Disadvantages:

Wastes resources when no sharing is involved.

Still requires heap allocation and disallows stack-allocated objects.

Plain ol' observing pointer

```<code>class Foobar {
    Widget *widget;
    public:
    Foobar(Widget *w) : widget(w) {}
    (…)
}
</code>```

Place raw pointer inside class and shift the burden of ownership to someone else. Pros:

As simple as it can get.

Universal, accepts just any Widget.

Cons:

Not safe anymore.

Introduces another entity that is responsible for ownership of both Foobar and Widget.

Some crazy template metaprogramming

The only advantage I can think of is that I'd be able to read all those books I didn't find time for while my software is builing;)

I lean towards the third solution, as it is most universal, something has to manage Foobars anyway, so managing Widgets is simple change. However, using raw pointers bothers me, on the other hand smart pointer solution feel wrong to me, as they make consumer of dependency restrict how that dependency is created.

Am I missing something? Or is just Dependency Injection in C++ not trivial? Should class own its dependencies or just observe them?

答:
First of all - this is C++, not Java - and here many things go differently. The Java people do not have those problems about ownership as there is automatic garbage collection that solves those for them.

Second: There is no general answer to this question - it depends on what the requirements are!

What is the problem about coupling FooBar and Widget? FooBar wants to use a Widget, and if every FooBar instance always will have its own and the same Widget anyway, leave it coupled...

In C++, you can even do "weird" things that simply do not exist in Java, e. g. have a variadic template constructor (well, there exists a ... notation in Java, which can be used in constructors, too, but that is just syntactic sugar to hide an object array, which actually has nothing to do with real variadic templates!) - category 'Some crazy template metaprogramming':

namespace WidgetFactory
{
    Widget* create(int, int)
    {
        return 0;
    }
    Widget* create(int, bool, long)
    {
        return 0;
    }
}
class FooBar
{
public:
    template < typename ...Arguments >
    FooBar(Arguments... arguments)
        : mWidget(WidgetFactory::create(arguments...))
    {
    }
    ~FooBar()
    {
        delete mWidget;
    }
private:
    Widget* mWidget;
};

FooBar foobar1(10, 12);
FooBar foobar2(51, true, 54L);
```

Like it?

Of course, there are reasons when you want or need to decouple both classes - e. g. if you need to create the widgets at a time far before any FooBar instance exists, if you want or need to reuse the widgets, ..., or simply because for the current problem it is more appropriate (e. g. if Widget is a GUI element and FooBar shall/can/must not be one).

Then, we get back to the second point: No general answer. You need to decide, what - for the actual problem - is the more appropriate solution. I like DominicMcDonnell's reference approach, but it can only be applied if ownership shall not be taken by FooBar (well, actually, you could, but that implies very, very dirty code...). Apart from that, I join David Packer's answer (the one meant to be written as comment - but a good answer, anyway).

Body:
First of all - this is C++, not Java - and here many things go differently. The Java people do not have those problems about ownership as there is automatic garbage collection that solves those for them.

Second: There is no general answer to this question - it depends on what the requirements are!

What is the problem about coupling FooBar and Widget? FooBar wants to use a Widget, and if every FooBar instance always will have its own and the same Widget anyway, leave it coupled...

In C++, you can even do "weird" things that simply do not exist in Java, e. g. have a variadic template constructor (well, there exists a ... notation in Java, which can be used in constructors, too, but that is just syntactic sugar to hide an object array, which actually has nothing to do with real variadic templates!) - category 'Some crazy template metaprogramming':

namespace WidgetFactory
{
    Widget* create(int, int)
    {
        return 0;
    }
    Widget* create(int, bool, long)
    {
        return 0;
    }
}
class FooBar
{
public:
    template < typename ...Arguments >
    FooBar(Arguments... arguments)
        : mWidget(WidgetFactory::create(arguments...))
    {
    }
    ~FooBar()
    {
        delete mWidget;
    }
private:
    Widget* mWidget;
};

FooBar foobar1(10, 12);
FooBar foobar2(51, true, 54L);

Like it?

Of course, there are reasons when you want or need to decouple both classes - e. g. if you need to create the widgets at a time far before any FooBar instance exists, if you want or need to reuse the widgets, ..., or simply because for the current problem it is more appropriate (e. g. if Widget is a GUI element and FooBar shall/can/must not be one).

Then, we get back to the second point: No general answer. You need to decide, what - for the actual problem - is the more appropriate solution. I like DominicMcDonnell's reference approach, but it can only be applied if ownership shall not be taken by FooBar (well, actually, you could, but that implies very, very dirty code...). Apart from that, I join David Packer's answer (the one meant to be written as comment - but a good answer, anyway).


问:
Will issues arise packaging libc and pthread with your C apps?
The issue I hit, is that I am packaging shared libraries with my code in order to load GNUTLS, except for libc, because I figured any system will have it. Most of them don't have the required 2.14 for it(except for Ubuntu or others with daunting upgrades and repo butchering). I know it's bad form to be dependent like that, but I need a very recent build of GNUTLS, so it was the only solution I thought of.

In order to solve the libc issue, is it safe to package libc & pthread(another dependent), with my program? My program is Java, using JNI to load these libraries if that's relevant. This is also all for Linux.

答:
Another way to solve this problem is to use a make and automake system like GNU Autotools to configure your code for the function calls in libc you need rather than the libc directly. That will solve the portability problem.

https://www.gnu.org/software/automake/

It is highly unwanted to transport your own libc as it might cause problems and unspecified behaviour.


问:
Writing comments for some small code with rather large background
So I had to write some code related to splitting Bezier curves into parts. I read through several references and particularly referred this rather  detailed one.

The final code outcome is however around 20-30 LOC. But without having this kind of background, it would be really difficult for someone to figure out what the code is doing.

Explaining it in details would require me to write too much comments as the function's explanation.

Putting a link to this document into comments did not seem a very nice an idea (links might break in future)

Q. Should I rather generate this as a doc, keep it locally with project docs, and give a reference to it in the comments ?

Q. Any other nicer way in general to give comments about some rather complex/large area of work associated with a particular functionality.

P.S. I don't want some body reading this code later to curse me for what it is, so, you see :p

答:
Having a big comment section explaining "whys" and "hows" details of a complicated algorithm is a good idea. And it is better to have close to the code, so that developer does not need to switch context to read about it (even worse - switching back and forth between algorithm and document).

Just remember to include a sort of TL;DR on top of the lengthy comment, for those who need to get just the idea/outline, without details of implementation.

P.S. I was porting a project with such comment blocks a few months ago - they were very helpful.


答:
Code is read far more often than it’s written, so carefully written comments are worth their weight in gold.

Distill the relevant details of the article you referenced while writing the code. Include a URL, even if it may be broken in the future; there is always the Internet Archive. And above all, make specific references to the theoretical results you used, such as De Casteljau’s algorithm.

It’s okay for code to be opaque to someone unfamiliar with the domain—in this case, splines and numerical analysis—as long as the reader can find detailed references for learning how to understand the code.

Title: Writing comments for some small code with rather large background

Body:
So I had to write some code related to splitting Bezier curves into parts. I read through several references and particularly referred this rather  detailed one.

The final code outcome is however around 20-30 LOC. But without having this kind of background, it would be really difficult for someone to figure out what the code is doing.

Explaining it in details would require me to write too much comments as the function's explanation.

Putting a link to this document into comments did not seem a very nice an idea (links might break in future)

Q. Should I rather generate this as a doc, keep it locally with project docs, and give a reference to it in the comments ?

Q. Any other nicer way in general to give comments about some rather complex/large area of work associated with a particular functionality.

P.S. I don't want some body reading this code later to curse me for what it is, so, you see :p


问:
Are there any arguments that can make a contractor reconsider working on fixed price?
I've been working for a contractor who brings in some good projects, but they are all fixed-price and often fixed-time.

As a result he always has me making a quote over loose requirements, which never fails to bring a lot of tension due to feature creep.

He claims he'd never get a contract if he couldn't agree on a price with his clients first, but as far as I'm concerned I don't wanna go through another project under these terms.

Is there any argument I could make to have him pay me by the hour, or should I just suck less at estimating ?

答:
I refuse to work on a fixed-bid project, for most of the reasons you listed.  It ain't just you — fixed-bid work is antithetical to an agile process (which is also the way I work.) If the contractor you work for insists on bidding out his projects as fixed-bid, then let him take on the risk.  If you're good at what you do, there are plenty of other places to go work.

Basically everyone sucks at estimating.  Unless you've done a project that was substantially similar at least a couple of times, you're not estimating, you're guessing.

also, he's wrong about not getting a contract without a fixed bid. If he can't, the problem isn't the fixed-bid vs hourly, its the salesman.  I've worked for a roster of clients on an hourly basis.  The key is to give them frequent communications about what you're doing and what its costing them, and make them understand that the tradeoffs are budget vs features— you can hit a budget, but they have to give on features sometimes.


问:
Find all the pairs in the array that match the condition
Problem:

We have an int array[n]. We need to find all the pairs for which array[a] + array[b] = 0.

The only algorithm I came up with so far has O(n^2) - tho most obious one. Is there a better way to do it?

答:
Sort your array, but maintain the original index number. Then you can loop through it once, each value can be instantly matched with the set of indexes stored against the matching point.

ie. loop through your array and store a key-value pair (where the key is array[n] and the value is n). A single iteration of this container will show you all matching indexes for the current value.


答:
Instead of describing the complex algorithm in the the sourcecode i prefer to add a reference to the ticketnumber of the Bug_tracking_system. Example:

```<code> /** Split a Bezier into several parts.
  * See #18864 for details */
 public BezierParts[] splittBezier(Bezier aBezier) {
    ...
 }
</code>```

18864 is the ticketnumber.
The ticket has all informations including

a http link to the algorithm

attachment with a pdf copy of the "http link to the algorithm" in case that the http link disapears.

Body:
Instead of describing the complex algorithm in the the sourcecode i prefer to add a reference to the ticketnumber of the Bug_tracking_system. Example:

 /** Split a Bezier into several parts.
  * See #18864 for details */
 public BezierParts[] splittBezier(Bezier aBezier) {
    ...
 }

18864 is the ticketnumber.
The ticket has all informations including

a http link to the algorithm

attachment with a pdf copy of the "http link to the algorithm" in case that the http link disapears.


问:
Design Patterns when Class Needs External Awareness
When I was first taught Object Oriented principles, it was drilled into me that when using objects in a "hasA" relationship (or any similar situations where a helper object encapsulates a discrete smaller purpose in a bigger system), the owned class should not have awareness of it's greater environment, so, for example:

Class Deck has a Card[], each Card has no upward access to Deck

Class GameBoard has GamePiece, each GamePiece has no upward access towards the board

This has held well and true for a while, but I've finally had a problem where I'm strongly tempted to break from this.

In an application where there's user defined "commands" that are parsed from input, and run, it made relative sense to define Class Command and Class Conditional, which each have subclasses for each of the many possible Command types the user can define.

Added context This is a Roleplaying utility, so each command relates to an operation done on the "Character" object, or messing with the generators rules. So AddStat(WIL,5) increments that value accordingly. Commands shouldn't need access to the greater generator to run themselves, but they'd need at least access to the object their represented command modifies. So for most purposes, the character is the "environment" the command would be acting on.

Makes sense, seems at first glance to help things. But there's a missing link when a lot of these classes can only do very basic input validation without a greater context, not to mention the fact that without more "aware" objects, every part of the code dealing with them would need to do that main ifelseif branch to first figure out which command it's dealing with...

The design thing I'm not sure where to go with here is as follows (this is not yet coded because of the amount of changes it'd take to adapt one of these divergent solutions)

Command remains "dumb" with no Character/Environment awareness. Conditional is allowed a resolve(Character obj) method, which lets it be passed enough awareness to return a meaningful true/false. This means Command remains a relatively simple basic syntax validator, and body code elsewhere does the heavy lifting for running

As before, except Command also gains it's own resolve(Character obj) method, and each subclass contains the code necessary to execute the command

As before, except we outright create Command objects with a reference to the Character

I'm not really sure where to go on this one... While technically there's already some code organization gained by the simplest option, it feels the readability of the application would benefit from Option 2/Option 3, even if the encapsulation purism suffers.

Which route is the way to go here? Or am I off the mark completely?

答:
Your learning experience is textbook example of situation, where you are taught that something is wrong without being taught why is it wrong. While this is easy for teacher to do and easier for student to remember, it will soon be challenged by situation where it is just too limiting. And knowing why this rule exists would allow you to weight pros and cons of abiding by this rule.

So why should "the owned class should not have awareness of it's greater environment"? Because it would create cyclic dependency. In your example Deck depends on Card and Card depend on Deck. It then becomes impossible to be able to use one without the other or vice versa. From modularity perspective, both Deck and Card for single logical "aggregate" and should be viewed as such from rest of the code. This reduces modularity and maintainability so it is mostly bad idea.

BUT! Sometimes it does make sense for multiple classes to form an aggregate. The case of Deck and Cards referencing each other would make sense if rest of the application never works with just cards without reference to the deck that the cards belong to. So that when Deck's lifetime ends, so do it's Card's.

So in your case, if you are not expecting that the Commands will outlive the Environment or Player, then I see no problem referencing them.


答:
A shorter form of your question would be "does unit tests make sense for a compiler". I believe the answer to that question is a strong yes. You need to know that the smallest parts of your transformation pipeline do what they should. You need to know that they're combined correctly and so on.

I'd say that unit tests, integration tests and end-to-end tests all make sense.

Title: Is there a benefit to unit testing code whose sole purpose is to generate non-human-readable code in another language?

Body:
A significant portion of the application I work on every day consists of Javascript that outputs a lot of (what might as well be) Excel spreadsheet formulas. Yes, Excel is barely a Turing-complete language, but the formulas are more than complex enough to qualify as "code". They're not meant to be human-readable or human-editable. The users never see these formulas at all, only the values which those formulas evaluate to.

The main problem with our codebase right now is a lack of automated testing, and thus far I've focused my efforts on integration tests which run both the Javascript and the formulas, then assert on the final values. After all, we don't care what formulas were used to create those values, so I don't really see the point in a unit test that asserts on the formulas produced by each piece of Javascript. I'd also expect such unit tests to be exceedingly brittle, as most of our changes to the Javascript code are intended to change the formulas in some way (albeit in a way that shouldn't affect most of the final values).

Note that the code which evaluates the formulas is owned by a different team, and they have loads of unit tests on it. I'm interested in tests for our code, the part that generates the formulas.

Also note that speed is a non-issue; the integration tests I've written so far are so fast they feel more like unit tests.

For the reasons given above I'm convinced that improving our integration test coverage is the higher priority, at least for now, but I honestly can't see any benefit at all to unit testing this code, which feels like a sign that I might be missing something important.

So, is there any purpose to having unit tests as well as integration tests for this particular kind of code, where the sole objective is to generate "code" in some other language, and nobody cares what "intermediate code" is used to achieve the final result?


问:
Is hardware accelerated GUI data kept on the GPU
I am doing some research as to how most hardware accelerated GUI libraries work. I am actually only care about the rendering backends of them here. I am trying to figure out what would be the best way to try and write my own as a sort of side project. I am trying to go for ultimate performance here instead of overly fancy features. I want to b able to draw primitives, text and animation.

Some good libraries that I know of are Qt, Skia and Cairo (though I'm not sure what the sate of HWA is on it). I have also looked at NanoVG which is a small library that seems to have a decent following. I did not manage to achieve decent performance with NanoVG though...

The one thing that struck me was that all these libraries seem to make use of the concept of "painting" where it seems that each primitive shape gets drawn from scratch over and over again. What I mean by that is that from the APIs, it does not appear as if though the shapes are created as "objects" on the GPU or whatever the terminology is and then left there to be rendered "automatically". In other words, they are not left on the GPU's memory for being redrawn in some large loop. To elaborate, it seems that for each i.e. rectangle that needs to be drawn, a whole OpenGL state is set up just to render that rectangle and is then destroyed again. It does appear though as if these rendered shapes are then at least rendered at their final destinations, allowing the GPU to then compose the entire scene.

The way I expected these libraries to work is by actually storing the entire scene on the GPU (excuse the horrible terminology). For instance, primitives would be triangulated and left in memory where after some intricate process would be used to have a main rendering loop for the scene. Furthermore there would then be mechanisms in place to update attributes or delete or add primitives. This is quite a vague description but I think that you get the idea.

What I would like to ask now, is if there is any performance benefit to the "painting" approach as compared to the "saved" approach (again, no idea if there are proper names for these things...). Some intricate caching mechanisms of sorts perhaps? Or is this just much simpler to work with?

I realize that the "saved" approach might use more memory on the GPU but are all the OpenGL calls needed for the "painting" approach not vastly expensive? I guess one might be able to compensate for this by caching the rendered shapes but does the GPU really provide one with so large a benefit when doing such a once-off (or not very regular) rasterization as compared to CPU, especially given the communication overhead? Also, does this communication overhead not pose serious problems for animations when drawing has to be done for every frame?

I am quite certain that NanoVG does not have an internal caching mechanism and I would assume that this could be responsible for its rather lackluster performance. Qt on the other hand seems to have excellent performance so it must be doing something right. Google also seems to be able to put Skia to good use.

PS. I am not a professional of any sorts and have only recently started to learn OpenGL.

EDIT:
Another possibility that I have thought of is that maybe the "painting" approach was deemed necessary purely because of the memory benefits? The reason I would think that is because all these libraries were of course started in a different era and also target embedded platforms meaning that GPU memory might be so scarce on the target(ed) platforms and that using as little as possible of it might be more important than performance. Again though, in a situation like this, I am not convinced that frame-by-frame GPU rasterization given the communication overhead will outperform a CPU, especially considering the probably low pixel count on platforms with such little memory.

Furthermore I have read on http://blog.qt.io/blog/2010/01/06/qt-graphics-and-performance-opengl/ that Qt apparently blends together shader code from precoded segments at runtime before "painting" and then hopes for the OGL compiler to inline the code properly at runtime. This sound like even more OGL initialization overhead to me...

答:
Saving the whole window as a single object into GPU (it would be bunch of rectangles saved as VBO) and then rendering it in a single OpenGL draw call would be fast, but it has several disadvantages:

The whole geometry would have to be rendered using single shader. Having separate shaders (for opaque copy, transparent copy, gradient, ...) is more useful.

The whole geometry could use only from limited amount of textures. Even if you use atlases, you need lot of textures for GUI. (Pieces of the GUI theme, icons, fonts, ...)

You have to rebuild and reload the whole object into GPU after every change.

Every widget must be able to produce their piece of geometry which is harder to abstract than 2D painting.

On some GPUs you can render 2D stuff (filling area with color, copying from picture to picture, ...) with 2D commands which is faster than using 3D pipeline.

If you break it into several objects, then you eventually end up with single or few rectangles per object. It's easier and faster to render them without any stored objects.

What GUI frameworks do is tracking which exact parts of the window changed and repainting only them. The old image is cached in the GPU. This approach can be used with various drawing backends, not only OpenGL/DirectX accelerated rendering.

If you want to check example of a GUI library that does generate geometries which you can feed into OpengGL (or into different 3D api), look at librocket. It can actually bake static geometries together and render them in single draw call, but any element that will be changing often or need to render with its own shader has to stay separate.


问:
Moving from a traditional waterfall methodology to an agile one
My development team is in the process of 'going agile' and lot of people are looking at each other blankly, not really too sure what it means. All management are saying is 'start working agile' without suggesting any particular methodology so they're waiting to see if we can come up with something ourselves. Has anyone been in this situation before and how did you handle it? Any do's and don'ts? I'm one of the senior members of the team so there's an expectation to show some initiative. I know that what works for one won't necessarily work for another so I'm more interested in the approach not so much the end result because I think the result will come naturally with the right approach.</p>

答:
My development team is in the process of 'going agile'

Playing Devil's Advocate for a minute: Why?

What's wrong with what you're doing already?

Is moving to an Agile (or any other) way of working going to allow you to do your jobs any better than you're currently doing them?

If you cannot qualify the benefits you hope to gain from this piece of work (and changing between any Methodologies is a lot of work!) then why are you wasting your time?

Without a clear idea of what you hope to achieve, you're going to have a really hard time making it happen.  And you Management, who clearly expect you, as an "Agile" team, to self-organise yourselves, will be "less than impressed" when you take [far] longer to produce [far] less, perhaps, then you currently do.

Agile is not a Magic Bullet.  Yes; it's good (great, even) for some types of Development (mostly the "shiny", front-end stuff that Users like to look at and have a hand in driving), but quite dreadful for many other kinds (the back-end "plumbing" that every system needs, but that nobody wants to get stuck with).


问:
Shared data in functional programming
I have been working on a project in JavaScript which requires a data structure (read only), to be shared between two functions.

```<code>var mySharedData = ['hours', 'minutes', 'seconds'];
</code>```

Now I have two functions that need access to this (static) read only data structure.

```<code>var sampleFunction1 = function(userSuppliedData) {
    //map over user data applying mySharedData to it
};

var sampleFunction2 = function(userSuppliedData) {
    //reduce user data also accessing mySharedData
};
</code>```

Since this is JavaScript and both functions are in the same scope I could just "cheat" and leverage the bad scoping of var and access the shared data in both functions but I don't feel like this is the proper way of doing it.

I also considered currying both functions and just passing the shared data as the first argument like so:

```<code>var mySharedData = ['hours', 'minutes', 'seconds'];

var sampleFunction1 = _.curry(function(sharedData, userSuppliedData) {
    //map over user data applying sharedData to it
})(mySharedData);

var sampleFunction2 = _.curry(function(sharedData, userSuppliedData) {
    //reduce user data also accessing sharedData
})(mySharedData);
</code>```

What is the recommended way of sharing data between functions? Should this even be done in functional programming or am I making my functions impure with shared data structures?

答:
If mySharedData is private for both closures:

```<code>(function (context) {
    var mySharedData = ['hours', 'minutes', 'seconds'];

    context.sampleFunction1 = function (userSuppliedData) {
        //map over user data applying mySharedData to it
        // mySharedData....
    };

    context.sampleFunction2 = function (userSuppliedData) {
        //reduce user data also accessing mySharedData
        // mySharedData....
    };
})(this);
</code>```

If mySharedData is public:

```<code>var mySharedData = ['hours', 'minutes', 'seconds'];

var sampleFunction1 = function (userSuppliedData) {
    //map over user data applying mySharedData to it
    // mySharedData...
};

var sampleFunction2 = function (userSuppliedData) {
    //reduce user data also accessing mySharedData
    // mySharedData...
};
</code>```

If what you need is that mySharedData can not be edited:

```<code>Object.defineProperty(this, 'mySharedData', {
    get: function () {
        return ['hours', 'minutes', 'seconds'];
    }
});

console.log(mySharedData);
// ['hours', 'minutes', 'seconds']

mySharedData.push('foo');
mySharedData[1] = 'bar';

console.log(mySharedData);
// ['hours', 'minutes', 'seconds']
</code>```

Title: Shared data in functional programming

Body:
If mySharedData is private for both closures:

(function (context) {
    var mySharedData = ['hours', 'minutes', 'seconds'];

    context.sampleFunction1 = function (userSuppliedData) {
        //map over user data applying mySharedData to it
        // mySharedData....
    };

    context.sampleFunction2 = function (userSuppliedData) {
        //reduce user data also accessing mySharedData
        // mySharedData....
    };
})(this);

If mySharedData is public:

var mySharedData = ['hours', 'minutes', 'seconds'];

var sampleFunction1 = function (userSuppliedData) {
    //map over user data applying mySharedData to it
    // mySharedData...
};

var sampleFunction2 = function (userSuppliedData) {
    //reduce user data also accessing mySharedData
    // mySharedData...
};

If what you need is that mySharedData can not be edited:

Object.defineProperty(this, 'mySharedData', {
    get: function () {
        return ['hours', 'minutes', 'seconds'];
    }
});

console.log(mySharedData);
// ['hours', 'minutes', 'seconds']

mySharedData.push('foo');
mySharedData[1] = 'bar';

console.log(mySharedData);
// ['hours', 'minutes', 'seconds']


答:
I personally like it if there is a comment with enough information to understand the code. If you store it any place else, there is always a chance this will get lost until the time someone tries to understand the code. Still, put a link there (it might work, else its maybe in the web archive), if there are any papers, put the title/authors there so it can be found.

But still, for someone who knows the field, it should be enough to read the comment to understand what's going on.

I don't know what you did exactly and never heard of de Casteljau before, but maybe something like this would be good:

```<code>Splitting the curves into parts because [thats more awesome|i like it|faster›...] using de Casteljau's algorithm.
The following differs from the usual de Casteljau's algorithm:
 a. all control points are cats
 b. we calculate using roman numerals
Maybe a reason why this differs.

A detailed description is at http://pomax.github.io/bezierinfo/#decasteljau
Also the paper "Towards the use of cats as curve points" by "Meow et al." is of great use (link to paper maybe)

If you want, more detailed description
</code>```

This should give enough information to either understand the code or (if one doesn't know the theory behind it) find sources for explanation.

The only disadvantages of longer comments are file size and the need for people to scroll over the comment. Both are not really a problem (filesize today only really matters for embedded systems etc. and comments are not in the binaries, and people complaining over the need to scroll over a 20 lines comment should get an IDE)

Think about this: If someone has to change parts of that code in a few years, what would cost the company employing him more:

He needs to ignore a large comment while editing the code he understands

He needs to search for information how this code works or even rewrite it, because the file describing it in the docs folder got lost and the links are dead

Body:
I personally like it if there is a comment with enough information to understand the code. If you store it any place else, there is always a chance this will get lost until the time someone tries to understand the code. Still, put a link there (it might work, else its maybe in the web archive), if there are any papers, put the title/authors there so it can be found.

But still, for someone who knows the field, it should be enough to read the comment to understand what's going on.

I don't know what you did exactly and never heard of de Casteljau before, but maybe something like this would be good:

Splitting the curves into parts because [thats more awesome|i like it|faster›...] using de Casteljau's algorithm.
The following differs from the usual de Casteljau's algorithm:
 a. all control points are cats
 b. we calculate using roman numerals
Maybe a reason why this differs.

A detailed description is at http://pomax.github.io/bezierinfo/#decasteljau
Also the paper "Towards the use of cats as curve points" by "Meow et al." is of great use (link to paper maybe)

If you want, more detailed description

This should give enough information to either understand the code or (if one doesn't know the theory behind it) find sources for explanation.

The only disadvantages of longer comments are file size and the need for people to scroll over the comment. Both are not really a problem (filesize today only really matters for embedded systems etc. and comments are not in the binaries, and people complaining over the need to scroll over a 20 lines comment should get an IDE)

Think about this: If someone has to change parts of that code in a few years, what would cost the company employing him more:

He needs to ignore a large comment while editing the code he understands

He needs to search for information how this code works or even rewrite it, because the file describing it in the docs folder got lost and the links are dead


答:
Note: an argument for why should documentation live in the code is made in the section at the bottom of this answer.

I would encourage you to include the details of the algorithm as a comment, and more.

Why this algorithm?

Before explaining the algorithm itself, you must first explain why this algorithm was chosen, rather than an alternative.

The explanation can be as simple as "We will use Bezier Curves, no other alternative was explored as they performed well enough". However, if you did test alternatives, please explain why they were rejected.

The idea here is that a maintainer coming later on may have to explore again (looking for better performance or accuracy for example), and if you already did the work with algorithm X and Y, and the reasons they were rejected still apply, then said maintainer can decide to start checking another algorithm instead rather than repeating your experiments.

Which algorithm?

Why this might seem silly, seeing as you said "Bezier Curves", bear in mind that sometimes there are slight variations of algorithms/data structures/... (B-Tree, B+-Tree, B*-Tree for example). Therefore, specifying with as much precision as possible which algorithm was selected, and which source it was pulled from (preferably one available online...) can help the readers' expectations with reality.

Also, if this is a variant compared to the general text-book version, make sure it is clearly labelled as such, lest readers wonder why it seems to deviate.

How does this algorithm work?

This really depends on the team you work with. If Bezier Curves are the bread and butter of the team, then a simple one-liner might be sufficient; however if the code may end-up being read/maintained by people for which this sounds like a surf figure, describing the algorithm sounds best.

Secondly, another advantage of describing the algorithm in comments is that it makes it easy to split the description, literate programming style. That is, you first start with a general outline of the algorithm which only identify sections, and then for each section you will have a comment block and immediately under the associated code. It makes it easier to check that the code is in adequation with the comments.

Finally, a last advantage of describing the algorithm in comments is that it makes it possible to annotate the algorithm itself. You may take short-cuts (a single round of approximation rather than two is sufficient for your accuracy needs for example), or on the contrary explain why a given step is necessary (and what are the consequences of removing it); you may even fix the algorithm (if you pointed to a printed version, for example, there might be an errata...).

Where?

Since this is an implementation detail, it should not get in the way of the caller. Implementation details should be documented in the function (not outside), and depending on your documentation generator, using "pure" comments as they do not need to appear in the documentation.

Why document in the code?

I will argue that code documentation should live as close to possible to the code. The reason is simple:

the bug tracking system might change, and even if the import tool works the IDs may change

the source control system might change

the repository might be re-organized, split into several, etc...

...

Any time such an event occur, there is a risk that links across (new) boundaries are severed.

The code is the only constant!

Indeed:

without the code, you do not need the documentation

with the code, you get the comments, and thus the documentation within

Thus documentation is therefore more likely to be available if included in the code.

There is a limit, obviously, for example text files cannot contain images, so graphics/diagrams are hard to include in comments (ASCII Art should not be underestimated, and yes, I am serious). Still text goes a long way, so at the very least you can provide a good explanation in place and then nothing prevents you from also providing a more in-depth explanation elsewhere and link to it.