问:
Member functions vs. Non-member functions for math operators
I'm writing a linear algebra library (long story short, it's a school assignment) that involves matrices, vectors, etc.  In the process of creating this library, I'm going to be creating functions that perform mathematical operations on objects.  For example, transpose matrix, invert matrix, normalize vector, etc.

I was curious as to what is the "best practice" for this sort of function...  That is, should I make the function a member function, or non-member?  (For clarity/library use sake)

Example:

```<code>//Member function way:
B = A.transpose();
C = A.inverse();

//Non-member function way:
B = linalg::transpose(A); //Non-member transpose function in linear algebra namespace
C = linalg::inverse(A);
</code>```

Is there some standard regarding these sorts of operations?  Or, at least, is there a common way people do this?  I'm leaning towards the first option, but I'd like to know if this is recommended.

答:
This is just a matter of style and taste. I have seen different linear algebra libraries, either

written in an OOP style using member functions

written in a non-OOP style using only free functions

providing an API with both

and all of them were working. At least, your API should be consistent, so pick your choice and make sure you don't mix those styles arbitrarily.


问:
Am I doing it wrong with Hibernate DAO layer? i.e. Feature Bloat
For quick prototyping I have been actively using Hibernate. Recently I came back to an old project and I wondered why I had a lot of DAOs with what I suspect is commonly named feature bloat. E.g.

I have a DAOs for single entities that contains from 15 to 20 methods each.

Recently I have been using Hibernate Generic D.A.O. Framework but I still think that the same problem arises when I'm trying to create custom data access logic and my code Olfaction starts to detect bad smells.

Is there a guideline for this scenarios?

答:
What you are talking about looks more like specific Repository pattern, than generic DAO.

And while many people will tell you there is some gain from using repositories as way to abstract the data access, there are some people that disagree. No only is repository's abstraction YAGNI bordering on wishful thinking, you get the problems of having 1000+1 methods that look like "GetCustomerBy(arbitrary number of fields)With(arbitraryNumberOfFields)" making it even harder to maintain. This becomes even more obvious when you start using ORMs like Hibernate.

I recommend reading Repository is the new Singleton and The evils of the repository abstraction layer by Ayende.

ContentLicense: CC BY-SA 3.0


答:
If you dive deeper in your problem statement, it is clear that at some point you'll use custom data structures that represent certain mathematical entities. For instance, you might represent a matrix my means of a n-dimensional array. To elaborate on your example,

```<code>// C way
typedef struct {
    int data[MAX_LEN][MAX_LEN];
} MATRIX;

MATRIX B = transpose(A);

// C++ way
class Matrix; // Forward Declaration
class Matrix {
    int data[MAX_LEN][MAX_LEN];
    public:
        Matrix transpose();
};

Matrix B = A.transpose();
</code>```

(The C++ example is simplified, you can use templates and such.)

The point to consider is the ease of using custom data structures in both cases. C++ (or any object oriented) as a language is more powerful in itself, and that extends to the consumer of the library as much as it benefits the implementer.
I've used C only libraries in the past and those custom data structures seem to get all over the place in no time! Whereas interoperability is easier to achieve with the latter (using special constructors, maybe?)

To wind it up, if you're using C++ then a object oriented approach is definitely recommended.

Title: Member functions vs. Non-member functions for math operators

Body:
I'm writing a linear algebra library (long story short, it's a school assignment) that involves matrices, vectors, etc.  In the process of creating this library, I'm going to be creating functions that perform mathematical operations on objects.  For example, transpose matrix, invert matrix, normalize vector, etc.

I was curious as to what is the "best practice" for this sort of function...  That is, should I make the function a member function, or non-member?  (For clarity/library use sake)

Example:

```<code>//Member function way:
B = A.transpose();
C = A.inverse();

//Non-member function way:
B = linalg::transpose(A); //Non-member transpose function in linear algebra namespace
C = linalg::inverse(A);
</code>```

Is there some standard regarding these sorts of operations?  Or, at least, is there a common way people do this?  I'm leaning towards the first option, but I'd like to know if this is recommended.

Body:
If you dive deeper in your problem statement, it is clear that at some point you'll use custom data structures that represent certain mathematical entities. For instance, you might represent a matrix my means of a n-dimensional array. To elaborate on your example,

// C way
typedef struct {
    int data[MAX_LEN][MAX_LEN];
} MATRIX;

MATRIX B = transpose(A);

// C++ way
class Matrix; // Forward Declaration
class Matrix {
    int data[MAX_LEN][MAX_LEN];
    public:
        Matrix transpose();
};

Matrix B = A.transpose();

(The C++ example is simplified, you can use templates and such.)

The point to consider is the ease of using custom data structures in both cases. C++ (or any object oriented) as a language is more powerful in itself, and that extends to the consumer of the library as much as it benefits the implementer.
I've used C only libraries in the past and those custom data structures seem to get all over the place in no time! Whereas interoperability is easier to achieve with the latter (using special constructors, maybe?)

To wind it up, if you're using C++ then a object oriented approach is definitely recommended.


问:
Using configuration to determine whether to handle exception or bubble it up
On a side project I'm working on I came up with a way of handling exceptions that's adjustable by configuration. So a try/catch block might look like this:

```<code>try
{
    fileHelper.MoveFile(file, destFolder);
}
catch (IOException ex)
{
    if (exceptionHandler.HandleException(ex))
    {
        return ResultCode.Fail;
    }
    throw;
}
</code>```

The granularity of exception handling is controlled through an enum that's set in the app.config file:

```<code>public enum SystemFailureMode
{
    AlwaysThrow = -1,
    Aggressive = 0,
    Standard = 1,
    Lenient = 2
}
</code>```

This determines whether an exception is "handled" and returned as an error, or if it bubbles up and crashes the system. At first I thought I'd uncovered a new design pattern but now it seems like it's probably an anti-pattern. What do you guys think?

After reviewing the comments and thinking about it myself, I've decided this is definitely an anti-pattern. The fact that this has the potential to turn writing unit tests into a nightmare is enough to turn me off of it.

答:
If you do this, you will have created a massively complex and effectively untestable system; the number of possible system behaviors goes up exponentiallty with the number of this type of configuration setting. As a result, it commonly won't work.

But on the upside, the failures introduced will, in principle, always be fixable by another configuration file change. And in some cases the correct configuration settings to change may be discoverable within only a few days of investigation...


问:
Are there any compilers that attempt to fix syntax errors on their own?
I heard a while back that there used to be a compiler that attempted to fix syntax errors by analyzing context and inferring what was intended.

Does such a compiler really exist? Obviously it has little practical value, but would be very interesting to play with and learn from.

答:
The goal of a compiler is to produce executables that behave as desired.  If a programmer writes something which is invalid, even if the compiler can with 90% probability guess what was intended, it would generally better to require the programmer fix the program to make the intention clear, than have the compiler go ahead and produce an executable which would have a significant chance of concealing a bug.

Of course, languages should generally be designed so that code which clearly expresses intention will be legal, and code which does not clearly express intent should be forbidden, but that doesn't mean they are.  Consider the following code [Java or C#]

```<code>const double oneTenth = 0.1;
const float  oneTenthF = 0.1f;
...
float f1 = oneTenth;
double d1 = oneTenthF;
</code>```

Having a compiler add an implicit typecast for the assignment to f1 would be helpful, since there's only one logical thing the programmer could want f1 to contain (the float value closest to 1/10).  Rather than encouraging compilers to accept improper programs, though, it would be better for the spec to allow implicit double-to-float conversions in some contexts.  On the flip-side, the assignment to d1 may or may not be what the programmer really intended, but there's no language rule forbidding it.

The worst sorts of language rules are those where compilers will make inferences in cases where something couldn't legitimately compile otherwise, but where a program might "accidentally" be valid in a case where inference had been intended.  Many situations involving implicit end-of-statement fall into this category.  If a programmer who intends to write two separate statements omits a statement terminator, a compiler might usually manage to infer the statement boundary, but might occasionally regard as one statement something that was supposed to be processed as two.

ContentLicense: CC BY-SA 2.5

Body:
The goal of a compiler is to produce executables that behave as desired.  If a programmer writes something which is invalid, even if the compiler can with 90% probability guess what was intended, it would generally better to require the programmer fix the program to make the intention clear, than have the compiler go ahead and produce an executable which would have a significant chance of concealing a bug.

Of course, languages should generally be designed so that code which clearly expresses intention will be legal, and code which does not clearly express intent should be forbidden, but that doesn't mean they are.  Consider the following code [Java or C#]

const double oneTenth = 0.1;
const float  oneTenthF = 0.1f;
...
float f1 = oneTenth;
double d1 = oneTenthF;

Having a compiler add an implicit typecast for the assignment to f1 would be helpful, since there's only one logical thing the programmer could want f1 to contain (the float value closest to 1/10).  Rather than encouraging compilers to accept improper programs, though, it would be better for the spec to allow implicit double-to-float conversions in some contexts.  On the flip-side, the assignment to d1 may or may not be what the programmer really intended, but there's no language rule forbidding it.

The worst sorts of language rules are those where compilers will make inferences in cases where something couldn't legitimately compile otherwise, but where a program might "accidentally" be valid in a case where inference had been intended.  Many situations involving implicit end-of-statement fall into this category.  If a programmer who intends to write two separate statements omits a statement terminator, a compiler might usually manage to infer the statement boundary, but might occasionally regard as one statement something that was supposed to be processed as two.


