答:
I honestly don't see a big problem with the code. In C# and C++ you can use optional parameters, that would be an alternative, but as far as I know Java doesn't support that kind of parameters.

In C# you could make all the overloads private and one method with optional parameters is public to call the stuff.

To answer your question part 2, I would take the parameter object or even a dictionary/HashMap.

Like so:

```<code>class DokumentHome {

  public Document createDocument(Map<string, object> params) {
    if (params.containsKey("yourkey")) {
       // do that
    }
    // here the real work gets done
    (...)
  }
}
</code>```

As disclaimer, I am first a C# and JavaScript programmer and then a Java programmer.

Title: How to avoid excessive method overloading?

Body:
We have quite a lot of places in the source code of our application , where one class has many methods with same names and different parameters. Those methods always have all the parameters of a 'previous' method plus one more.

It's a result of long evolution (legacy code) and this thinking (I believe):

"There is a method M that does thing A. I need to do A + B. OK, I know ... I will add a new parameter to M, create a new method for that, move code from M to the new method with one more parameter, do the A + B over there and call the new method from M with a default value of the new parameter."

Here is an example (in Java-like-language):

```<code>class DocumentHome {

  (...)

  public Document createDocument(String name) {
    // just calls another method with default value of its parameter
    return createDocument(name, -1);
  }

  public Document createDocument(String name, int minPagesCount) {
    // just calls another method with default value of its parameter
    return createDocument(name, minPagesCount, false);
  }

  public Document createDocument(String name, int minPagesCount, boolean firstPageBlank) {
    // just calls another method with default value of its parameter
    return createDocument(name, minPagesCount, false, "");
  }

  public Document createDocument(String name, int minPagesCount, boolean firstPageBlank, String title) {
    // here the real work gets done
    (...)
  }

  (...)
}
</code>```

I feel like this is wrong. Not only that we can't keep adding new parameters like this forever, but the code hard to extend/change because of all the dependencies between methods.

Here are few ways how to do this better:

Introduce a parameter object:

```<code>class DocumentCreationParams {

  String name;
  int minPagesCount;
  boolean firstPageBlank;
  String title;

  (...)
}

class DokumentHome {

  public Document createDocument(DocumentCreationParams p) {
    // here the real work gets done
    (...)
  }
}
</code>```

Set the parameters to the DocumentHome object before we call createDocument()

```<code>  @In
  DocumentHome dh = null;

  (...)

  dh.setName(...);
  dh.setMinPagesCount(...);
  dh.setFirstPageBlank(...);

  Document newDocument = dh.createDocument();
</code>```

Separate the work into different methods and call them as needed:

```<code>  @In
  DocumentHome dh = null;

  Document newDocument = dh.createDocument();
  dh.changeName(newDocument, "name");
  dh.addFirstBlankPage(newDocument);
  dh.changeMinPagesCount(new Document, 10);
</code>```

My questions:

Is the described problem really a problem?

What do you think about suggested solutions? Which one would you prefer (based on your experience)?

Can you think of any other solution?

Body:
I honestly don't see a big problem with the code. In C# and C++ you can use optional parameters, that would be an alternative, but as far as I know Java doesn't support that kind of parameters.

In C# you could make all the overloads private and one method with optional parameters is public to call the stuff.

To answer your question part 2, I would take the parameter object or even a dictionary/HashMap.

Like so:

class DokumentHome {

  public Document createDocument(Map<string, object> params) {
    if (params.containsKey("yourkey")) {
       // do that
    }
    // here the real work gets done
    (...)
  }
}

As disclaimer, I am first a C# and JavaScript programmer and then a Java programmer.


问:
Ensure that each class has only one responsibility, why?
According to Microsoft documentation, the Wikipedia SOLID principe article, or most IT architects we must ensure that each class has only one responsibility. I would like to know why, because if everybody seems to agree with this rule nobody seems to agree about the reasons of this rule.

Some cite better maintenance, some say it provides easy testing or makes the class more robust, or security. What is correct and what does it actually mean? Why does it make maintenance better, testing easier or the code more robust?

答:
Because software is organic. Requirements change constantly so you have to manipulate components with as little headache as possible. By not following SOLID principles, you may end up with a code base that is set in concrete.

Imagine a house with a load bearing concrete wall. What happens when you take this wall out without any support? The house will probably collapse. In software we don't want this, so we structure applications in such a way so that you can easily move/replace/modify components without causing lots of damage.

ContentLicense: CC BY-SA 3.0


问:
How to avoid excessive method overloading?
We have quite a lot of places in the source code of our application , where one class has many methods with same names and different parameters. Those methods always have all the parameters of a 'previous' method plus one more.

It's a result of long evolution (legacy code) and this thinking (I believe):

"There is a method M that does thing A. I need to do A + B. OK, I know ... I will add a new parameter to M, create a new method for that, move code from M to the new method with one more parameter, do the A + B over there and call the new method from M with a default value of the new parameter."

Here is an example (in Java-like-language):

```<code>class DocumentHome {

  (...)

  public Document createDocument(String name) {
    // just calls another method with default value of its parameter
    return createDocument(name, -1);
  }

  public Document createDocument(String name, int minPagesCount) {
    // just calls another method with default value of its parameter
    return createDocument(name, minPagesCount, false);
  }

  public Document createDocument(String name, int minPagesCount, boolean firstPageBlank) {
    // just calls another method with default value of its parameter
    return createDocument(name, minPagesCount, false, "");
  }

  public Document createDocument(String name, int minPagesCount, boolean firstPageBlank, String title) {
    // here the real work gets done
    (...)
  }

  (...)
}
</code>```

I feel like this is wrong. Not only that we can't keep adding new parameters like this forever, but the code hard to extend/change because of all the dependencies between methods.

Here are few ways how to do this better:

Introduce a parameter object:

```<code>class DocumentCreationParams {

  String name;
  int minPagesCount;
  boolean firstPageBlank;
  String title;

  (...)
}

class DokumentHome {

  public Document createDocument(DocumentCreationParams p) {
    // here the real work gets done
    (...)
  }
}
</code>```

Set the parameters to the DocumentHome object before we call createDocument()

```<code>  @In
  DocumentHome dh = null;

  (...)

  dh.setName(...);
  dh.setMinPagesCount(...);
  dh.setFirstPageBlank(...);

  Document newDocument = dh.createDocument();
</code>```

Separate the work into different methods and call them as needed:

```<code>  @In
  DocumentHome dh = null;

  Document newDocument = dh.createDocument();
  dh.changeName(newDocument, "name");
  dh.addFirstBlankPage(newDocument);
  dh.changeMinPagesCount(new Document, 10);
</code>```

My questions:

Is the described problem really a problem?

What do you think about suggested solutions? Which one would you prefer (based on your experience)?

Can you think of any other solution?

答:
I think this is a good candidate for the builder pattern. Builder pattern is useful when you want to create objects of the same type, but with different representations.

In your case, I would have a builder with the following methods:

```<code>SetTitle (Document document) { ... }
SetFirstPageBlank (Document document) { ... }
SetMinimumPageCount (Document document) { ... }
</code>```

You can then use the builder in the following way:

```<code>_builder.SetTitle(document);
_builder.SetFirstPageBlank(document);
</code>```

On the side note, I don't mind few simple overloads - what the hell, .NET framework uses them all over the place with HTML helpers. However, I would re-evaluate what I'm doing if I have to pass more than two parameters to every method.

Body:
I think this is a good candidate for the builder pattern. Builder pattern is useful when you want to create objects of the same type, but with different representations.

In your case, I would have a builder with the following methods:

SetTitle (Document document) { ... }
SetFirstPageBlank (Document document) { ... }
SetMinimumPageCount (Document document) { ... }

You can then use the builder in the following way:

_builder.SetTitle(document);
_builder.SetFirstPageBlank(document);

On the side note, I don't mind few simple overloads - what the hell, .NET framework uses them all over the place with HTML helpers. However, I would re-evaluate what I'm doing if I have to pass more than two parameters to every method.


问:
Relevance of HTML5: Is now the time?
It seems like most of the jobs I'm receiving, and most of the Internet, is still using standard HTML (HTML 4, let's say) + CSS + JS. Does anyone have any vision on where HTML5 is as a standard, particularly regarding acceptance and diffusion? It's easy to find information about inconsistencies between implementations of HTML5 and so forth. What I want to know about is relevance of HTML5.

答: I think HTML 5 is the future; but as other posts have said it's not prime time yet.  Rich Internet Applications (RIA) are coming into greater demand and I use to think Flash/Flex would win that battle over Silverlight and JavaFX.  But the iPhone and iPad changed all of that.  Flash is out and the HTML 5 canvas tag is its successor.</p>

ContentLicense: CC BY-SA 2.5

Title: Relevance of HTML5: Is now the time?


答:
Modularity. Any decent language will give you the means to glue together pieces of code, but there's no general way to unglue a large piece of code without the programmer performing surgery on the source. By jamming a lot of tasks into one code construct, you rob yourself and others of the opportunity to combine its pieces in other ways, and introduce unnecessary dependencies that could cause changes to one piece to affect the others.

SRP is just as applicable to functions as it is to classes, but mainstream OOP languages are relatively poor at gluing functions together.