问:
How to encapsulate method parameters in Java?
An HTTP query can be parametrized to a list of pairs like name=value that can be encapsulated in general as Map<String, String>  since an HTTP GET query is string pairs. I could need something for any combination of objects and primitives. A varargs method for example update(String s1...) could be written in general as update(Map<String, String>) where the key is the name and the value is the data.

Therefore I wonder if it could be good to use a definition as Map<K, V> instead of writing a custom object in this case wrapping the specific 3 parameters to a class in their specific types which can't be reused whereas a Map<K, V> can be used to encapsulate any 2-tuples when we must write a pair like Integer i or int i or int i=0.

But I think it will only work for classes and not for primitive types, so the primitive types must be boxed in their objects so I must also box an int to an Integer for this to also work with primitive types.

Is there a better way than Map<K, V>to encapsulate method parameters when we must select a list of unknown length and unknown types where the types could be primitives or objects?

So instead of being specific about types and their values in the method, can I use a Map<K, V> instead of a list of named pairs such as String s, int i, Object o...

答:
Abstract data types are not good things in Java for passing around complex objects or parameters.

Type safety

Lets compare two bits of code

```<code>String foo(Integer a, Integer b, String s) {
  if(a.compareTo(b) == 0) {
    return s;
  } else {
    return "" + (a - b); // just as an example
  }
}
</code>```

vs

```<code>String foo(Map<String, Object> m) {
  if(m.get("a").compareTo(m.get("b")) == 0) {
    return (String)m.get("s");
  } else {
    return "" + (((Integer)m.get("a") - (Integer)m.get("b"));
  }
}
</code>```

In the second example, we have to use Object as the value because its the only object that String and Integer share in common.  This means that all objects further down need to be cast.  This has the distinct possibility of throwing a ClassCastException (javadoc) anywhere or everywhere in your code... unless you add a ton of boiler plate code to prevent that (guard conditions for instanceof all over).

Whats worse, is that those exceptions (if you don't check everything - and the paths you follow if you do) are runtime errors.  The errors of your types won't be found until you run the program rather than when you compile it.  Errors found when you compile are easier to fix than ones you discover at runtime.  For that matter, the static analysis tools and inspections that most IDEs give you will catch them for you as you type them (and throw up horrendous warnings about trying to do it with the abstract data type).

Overloads

Passing all of the arguments as a single ADT means you have a single method.  In the example above, what if you had:

```<code>String foo(Integer a, Integer b) { ... }
String foo(Integer a, Integer b, String s) { ... }
String foo(Integer a, Integer b, String s, String t) { ... }
</code>```

as different ways to call the function.  With passing one ADT, you've got just

```<code>String foo(Map<String, Object> m) { ... }
</code>```

There is no way to differentiate the overloads.  This leads to code that will look like:

```<code>String foo(Map<String, Object> m) {
  if(m.containsKey("t")) { ... }
  else if(m.containsKey("s")) { ... }
  else { ... }
}
</code>```

The complexity of the function will go through the roof (unless you start extracting those to other methods that are somehow indicating what type they're dealing with and my head is starting to hurt thinking about the hungarian notation you're going to be sticking into the method names).

This further gets problematic when you have different types that are valid arguments.

```<code>String foo(Integer a, Integer b, String s) { ... }
String foo(BigInteger a, BigInteger b, String s) { ... }
</code>```

Typo safety

Long ago, I was a perl programmer - back in the days before OOP found its way into perl (bless its reference).  The only way to pass around complex objects was with %hashes, and @arrays.  And you had to pull out the keys of the hash.  There were numerous bugs that could only be caught at runtime (and the joys of autovivication made that challenging at times).

A simple typo in a key would mean some parameter was there wasn't found (when it was there) or was just created in the wrong spot and passed to another method.

```<code>String plusOne(Map<String, Integer> m) {
  if(m.containsKey("type") && m.containsKey("1") {
    return m.get("typo") + m.get("I");
  }
  return 0;
}
</code>```

These are not fun bugs to have to find.  No bugs are really fun, but these bugs just smack you in the face because they are completely preventable if you had just used a proper parameter list and work with the language and the compiler.

Calling Packaging

So far, I've talked about the dangers in the method itself.  What about work that the callee has to do.

```<code>System.out.println(foo(1,2,"bar"));
</code>```

And we're done with the simple parameter list.

```<code>Map<String, Object> m = new HashMap<String, Object>();
m.put("a", 1);
m.put("b", 2);
m.put("s", "bar");
System.out.println(foo(m));
</code>```

Now, you want to debug this?  What are you passing into foo?  You've got to look back through the code and track it.  Besides being a significantly larger block of code to do any method call of this type, its also obscufcating what is going into this.

Refactors

foo now takes Doubles rather than Integers.  You change the method signature and fix all the compile time errors.  You've found them all and it compiles correctly (see type safety above).

However, the map version works just as well with Integer as it does with Double.  You can't find out if you've fixed the refactoring or not.

Why are they in a Map together?

This is more a philosophical question.  Why are these objects in a map together?  What common attribute do they share?  If they really are part of some other data structure

```<code>class Cell {
  int x, y;
  String value;
}
</code>```

make them into a proper data structure that sticks together.  If they aren't things that are honestly related to each other, well... don't.

Putting things together in some structure makes them related to each other in our mind, even if they aren't.  If they aren't this adds significant mental gymnastics in order to keep what things are related to each other and what ones aren't apart.

Body:
Abstract data types are not good things in Java for passing around complex objects or parameters.

Type safety

Lets compare two bits of code

String foo(Integer a, Integer b, String s) {
  if(a.compareTo(b) == 0) {
    return s;
  } else {
    return "" + (a - b); // just as an example
  }
}

vs

String foo(Map<String, Object> m) {
  if(m.get("a").compareTo(m.get("b")) == 0) {
    return (String)m.get("s");
  } else {
    return "" + (((Integer)m.get("a") - (Integer)m.get("b"));
  }
}

In the second example, we have to use Object as the value because its the only object that String and Integer share in common.  This means that all objects further down need to be cast.  This has the distinct possibility of throwing a ClassCastException (javadoc) anywhere or everywhere in your code... unless you add a ton of boiler plate code to prevent that (guard conditions for instanceof all over).

Whats worse, is that those exceptions (if you don't check everything - and the paths you follow if you do) are runtime errors.  The errors of your types won't be found until you run the program rather than when you compile it.  Errors found when you compile are easier to fix than ones you discover at runtime.  For that matter, the static analysis tools and inspections that most IDEs give you will catch them for you as you type them (and throw up horrendous warnings about trying to do it with the abstract data type).

Overloads

Passing all of the arguments as a single ADT means you have a single method.  In the example above, what if you had:

String foo(Integer a, Integer b) { ... }
String foo(Integer a, Integer b, String s) { ... }
String foo(Integer a, Integer b, String s, String t) { ... }

as different ways to call the function.  With passing one ADT, you've got just

String foo(Map<String, Object> m) { ... }

There is no way to differentiate the overloads.  This leads to code that will look like:

String foo(Map<String, Object> m) {
  if(m.containsKey("t")) { ... }
  else if(m.containsKey("s")) { ... }
  else { ... }
}

The complexity of the function will go through the roof (unless you start extracting those to other methods that are somehow indicating what type they're dealing with and my head is starting to hurt thinking about the hungarian notation you're going to be sticking into the method names).

This further gets problematic when you have different types that are valid arguments.

String foo(Integer a, Integer b, String s) { ... }
String foo(BigInteger a, BigInteger b, String s) { ... }

Typo safety

Long ago, I was a perl programmer - back in the days before OOP found its way into perl (bless its reference).  The only way to pass around complex objects was with %hashes, and @arrays.  And you had to pull out the keys of the hash.  There were numerous bugs that could only be caught at runtime (and the joys of autovivication made that challenging at times).

A simple typo in a key would mean some parameter was there wasn't found (when it was there) or was just created in the wrong spot and passed to another method.

String plusOne(Map<String, Integer> m) {
  if(m.containsKey("type") && m.containsKey("1") {
    return m.get("typo") + m.get("I");
  }
  return 0;
}

These are not fun bugs to have to find.  No bugs are really fun, but these bugs just smack you in the face because they are completely preventable if you had just used a proper parameter list and work with the language and the compiler.

Calling Packaging

So far, I've talked about the dangers in the method itself.  What about work that the callee has to do.

System.out.println(foo(1,2,"bar"));

And we're done with the simple parameter list.

Map<String, Object> m = new HashMap<String, Object>();
m.put("a", 1);
m.put("b", 2);
m.put("s", "bar");
System.out.println(foo(m));

Now, you want to debug this?  What are you passing into foo?  You've got to look back through the code and track it.  Besides being a significantly larger block of code to do any method call of this type, its also obscufcating what is going into this.

Refactors

foo now takes Doubles rather than Integers.  You change the method signature and fix all the compile time errors.  You've found them all and it compiles correctly (see type safety above).

However, the map version works just as well with Integer as it does with Double.  You can't find out if you've fixed the refactoring or not.

Why are they in a Map together?

This is more a philosophical question.  Why are these objects in a map together?  What common attribute do they share?  If they really are part of some other data structure

class Cell {
  int x, y;
  String value;
}

make them into a proper data structure that sticks together.  If they aren't things that are honestly related to each other, well... don't.

Putting things together in some structure makes them related to each other in our mind, even if they aren't.  If they aren't this adds significant mental gymnastics in order to keep what things are related to each other and what ones aren't apart.


问:
Is Lisp the first language to adopt structured programming?
I couldn't find any links or books claiming that Lisp is the first programming language to adopt structured programming (actually, most of them don't even mention Lisp at all), but if conditionals were invented by McCarthy and got into Algol later, is it fair to say that Lisp is the first?</p>

答:
I've done some research on the history of programming languages.

But first, lets see what Wikipedia says about structured programming:

Structured programming is a programming paradigm aimed on improving the clarity, quality, and development time of a computer program by making extensive use of subroutines, block structures and for and while loops—in contrast to using simple tests and jumps such as the goto statement which could lead to "spaghetti code" which is both difficult to follow and to maintain.

And that, of course, includes the use of recursive functions.

From History of Lisp (written by McCarthy. Bold emphasis mine):

As a programming language, LISP is characterized by the following ideas: ..., the recursive use of conditional expressions as a sufficient tool for building computable functions, ...

Towards the end of the initial period, it became clear that this
  combination of ideas made an elegant mathematical system as well
  as a practical programming language. Then mathematical neatness became
  a goal and led to pruning some features from the core of the language.
  This was partly motivated by esthetic reasons and partly by the
  belief that it would be easier to devise techniques for proving
  programs correct if the semantics were compact and without exceptions.

I invented conditional expressions in connection with a set of chess legal move routines I wrote in FORTRAN for the IBM 704 at M.I.T. during 1957-58. This program did not use list processing. The IF statement provided in FORTRAN 1 and FORTRAN 2 was very awkward to use, and it was natural to invent a function XIF(M,N1,N2) whose value was N1 or N2 according to whether the expression M was zero or not. The function shortened many programs and made them easier to understand, but it had to be used sparingly, because all three arguments had to be evaluated before XIF was entered, since XIF was called as an ordinary FORTRAN function though written in machine language. This led to the invention of the true conditional expression which evaluates only one of N1 and N2 according to whether M is true or false and to a desire for a programming language that would allow its use.

A paper defining conditional expressions and proposing their use in Algol was sent to the Communications of the ACM but was arbitrarily demoted to a letter to the editor, because it was very short.

From The Advent of Recursion & Logic in Computer Science:

Since FORTRAN did not contain recursion either, he(McCarthy) tried to add it to the language, but without success.

In August 1959, McCarthy wrote a letter in which he openly advocated for recursive procedures [80], and, in January 1960, at the final ALGOL60 Paris conference, McCarthy suggested to add recursive procedures to the ALGOL60 language [116, p.30].

Perlis even stated in 1978 with respect to the ALGOL Effort that:

"The implications of recursion were not really understood, except by McCarthy." [91, p.160]

To summarize, he had not only thought recursive functions and conditional expresions are sufficient for building computable functions, but also believed they would lead to a readable and easy to verify code, and spread the idea to other languages.

Therefore, even though McCarthy didn't say goto is harmful, I think he is the first one to perceive the importance of structured programming and Lisp is the first language that can be called structured programming language. (Fortran I didn't even support subroutines or nested expressions, and only had an arithmetic if statement)


问:
In C++ what is the commonly accepted method for making a program platform-agnostic?
The way I usually do it is I make some namespace Platform in Platform.h and every OS call is encapsulated by a static function in this namespace. So the only place in the entire code base that knows what OS is being used is Platform.cpp. Is this a good way of making things easier? For instance when I call Platform::MessageBox(...), what actually happens is:</p>

```<code>void Platform::MessageBox(...)
{
#ifdef(_WINDOWS)
....
#elif(_LINUX)
....
#elif(_MAC)
....
#endif
}
</code>```

答:
If you can't use a platform independent library to take the hard work away from you, then the best option is to keep the complexity of platform independence out of the main application logic by creating a wrapper to encapsulate the platform-dependent code.

When implementing the wrapper, there are two main approaches.

Use preprocessor macros like you did in the sample code in the question

Use a separate file for each platform with the code for that platform. Then you use the build system to select the right implementation for the platform you are building for.


问:
In MV* pattern where does non-business model goes?
I am passing Menu items to View from ViewModel. My menu definition is a model with properties title, image, hasChildren and isEnabled. But this model is meant for UI unlike business domain models like Person, ContactDetail, Transaction, etc.

So, when i see this menu model sitting along with business domain models i felt like polluted. Is there a right place to put these kind of UI specific models?

Thanks.

答:
I am passing Menu items to View from ViewModel.

I think you're really close but missing the mark on MVVM slightly. I'm not sure what language/framework you're applying this in, so I'll answer generically. I know .NET is typical when you hear MVVM but the pattern can be applied anywhere.

Let me start by correcting your initial statement:

I am passing menu ViewModels to the View.

You are absolutely right to consider this view-specific model of a menu item to be distinct from your business domain models. Make sure you're calling them ViewModels as opposed to Models.

As for where you put them, you have a few options. You could put them in the same folder as your Models but name them distinctly as ViewModels. You can also give them their own directory, so your Models and ViewModels are not intermingled. This is all a matter of code organization, and either of these options is valid. Perhaps the latter (separate folders) is slightly cleaner.

Note, I didn't say where the ViewModels are passed from. A better way to think about how Models, ViewModels, and Views pass each other around is to describe where each are consumed. This also depends on your framework how things are passed around (or declared), but here's the basic idea.

The View can reference a ViewModel that has the data it needs to bind. The View has no concept of a business model, or at least, it doesn't work with one directly.

The ViewModel can reference a Model. It might get data right off of it, or even invoke the Model's methods to derive data. It might also have some logic of its own, logic that is view-specific as opposed to domain-specific. It is often a subset of the original Model, with the added responsibility of view-specific concerns like formatting dates and numbers. The ViewModel doesn't need to know about the View, and it could even be consumed by multiple Views.

The Model has no concept of ViewModels or Views. It is your pure business model/domain object. It might handle data calculations or derivations based on business logic. It should not care about presentations concerns like formatting.

For further reading, I suggest the section titled The Evolution of Model-View-ViewModel in this article, specifically, the last two paragraphs of that section.


问:
Language that embraces mutable state?
There seems to be a trend towards immutable objects, and pure functional programming. While I recognize the benefits, I find it hard to apply these principles to GUI programming, for example. But I also find classical imperative languages with mutable objects lacking. I was wondering whether there is a language or system that embraces mutable state, and makes it especially easy to work with.

Below are some features I would consider to be "designed around mutability":

The ability to hook up events and get a change notification for any variable. It would make it very easy to write GUIs and MVC applications. And you could just make a List<MyObject>, and stuff it into a list widget, and with a bit of configuration it would manage your list for you, no manual listview.insert() etc..

A type system that considers state. For example, If I pass a Car into a function that requires a working one, the compiler should try to proove that car.broken == False. If it can't proove it, it won't compile, and I have to ensure it (by putting the code in an if block, or setting it manually to False).

A take on concurrency that makes sense for mutable objects. For example an atomic statement, that guarantees that certain statements are run together, using transactions or locks. The goal is not performance, but ease of use and GUI responsiveness. I should be able to manipulate data and the GUI from any thread, using atomic {step1; step2} to ensure invariants.

I'm not looking for a system with these exact features, but one written in a similar spirit. The closest I've seen to this is C#/.NET with its data binding features.

Gtk+ has custom ListModels that keep a GtkTreeView in like with your data without manual inserts/updates. Android has ListAdapters which are similar. I haven't found a thread-safe GUI, but you can get pretty close with a liberal use of Invoke() in C#/WinForms, or gobject_idle_add in Gtk+. Are there any systems like what I describe? Or research material, references, etc.?

答:
The biggest difficulty I see with mutability in many programming languages, and part of the reason for the trend toward immutable objects, is that many languages and frameworks make no distinction between mutable values, immutably-encapsulated values, and entities.  A variable of type int[] may always, if non-null, hold a reference to a heap object instance of type int[], but there are at least four different ways in which that variable might encapsulate state:

It might identify an unshared array, whose owner is apt to mutate it as it sees fit, and serve to encapsulates the array's contents on behalf of the owner.

It might identify a array which is shared with code that agrees never to modify it, and serve to encapsulate the array's contents on behalf of anyone with a reference.

It might identify an array which is owned by some other object, and encapsulates a "connection" with the object that owns the array

It might identify an array which is owned by the same object as the reference, but to which other references may exist, and encapsulates both the contents of the array and a "connection" with other objects holding references.

An array which will never be modified is effectively a value, as is an array to which no references will exist outside its owner [if an object holds the only reference to a collection, things in that collection which cannot be accessed but through that reference are considered "inside" the owner of the reference].  If multiple independent references exist to an array, and its value may be modified, then it is an entity.

Often times, it's desirable to make sure things will behave as values; having values accidentally turn into entities is apt to cause bugs.  Making sure that something will behave as a value will require ensuring that either it never change, or else that all references to it will be contained within a single "owner".  Unshared values are often very useful and efficient types to work with; unfortunately, none of the Java-inspired languages I'm aware of seem to recognize them as a concept and provide the tools necessary to work with them while ensuring that they don't accidentally "leak" and turn into entities.

When you talk about attaching change notifications to things, it seems like you're leaning toward an "everything is an entity" philosophy.  I really wouldn't recommend such a thing; while change notifications can be good, having everything be a fully-mutable entity can quickly turn into a mess (e.g. if ObservedObject is itself a mutable property, and if another object might want to know if the particular entity identified by ObservedObject changes, what should it do if ObservedObject itself changes so as to identify a different entity?)  It's far better to minimize the number of points at which entities are attached to each other.

Title: Language that embraces mutable state?


问:
What is the difference between dependent typing and contracts?
What is the difference between dependent typed languages and languages like Spec# and Eiffel that allow you to specify "contracts" for functions in your code for pre/postconditions? Is dependent typing basically the purely functional version of Eiffel's "contracts"?

From what I understand, dependently typed languages let you specify your function's pre and post conditions using predicate logic as part of the type.

Eiffel's concept of contracts seems to be similar, but based on imperative programming, not functional programming.

答:
Contracts should always be expressed in a functional, sideeffect free manner. They are language agnostic as such. Contract libraries and extensions exist for languages such as scheme, java, c# and haskell. They are very expressive but seldom statically checked.

Dependent types on the other hand are often less expressive and to my knowledge always statically checked.

My point with this post is to dismiss the notion that contracts are limited to imperative languages.

OwnerDisplayName: Sintrastes


问:
How to add contributors to LICENSE file?
I am the main developer of a library, licensed under the MIT license, and hosted on Github. The Github repository includes a LICENSE file.

When someone sends me a pull request, do I have to list those as copyright holders in the accompaning license.txt, or should I list these in a special section there? Am I required to do it?

Can I assume, that contributors agree to include their code with the license specified in LICENSE, when they send a pull request?

答:
This is precisely what a Contributor License Agreement is for.  Do not, under any circumstances, assume anything about what rights someone else does or does not waive.  You're in doubt, so talk with your actual contributors, not random strangers who don't even know what project you're talking about.

The MIT License is not much of a license at all.  All you're saying is "use this if you want, but don't take my name off it and don't sue me if it blows up in your face."  The MIT license is not in any way a sticky copyleft, and the negotiations about as to who gets to claim copyright at all are entirely beyond the scope of the license.

What you need to decide, and possibly discuss with your contributors, is who owns the copyright to the code.  Do you want to own it jointly with them, or do you want to own it free and clear?  If Facebook comes to you and offers sixteen billion dollars to hand over the copyright, do you want to share the money?  If you decide to switch licenses to the GPL and give your code to the FSF, would your contributors want a say in the matter?

Do not assume.  Decide what you want, write it down, and either give your past contributors copyright or refuse their pull requests until they agree to your new CLA.


问:
What are the advantages of pass by value?
I always thought pass by value is a legacy from the early languages, because the designers had never seen anything else. But after seeing the brand new languages like Go adapting the same principle confused me.

The only advantage I can think of is you make sure that the value you are passing won't be modified. But every time you need to pass a big structure to a function, you need to pass the pointer (or reference) to prevent copying, if the language permits it.

To prevent modification of parameters, some constness mechanism could be introduced instead of making the whole language pass by value.

I have been coding for years and I rarely needed to pass by value. Almost always, I don't need my value/object to be copied to a function call; and often I don't need it to be modified inside the function*.

What is the motivation behind making modern languages pass by value? Are there any advantages that I am not aware of?

Edit: When I say pass by value, I don't mean primitives. They are easy and cheap to pass by value. My main focus is objects or structs that consists of more than 1 primitive and thus expensive to copy.

*: I have asked around and others reported similar thing with their parameter usage.

答:
Pass by value is just a corollary to value semantics (i.e. by-value variables, object members, etc). Aside from the advantage you mention, this adds:

Very efficient aggregates. A type like struct Foo { T a; U b; } does not require a separate allocation or extra indirection for the members.

Zero cost abstractions: class IntWithDifferentBehavior { int value; ... } is exactly as efficient as an int, assuming static dispatch for the methods.

It goes very well with tracking ownership and lifetimes. One consequence is support for deterministic destruction, enabling RAII as an alternative to (semi-)manual resource management.

In addition, pass-by-value is much easier to make memory safe and efficient. If you pass pointers/references to stack-allocated memory, you need to make sure the memory outlives the reference. If you instead use automatic memory management to ensure that, you pay a run-time price for that.


问:
Would this be a correct way to use the Repository pattern in ASP .NET MVC application implementing Entity Framework?
This ASP .NET MVC application implements Entity Framework.

I've declared the repositories in the DbContext like this:

```<code>public class CompanyDbContext : DbContext
{
        // constructor goes here

        public DbSet<Customer> Customers { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<CustomerOrder> CustomerOrders { get; set; }

        private IGeneralEntityRepository<Customer> customersRepository;
        private IGeneralEntityRepository<Order> ordersRepository;

        // ...................
}
</code>```

This way we can declare and initialise CompanyDbContext within a controller and then access the repositories using the CompanyDbContext instance.

Is this correct? Or should I create a separate "Unit Of Work" class to access the repositories?

答:
Your repositories need to depend on the DbContext and not vice versa. Also, you don't have to implement Unit of Work since the DbContext already implements it. You could do it like this:

```<code>public interface IRepository<T>
{
    T ReadOne(object key);

    // so on, so forth...
}

public class Repository<T> : IRepository<T> where T : class, new()
{
    public Repository(DbContext context)
    {
        _context = context;
    }

    private readonly DbContext _context;

    public T ReadOne(object key)
    {
        return _context.Set<T>().Find(key);
    }
}
</code>```

This way, you keep your context clean and only need to worry about adding new entity configurations to it, when it is needed. If you use EF6 there's a method called AddFromAssembly which allows you to add the configurations from an assembly. This saves you from modifying the DbContext each time you add a new entity.

I'd suggest looking into a DI container as it will greatly simplify the work required to put things together. You can sort out your DAL configuration with 2 or 3 lines of code.

Body:
Your repositories need to depend on the DbContext and not vice versa. Also, you don't have to implement Unit of Work since the DbContext already implements it. You could do it like this:

public interface IRepository<T>
{
    T ReadOne(object key);

    // so on, so forth...
}

public class Repository<T> : IRepository<T> where T : class, new()
{
    public Repository(DbContext context)
    {
        _context = context;
    }

    private readonly DbContext _context;

    public T ReadOne(object key)
    {
        return _context.Set<T>().Find(key);
    }
}

This way, you keep your context clean and only need to worry about adding new entity configurations to it, when it is needed. If you use EF6 there's a method called AddFromAssembly which allows you to add the configurations from an assembly. This saves you from modifying the DbContext each time you add a new entity.

I'd suggest looking into a DI container as it will greatly simplify the work required to put things together. You can sort out your DAL configuration with 2 or 3 lines of code.


问:
System Programming & Object Oriented Design - what to look out for
Next semester (starts in just under 5 weeks), I'm taking System Programming and OOD concurrently.  Apparently SP centers on working in C on Linux, and I only have Java and Python experience, so I am a little nervous about this.

For those of you who've taken these at an university, what should I look out for?

I've already taken Computer Organization which included an overview of Assembly.  With the exception of implementing loops in assembly, I ranged from B+ to A- in the assembly projects.  Building circuitry was another story, however.

答:
I always found it difficult to take classes with opposing points in the same semester.

If your systems class is very low level you will likely need to do some very non-OO things.

If you can keep the two straight though it might be a good time to learn the advantages of each approach.

My personal experience with OOD classes were that you needed to go to a nearly theoretical level of abstraction to get full credit and that the systems classes were usually more theory than code because it was not reasonable to build much of an OS feature in a single semester.


答:
Syntax errors are especially hard to correct. Take the case of a missing right ): We knwo we can repair the code by inserting one, but there are usually many places where we could insert one and obtain a syntactically correct program.

A much easier point are misspelled identifiers (but note this are not syntax errors). One can compute the edit distance between the unresolvable identifier and all identifiers in scope, and by replacing the unresolvable word with the one the user most likely meant, one would come up with a correct program in many cases. However, it turns out that it is still better to flag the error, and let the IDE suggest valid replacements.

Title: Are there any compilers that attempt to fix syntax errors on their own?

Body:
I heard a while back that there used to be a compiler that attempted to fix syntax errors by analyzing context and inferring what was intended.

Does such a compiler really exist? Obviously it has little practical value, but would be very interesting to play with and learn from.


问:
In what programming language did "let" first appear?
I was wondering about the origins of the "let" used in Lisp, Clojure, and Haskell.  Does anyone know which language it appeared in first?</p>

答:
Lisp is the oldest language of these having LET now. But BASIC was the first that got it, for Lisp had obtained it much later.

In Ada Lovelace Analytical Engine (1843) - no LET, a program looks as:

```<code>N0 6 N1 1 N2 1 × L1 L0 S1  L0 L2 S0 L2 L0 CB?11 '
</code>```

In Plankalkül of Zuse (1943-45) the program looks:

```<code>P1 max3 (V0[:8.0],V1[:8.0],V2[:8.0]) → R0[:8.0]
max(V0[:8.0],V1[:8.0]) → Z1[:8.0]
max(Z1[:8.0],V2[:8.0]) → R0[:8.0]
END
</code>```

Short Code was proposed by John Mauchly in 1949

```<code>X3 =  (  X1 +  Y1 )  /  X1 * Y1
</code>```

Intermediate PL of Burks, 1950, used for assignment ->

Rutishauser in 1952 used =>=

Böhms compiler, 1952, used ->

At the University of Manchester, Alick Glennie developed Autocode in the early 1950s.  The first code and compiler was developed in 1952 for the Mark 1 computer at the University of Manchester and is considered to be the first compiled high-level programming language. Again, -> for assignment

Charles Adams, FORTRAN 0 of Backus's group , Brooker's Autocode 2, ПП1 of Lubimsky and Kamynin; all in 1954, again =

BACAIC (Grems, Porter), 1954, * for assignment!

Kompiler, ADES, 1955, =

IT, 1956, <-

FORTRAN, 1957,  =

AT-3 (1956), Math-Matic (1957), again =,

but Flow-Matic in 1957 had two assignments, and both are in words

TRANSFER a TO b and MOVE a TO b

Bauer and Samelson's machine, 1957: =>

Sorry, I can't cover all languages between 1957 and 1964, but greater languages

```<code>1957 - COMTRAN (forerunner to COBOL)
1958 - LISP
1958 - ALGOL 58
1959 - FACT (forerunner to COBOL)
1959 - COBOL
1959 - RPG
1962 - APL
1962 - Simula
1962 - SNOBOL
1963 - CPL (forerunner to C)
</code>```

have not LET for assignment. Or had not, in the case of LISP.

Dartmouth BASIC is the original version of the BASIC programming language. The first interactive version was made available to general users in June 1964;

```<code> LET / = — assign formula results to a variable
</code>```

Body:
Lisp is the oldest language of these having LET now. But BASIC was the first that got it, for Lisp had obtained it much later.

In Ada Lovelace Analytical Engine (1843) - no LET, a program looks as:

N0 6 N1 1 N2 1 × L1 L0 S1  L0 L2 S0 L2 L0 CB?11 '

In Plankalkül of Zuse (1943-45) the program looks:

P1 max3 (V0[:8.0],V1[:8.0],V2[:8.0]) → R0[:8.0]
max(V0[:8.0],V1[:8.0]) → Z1[:8.0]
max(Z1[:8.0],V2[:8.0]) → R0[:8.0]
END

Short Code was proposed by John Mauchly in 1949

X3 =  (  X1 +  Y1 )  /  X1 * Y1

Intermediate PL of Burks, 1950, used for assignment ->

Rutishauser in 1952 used =>=

Böhms compiler, 1952, used ->

At the University of Manchester, Alick Glennie developed Autocode in the early 1950s.  The first code and compiler was developed in 1952 for the Mark 1 computer at the University of Manchester and is considered to be the first compiled high-level programming language. Again, -> for assignment

Charles Adams, FORTRAN 0 of Backus's group , Brooker's Autocode 2, ПП1 of Lubimsky and Kamynin; all in 1954, again =

BACAIC (Grems, Porter), 1954, * for assignment!

Kompiler, ADES, 1955, =

IT, 1956, <-

FORTRAN, 1957,  =

AT-3 (1956), Math-Matic (1957), again =,

but Flow-Matic in 1957 had two assignments, and both are in words

TRANSFER a TO b and MOVE a TO b

Bauer and Samelson's machine, 1957: =>

Sorry, I can't cover all languages between 1957 and 1964, but greater languages

1957 - COMTRAN (forerunner to COBOL)
1958 - LISP
1958 - ALGOL 58
1959 - FACT (forerunner to COBOL)
1959 - COBOL
1959 - RPG
1962 - APL
1962 - Simula
1962 - SNOBOL
1963 - CPL (forerunner to C)

have not LET for assignment. Or had not, in the case of LISP.

Dartmouth BASIC is the original version of the BASIC programming language. The first interactive version was made available to general users in June 1964;

 LET / = — assign formula results to a variable


答:
Well, exactly what you're going to need wil depend on the class, though some generalities will likely hold. I'd suggest getting a C book intended for Java programmers. It's likely to point out the major pitfalls and help you transition.

The biggest items that you're going to worry in C that you don't really worry about in Java are pointers and memory management. Java references are technically pointers, but they're seriously dumbed-down pointers, and from what I've seen, Java programmers don't really see them as the pointers that they are and often have some trouble dealing with pointers initially. Going hand in hand with that is the fact that you won't have a garbage collector, so anything that gets allocated on the heap will not only have to be manually allocated, but you'll have to manually de-allocate it when you're done with it. So, you're going to have to become familiar with malloc and free. You also aren't going to have classes, and structs in C can't have functions in them, so you don't generally program in C in an object-oriented manner. That may or may not be a big deal for you. It does mean, however, that what you'll be learning in your systems programming course and your object-oriented design course are likely to be very different.

OOD should be more of an extension of what you know, teaching you how to better program in an object-oriented manner. Systems programming, on the other hand is much more about getting down and dirty and will be much more low-level in what it deals with. Both are really important to being a good programmer though.

Without knowing your exact skill set and experiences and without knowing the exact courses, giving more detailed advice would be difficult, but primarily, the issue is likely to be in dealing with how C doesn't doesn't manage things for you and doesn't try and keep you safe from yourself. You will have to be more careful programming in C than you would be in Java or Python. There's plenty of stuff that's perfectly legal C which would be illegal many other languages and could surprise you. The main things to be concerned about though are pointers and manual memory management.

Title: System Programming & Object Oriented Design - what to look out for

Body:
Next semester (starts in just under 5 weeks), I'm taking System Programming and OOD concurrently.  Apparently SP centers on working in C on Linux, and I only have Java and Python experience, so I am a little nervous about this.

For those of you who've taken these at an university, what should I look out for?

I've already taken Computer Organization which included an overview of Assembly.  With the exception of implementing loops in assembly, I ranged from B+ to A- in the assembly projects.  Building circuitry was another story, however.


问:
What process should I follow to implement (code) a web site in HTML5/CSS?
The title question is unfortunately pretty vague (or at least may be asking differently than what I intend)... but let me elaborate.

I know basic HTML5 and CSS. I don't need to learn the tags and how they work. What I'm looking for is some information on what sort of process to follow when actually coding a professional style website. I want to make a portfolio website for myself from scratch (that is, not to use turnkey software such as Wordpress and such) but I don't know what to do as a process to making a clean site from the start. I'm a CS student and my skill set is in Java/C#, but I do want to learn web development as well.

I know that HTML is for the content of the site, CSS is for the look, and Javascript is for the behavior.

Do I need to have an idea of what the site is ultimately going to look like before I start the HTML? Can I just write the HTML to describe the content and worry about the look of the site afterward, or do I have to write the HTML knowing what I want the site to look like as I write it?

If I want a horizontal nav bar at the top, do the links have to be side by side in the HTML code?

These are all things I don't know... how to actually build a proper website. I know how to make basic pages with text and links and headers and all that, but to make a professional website is foreign to me. Every page I find on Google is either too high level (giving a design and implementation process without giving examples of how to implement once you know what you want) or is too beginner (trying to teach me HTML and CSS when I already know what I need to know in that regard).

答:
If you know how HTML / CSS works then I'm sure you are aware that the concept of CSS is to move the presentation away from the site content. So to answer your question you could just write your content and look to style it later. In reality however most people will create a HTML / CSS template from some wireframes and then work on making it dynamic.

In terms of professional code style why not view the source of pages that you respect and see how they lay things out. Google has a style guide that you may want to check out for this too http://google-styleguide.googlecode.com/svn/trunk/htmlcssguide.xml

A good start to creating a dynamic webpage would be to look into a language like PHP. There are plenty of tutorials of how to generate a HTML pages in this way and once you have the basics down you can remove some of the boilerplate associated with web development by using a Framework such as Zend Framework or Code Igniter (PHP) as this is often how professional web services are developed.

Another tool that can make your life easier if you wish to lean on other developers would be to use a UI Framework such as bootstrap to aid your HTML / CSS / JS implementation. http://getbootstrap.com/

My advice would be to decide if you are more focused on dynamically generating webpages or just serving static HTML / CSS / JS files and focus on the techniques involved in doing that first. I hope some of these resources are useful.

-edit-

To clarify my advice would be to draw some wireframes: http://en.wikipedia.org/wiki/Website_wireframe first and then create the HTML / CSS to match this although you do not have to do this if you don't want to. If you choose to just write the content then my advice would be to make sure you use appropriate HTML5 tags such as article, header, footer etc. This will make your life easier when you come to style it.


答:
I would start with what content you need, and be fairly generous in using id properties.

If you look at http://www.csszengarden.com you can see many examples of how to drastically change look by using css.

I also use http://caniuse.com to decide which html5 elements to use based on which browsers I care about, or which ones I need to add in javascript to fail gracefully.

You should also use unobtrusive javascript, http://en.m.wikipedia.org/wiki/Unobtrusive_JavaScript, to keep the webpage clean and fail gracefully.

So, start with content, then look at graceful degradation with javascript, then make it look nice.  This will be iterative,so you may need to bounce between these often.

Title: What process should I follow to implement (code) a web site in HTML5/CSS?

Body:
The title question is unfortunately pretty vague (or at least may be asking differently than what I intend)... but let me elaborate.

I know basic HTML5 and CSS. I don't need to learn the tags and how they work. What I'm looking for is some information on what sort of process to follow when actually coding a professional style website. I want to make a portfolio website for myself from scratch (that is, not to use turnkey software such as Wordpress and such) but I don't know what to do as a process to making a clean site from the start. I'm a CS student and my skill set is in Java/C#, but I do want to learn web development as well.

I know that HTML is for the content of the site, CSS is for the look, and Javascript is for the behavior.

Do I need to have an idea of what the site is ultimately going to look like before I start the HTML? Can I just write the HTML to describe the content and worry about the look of the site afterward, or do I have to write the HTML knowing what I want the site to look like as I write it?

If I want a horizontal nav bar at the top, do the links have to be side by side in the HTML code?

These are all things I don't know... how to actually build a proper website. I know how to make basic pages with text and links and headers and all that, but to make a professional website is foreign to me. Every page I find on Google is either too high level (giving a design and implementation process without giving examples of how to implement once you know what you want) or is too beginner (trying to teach me HTML and CSS when I already know what I need to know in that regard).


答:
I tend to create platform specific libraries so I have common code in one project and by keeping everything in a repository I can go onlinux and pull down common project and compile, pulling in the Linux library and on windows a dll.

This is due to so many libraries being needed for inclusion on each platform, so if I use directx on windows and those libraries and opengl on Linux this pattern helps.

Title: In C++ what is the commonly accepted method for making a program platform-agnostic?

Body:
The way I usually do it is I make some namespace Platform in Platform.h and every OS call is encapsulated by a static function in this namespace. So the only place in the entire code base that knows what OS is being used is Platform.cpp. Is this a good way of making things easier? For instance when I call Platform::MessageBox(...), what actually happens is:</p>

```<code>void Platform::MessageBox(...)
{
#ifdef(_WINDOWS)
....
#elif(_LINUX)
....
#elif(_MAC)
....
#endif
}
</code>```


答:
I always thought pass by value is a legacy from the early languages, because the designers had never seen anything else.

This is a bogus characterization in two respects:

It (kind of) assumes that pass-by-value was the original form of passing, and that it was superseded by better things.  In fact, the history clearly demonstrates this is not true (as does the Answer you cited as a source).

It implies (without any logical argument or supporting evidence) that the designers of mainstream programming languages are ignorant of programming language history.  A proper review of the relevant documentation will reveal that this notion is completely false ... not to mention insulting to the people involved.

The actual decision to support pass-by-reference, pass-by-value and/or one of the more obscure / historic forms (such as pass-by-copying or pass-by-name) is heavily intertwined with other aspects of the overall language design ... and motivated by the goals of the design.

For example:

Is the goal to provide a language where programs are easy to read and understand?

Is the goal to provide a language which maximizes "expressive power" or "conciseness"?

Is the goal to provide a language which maximizes "performance" on certain kinds of problems?

Is the goal to support a particular programming "paradigm" over others; e.g. procedural, OO, functional, pure functional, parallel / concurrent?

And so on.

In short, they have gone way beyond simplistic thinking like "the advantages of pass by value".

I have been coding for years and I rarely needed to pass by value. Almost always, I don't need my value/object to be copied to a function call.

Something does not make sense with that ...

If you have been coding for years in Java, C, C++, C# or most other modern programming languages, you have been using pass by value most of the time.  It is the default way of doing things ... and in some languages (like Java) it is the only way.

For example

```<code>    int i = 1;
    myFunction(i);
</code>```

AFAIK, i will be passed by value in C, C++, Java and C#.  If you want pass by reference (in C and C++) you have to write it explicitly; e.g.

```<code>    myOtherFunction(&i);
</code>```

Do you actually do that all the time in your code?  For primitive-typed variables?  I don't think so.

Title: What are the advantages of pass by value?

Body:
I always thought pass by value is a legacy from the early languages, because the designers had never seen anything else. But after seeing the brand new languages like Go adapting the same principle confused me.

The only advantage I can think of is you make sure that the value you are passing won't be modified. But every time you need to pass a big structure to a function, you need to pass the pointer (or reference) to prevent copying, if the language permits it.

To prevent modification of parameters, some constness mechanism could be introduced instead of making the whole language pass by value.

I have been coding for years and I rarely needed to pass by value. Almost always, I don't need my value/object to be copied to a function call; and often I don't need it to be modified inside the function*.

What is the motivation behind making modern languages pass by value? Are there any advantages that I am not aware of?

Edit: When I say pass by value, I don't mean primitives. They are easy and cheap to pass by value. My main focus is objects or structs that consists of more than 1 primitive and thus expensive to copy.

*: I have asked around and others reported similar thing with their parameter usage.

Body:
I always thought pass by value is a legacy from the early languages, because the designers had never seen anything else.

This is a bogus characterization in two respects:

It (kind of) assumes that pass-by-value was the original form of passing, and that it was superseded by better things.  In fact, the history clearly demonstrates this is not true (as does the Answer you cited as a source).

It implies (without any logical argument or supporting evidence) that the designers of mainstream programming languages are ignorant of programming language history.  A proper review of the relevant documentation will reveal that this notion is completely false ... not to mention insulting to the people involved.

The actual decision to support pass-by-reference, pass-by-value and/or one of the more obscure / historic forms (such as pass-by-copying or pass-by-name) is heavily intertwined with other aspects of the overall language design ... and motivated by the goals of the design.

For example:

Is the goal to provide a language where programs are easy to read and understand?

Is the goal to provide a language which maximizes "expressive power" or "conciseness"?

Is the goal to provide a language which maximizes "performance" on certain kinds of problems?

Is the goal to support a particular programming "paradigm" over others; e.g. procedural, OO, functional, pure functional, parallel / concurrent?

And so on.

In short, they have gone way beyond simplistic thinking like "the advantages of pass by value".

I have been coding for years and I rarely needed to pass by value. Almost always, I don't need my value/object to be copied to a function call.

Something does not make sense with that ...

If you have been coding for years in Java, C, C++, C# or most other modern programming languages, you have been using pass by value most of the time.  It is the default way of doing things ... and in some languages (like Java) it is the only way.

For example

    int i = 1;
    myFunction(i);

AFAIK, i will be passed by value in C, C++, Java and C#.  If you want pass by reference (in C and C++) you have to write it explicitly; e.g.

    myOtherFunction(&i);

Do you actually do that all the time in your code?  For primitive-typed variables?  I don't think so.


答:
Do I need to have an idea of what the site is ultimately going to look
  like before I start the HTML? Can I just write the HTML to describe
  the content and worry about the look of the site afterward, or do I
  have to write the HTML knowing what I want the site to look like as I
  write it?

Yes, definitely start with an outline of what the site is going to do before you start. It'll make your life a lot easier. I usually start with a notepad and just draw a rough outline of where this element is going, what I want the user to be directed towards, and so on.

If I want a horizontal nav bar at the top, do the links have to be
  side by side in the HTML code?
      Yes. The simplest semantic way to do something like this is probably:

```<code><header>
   <nav>
      <ul>
         <li><a href='LINK1'>Link name 1</li>
         <li><a href='LINK2'>Link name 2</li>
         <li><a href='LINK1'>Link name 3</li>
      </ul>
   </nav>
</header>
</code>```

with some css like:

```<code>nav ul li{
   display:inline-block;
}
</code>```

would give you a pretty good starting point.

Do I need to have an idea of what the site is ultimately going to look
  like before I start the HTML? Can I just write the HTML to describe
  the content and worry about the look of the site afterward, or do I
  have to write the HTML knowing what I want the site to look like as I
  write it?

Yes, definitely start with an outline of what the site is going to do before you start. It'll make your life a lot easier. I usually start with a notepad and just draw a rough outline of where this element is going, what I want the user to be directed towards, and so on.

If I want a horizontal nav bar at the top, do the links have to be
  side by side in the HTML code?

But honestly, if I was in your situation, I'd start off with a CSS framework like Bootstrap, or Foundation to really get a handle on how a good percent of web developers are developing their code.

If you decide not to start with a framework, at least follow some frontend coding standards, like using a grid system (Simple Grid is one I like, but there are gazillions out there), or following Object Oriented CSS.

Body:
Do I need to have an idea of what the site is ultimately going to look
  like before I start the HTML? Can I just write the HTML to describe
  the content and worry about the look of the site afterward, or do I
  have to write the HTML knowing what I want the site to look like as I
  write it?

Yes, definitely start with an outline of what the site is going to do before you start. It'll make your life a lot easier. I usually start with a notepad and just draw a rough outline of where this element is going, what I want the user to be directed towards, and so on.

If I want a horizontal nav bar at the top, do the links have to be
  side by side in the HTML code?
      Yes. The simplest semantic way to do something like this is probably:

<header>
   <nav>
      <ul>
         <li><a href='LINK1'>Link name 1</li>
         <li><a href='LINK2'>Link name 2</li>
         <li><a href='LINK1'>Link name 3</li>
      </ul>
   </nav>
</header>

with some css like:

nav ul li{
   display:inline-block;
}

would give you a pretty good starting point.

Do I need to have an idea of what the site is ultimately going to look
  like before I start the HTML? Can I just write the HTML to describe
  the content and worry about the look of the site afterward, or do I
  have to write the HTML knowing what I want the site to look like as I
  write it?

Yes, definitely start with an outline of what the site is going to do before you start. It'll make your life a lot easier. I usually start with a notepad and just draw a rough outline of where this element is going, what I want the user to be directed towards, and so on.

If I want a horizontal nav bar at the top, do the links have to be
  side by side in the HTML code?

But honestly, if I was in your situation, I'd start off with a CSS framework like Bootstrap, or Foundation to really get a handle on how a good percent of web developers are developing their code.

If you decide not to start with a framework, at least follow some frontend coding standards, like using a grid system (Simple Grid is one I like, but there are gazillions out there), or following Object Oriented CSS.


问:
what's a good approach to working with multiple databases?
I'm working on a project that has its own database call it InternalDb, but also it queries two other databases, call them ExternalDb1 and ExternalDb2.  Both ExternalDb1 and ExternalDb2 are actually required by a few other projects.  I'm wondering what the best approach for dealing with this is?

Currently, I've just created a project for each of these external databases and then generated Edmx and entities using the entity-framework approach.  My thought was that I could then include these projects in any of my solutions that require access to these databases.  Also, I don't have any separate business layers. I just have a solution like below:

```<code>Project.Domain
ExternalDb1Project.Domain
ExternalDb2Project.Domain
Project.Web
</code>```

So my Domain projects contain the data access as well as the POCOs generated by Entity Framework and any business logic.  But I'm not sure if this is a good approach.  For example if I want to do Validation in my Project.Domain on the entities in the InternalDb, it's fine.  But if I want to do Validation for entities from either of the ExternalDbs, then I wonder where it should go?  To be more specific, I retrieve Employees from ExternalDb1Project.Domain.  However, I want to make sure they are Active.  Where should this Validation go?

How to architect a project like this at a high level?  Also, I want to make sure that I use IoC for my data contexts so I can create Fakes when writing tests.  I wonder where the interfaces for these various data contexts would reside?

答:
It sounds like your domain is split only because the information is in multiple databases.  If there is one domain object (Employee) then the domain should expose a single source for Employees, and the multiple data sources should be aggregated to present a single Employee to the rest of the system (including a validation method).  I can think of two ways to accomplish this:

1) If multiple services will need to access the data sources, you could have an service in front of each database:

```<code>EmployeeInfoService -> EmployeeInfoRepository -> db1
EmployeeRoleService -> EmployeeRoleRepository -> db2

EmployeeService -> depends on EmployeeInfoService and EmployeeRoleService
SomeOtherService -> depends on EmployeeInfoService
SomeOtherServiceTwo -> depends on EmployeeRoleService
</code>```

2) If the employee entity is the only interested party in the information:

```<code>EmployeeRepository -> direct queries to db1 and db2
EmployeeService -> depends on EmployeeRepository
SomeOtherService -> depends on EmployeeService
SomeOtherServiceTwo -> depends on EmployeeService
</code>```

The multiple databases should only be a concern only at the repository and the storage layer.  Revisit the separation of layers if the database storage is impacting the validation service.

Body:
It sounds like your domain is split only because the information is in multiple databases.  If there is one domain object (Employee) then the domain should expose a single source for Employees, and the multiple data sources should be aggregated to present a single Employee to the rest of the system (including a validation method).  I can think of two ways to accomplish this:

1) If multiple services will need to access the data sources, you could have an service in front of each database:

EmployeeInfoService -> EmployeeInfoRepository -> db1
EmployeeRoleService -> EmployeeRoleRepository -> db2

EmployeeService -> depends on EmployeeInfoService and EmployeeRoleService
SomeOtherService -> depends on EmployeeInfoService
SomeOtherServiceTwo -> depends on EmployeeRoleService