Title: Ensure that each class has only one responsibility, why?

Body:
According to Microsoft documentation, the Wikipedia SOLID principe article, or most IT architects we must ensure that each class has only one responsibility. I would like to know why, because if everybody seems to agree with this rule nobody seems to agree about the reasons of this rule.

Some cite better maintenance, some say it provides easy testing or makes the class more robust, or security. What is correct and what does it actually mean? Why does it make maintenance better, testing easier or the code more robust?


问:
What are the perks and drawbacks of using html templates versus building the html in-code
As far as I can see there are two ways of building a html page: "inside" the language (I'll call it building for lack of a better name) or outside the language (using templates). Let me explain a bit what I
mean by this before I jump to the questions.

Building

One way is to build the html page "inside" the language you are using,
using preferably in-language constructs (not just by concatenating strings),
and converting these constructs to html in one last step.

A really good example of this is Clojure's hiccup library, which uses the
Clojure maps and vectors to represent the html. This allows one to use the full
power of the language one's working in to manipulate these structures.

Templating

The second way is to write the html separately from the main program
and use some kind of template DSL to insert logic into the templates.
The hamlet package for Haskell is an example of this.

Now my question is: what are other advantages and disadvantages of both approaches?

I'd love to get more acquainted with these concepts so pointers
to articles etc. are more than welcome. Also please inform me if there
is another approach I didn't think of.

Summary of answers so far

Pro templating

It's easier to separate the view from the rest of the code. The code will be easier to maintain and you avoid mixing business logic with the rest of your code.

This approach generally is much more accessible to people with less technical skills.

Con templating

(none so far)

Pro building

Functional languages, make it easy to write declarative code natively so a template language is not required.

You can get all the power and flexibility of your programming language, and still get the benefits of a declarative syntax.

Con building

Designers/clients are bad at your preferred logic language.

It still boils down to hard-coding the page into codem just that it
is not separate template code.

Has more power, that could be used inappropriately. You have to take extra care

to separate view code and business logic.

In ideal cases it is faster though.

答:
Template languages provide a declarative syntax, which is much less error-prone for this particular use case than an imperative syntax.  In other words, you're specifying what the end result looks like rather than step by step instructions for how to build it.  That's why template languages are so popular when the back end is written in a more imperative language.

On the other hand, functional languages, especially in the Lisp family, make it very easy to write declarative code natively, so a template language is not really required.  You can get all the power and flexibility of your programming language, and still get the benefits of a declarative syntax.

However, if you have more power, that tempts you to use it inappropriately.  You have to take extra care to separate view code and business logic, or else you will end up with something very difficult to maintain.

The other huge drawback is some of the best designers are not very good programmers.  Even a lot of good object oriented programmers get lost in functional languages.  If you want to work with those designers without a workflow where they always hand off an HTML file to a programmer for transcription, then you probably want to stick with a dedicated template language.


答:
Here are the arguments that, in my view, support the claim that the Single-Responsibility Principle is a good practice.  I provide also links to further literature, where you can read even more detailed reasonings -- and more eloquent than mine:

Better maintenance: ideally, whenever a functionality of the system has to change, there will be one and only one class that has to be changed.  A clear mapping between classes and responsibilities means that any developer involved in the project can identify which class this is. (As @MaciejChałapuk has noted, see Robert C. Martin, "Clean Code".)

Easier testing: ideally, classes should have as minimal a public interface as possible, and tests should address only this public interface.  If you cannot test with clarity, because many parts of your class are private, then this is a clear sign that your class has too many responsibilities, and that you should split it in smaller subclasses.  Please notice this applies also to languages where there are no 'public' or 'private' class members; having a small public interface means that it is very clear to client code which parts of the class it is supposed to use. (See Kent Beck, "Test-Driven Development" for more details.)

Robust code: your code will not fail more or less often because it is well-written; but, as all code, its ultimate goal is not to communicate with the machine, but with fellow developers (see Kent Beck, "Implementation Patterns", Chapter 1.)  A clear codebase is easier to reason about, so less bugs will be introduced, and less time will pass between discovering a bug and fixing it.


问:
What is the path to JavaScript mastery?
I know how we start with JavaScript, we cut-and-paste a snippit to gain a little client-side functionality or validation.

But if you follow this path in trying to implement rich interactive behavior, it doesn't take long before you realize that you are creating a Big Ball Of Mud.

So what is the path towards expertise in programming the interaction layer?  What books, tutorials, exercises, and processes contribute towards the ability to program robust, maintainable JavaScript?

We all know that practice is important in any endeavor, but I'm looking for a path similar to the answer here: https://stackoverflow.com/questions/2573135/

答:
read other peoples code (A LOT) and try to get an understanding of what they are doing, and why they are doing it. Write your own code (A LOT) try out new concepts and ideas, above all play and have fun. The best way to get better at something is to practice, practice, and then practice some more.

Read books, tutorials, articles, blogs, RSS feeds, etc.

Create some project to work on in your spare time.  If you can't think of something, find an open source project you might be interested in working on.

also, don't get discouraged and above all, remember "mastery" is not a destination, but a journey--take it at your own pace, have fun, and enjoy the scenery. If you take it too seriously, you will get burnt out and that does nobody any good.

Title: What is the path to JavaScript mastery?


问:
What is meant by change the main routine? The C Programming Language
In exercise 1-16 in The C Programming Language (K & R) it asks for us to: revise the main routine of the longest-line program so it will correctly print the length of arbitrary long input lines, and as much as possible of the text.

From what I read here, I get the notion that the main routine is everything inside of main, is this correct? I posted the code for the longest-line program below for more context, but I am confused my what I am being asked to do not the code. Thanks!

```<code>#include <stdio.h>

#define MAXLINE 1000                /* maximum input line length */

int getline( char line[], int maxline );
void copy( char to[], char from[] );

/* print the longest input line */

main()
{

int len;                /* current line length */
int max;                /* maximum length seen so far */
char line[MAXLINE];     /* current input line */
char longest[MAXLINE];  /* longest line saved here */

max = 0;
while (( len = getline( line, MAXLINE )) > 0)
    if ( len > max ) {
        max = len;
        copy( longest, line );
    }
if ( max > 0 )
    printf( "%s", longest );
return 0;
}

/* getline: read a line into s, return length */
int getline( char s[], int lim )

{
    int c, i;

    for ( i = 0; i <  lim - 1 && ( c = getchar() ) != EOF && c != '\n'; ++i )
        s[i] = c;
    if ( c == '\n' ){
        s[i] = c;
        ++ i;
    }
    s[i] = '\0';
    return i;
    }

/* copy: copy 'from' into 'to'; assume to is big enough */
void copy( char to[], char from[] )
{
    int i;

    i = 0;
    while ( (to[i] = from[i] ) != '\0' )
        ++i;
}
</code>```

答:
Yes, the term main routine typically means the routine (AKA function, method, etc) named main, which is the entry-point of a C program. From Wikipedia:

The main function serves a special purpose in C programs; the run-time environment calls the main function to begin program execution.


答:
When talking about generating ("building") HTML vs. using template language one thing always pops into my mind: separation of concerns i.e. separating the representation ("view") from the business logic.

I'm always in favor of using template languages:

It's easier to separate the view from the rest of the code. The code will be easier to maintain and you avoid mixing business logic with the rest of your code.

Designers will often know some template language but very few designers will know Clojure or Haskell.

Templating languages are often very easy to learn and very good at creating the presentation layer.

By building HTML in the code you can certainly be more flexible and use the whole power of the language, but you will need to be more careful to not mix the business logic and the presentation code.

To compare it to other (non-functional languages): Microsoft created XAML as a language to create the presentation layer (WPF, Silverlight) and always recommended to use the XAML (not code-behind to create elements).

Title: What are the perks and drawbacks of using html templates versus building the html in-code

Body:
As far as I can see there are two ways of building a html page: "inside" the language (I'll call it building for lack of a better name) or outside the language (using templates). Let me explain a bit what I
mean by this before I jump to the questions.

Building

One way is to build the html page "inside" the language you are using,
using preferably in-language constructs (not just by concatenating strings),
and converting these constructs to html in one last step.

A really good example of this is Clojure's hiccup library, which uses the
Clojure maps and vectors to represent the html. This allows one to use the full
power of the language one's working in to manipulate these structures.

Templating

The second way is to write the html separately from the main program
and use some kind of template DSL to insert logic into the templates.
The hamlet package for Haskell is an example of this.

Now my question is: what are other advantages and disadvantages of both approaches?

I'd love to get more acquainted with these concepts so pointers
to articles etc. are more than welcome. Also please inform me if there
is another approach I didn't think of.

Summary of answers so far

Pro templating

It's easier to separate the view from the rest of the code. The code will be easier to maintain and you avoid mixing business logic with the rest of your code.

This approach generally is much more accessible to people with less technical skills.

Con templating

(none so far)

Pro building

Functional languages, make it easy to write declarative code natively so a template language is not required.

You can get all the power and flexibility of your programming language, and still get the benefits of a declarative syntax.

Con building

Designers/clients are bad at your preferred logic language.

It still boils down to hard-coding the page into codem just that it
is not separate template code.

Has more power, that could be used inappropriately. You have to take extra care

to separate view code and business logic.

In ideal cases it is faster though.


问:
Is it possible to learn maths via programming, or you should learn maths for programming?
I am not the best in maths, not very horrid either, but lower than the average, I've always been thinking to improve my maths, but schools and books didn't do the job because I get bored too fast. The only thing I don't get bored with is coding and gaming, so I thought what if coding a program that solves mathematical problems will help me understand maths better, most of these problems are limits (calculus), functions, Differential calculus, and some other subjects (I already said am not that good) similar to the previous noted.

My question is: Am I able to achieve a better knowledge in maths if I do some specific program coding, and if possible, is physics possible that way too? Or am I wrong and Maths should be learned before programming to help improve my coding?

P.S : C++ is the preferred language.

答: Well, You can ask students to solve some geometry problems like to draw square, pentagon, hexagon and circle with Scratch. Challenge them to develop solutions and DON´T answer them about HOW to code it. Let them explore and test solutions. At least you can ask things like the angles sum in polygons. Then they can build the algorithms and their own categories.</p>


问:
Why do projects opt to stay on an older version of the .NET Framework?
Why do projects opt to stay on an older framework version of the .NET Framework?

For example, staying on .NET Framework version 3.5 which was released in 2007 instead of upgrading to the latest 4.5.1 version?

Jon Skeet's Noda Time also targets .NET 3.5. Why?

答:
Targeting a newer version of .NET when your application doesn't rely on anything from the latest version of .NET is unnecessary, unless the target framework itself is reaching end of life.  You're introducing additional work to upgrade and test your application with no real benefit.

With that being said, we've had some software in our group that we've upgraded in the past from .NET 2.0 or .NET 3.5 to .NET 4.0.  In most cases it was because we wanted to take advantage of the Task Parallel Library to improve performance.

We can't upgrade anything to .NET 4.5 yet in our organization because it hasn't been rolled out to any of our environments


答:
First off, you need to know what your goal in regards to learning JavaScript is going to be. If you are just looking to do some input validation and make the UI a bit easier on the user then you really don't need to have a full in-depth understanding of the language if you are using frameworks such as jQuery.

That said, if you want to gain a solid understanding o JavaScript, then try and write an extension to an existing framework that implements a useful tool.

In terms of books and other resources, I haven't really heard of much in the way of useful books and generally I've learned the language though trying to solve problems and checking to make sure my code is clean according to JSLint. A combination of an interesting problem (e.g. framework extension), JSLint, and enough time to get some solid practice in is likely going to be your best bet in terms of learning the language.

Title: What is the path to JavaScript mastery?

Body:
I know how we start with JavaScript, we cut-and-paste a snippit to gain a little client-side functionality or validation.

But if you follow this path in trying to implement rich interactive behavior, it doesn't take long before you realize that you are creating a Big Ball Of Mud.

So what is the path towards expertise in programming the interaction layer?  What books, tutorials, exercises, and processes contribute towards the ability to program robust, maintainable JavaScript?

We all know that practice is important in any endeavor, but I'm looking for a path similar to the answer here: https://stackoverflow.com/questions/2573135/


问:
Best Practices - separation of concerns and inheritance issues
Here's the situation:
I have a "common" Data Access  assembly that contains classes used in all my projects.  Some of those are abstract classes that are only implemented by my data access layers for each project.

In my projects I have a layered approach - separated data access, business layer, and UI.  My data access classes may inherit from the abstract classes in Common.  These abstract classes contain an "execute" method.

In my business layer of the project I only reference the data access layer of the project - I don't reference other projects or the Common assembly.  But once I put my abstract classes that are reused all the time into Common, my business layer could no longer call the "Execute" method without having a reference to common.

I hope that's not too confusing.

If I don't want lots of interdependencies between assemblies, I need to move the abstract classes back into each project's data access layer.  But then I have repeated code and potentially inconsistent behavior between projects.

But if I keep it as it is, all my business layers need to be able to access this common data access assembly, which seems wrong.

Any thoughts on this architecture?

I know some might try to say "use Entity Framework" or some other ORM.  But my projects are not complex enough to warrant that much overhead, especially given the need for fast performance.  I have found that a simple framework of my own directly implementing ADO.Net is remarkably faster.  So please just advise me on the separation of concerns and inheritance issues and don't try to talk me into adding an ORM.

Example code:

In Common: base class

```<code>Public MustInherit Class AbstractDatabaseAction
    Protected Property Factory As DbProviderFactory
    Protected Property Connection As DbConnection
    Protected Property Command As DbCommand
    Protected Property MessageForExceptions As String
    Protected Property ProviderName As String

    Protected Sub New(connString As String, providerName As String, messageForExceptions As String)
        Factory = DbProviderFactories.GetFactory(providerName)

        'set up connection
        Connection = Factory.CreateConnection
        Connection.ConnectionString = connString
        Me.ProviderName = providerName
        'set up command
        Command = Factory.CreateCommand

        Me.MessageForExceptions = messageForExceptions
    End Sub

    Public MustOverride Sub Execute()
    Protected Overridable Sub SetParameters()
        'nothing
    End Sub
    Protected MustOverride Sub SetCommandText()
    Protected Overridable Sub SetCommandType()
        Command.CommandType = CommandType.StoredProcedure
    End Sub

    Protected Sub BuildCommand()
        Command.Connection = Connection
        Me.SetCommandText()
        Me.SetCommandType()
        Me.SetParameters()

        If Me.ProviderName = "Oracle.DataAccess.Client" Then
            OracleSpecificCommandEdits()
        End If
    End Sub

    Protected Overridable Sub OracleSpecificCommandEdits()
        CType(Command, OracleCommand).BindByName = True
    End Sub

End Class
</code>```

In Common: second base class (I have both a search and a save version, with the save version optionally allowing transactions.)

```<code>Public MustInherit Class AbstractSearch
    Inherits AbstractDatabaseAction

    Protected Sub New(connString As String, providerName As String, messageForExceptions As String)
        MyBase.New(connString, providerName, messageForExceptions)
    End Sub

    Public Overrides Sub Execute()
        Try
            Me.BuildCommand()

            Using Connection
                Connection.Open()

                Using Command
                    Try
                        Dim rdr As IDataReader = Command.ExecuteReader
                        Me.fill(rdr)
                        rdr.Close()
                    Catch ex As Exception
                        Throw New Exception(MessageForExceptions & "->Search", ex)
                    End Try
                End Using
            End Using
        Catch ex As Exception
            Throw New Exception(MessageForExceptions & "->Search", ex)
        End Try
    End Sub

    Protected MustOverride Sub fill(ByRef rdr As System.Data.IDataReader)

    Protected Overrides Sub OracleSpecificCommandEdits()
        MyBase.OracleSpecificCommandEdits()

        If TypeOf (Factory) Is OracleClientFactory Then
            Dim p As DbParameter = New OracleParameter
            p.ParameterName = "results"
            p.Direction = ParameterDirection.Output
            CType(p, OracleParameter).OracleDbType = OracleDbType.RefCursor
            Command.Parameters.Add(p)
        End If
    End Sub

Protected Sub AddInParameter(key As String, value As Object)
    Dim p As IDataParameter = Command.CreateParameter
    p.Direction = ParameterDirection.Input
    p.Value = value
    p.ParameterName = key
    Command.Parameters.Add(p)
End Sub

Protected Sub AddOutParameter(key As String, type As System.Data.DbType)
    Dim p As IDataParameter = Command.CreateParameter
    p.Direction = ParameterDirection.Output
    p.DbType = type
    p.ParameterName = key
    Command.Parameters.Add(p)
End Sub

End Class
</code>```

A very simple implementation example of a data access layer implementation:

```<code>Public Class IpBlackListSearch
        Inherits Common.DataAccess.AbstractSearch

        Private Property IPToSearch As String
        Public Property Results As List(Of String) = Nothing

        Public Sub New(connString As String, providerName As String, ipAddressToSearch As String)
            MyBase.New(connString, providerName, "IpAddressSearch")
            Me.IPToSearch = IPToSearch
        End Sub

        Protected Overrides Sub fill(ByRef rdr As System.Data.IDataReader)
            Results = New List(Of String)

            While rdr.Read
                Results.Add(HelperFunctions.NullScrubber(Of String)("ip"))
            End While

        End Sub

        Protected Overrides Sub SetCommandText()
            Command.CommandText = "Get_IPBlacklist"
        End Sub

        Protected Overrides Sub SetParameters()
            MyBase.AddInParameter("in_ip", Me.IPToSearch)
        End Sub
    End Class
</code>```

The problem would come when in the business layer of my project that would do something like:

```<code>Dim srch as new IpBlackListSearch(connstring, providername, "12.12.12.12.")
srch.execute
</code>```

srch.Execute can only compile if the business layer references the common data access assembly.

It sounds like from the comments that there is nothing wrong with my business layer containing that reference.

答: Consider using delegates instead of abstract classes. The Template Method pattern is mostly a hack to work around a language's lack of first-class functions. So instead of overriding "execute", pass it in as an argument. That aside, why don't you want dependencies between assemblies? What good is your Common assembly if you're not going to use it?</p>


问:
Dealing with a large pull request
I'm currently working on a project with a team that's using a git workflow. It's fairly simple: master should be in a deployable state and branches are used to create features and hotfixes. Whenever we have a feature or bugfix completed and tested then we move that over to master as soon as we can. The idea is that branches should be as small as possible to make it easier to merge them back into master. We have a policy that any code pushed to master branch should be in a deployable state and pass the tests.

We have got a situation where one of the developers has done a lot of work (a few months worth) on a single branch and this branch hasn't been merged back into the master yet. There's now a few separate features and a bunch of commits on this branch. Essentially, this branch really should have been merged back in a few times already but so far hasn't been. Most of the code is in a good state with unit tests that could be merged back into master but the most recent changes should certainly not be as they are not completed and aren't tested.

What is the best way to deal with such a situation where one branch is really far away from the others? What ways can we avoid branches getting a very large number of commits away from master in the future?

答:
First, see if there truly are separate commits that can be merged or cherry-picked, like suggest by @Maciej Chalpuk. If this is the case, then the situation really isn't that bad, and I wouldn't worry too much about it in the future.

However, if the real situation is that multiple features have been developed concurrently in a single branch, within the same commits, then it becomes a much larger pain to deal with. Luckily, the prevention method is built in: require the developer to separate out the changes for each feature into separate branches and pull requests before merging them in. You'll both get your atomic merges, as well as dissuade this developer from doing it in the future.

The actual process of separating out the features is entirely manual. Create new branches off of master, and copy in whatever changes from the mega branch that are related to it. Compile, test the feature, push and issue a pull request. The less intermingled the code changes are, the easier it will be to do. If he was hacking a single method for all of them, well, have fun. He won't do it again.

ContentLicense: CC BY-SA 4.0

Title: Dealing with a large pull request


答:
I follow the thought: 1 Class = 1 Job.

Using a Physiology Analogy: Motor (Neural System), Respiration (Lungs), Digestive (Stomach), Olfactory (Observation), etc.  Each of these will have a subset of  controllers, but they each only have 1 responsibility, whether its to manage the way each of their respective subsystems works or whether they are an end-point subsystem and perform only 1 task, such as lifting a finger or growing a hair-follicle.

Don't confuse the fact that it may be acting as a manager instead of a worker.  Some worker's eventually get promoted to Manager, when the work they were performing has become too complicated for one process to handle by itself.

The most complicated part of what i have experienced, is knowing when to designate a Class as an Operator, Supervisor, or Manager process.  Regardless, you will need to observe and denote its functionality for 1 responsibility (Operator, Supervisor, or Manager).

When a Class/Object performs more than 1 of these type roles, you will find that the overall process will start having performance issues, or process bottle-necks.


问:
Real time unit testing - or "how to mock now"
When you are working on a feature that depends on time... How do you organize unit testing ? When your unit tests scenarios depend on the way your program interprets "now", how do you set them up ?

Second Edit: After a Couple of days reading your experience

I can see that the techniques to deal with this situation usually revolve around one of these three principles:

 Add (hardcode) a dependency: add a small layer over the time function/object, and always call your datetime function through this layer. This way, you can get control of time during the test cases.

 Use mocks: your code stays exactly the same. In your tests, you replace the time object by a fake time object. Sometimes, the solution involves modifying the genuine time object that is provided by your programming language.

 Use dependency injection: Build your code so that any time reference is passed as a parameter. Then, you have control of the parameters during the tests.

Techniques (or libraries) specific to a language are very welcome, and will be enhanced if an illustrative piece of code comes along. Then, most interesting is how similar principles may be applied on any platform.
And yes... If I can apply it straight away in PHP, better than better ;)

Let's start with a simple example: a basic booking application.

Let's say we have JSON API and two messages: a request message, and a confirmation message.
A standard scenario goes like this:

You make a request. You get a response with a token. The resource that is needed to fulfill that request is blocked by the system for 5 minutes.

You confirm a request, identified by the token. If token was issued within 5 minutes, it will be accepted (the resource is still available). If more than 5 minutes have passed, you have to make a new request (the resource was freed. You need to check for its availability again).

Here come the corresponding test scenario:

I make a request. I confirm (immediately) with the token I received. My confirmation is accepted.

I make a request. I wait 3 minutes. I confirm with the token I received. My confirmation is accepted.

I make a request. I wait 6 minutes. I confirm with the token I received. My confirmation is rejected.

How can we get to program these unit tests ? What architecture should we use so that these functionalities remain testable ?

Edit Note: When we shoot a request, the time is stored in a database in a format that looses any information about milliseconds.

EXTRA - but maybe a bit verbose: Here come details about what I found out doing my "homework":

I Built my feature with a dependency on a time function of my own. My function VirtualDateTime has a static method get_time() that I call where I used to call new DateTime(). This time function allows me to simulate and control what time is "now", so that I can build tests like: "Set now to 21st jan 2014 16h15. Make a request. Move ahead 3 minutes. Make confirmation.". This works fine, at the cost of the dependency, and "not so pretty code".

A little more integrated solution would be to build a myDateTime function of my own that extends DateTime with additional "virtual time" functionnalities (most importantly, set now to what I want). This is making the first solution's code slightly more elegant (use of new myDateTime instead of new DateTime), but ends up to be very similar: I have to build my feature using my own class, thus creating a dependency.

I have though about hacking the DateTime function, to make it work with my dependency when I need it. Is there any simple and neat way to replace a class by another, though ? (I think I got an answer to that: See namespace below).

In a PHP environment, I read "Runkit" may allow me to do this (hack the DateTime function) dynamically. What is nice is that I would be able to check I am running in test environment before modifying anything about DateTime, and leave it untouched in production [1]. This sounds much safer and cleaner than any manual DateTime hack.

Dependency injection of a clock function in each class that uses time [2]. Is this not overkill ? I see that in some environments it gets very usefull [5]. In this case, I do not like it so much, though.

Remove dependency of time in all the functions [2]. Is this always feasible ? (See more examples below)

Using namespaces [2][3] ? This looks quite good. I could mock DateTime with my own DateTime function that extends \DateTime... Use DateTime::setNow("2014-01-21 16:15:00"), and DateTime::wait("+3 minutes"). This covers pretty much what I need. What if we use the time() function though ? Or other time functions ? I still have to avoid their use in my original code. Or I would need to make sure any PHP time function I use in my code is overridden in my tests... Is there any library available that would do just this ?

I have been looking for a way to change the system time just for a thread. It seems that there is none  [4]. This is a pity: a "simple" PHP function to "Set time to 21st jan 2014 16h15 for this thread" would be a great feature for this kind of tests.

Change the system date and time for the test, using exec(). This can work out if you are not afraid to mess up with other things on the server. And you need to set back the system time after you ran your test. It can do the trick in some situations, but feels quite "hacky".

This looks like a very standard problem to me. However, I still miss a simple an generic way to deal with it. Maybe I missed something ?
    Please share your experience !

NOTE: Here are some other situations where we may have similar testing needs.

Any feature that works with some kind of timeout (e.g. chess game ?)

processing a queue that triggers events at a given time (in the above scenario we could keep going like this: one day before the reservation starts, I want to send a mail to the user with all the details. Test scenario...)

You want to set up a test environment with data collected in the past - you would like to see it like if it was now. [1]

1 https://stackoverflow.com/questions/3271735/simulate-different-server-datetimes-in-php

2 https://stackoverflow.com/questions/4221480/how-to-change-current-time-for-unit-testing-date-functions-in-php

3 http://www.schmengler-se.de/en/2011/03/php-mocking-built-in-functions-like-time-in-unit-tests/

4 https://stackoverflow.com/questions/3923848/change-todays-date-and-time-in-php

5 Unit testing time-bound code

答:
The first thing you need to do is remove the magic numbers from your code. In this case, your "5 minute" magic number. Not only will you inevitably need to change these later when some client demands it, it makes unit testing way better. Who's going to wait 5 minutes for their test to run?

Second, if you haven't already, use UTC for actual timestamps. This will prevent issues with daylight savings and most other clock hiccups.

In the unit test, switch the configured duration to something like 500ms and do your normal test: does it work one way before the timeout and another way after.

~1s is still fairly slow for unit tests, and you likely will need some sort of threshold to account for machine performance and clock shifts due to NTP (or other drift). But in my experience, this is the best practical way to unit test time based stuff in most systems. Simple, quick, reliable. Most other approaches (as you've found) require tons of work and/or are terribly error prone.


答:
For my money, holding a dependency on some clock class is the clearest way to go about handling time-dependent testing. In PHP, it may be as simple as a a class with a single function now which returns the current time using time() or new DateTime().

Injecting this dependency allows you to manipulate the time in your tests and use the real time in production, without having to write too much extra code.

Title: Real time unit testing - or "how to mock now"

Body:
When you are working on a feature that depends on time... How do you organize unit testing ? When your unit tests scenarios depend on the way your program interprets "now", how do you set them up ?

Second Edit: After a Couple of days reading your experience

I can see that the techniques to deal with this situation usually revolve around one of these three principles:

 Add (hardcode) a dependency: add a small layer over the time function/object, and always call your datetime function through this layer. This way, you can get control of time during the test cases.

 Use mocks: your code stays exactly the same. In your tests, you replace the time object by a fake time object. Sometimes, the solution involves modifying the genuine time object that is provided by your programming language.

 Use dependency injection: Build your code so that any time reference is passed as a parameter. Then, you have control of the parameters during the tests.

Techniques (or libraries) specific to a language are very welcome, and will be enhanced if an illustrative piece of code comes along. Then, most interesting is how similar principles may be applied on any platform.
And yes... If I can apply it straight away in PHP, better than better ;)

Let's start with a simple example: a basic booking application.

Let's say we have JSON API and two messages: a request message, and a confirmation message.
A standard scenario goes like this:

You make a request. You get a response with a token. The resource that is needed to fulfill that request is blocked by the system for 5 minutes.

You confirm a request, identified by the token. If token was issued within 5 minutes, it will be accepted (the resource is still available). If more than 5 minutes have passed, you have to make a new request (the resource was freed. You need to check for its availability again).

Here come the corresponding test scenario:

I make a request. I confirm (immediately) with the token I received. My confirmation is accepted.

I make a request. I wait 3 minutes. I confirm with the token I received. My confirmation is accepted.

I make a request. I wait 6 minutes. I confirm with the token I received. My confirmation is rejected.

How can we get to program these unit tests ? What architecture should we use so that these functionalities remain testable ?

Edit Note: When we shoot a request, the time is stored in a database in a format that looses any information about milliseconds.

EXTRA - but maybe a bit verbose: Here come details about what I found out doing my "homework":

I Built my feature with a dependency on a time function of my own. My function VirtualDateTime has a static method get_time() that I call where I used to call new DateTime(). This time function allows me to simulate and control what time is "now", so that I can build tests like: "Set now to 21st jan 2014 16h15. Make a request. Move ahead 3 minutes. Make confirmation.". This works fine, at the cost of the dependency, and "not so pretty code".

A little more integrated solution would be to build a myDateTime function of my own that extends DateTime with additional "virtual time" functionnalities (most importantly, set now to what I want). This is making the first solution's code slightly more elegant (use of new myDateTime instead of new DateTime), but ends up to be very similar: I have to build my feature using my own class, thus creating a dependency.

I have though about hacking the DateTime function, to make it work with my dependency when I need it. Is there any simple and neat way to replace a class by another, though ? (I think I got an answer to that: See namespace below).

In a PHP environment, I read "Runkit" may allow me to do this (hack the DateTime function) dynamically. What is nice is that I would be able to check I am running in test environment before modifying anything about DateTime, and leave it untouched in production [1]. This sounds much safer and cleaner than any manual DateTime hack.

Dependency injection of a clock function in each class that uses time [2]. Is this not overkill ? I see that in some environments it gets very usefull [5]. In this case, I do not like it so much, though.

Remove dependency of time in all the functions [2]. Is this always feasible ? (See more examples below)

Using namespaces [2][3] ? This looks quite good. I could mock DateTime with my own DateTime function that extends \DateTime... Use DateTime::setNow("2014-01-21 16:15:00"), and DateTime::wait("+3 minutes"). This covers pretty much what I need. What if we use the time() function though ? Or other time functions ? I still have to avoid their use in my original code. Or I would need to make sure any PHP time function I use in my code is overridden in my tests... Is there any library available that would do just this ?

I have been looking for a way to change the system time just for a thread. It seems that there is none  [4]. This is a pity: a "simple" PHP function to "Set time to 21st jan 2014 16h15 for this thread" would be a great feature for this kind of tests.

Change the system date and time for the test, using exec(). This can work out if you are not afraid to mess up with other things on the server. And you need to set back the system time after you ran your test. It can do the trick in some situations, but feels quite "hacky".

This looks like a very standard problem to me. However, I still miss a simple an generic way to deal with it. Maybe I missed something ?
    Please share your experience !

NOTE: Here are some other situations where we may have similar testing needs.

Any feature that works with some kind of timeout (e.g. chess game ?)

processing a queue that triggers events at a given time (in the above scenario we could keep going like this: one day before the reservation starts, I want to send a mail to the user with all the details. Test scenario...)

You want to set up a test environment with data collected in the past - you would like to see it like if it was now. [1]

1 https://stackoverflow.com/questions/3271735/simulate-different-server-datetimes-in-php

2 https://stackoverflow.com/questions/4221480/how-to-change-current-time-for-unit-testing-date-functions-in-php

3 http://www.schmengler-se.de/en/2011/03/php-mocking-built-in-functions-like-time-in-unit-tests/

4 https://stackoverflow.com/questions/3923848/change-todays-date-and-time-in-php

5 Unit testing time-bound code


答:
This exact problem is why Dependency Inversion Principle exists. This principle says.

High-level modules should not depend on low-level modules. Both should depend on abstractions.

Abstractions should not depend on details. Details should depend on abstractions.

In your case, the business layer depends on detail that is data access. To fix this you should create abstraction that is part of business layer that says what kind of data operations the business layer needs to function. The data access layer then realizes this abstraction while inheriting from data access common/base class. This concrete implementation is then created using some kind of factory mechanism, like Abstract Factory pattern or using Dependency Injection.

Title: Best Practices - separation of concerns and inheritance issues

Body:
Here's the situation:
I have a "common" Data Access  assembly that contains classes used in all my projects.  Some of those are abstract classes that are only implemented by my data access layers for each project.

In my projects I have a layered approach - separated data access, business layer, and UI.  My data access classes may inherit from the abstract classes in Common.  These abstract classes contain an "execute" method.

In my business layer of the project I only reference the data access layer of the project - I don't reference other projects or the Common assembly.  But once I put my abstract classes that are reused all the time into Common, my business layer could no longer call the "Execute" method without having a reference to common.

I hope that's not too confusing.

If I don't want lots of interdependencies between assemblies, I need to move the abstract classes back into each project's data access layer.  But then I have repeated code and potentially inconsistent behavior between projects.

But if I keep it as it is, all my business layers need to be able to access this common data access assembly, which seems wrong.

Any thoughts on this architecture?

I know some might try to say "use Entity Framework" or some other ORM.  But my projects are not complex enough to warrant that much overhead, especially given the need for fast performance.  I have found that a simple framework of my own directly implementing ADO.Net is remarkably faster.  So please just advise me on the separation of concerns and inheritance issues and don't try to talk me into adding an ORM.

Example code:

In Common: base class

```<code>Public MustInherit Class AbstractDatabaseAction
    Protected Property Factory As DbProviderFactory
    Protected Property Connection As DbConnection
    Protected Property Command As DbCommand
    Protected Property MessageForExceptions As String
    Protected Property ProviderName As String

    Protected Sub New(connString As String, providerName As String, messageForExceptions As String)
        Factory = DbProviderFactories.GetFactory(providerName)

        'set up connection
        Connection = Factory.CreateConnection
        Connection.ConnectionString = connString
        Me.ProviderName = providerName
        'set up command
        Command = Factory.CreateCommand

        Me.MessageForExceptions = messageForExceptions
    End Sub

    Public MustOverride Sub Execute()
    Protected Overridable Sub SetParameters()
        'nothing
    End Sub
    Protected MustOverride Sub SetCommandText()
    Protected Overridable Sub SetCommandType()
        Command.CommandType = CommandType.StoredProcedure
    End Sub

    Protected Sub BuildCommand()
        Command.Connection = Connection
        Me.SetCommandText()
        Me.SetCommandType()
        Me.SetParameters()

        If Me.ProviderName = "Oracle.DataAccess.Client" Then
            OracleSpecificCommandEdits()
        End If
    End Sub

    Protected Overridable Sub OracleSpecificCommandEdits()
        CType(Command, OracleCommand).BindByName = True
    End Sub

End Class
</code>```

In Common: second base class (I have both a search and a save version, with the save version optionally allowing transactions.)

```<code>Public MustInherit Class AbstractSearch
    Inherits AbstractDatabaseAction

    Protected Sub New(connString As String, providerName As String, messageForExceptions As String)
        MyBase.New(connString, providerName, messageForExceptions)
    End Sub

    Public Overrides Sub Execute()
        Try
            Me.BuildCommand()

            Using Connection
                Connection.Open()

                Using Command
                    Try
                        Dim rdr As IDataReader = Command.ExecuteReader
                        Me.fill(rdr)
                        rdr.Close()
                    Catch ex As Exception
                        Throw New Exception(MessageForExceptions & "->Search", ex)
                    End Try
                End Using
            End Using
        Catch ex As Exception
            Throw New Exception(MessageForExceptions & "->Search", ex)
        End Try
    End Sub

    Protected MustOverride Sub fill(ByRef rdr As System.Data.IDataReader)

    Protected Overrides Sub OracleSpecificCommandEdits()
        MyBase.OracleSpecificCommandEdits()

        If TypeOf (Factory) Is OracleClientFactory Then
            Dim p As DbParameter = New OracleParameter
            p.ParameterName = "results"
            p.Direction = ParameterDirection.Output
            CType(p, OracleParameter).OracleDbType = OracleDbType.RefCursor
            Command.Parameters.Add(p)
        End If
    End Sub

Protected Sub AddInParameter(key As String, value As Object)
    Dim p As IDataParameter = Command.CreateParameter
    p.Direction = ParameterDirection.Input
    p.Value = value
    p.ParameterName = key
    Command.Parameters.Add(p)
End Sub

Protected Sub AddOutParameter(key As String, type As System.Data.DbType)
    Dim p As IDataParameter = Command.CreateParameter
    p.Direction = ParameterDirection.Output
    p.DbType = type
    p.ParameterName = key
    Command.Parameters.Add(p)
End Sub

End Class
</code>```

A very simple implementation example of a data access layer implementation:

```<code>Public Class IpBlackListSearch
        Inherits Common.DataAccess.AbstractSearch

        Private Property IPToSearch As String
        Public Property Results As List(Of String) = Nothing

        Public Sub New(connString As String, providerName As String, ipAddressToSearch As String)
            MyBase.New(connString, providerName, "IpAddressSearch")
            Me.IPToSearch = IPToSearch
        End Sub

        Protected Overrides Sub fill(ByRef rdr As System.Data.IDataReader)
            Results = New List(Of String)

            While rdr.Read
                Results.Add(HelperFunctions.NullScrubber(Of String)("ip"))
            End While

        End Sub

        Protected Overrides Sub SetCommandText()
            Command.CommandText = "Get_IPBlacklist"
        End Sub

        Protected Overrides Sub SetParameters()
            MyBase.AddInParameter("in_ip", Me.IPToSearch)
        End Sub
    End Class
</code>```

The problem would come when in the business layer of my project that would do something like:

```<code>Dim srch as new IpBlackListSearch(connstring, providername, "12.12.12.12.")
srch.execute
</code>```

srch.Execute can only compile if the business layer references the common data access assembly.

It sounds like from the comments that there is nothing wrong with my business layer containing that reference.


答:
From what I understand your question to be, it seems like your Data Access Layer classes were accessing the Common Assembly and then your Business Layer accessed your Project Specific Data Access Layer.

Now you want to put some of your Common Data Access layer classes into the Common Assembly. You think it is no longer OK for the Business Layer to access the DAL. However, the business layer was already accessing the DAL. So in reality, what is different?

If you only want to expose your abstract classes then it sounds like they need to go in their own Common DAL assembly.


问:
What are security advantages of Google Caja over using the web worker API?
I am currently looking into Google Caja to run user-supplied JS code in the browser and in Node.

So far, I understand, that, in a browser context, "cajoled code" disallows reading and messing with the window state by running unsafe code through a full-blown parser that gets rid of all kinds of attack vectors, and then safely executing that code in an iframe of the same origin.

However, I am currently working on a solution using HTML5's Worker (see here) and it seems to have the same effect. What does Caja have to offer that Worker does not have, other than the ability to customize security policies? Does it have any additional safety features?

答:
Whether Caja has a security advantage depends on what your goals are.

These are the main features Caja offers for code sandboxing that all sandboxing methods currently available in browsers do not, as far as I know:

Synchronous interaction: you can define APIs which can be called by the guest code and respond immediately — they look like ordinary objects and functions. With workers, since they are explicitly threaded, all interaction must be via postMessage and therefore asynchronous.

Further, if you write your code in the object-capability style it is possible to place both your own application and the user-supplied code within the Caja sandbox and have them interact in arbitrary ways without having to use any heavyweight intermediation at the boundaries between them.

Confinement: you can prohibit the guest code from communicating with third-party servers. This means you can execute untrusted code on private data without allowing it to leak that data (it can only return the results of its computation, or display it to the user).

If neither of these is interesting to you, then go ahead and use workers.

(There are additional things you can do with Caja for HTML, e.g. controlling external links, which I have not addressed here because you seem interested in running “headless” JS only.)


答:
When I first learned TDD, I was working in a c# environment. The way I learned to do it is to have a complete IoC environment, which also included an ITimeService, which was responsible for all time services, and could easily be mocked in tests.

Nowadays I'm working in ruby, and stubbing time is a lot easier - you simply stub time:

describe 'some time based module' do

  before(:each) do
    @now = Time.now
    allow(Time).to receive(:now) { @now }
  end

  it 'times out after five minutes' do
    subject.do_something

    @now += 5.minutes

    expect { subject.do_another_thing }.to raise TimeoutError
  end
end
```


答:
Use Microsoft Fakes - instead of altering your code to suit the tool, the tool alters your code at runtime, injecting a new Time object (that you define in your test) in place of the standard clock.

If you're running a dynamic language - then Runkit is just the same type of thing.

For example with Fakes:

```<code>[TestMethod]
public void MyDateProvider_ShouldReturnDateAsJanFirst1970()
{
    using (Microsoft.QualityTools.Testing.Fakes.ShimsContext.Create())
    {
        // Arrange: set up a shim to our own date object instead of System.DateTime.Now
        System.Fakes.ShimDateTime.NowGet = () => new DateTime(1970, 1, 1);

        //Act: call the method under test
        var curentDate = MyDateTimeProvider.GetTheCurrentDate();

        //Assert: that we have a moustache and a brown suit.
        Assert.IsTrue(curentDate == new DateTime(1970, 1, 1));
    }
}

public class MyDateTimeProvider
{
    public static DateTime GetTheCurrentDate()
    {
        return DateTime.Now;
    }
}
</code>```

So when the text method calls return DateTime.Now it will return the time you injected, rather than the real current time.

Body:
Use Microsoft Fakes - instead of altering your code to suit the tool, the tool alters your code at runtime, injecting a new Time object (that you define in your test) in place of the standard clock.

If you're running a dynamic language - then Runkit is just the same type of thing.

For example with Fakes:

[TestMethod]
public void MyDateProvider_ShouldReturnDateAsJanFirst1970()
{
    using (Microsoft.QualityTools.Testing.Fakes.ShimsContext.Create())
    {
        // Arrange: set up a shim to our own date object instead of System.DateTime.Now
        System.Fakes.ShimDateTime.NowGet = () => new DateTime(1970, 1, 1);

        //Act: call the method under test
        var curentDate = MyDateTimeProvider.GetTheCurrentDate();

        //Assert: that we have a moustache and a brown suit.
        Assert.IsTrue(curentDate == new DateTime(1970, 1, 1));
    }
}

public class MyDateTimeProvider
{
    public static DateTime GetTheCurrentDate()
    {
        return DateTime.Now;
    }
}

So when the text method calls return DateTime.Now it will return the time you injected, rather than the real current time.


问:
What hat should a programmer not wear?
In my experience, software developers tend to wear multiple hats and fill multiple roles with different responsibilities.  From not only coding, but sometimes also writing SQL, designing the user-interface, designing the database, graphics manipulation, to even QA testing.

If the primary role is to write software/code, what roles should the developer not take on?  Are there any?

The intention of this question is not because a developer is incapable of filling another role-- but having the additional role actually works against the primary role, or should really be a dedicated role of someone who does not primarily program.

答:
Never wear more "hats" than you can reasonably handle and are comfortable with, trying to pigeon hole developers by saying that they shouldn't do A or B means that a great UI designer might go unnoticed because someone thinks that programmers should stay away from the UI.

At the end of the day everyone is going to have different strengths and weaknesses and a good manager/supervisor/team leader should know the best way to direct the people working for them to ensure that talents are being used appropriately. Likewise, if you are not comfortable with designing UIs or dealing with the end users, then let you team know so you can minimize your role in that area. However, you should be prepared to pick up some additional work in another area.

Also, if you are wearing too many hats (e.g. programmer, UI designer, tester, business analyst, etc) then you are either going to do poorly at some of them, or you will burn yourself out. Make sure that you know how many hats you can handle and try to keep the workload around that level.

Beyond that, there really are no "hats" that a developer shouldn't wear if they have the skills to excel in that role.

Title: What hat should a programmer not wear?


问:
Types of unit tests based on usefulness
From value point of view I see two groups of unit tests in my practice:

Tests that test some non-trivial logic. Writing them (either before
implementation or after) reveals some problems/potential bugs and
helps to be confident in case logic is changed in the future.

Tests that test some very trivial logic. Those tests more like
document code (typically with mocks) than test it. The maintenance
workflow of those tests is not "some logic changed, test became red - thanks God I wrote this test" but "some trivial code changed, test became false negative - I have to maintain (rewrite) the test
without gaining any profit". Most of the time those tests are not
worth maintaining (except religious reasons). And according to my
experience in many systems those tests are like 80% of all tests.

I am trying to find out what other guys think on the topic of unit tests separation by value and how it corresponds to my separation. But what I mostly see is either fulltime TDD propaganda or tests-are-useless-just-write-the-code propaganda. I'm interested in something in the middle. Your own thoughts or references to articles/papers/books are welcome.

答:
I think it's natural to encounter a divide within unit testing. There are many different opinions on how to do it properly and naturally all other opinions are inherently wrong. There are quite a few articles on DrDobbs recently that explore this very issue to which I link at the end of my answer.

The first problem I see with tests is that it's easy to get them wrong. In my college C++ class we were exposed to unit tests in both the first and second semester. We knew nothing about programming in general in either of the semesters- we were trying to learn the fundamentals of programming via C++. Now imagine telling the students, "Oh hey, you wrote a little yearly tax calculator! Now write some unit tests to ensure that it works correctly." The results should be obvious- they were all horrible, including my attempts.

Once you admit that you suck at writing unit tests and wish to get better, you will soon be faced with either trendy styles of testing or different methodologies. By testing methodologies I refer to practices such as test-first or what Andrew Binstock of DrDobbs does, which is write the tests alongside the code. Both have their pros and cons and I refuse to go into any subjective detail because that will incite a flame war. If you're not confused about which programming methodology is better, then maybe the style of testing will do the trick. Should you use TDD, BDD, Property-based testing? JUnit has advanced concepts called Theories that blurs the line between TDD and Property-based testing. Which to use when?

tl;dr It's easy to get testing wrong, it's incredibly opinionated and I don't believe that any one testing methodology is inherently better as long as they are used diligently and professionally within the context that they're appropriate in. Furthermore, testing is in my mind an extension to assertions or sanity-tests that used to ensure a fail-fast ad-hoc approach to development which is now much, much easier.

For a subjective opinion, I prefer to write "phases" of tests, for lack of a better phrase. I write unit tests which test classes in isolation, using mocks where necessary. These will probably be executed with JUnit or something similar. Then I write integration or acceptance tests, these are run separately and usually only a few times a day. These are your non-trivial use case. I usually use BDD as it is nice to express features in natural language, something that JUnit cannot easily provide.

Lastly, resources. These will present conflicting opinions mostly centered around unit testing in different languages and with different frameworks. They should present the divide in ideology and methodology while allowing you to make up your own opinion as long as I haven't manipulated yours too much already :)

[1] The Corruption of Agile by Andrew Binstock

[2] Response to the Responses of the previous article

[3] Response to Corruption of Agile by Uncle Bob

[4]Response to Corruption of Agile by Rob Myers

[5]Why Bother With Cucumber Testing?

[6] You're Cuking it Wrong

[7]Step Away From the Tools

[8]Commentary on 'Roman Numerals Kata with Commentary'

[9]Roman Numerals Kata With Commentary

Title: Types of unit tests based on usefulness


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答:
Miss Understood, if i were you i would hold something behind your hand.

Since he has appeared to be such a louzy, verbal contract breaker, and much more than that, such an un-ethically abusive client who raises the demands ( changes the verbal contracts ) while lowers the payment, there is unfortunately no reason to think he will quickly become a very honest person overnight.

So, here is what to do:

```<code> 1. dont care the empty webspace, anybody
    can host that empty space.

 2. pull everything YOU have designed to another
    webspace and redirect his webspace
    in full secrecy towards your own
    webspace (if you have the webspace
    for this, would be great)

 3. THEN send a warning signal and give him a term to fulfil the
    payment, or else you will rais the
    charges for the raised requirements.
</code>```

The world is filled with such kind people like yourself Miss Understood.
Such a pity louzy clients abused the kindness. They don't deserve the title client. He is not a client, just a clouzy. they are two different kinds, and you should deal with them differently.

Leave your kindness for good clients, who not only appreaciate your vision, but also will never abuse them. I have seen such things so many times i can spot such case right from the start nowadays and dont fall into the old traps anymore.  Furthermore i would advise AGAINST any kinds of lawers you have to hire, those advising you have never done it i guesse. Most of them just want your money and you will end up paying them, after that person has payed you, no way that can be called EVEN.

Above all this, i hope you have not lost your creative passion and will move on after this somewhat-bitter experience, knowing that the world is filled with good, honest people, and navigate your sensors from now on more strongly towards them. Cheers, Sam

Title: How to get money from reluctant client?

Body:
Miss Understood, if i were you i would hold something behind your hand.

Since he has appeared to be such a louzy, verbal contract breaker, and much more than that, such an un-ethically abusive client who raises the demands ( changes the verbal contracts ) while lowers the payment, there is unfortunately no reason to think he will quickly become a very honest person overnight.

So, here is what to do:

 1. dont care the empty webspace, anybody
    can host that empty space.

 2. pull everything YOU have designed to another
    webspace and redirect his webspace
    in full secrecy towards your own
    webspace (if you have the webspace
    for this, would be great)

 3. THEN send a warning signal and give him a term to fulfil the
    payment, or else you will rais the
    charges for the raised requirements.

The world is filled with such kind people like yourself Miss Understood.
Such a pity louzy clients abused the kindness. They don't deserve the title client. He is not a client, just a clouzy. they are two different kinds, and you should deal with them differently.

Leave your kindness for good clients, who not only appreaciate your vision, but also will never abuse them. I have seen such things so many times i can spot such case right from the start nowadays and dont fall into the old traps anymore.  Furthermore i would advise AGAINST any kinds of lawers you have to hire, those advising you have never done it i guesse. Most of them just want your money and you will end up paying them, after that person has payed you, no way that can be called EVEN.

Above all this, i hope you have not lost your creative passion and will move on after this somewhat-bitter experience, knowing that the world is filled with good, honest people, and navigate your sensors from now on more strongly towards them. Cheers, Sam


问:
Assert Message in Unit Tests
I've just begun reading "The Art Of Unit Testing" by Roy Osherove, and while I'm mostly finding the material very helpful, he makes a statement about not using messages in your Assert statements.

"Please never, ever, use this parameter.  Just make sure your test name explains what's supposed to happen."

My question is, in you experience do you find this advice to be good or bad?  If you use assert messages in your unit tests, what information do you use it to capture beyond what a well named unit test could give you in the first place?

答:
This sort of advice makes two key assumptions:

You're going to be spending more time looking at some pass/fail summary of all your tests than the assert output.

Your tests are only testing a single thing.

Now #1 is pretty much guaranteed to be true. #2 is less often going to be true, even if it's good advice. The spirit of the advice is: you should be able to tell at a glance why your unit tests did not pass.

The book's advice combines with these two assumptions to achieve the spirit of the advice. In my experience, this spirit is really what is key to follow. Once you have a good test name, and your test only tests one thing (even if you use multiple asserts to do it) - everything else is gravy.

At that point, if you find it useful to use messages to differentiate asserts, go nuts. If you find it more useful to save time typing assert messages that nobody looks at, go nuts. The important thing is that you can tell at a glance what failed your tests.

Title: Assert Message in Unit Tests


问:
Are closures considered impure functional style?
Are closures considered impure in functional programming?

It seems one can generally avoid closures by passing values directly to a function. Therefore should closures be avoided where possible?

If they are impure, and I am correct in stating that they can be avoided, why do so many functional programming languages support closures?

One of the criteria for a pure function is that "The function always evaluates the same result value given the same argument value(s)."

Suppose

```<code>f: x -> x + y
</code>```

f(3) will not always give the same result. f(3) depends on the value of y which is not an argument of f. Thus f is not a pure function.

Since all closures rely on values which are not arguments, how is it possible for any closure to be pure? Yes, in theory the closed value could be constant but there is no way of  knowing that just by looking that the source code of the function itself.

Where this leads me to is that the same function may be pure in one situation but impure in another. One cannot always determine if a function is pure or not by studying its source code. Rather, one may have to consider it in context of its environment at the point when it is being called before such distinction can be made.

Am I thinking about this correctly?

答:
Purity can be measured by two things:

Does the function always return the same output, given the same input; i.e. is it referentially transparent?

Does the function modify anything outside of itself, i.e. does it have side-effects?

If the answer to 1 is yes and the answer to 2 is no, then the function is pure.  Closures only make a function impure if you modify the closed-over variable.


问:
What do we call the process of changing hard-coded codes into soft-coded codes?
Is there a specific term to call the process of modifying hard-coded codes into soft-coded codes? I have to report what I am doing to the Project manager, shall I just put "modifying hard-coded codes into soft-coded codes"?

Example of "hard-coded codes"

```<code>int random(){
return 42;
}
</code>```

Example of "soft-coded codes"

```<code>int random(){
return Random.nextInt();
}
</code>```

hard coded codes might fulfill requirements for a set of inputs, but it is not flexible.

EDIT: Accepted as Code Refactoring.

答:
It is called "binding time." So, the contrast is between early binding and late binding. If you hard code a number then you bind very early in the process; if you load the number from a file at run time, you are late binding. In general, the later you bind, the easier the code is to test and maintain.

Here is a good discussion: http://en.wikipedia.org/wiki/Late_binding


答:
Normally I'd ask you to clarify your definition of "impure", but in this case it doesn't really matter. Assuming you're contrasting it the term purely functional, the answer is "no", because there's nothing about closures that's inherently destructive. If your language was purely functional without closures, it'd still be purely functional with closures. If instead you mean "not functional", the answer is still "no"; closures facilitate the creation of functions.

It seems one can generally avoid closures by passing data directly to a function.

Yes, but then your function would have one more parameter, and that would change its type. Closures allow you to create functions based on variables without adding parameters. This is useful when you have, say, a function that takes 2 arguments, and you want to create a version of it that only takes 1 argument.

EDIT: With regards to your own edit/example...

Suppose

f: x -> x + y

f(3) will not always give the same result. f(3) depends on the value of y which is not an argument of f. Thus f is not a pure function.

Depends is the wrong choice of word here. Quoting the very same Wikipedia article you did:

In computer programming, a function may be described as a pure function if both these statements about the function hold:

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

Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices.

Assuming y is immutable (which is usually the case in functional languages), condition 1 is satisfied: for all values of x, the value of f(x) doesn't change. This should be clear from the fact that y is no different from a constant, and x + 3 is pure. It's also clear there's no mutation or I/O going on.

Title: Are closures considered impure functional style?

Body:
Are closures considered impure in functional programming?

It seems one can generally avoid closures by passing values directly to a function. Therefore should closures be avoided where possible?

If they are impure, and I am correct in stating that they can be avoided, why do so many functional programming languages support closures?

One of the criteria for a pure function is that "The function always evaluates the same result value given the same argument value(s)."

Suppose

```<code>f: x -> x + y
</code>```

f(3) will not always give the same result. f(3) depends on the value of y which is not an argument of f. Thus f is not a pure function.

Since all closures rely on values which are not arguments, how is it possible for any closure to be pure? Yes, in theory the closed value could be constant but there is no way of  knowing that just by looking that the source code of the function itself.

Where this leads me to is that the same function may be pure in one situation but impure in another. One cannot always determine if a function is pure or not by studying its source code. Rather, one may have to consider it in context of its environment at the point when it is being called before such distinction can be made.

Am I thinking about this correctly?


答:
Closures appear Lambda Calculus, which is the purest form of functional programming possible, so I wouldn't call them "impure"...

Closures are not "impure" because functions in functional languages are first class citizens - that means they can be treated as values.

Imagine this(pseudocode):

```<code>foo(x) {
    let y = x + 1
    ...
}
</code>```

y is a value. It's value depends on x, but x is immutable so y's value is also immutable. We can call foo many times with different arguments which will produce different ys, but those ys all live in different scopes and depend on different xs so purity remains intact.

Now let's change it:

```<code>bar(x) {
    let y(z) = x + z
    ....
}
</code>```

Here we are using a closure(we are closing over x), but it's just the same as in foo - different calls to bar with different arguments create different values of y(remember - functions are values) which are all immutable so purity remains intact.

Also, please note that closures have a very similar effect to currying:

```<code>adder(a)(b) {
    return a + b
}
baz(x) {
    let y = adder(x)
    ...
}
</code>```

baz is not really different than bar - in both we create a function value named y that returns it's argument plus x. In matter of fact, in Lambda Calculus you use closures to create functions with multiple arguments - and it's still not impure.

Body:
Closures appear Lambda Calculus, which is the purest form of functional programming possible, so I wouldn't call them "impure"...

Closures are not "impure" because functions in functional languages are first class citizens - that means they can be treated as values.

Imagine this(pseudocode):

foo(x) {
    let y = x + 1
    ...
}

y is a value. It's value depends on x, but x is immutable so y's value is also immutable. We can call foo many times with different arguments which will produce different ys, but those ys all live in different scopes and depend on different xs so purity remains intact.

Now let's change it:

bar(x) {
    let y(z) = x + z
    ....
}

Here we are using a closure(we are closing over x), but it's just the same as in foo - different calls to bar with different arguments create different values of y(remember - functions are values) which are all immutable so purity remains intact.

Also, please note that closures have a very similar effect to currying:

adder(a)(b) {
    return a + b
}
baz(x) {
    let y = adder(x)
    ...
}

baz is not really different than bar - in both we create a function value named y that returns it's argument plus x. In matter of fact, in Lambda Calculus you use closures to create functions with multiple arguments - and it's still not impure.


答:
No, closures do not cause a function to be impure, as long as the closed value is constant (neither changed by the closure nor other code), which is the usual case in functional programming.

Note that while you can always pass in a value as an argument instead, usually you can't do so without a considerable amount of difficulty.  For example (coffeescript):

closedValue = 42
return (arg) -> console.log "#{closedValue} #{arg}"
```

<p>By your suggestion, you could just return:</p>

<pre class="lang-js prettyprint-override"><code>return (arg, closedValue) -> console.log "#{closedValue} #{arg}"
</code>```

This function isn't being called at this point, just defined, so you'd have to find some way to pass your desired value for closedValue to the point at which the function is actually being called.  At best this creates a lot of coupling.  At worst, you don't control the code at the calling point, so it's effectively impossible.

Event libraries in languages that don't support closures usually provide some other way to pass arbitrary data back to the callback, but it's not pretty, and creates a lot of complexity both for the library maintainer and the library users.

Body:
No, closures do not cause a function to be impure, as long as the closed value is constant (neither changed by the closure nor other code), which is the usual case in functional programming.

Note that while you can always pass in a value as an argument instead, usually you can't do so without a considerable amount of difficulty.  For example (coffeescript):

closedValue = 42
return (arg) -> console.log "#{closedValue} #{arg}"

By your suggestion, you could just return:

return (arg, closedValue) -> console.log "#{closedValue} #{arg}"

This function isn't being called at this point, just defined, so you'd have to find some way to pass your desired value for closedValue to the point at which the function is actually being called.  At best this creates a lot of coupling.  At worst, you don't control the code at the calling point, so it's effectively impossible.

Event libraries in languages that don't support closures usually provide some other way to pass arbitrary data back to the callback, but it's not pretty, and creates a lot of complexity both for the library maintainer and the library users.


问:
What features does MIT-Scheme have that make it ideal for SICP?
I've been thinking about trying to get through the SICP again, this time well-armed with a better idea of what the SICP is meant to accomplish, and being older and wiser than my first attempt back in university.  I've been told by old hands that the MIT Scheme is the only scheme I should think about using, and that other schemes lack features that make the SICP harder to accomplish.  "There's a reason all the 'SICP-in-X' end with chapter 3.  Other languages can't support what's in chapter 4."

When I asked what's in chapter 4, the answer is, "You'll have to get through the first three chapters to understand."  Which is very Zen, I admit, but not helpful.

The only things I can think of that older lisps have is dynamic scope and fexprs, but those don't seem to be the issue.  What features does MIT Scheme possess that makes it "ideal" for getting through SICP?  (Other than that it's the target language of the book, of course.)

答:
I'm not so sure I believe these people. I've gone through SICP and the biggest blocker you'll run into is how call-with-current-continuation (call/cc) is implemented.

While MIT-Scheme is officially endorsed, there are a few downsides to MIT-Scheme

Old

Unmaintained as far as I can tell

Pretty mediocre environment/repl

Not so great errors

On the other hand it is "pure scheme" with relatively few extensions which might be considered nice for a beginner.

Racket provides a pretty swell IDE and Neil Van-Dyke has written a nice package that implements a Scheme precisely tailored for SICP.

It's a more modern and pleasant environment overall, and if you decide to write some more Scheme after SICP like me, Racket en-proper is a darn good Scheme-ish language to be writing.


问:
What's the reason of choosing PascalCasing over camelCasing or vice versa from a programming language design POV?
I like both but I notice languages that use camelCasing for members sometimes need more adjustments when you want to edit your code. For example (in Python):

```<code>node.customData()
</code>```

vs

```<code>node.setCustomData()
</code>```

custom changes casing. It could be avoided if it was:

```<code>node.getCustomData()
</code>```

In C# they will use PascalCasing for example.

I know some even use no casing so:

```<code>node.getcustomdata()
</code>```

It seems to be that scripting languages generally prefer camelCasing more than PascalCasing to be more relaxed?

Is there a reason for choosing one over the other from a programming language design POV?

答:
There really isn't hard evidence for preferring camel-casing over pascal-casing. Though that doesn't stop people from arguing over it a lot. If you're consistent, then there's not a huge difference either way.

No casing comes with disadvantage of providing no hints for what words start where, which makes it more difficult to mentally parse and can lead to unfortunate ambiguities.

Finally, this really isn't a design choice from a programming language point of view, but a standard library point of view. This may seem like a silly distinction, but nothing really stops you from building a new standard library and importing it. In fact people do this quite often in Haskell. There's nothing that stops you from changing conventions with a new standard library, as everything could then be kept consistent.


答:
In many languages the convention is to use PascalCasing for types(the only exceptions I can think of are lisps and STL). Using camelCasing or snake_casing allows you to easily name a variable after it's type(like void foo(Bar bar)).

snake_casing also allows that. You'll have to change more letters(remove underscores and decapitalize letters), but you get the ability to prefix get_ and set_ to intact property names. Some languages use this and some use that.

While it sounds like C# could benefit from using camelCasing for things like property names(public CustomData customData{get; set;}) it have to consider the other main language of the .NET framework - Visual Basic.NET. VB.NET is case insensitive and can't differ between CustomData, customData and cUstOMdAta. By making everything PascalCased C# ensures no name conflicts when using C# classes in VB.NET.

Title: What's the reason of choosing PascalCasing over camelCasing or vice versa from a programming language design POV?

Body:
I like both but I notice languages that use camelCasing for members sometimes need more adjustments when you want to edit your code. For example (in Python):

```<code>node.customData()
</code>```

vs

```<code>node.setCustomData()
</code>```

custom changes casing. It could be avoided if it was:

```<code>node.getCustomData()
</code>```

In C# they will use PascalCasing for example.

I know some even use no casing so:

```<code>node.getcustomdata()
</code>```

It seems to be that scripting languages generally prefer camelCasing more than PascalCasing to be more relaxed?

Is there a reason for choosing one over the other from a programming language design POV?