2) If the employee entity is the only interested party in the information:

EmployeeRepository -> direct queries to db1 and db2
EmployeeService -> depends on EmployeeRepository
SomeOtherService -> depends on EmployeeService
SomeOtherServiceTwo -> depends on EmployeeService

The multiple databases should only be a concern only at the repository and the storage layer.  Revisit the separation of layers if the database storage is impacting the validation service.


问:
How do you stay focused at work?
Sometimes, the things I have to do for my job are interesting and engaging.  Sometimes, they aren't.  Occasionally, they really aren't.

Do you have any particular strategies or tricks for dealing with those dull stretches when your brain would rather be doing anything other than what you're supposed to be doing, particularly when the Internet and its boundless opportunities for interesting Slack beckon?

答:
Hmm, I'm only able to focus if I'm really interested in what I'm doing. For boring activities I use a "hopping" method, jumping frequently from the actual work to something different (even web browsing), and so I maintain a reasonable productivity.

By the way, a basic thing to understand (especially for employers!) is that you can't be focused indefinitely. Our brain will reach a climax of concentration after some time, will keep it for some time (it's that time when you have that full comprehensive vision of your work!) but then it will drop quickly. This attention pattern may vary a lot on individual basis, but a cycle usually lasts 45 minutes.

Title: How do you stay focused at work?


问:
What is the point of a Gantt Chart, and will it help me?
My (non-technical) colleague has threatened me with a Gantt chart for a new project that we are currently planning.  What is this likely to provide for us, and will it be a helpful tool?</p>

答:
I LOVE Gantt charts and if there were better software choices for the Mac to create them, I'd use them all the time.

Getting to see the dependencies is huge.  "If we don't get the data backfilling part of the project done, then construction on the whatsit enhancements can't start."


答:
(Full) dependent typing allows you to write arbitrary expressions on the type level including ones that, in a more "mainstream" language, would be exclusive to the value level.  This can let you write type-checked pre- and post-conditions for your functions, but only as a special case of being able to write anything you like.

In contrast, "contracts" can only do some very specific checking, as opposed to checking literally anything you can conceive of (as long as it's computable).

So-called "refinement types" fall somewhere in between.

Title: What is the difference between dependent typing and contracts?

Body:
What is the difference between dependent typed languages and languages like Spec# and Eiffel that allow you to specify "contracts" for functions in your code for pre/postconditions? Is dependent typing basically the purely functional version of Eiffel's "contracts"?

From what I understand, dependently typed languages let you specify your function's pre and post conditions using predicate logic as part of the type.

Eiffel's concept of contracts seems to be similar, but based on imperative programming, not functional programming.


问:
Do you believe it's a good idea for Software Engineers to have to work as Quality Assurance Engineers for some period of time?
I believe it is.  Why?

I've encountered many Software Engineers who believe they are somehow superior to QA engineers.  I think it may help quench this belief if they do the job of a QA engineer for some time, and realize that it is a unique and valuable skill-set of its own.

The better a Software Engineer is at testing their own programs, the less cost in time their code incurs when making its way through the rest of the software development life-cycle.

The more time a Software Engineer spends thinking about how a program can break, the more often they are to consider these cases as they are developing them, thus reducing bugs in the end product.

A Software Engineer's definition of "complete" is always interesting...if they have spent time as a QA engineer maybe this definition will more closely match the designer of the software's.

Note I make above suggestion with a small time-frame in mind as I am aware having someone work in a position that is not the position they are hired for is definitely a recipe for losing that developer.

What do you all think?

答:
Here are some potential problems I see with your proposal:

1) If you're suggesting that you would put new-to-the-field software engineers into the QA department for a short stint, won't this just have the opposite effect? - they may assume that QA is something you do when you're a newbie and you don't understand what you're doing - after all, that's how it worked for them.

2) Being a very bad tester for a while will not necessarily teach them anything valuable.  But it may make them unteachable later on, because they will assume that they know all about testing now, because they spent 6 weeks in a test department once upon a time.

3) Given that they'll obviously only be there for a short time, and the QA dept will know this, it's also likely that they will only be given relatively undemanding, easy tasks that require little supervision or understanding, but which keep them busy.  This will only reinforce 1 and 2.

4) If you want to avoid 1, 2, and 3, how will you persuade your test department that it is worth investing a tremendous amount of energy in teaching and supervising someone who isn't even interested in testing?  (I can tell you, it takes a scary amount of time and energy to work with someone who, let's remember, hasn't been picked for their testing aptitude.  You're not offering the test team additional resource for a few weeks, you're asking them to lose one of their most experienced people for a few weeks, while they teach your newbie).

Having said all that, I think your overall goal - to increase new software engineers' understanding of testing - is really fantastic.  I think that Greg's suggestion is more likely to achieve it though - get your dev & QA teams collaborating closely together, and work on breaking down any barriers between the teams.  (I'm currently working in a company where testers and programmers are on the same team - it really is great, and I never want to go back to working in separate teams.)

If you're still keen on having programmers do a stint in QA - here's a suggestion: lead by example.  Go yourself first.  Perhaps make it into something members of your team get to do when they're already good, and want to get that extra edge, by spending a little time each week with other teams who specialise in overlapping areas - test, DBAs, etc.  If you present it like that, then you'll have more chance of success.


问:
Does producing potentially shippable product make you less agile?
The cost of developing a feature in Agile is very high because it needs to be ready for shipment.
It includes:

Significant bug fixing

Writing/updating and executing tests

Writing/updating the user manual

Polishing the UI design (placement of controls, color schemes, etc...)

Updating the documents for FDA (in our organization)

When the cost is that high you are less likely to change the feature once you implement it. So does it make your less agile?

答:
I fail to see any point in there that is specific to agile. Would you leave any one out in other methodologies, or do you think you could, e.g., save money by updating the user manual for different changes all at once?

Also, typically, later points in that list cause work located in earlier points (the failure of the waterfall model). From my experience (and I believe that is backed by the standard literature on software design, but I’d need to go looking for references), going back considerably later is more expensive than doing so sooner after you thought you were done with that step. Which means that if polishing the user interface shows a design flaw and how you could make the feature much more user-friendly, you are more likely to do that if the programmers declared their part done three days ago than if they’ve been working in other projects for two months.

It all depends on how often and by whom you get feedback. If you are thinking about change requests from the VP who only looks at your software twice a year, then sure, changing finished features is more expensive than changing half-finished ones where you held off for exactly that occasion. Agile requires frequent customer feedback for that reason.


问:
Difference between the two enums
I came across an enum definition :-

```<code>typedef enum NSInteger {
    kBorderTypeNone   = 0,
    kBorderTypeLeft   = 1 << 0,
    kBorderTypeRight  = 1 << 1,
    kBorderTypeTop    = 1 << 2,
    kBorderTypeBottom = 1 << 3
} BorderType;
</code>```

and also (possibly) it can be equivalent to

```<code>typedef enum NSInteger {
    kBorderTypeNone   = 0,
    kBorderTypeLeft   = 1 ,
    kBorderTypeRight  = 2,
    kBorderTypeTop    = 4,
    kBorderTypeBottom = 8
} BorderType;
</code>```

What are the internal differences(if any)? Is there any advantage of one over the other? Which one is recommended?

If both are same then how compiler handles it? In which phase of compiler is it reduced to same set of instructions?

答:
Regarding the programming style, I think it is more idiomatic and should be used

```<code>typedef NS_OPTIONS(NSInteger, RoundCorner) {
    RoundCornedNone   = 0,
    RoundCornerLeft   = 1 << 0,
    RoundCornerRight  = 1 << 1,
    RoundCornerTop    = 1 << 2,
    RoundCornerBottom = 1 << 3,
    RoundCornerAll = RoundCornerLeft | RoundCornerRight | RoundCornerTop | RoundCornerBottom,
};
</code>```

when one is listing a set of bitmask whose possible combinations represent a state.

Whereas, when one is listing a set of mutually exclusive states

```<code>typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
    UITableViewCellStyleDefault,
    UITableViewCellStyleValue1,
    UITableViewCellStyleValue2,
    UITableViewCellStyleSubtitle
};
</code>```

NS_ENUM should be used.

Title: Difference between the two enums

Body:
Regarding the programming style, I think it is more idiomatic and should be used

typedef NS_OPTIONS(NSInteger, RoundCorner) {
    RoundCornedNone   = 0,
    RoundCornerLeft   = 1 << 0,
    RoundCornerRight  = 1 << 1,
    RoundCornerTop    = 1 << 2,
    RoundCornerBottom = 1 << 3,
    RoundCornerAll = RoundCornerLeft | RoundCornerRight | RoundCornerTop | RoundCornerBottom,
};

when one is listing a set of bitmask whose possible combinations represent a state.

Whereas, when one is listing a set of mutually exclusive states

typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
    UITableViewCellStyleDefault,
    UITableViewCellStyleValue1,
    UITableViewCellStyleValue2,
    UITableViewCellStyleSubtitle
};

NS_ENUM should be used.


答: One important difference that hasn't been explicitly mentioned so far, is that dependent types are checked at type-checking time (duh!), i.e. statically, before runtime. Eiffel contracts are checked dynamically, at runtime. Spec# falls somewhere in between: contracts are checked dynamically, at runtime, but you can get a theorem prover which can (try to) prove (some) contracts statically, before runtime.</p>


问:
Running time question
I have an array A of n integers, sorted from min to max, and two numbers a<=b, which are known to be in A. I would like to write a pseudo-code for a procedure whose running time is c1+c2log(n) and which returns the number of elements in A which satisfy a<=A[i]<=b.

I wrote the following but am not sure it satisfies the requirement for the running time and would appreciate some help:

NB <- denotes an arrow

```<code>LBound(Input: integer n, sorted array of integers A, integer a) {
  min  ← 1
  max  ← n
  while (min <= max) {
mid  ←  |_(min + max) / 2_|
    if (A[mid] < a)
      min  ←  mid + 1
else
      max  ←  mid - 1
  }
  output(min)
}
LBound(Input: integer n, sorted array of integers A, integer a) {
  min  ← 1
  max  ← n
  while (min <= max) {
mid  ←  |_(min + max) / 2_|
    if (A[mid] > b)
      max  ←  mid - 1
else
      min  ←  mid + 1
  }
  output(max)
}
Range(Input: integer n, sorted array of integers A) {
output (1 + UBound(n,A,b) – LBound(n,A,a))
}
</code>```

答:
Yes, the approach you have selected will satisfy the requirement. Each binary search is O(log n), so two of them are still O(log n).

No, you haven't got the code right yet. You've got an off-by-one error in the first block and mangled formatting in the second block. As you're using 1-based subscripting there is probably another off-by-one error in your binary search but until you get the formatting right it's too hard to work out.

Actually, I haven't written a binary search in years. Isn't that what the C/C++ libraries are for?

Title: Running time question


答:
Have no fear - it's only code

Java and C have very similar syntax coming from the same family of languages. As others have said, your biggest hurdles will be learning pointers (hint: they're just indirection), and memory management. Suddenly all those arrays you've been declaring in your Java have to be disposed of. Like any subject, once you've twigged what it's all about then it suddenly becomes straightforward.

Overall, it's more about learning the environment you'll be working in rather than some language syntax and constructs. Linux programming is very different to general Java programming. One relies closely on the operating system APIs, all C pointers and structs, and the other is generally much simpler because it's at a higher level of abstraction, there's just a lot more of it.

Developing the mindset

Perhaps the way for you to approach this is to maintain two working environments as virtual machines (Parallels or VMWare come to mind). One is purely for developing C code, the other for Java and no mixing them up. You could use different themes for the desktop to reinforce the different mindset (black for C, blue for Java or whatever). Each time you come to work in one or other environments you have many visual cues to promote the appropriate mindset you need to get the work done.


问:
Which statement performs best?
I was faced with this question by my team leader.

Statement 1 (written by me):

```<code>lnkbtn1.visible = lnkbtn2.visible = lnkbtn.visible = false;
</code>```

Statement 2 (written by my team leader):

```<code>lnkbtn1.visible = false;
lnkbtn2.visible = false;
lnkbtn3.visible = false;
</code>```

Which statement is better and why?

答:
The performance difference will be so incredibly minor that you should never even think about it.

The only thing that matters here is what one you would rather be using.

The first option might be in one line but oneliners aren't necessarily better.
It is harder to read and your approach also means that if you want to have false-true-false, you would have to retype everything.

The second option is very clear and each statement is self contained, I would go with this.

Title: Which statement performs best?


答:
I have to say I prefer the first option. It is crystal clear that all values are being set to false.

With the second option I'm having to read every line and wonder why it isn't all on one line following DRY principles due the redundant literal.

I'd find it hard to justify the second case on the grounds that the values might change at some point in the future. So much code cruft comes about because of something the programmer thought might happen but never did. This code then has to be tested and maintained. Not to mention being read by potentially dozens of programmers over the course of its life.

Title: Which statement performs best?

Body:
I was faced with this question by my team leader.

Statement 1 (written by me):

```<code>lnkbtn1.visible = lnkbtn2.visible = lnkbtn.visible = false;
</code>```

Statement 2 (written by my team leader):

```<code>lnkbtn1.visible = false;
lnkbtn2.visible = false;
lnkbtn3.visible = false;
</code>```

Which statement is better and why?


答:
There's no difference in performance at all. They will compile to virtually identical IL1.

However, there is a difference in readability and code style. The first option may be more compact, but the second is clear and conforms to most .NET coding guidelines. I personally prefer the second.

1. I ran a simple test in LINQPad. The only difference between the two options was in how the false value was loaded on the stack between calls to set_Visible. The first option produced one ldc.i4.0 and two dup's while the second produced three ldc.i4.0's.

Title: Which statement performs best?


问:
Python sorted iterable set, modifiable during iteration
I am looking for a datastructure to handle cycling through a large number of ordered subroutines, some of which are active, most of which are not.

I am thinking I need an implementation of a python set like object which remains ordered when modified, can be easily iterated over (I don't care if an actual for loop works, as long as there is a simple and efficient way to read each element in order). And most notably can be modified while being iterated over.

This is to allow an implementation of a very specific form of subroutine program (unfortunately I cannot use the built in subroutine modules as my python program is emulating the behaviour of a legacy system precisely so I need finer control.)

Effectively I have a list of subroutines which are referenced by an index number in a dictionary, the subroutines are iterated over in ascending order until the last is reached at which point we return to the lowest number one. However there are a large number of subroutines and only a few at any time will be 'active' and ones which are not active are skipped in the order for running. I considered simply giving each routine an active flag which would be tested before running however the enormous number of potential routines compared to the tiny number of active ones makes this method much to slow. Subroutines are only occasionally activated or deactivated but running them must be very fast. As such I have been looking to keep a list of the keys of the active ones and iterate through that, adding or removing them as they are activated or deactivated but am looking for a reasonably efficient way of maintaining this list.

The main two systems which seem feasible to me are blist sorted sets, however I am not sure if they support being modified while iterated over, and using two heapq and shifting the items between them in order, this will definitely support modification at any time but would require a lot more manual work, and would probably be slower.

However somebody may have a much better answer than either of those so I will appreciate any ideas on how to achieve this with reasonable efficiency and ideally in a 'pythonic' way, though I can deal with it being a little ugly if it does the job.

答: I'd use one heapq, give the subroutines a sort key, and simply add active routines to the heap. The inactive subroutines don't need to be in a heap; they can be in a dictionary, as you are not going to loop over those in order.</p>

OwnerDisplayName: Vality

OwnerDisplayName: Martijn Pieters


答:
In non agile environment you can develop the feature, but not to fix all bugs, not to do thorough testing, not update the user manual or other documentation. You can still show the feature to the user and get feedback.

I think you have a big misconception about the term "agile". Agile in its core means that you adapt your development process to your needs - instead of blindly following some fixed written process. Using your brain is permitted, especially in an agile process. If you have a requirement for which you know that you first need a prototype to discuss it with some of your users (but without writing complete docs  or full testing), then develop one. Agile or not, you don't want your users to use such an unfinished feature in the "production version" of the product, so take measures to prevent that.

Agile also means that you implement small feature slices you believe you have understood the requirements for to bring them into production quickly. To my experience, it is likely that you will get more and better feedback from your user base when they are using the thing in production. When you have discussed that feature beforehand using a prototype, it is unlikely that you have to rewrite the documentation and the tests completly then, but it is likely that you have to make some corrections to those documents and code.

Title: Does producing potentially shippable product make you less agile?

Body:
The cost of developing a feature in Agile is very high because it needs to be ready for shipment.
It includes:

Significant bug fixing

Writing/updating and executing tests

Writing/updating the user manual

Polishing the UI design (placement of controls, color schemes, etc...)

Updating the documents for FDA (in our organization)

When the cost is that high you are less likely to change the feature once you implement it. So does it make your less agile?