答:
Is each and every language written in C language?

A language is a set of abstract mathematical rules and restrictions ("if I write this, that happens"). It isn't written in anything, really.

It is specified, usually in a mixture of a formalized subset of English, mathematical notation, and maybe some specialized specification language. The syntax is often specified in a variant of EBNF or ABNF.

For example, here is the specification of the for expression from the ISO Ruby Language Specification:

§11.5.2.3.4 The for expression

Syntax

for-expression → for for-variable [no line-terminator here] in expression  do-clause end

for-variable → left-hand-side | multiple-left-hand-side

Semantics

A for-expression is evaluated as follows:

Evaluate the expression. If the evaluation of the expression is terminated by a break-expression, next-expression, or redo-expression, the behavior is unspecified. Otherwise, let O be the resulting value.

Let E be the primary-method-invocation of the form primary-expression [no line-terminator here].each do | block-parameter-list | block-body end, where the value of the primary-expression is O, the block-parameter-list is the for-variable, the block-body is the compound-statement of the do-clause.

Evaluate E; however, if a block whose block-body is the compound-statement of the do-clause of the for-expression is called during this evaluation, the steps in §11.3.3 except the Step c) and the Step e) 4) shall be taken for the evaluation of this call.

The value of the for-expression is the resulting value of the invocation.

Here's a different example from the type conformance rules of Scala:

The polymorphic type [a1 >: L1 <: U1 , … , an >: Ln <: Un]T conforms to the polymorphic type [a1 >: L′1 <: U′1 , … , an >: L′n <: U′n]T′ if, assuming L′1 <: a1 <: U′1 , … , L′n <: an <: U′n one has T <: T′ and Li <: L′i and U′i <: Ui for i ∈ { 1 , … , n }.

Is C language mother/father of all languages?

No, it is not. C is pretty young. There are a lot of old languages. Since time travel is physically impossible, it is simply impossible for C to have had any influence whatsoever on those old languages.

Plankalkül (1943)

Speedcoding (1953)

Fortran (1954)

IPL (1956)

Lisp (1958)

Algol (1958)

COBOL (1959)

JOVIAL (1960)

APL (1962)

SIMULA (1962)

SNOBOL (1962)

CPL (1963)

BASIC (1964)

PL/I (1964)

RPG (1964)

BCPL (1966)

ISWIM (1966)

MUMPS (1967)

Forth (1968)

LOGO (1968)

REFAL (1968)

B (1969)

BLISS (1970)

Pascal (1971)

KRL (1971)

Smalltalk (1972)

All of those existed before C was even invented. And many others have no influence of C in them, even after it existed. The PASCAL-family of languages (ALGOL-58, ALGOL-60, ALGOL-X, ALGOL-W, PASCAL, Modula-2, Oberon, Oberon-2, Active Oberon, Component Pascal) is a completely separate lineage. The whole Lisp family (LISP, Franz Lisp, InterLisp, MacLisp, Scheme, Flavors, LOOPS, CommonLoops, Dylan, CommonLisp, Arc, Clojure, Racket, etc.) is unrelated as well. Functional languages (ISWIM, KRL, Miranda, ML, SML, CAML, OCaml, F#, Haskell, Gofer, Clean) and the whole dependently-typed family (Agda, Coq, GURU, Idris) are about as far from C as possible. The same is true for the Smalltalk family (Smalltalk, Self, Newspeak, Us, Korz), the logic programming family (PLANNER, Prolog, Mercury), SQL, and many others.

Each concept (OOP etc) is all implemented in C language?

The first languages with OO concepts were Simula (1960) and Smalltalk (1972), but object-oriented systems had been built as far back as 1953 (without calling them that). Again, that's long before C existed, so OO cannot possibly have any relation to C.

Title: Is every language written in C?


问:
What's the returning a value in Java?
```<code>public void warning(){
    System.out.println("Watch out!");
}
</code>```

```<code>public void warning(){
    System.out.println("Watch out!");
    return;
}
</code>```

We must use "return" statement with void methods. Bot of these bring same output. What's the difference?

答:
You needn't use return with void methods in Java, although some coding conventions may call for it, it is not a requirement of the language.  Semantically they behave exactly the same way, as the "end" of a void method is an implicit return.

Now, it is also possible to put a return; in a conditional block (if, for, while, etc...) where it might exit the method early. For example:

```<code>void someMethod() {
   if (this.avoidSomething) {
       return;
   }
   System.out.println("Something not avoided.");
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: What's the returning a value in Java?

Body:
You needn't use return with void methods in Java, although some coding conventions may call for it, it is not a requirement of the language.  Semantically they behave exactly the same way, as the "end" of a void method is an implicit return.

Now, it is also possible to put a return; in a conditional block (if, for, while, etc...) where it might exit the method early. For example:

void someMethod() {
   if (this.avoidSomething) {
       return;
   }
   System.out.println("Something not avoided.");
}


问:
Is there a stronger stress on management than on technical education in recent years?
In my working environment, over the past few years I have observed an increasing stress on developer management and self-management over technical education.

For example, at work I hear lots of discussions about software development processes, about ways to handle software specifications, e.g. through automatic tests, and so on. I hear less discussions about programming concepts / techniques like data structures, lazy evaluation, memoization, and so on.

To give another example, if I asked a colleague how he would manage the complexity of a certain problem, I would expect that he'd indicate me some solution approach (try to solve a subproblem first, identify subtasks) instead of suggesting a programming abstraction (try using pattern X).

Is it just something specific to my working environment or there is a general trend towards management / work organization and away from the more conceptual aspects of programming?

To make my question specific (and answerable), are there any authors or modern schools of thought that consider organizational aspects more important than educational ones for improving developer productivity?

答: If by "recent years" you mean the last 22 then yes, because that's all the experience I have to go by. Focus on managerial/process oriented aspects of software projects has been really high ever since I started in the field. If you mean just the last 4 or 5 then absolutely not.</p>


问:
Disadvantages of Pointers
I was wondering why pointers are not included in modern languages now-a-days. I already did research on this on internet, and found out few theories/reasons:

Memory leakage is the biggest concern while using pointers.

If not handled properly it may ruin whole project or application.

Understanding and using pointers in best way possible requires a lot of time.

Well there are few problems but if some work is done properly on pointers i.e., exception handling etc. I think pointers can still be very helpful where required. Kindly help me out on this one.

答:
Almost all modern programming languages use indirection extensively under the hood - any instance of a Java type that's derived from Object is referenced through a pointer (or pointer-like object), for example.

The difference is that those programming languages don't expose any pointer types or operations on pointer values to the programmer.  You can't take the address of a Java Object instance and examine it directly, nor can you use it to offset an arbitrary number of bytes into the instance (even though the JVM does so internally).   The language simply doesn't provide any mechanism for the programmer to do so.  It doesn't define a method or operator to obtain an object's address; it doesn't define a method or operator to examine the contents of an arbitrary address; it doesn't define the binary + or - operators to work with address types.  The [] operator doesn't just offset from a base address; it's smart enough to throw an exception if you attempt to index past the end of the array.

Remember that C was developed (at least in part) to implement the Unix operating system; since any OS needs to manage memory, the language needed to provide operations on memory addresses as well as other types.

C became popular for applications programming because C compilers were small, fast, and produced fast code.  Being able to manipulate memory directly sped up a number of operations.  Unfortunately, being able to manipulate memory directly also opened up a huge can of worms with respect to security, correctness, etc.  Everything from the Morris worm to the Heartbleed bug was enabled by C's ability to manipulate memory.  Also, C's pointer syntax could be confusing, especially since unary * has lower precedence than postfix operators like [], (), ++, ., ->, etc.  The fact that array expressions "decay" to pointer types also leads to problems for people who don't really know the language that well.

So modern programming languages don't expose pointers the way C does to avoid many of these problems.  However, note that most of C's contemporaries (Pascal, Fortran, BASIC, etc.) didn't expose operations on pointer values either, even though they used pointer-like semantics under the hood (passing arguments by reference, COMMON blocks, etc.).

Title: Disadvantages of Pointers


问:
How to express what do do when error occurs in a user story?
How do you express what to do when error occurs in a user story? Should the response to what happen on errors be in a task of the original user story, or should I create another user story that is concerned with what happens on errors?

E.g.

This says nothing about what to do on errors such as credit card is invalid, not enough money, …

As a buyer I want to pay for the order with a credit card to get immediately access to the services.

I could add another user story like this:

As a buyer I want to get information about errors during payment immediately so that I can fix the errors and try again.

Which of these is common/correct? Should the error handling be part of the original user story?

答:
Write your story.  If there is lots of error handling, split it up into 2 stories.  After all, the business value of completing the happy path is different than the business value of understanding the reason for an error.

Add acceptance criteria that focus on the happy path(s) for each story or the 1 big story.  If you have a story for error handling, then your AC describe the happy path errors.

If an exception case has a significant impact to the business consider putting it in the AC if you write one big story, but don't try and list every edge/error/exception scenario

Let your QA resources worry about the majority of edge/exception cases and let them document these via test cases.  They should also be understanding your acceptance criteria and generating the positive test cases from those.

When possible, try and automate as many of your test cases a possible BUT, be risk neutral. Automating everything is costly; consider if some cases are not worth automating.


问:
Is there a useful correlation between choice of web-browser/search engine and good quality programmers?
After a round of interviews earlier this year, which included some practical questions with access to a computer, I noticed that, at least for the applicants we were seeing, there was a high inverse correlation between quality of applicant and the explicit choice of Bing/IE as the stack for search/browsing the web. That is, a large number of applicants specifically searched for IE to use as a browser when browsing the web, and specifically used Bing as the search engine (even typing in Bing in the Google search box, before starting a search)

Is this just an outlier, a fluke, or is there some sort of information I can obtain from this observation? So far, my best candidates are:

Yes, there is a high correlation between good programmers and choice of web browser/search engine

There is some training program, or community, which advises using IE/Bing during interviews, and I just happened to run into a poor selection from that group

Something else is going on, that I don't know about, but someone here might know.

So, to repeat, the question is: is there more than coincidence at work here, and, if there is, what's going on?

答:
Theorhetically there should be about as much correlation as a person's blood type and their temperament as a person.  The blood type theory is pretty common in many Asian countries, to the point where that information is in the bio for important people.  It's the same type of unrelated association that brought that theory into being.

You will probably see a higher incidence of IE/Bing usage among .NET developers, particularly if they've gone through any type of training.  Microsoft is very good at promoting its own products through every channel it can.  I used to believe there was an inverse proportion to a programmer's quality and the number of certificates they had, but I met a few certified Sun, Microsoft, etc. developers who were really good.  It's luck of the draw there.

There may be some psychological effects going on here as well.  People who are content with the status quo will accept anything that is set before them the first time as normal.  They will feel strange and out of place by attempting anything that is not the default behavior, which would explain people actively seeking out IE and Bing--consequently leading to your observation.  It's this type of person that will not be a good programmer.  They won't be able to think in ways that will improve long standing problems.  The same type of person might instinctively reach for Apple Safari if they grew up on a Mac.

However, once you get outside the defaults, there are a miriad of reasons why people choose the browsers they do.  For example, for day to day browsing I choose Google Chrome due to its good security record and its very fast response.  However, for web development I choose Firefox because the dev plugins on that browser are most mature and helpful.  I'll check in IE and Chrome to ensure I'm not missing anything (covering the three most common rendering systems [Chrome and Safari share the same rendering library]).  These days, the story is getting better on both Chrome and IE 8 and up--but still not as good as Firefox.

I think the most useful course of action would be to ask the person why they chose the browser/search engine they did.  If the answer is along the lines of "I've always used it" or "I don't know", there is a possibility that they might be the status quo kind of person.  Further questions will weed that out.  If they give you a reasonable explanation, it shows they are thinking about the choice.

Who knows, maybe there is some benefit to the IE/Bing combination we aren't aware of.  I personally doubt it, but there just may be.

ContentLicense: CC BY-SA 2.5


问:
Licensing: CC-BY-SA to CC-BY-NC-SA
Disclaimer: I am not a lawyer, and I don't expect anyone answering this question to also be, and I will not take the answer as legal advice.

Starting from a piece of software (in this case, a game mod) that is licensed as CC-BY-SA, can I create a derivative code (another mod, plus art assets) and publish my software as CC-BY-NC-SA? Or does the "SA" part in the original mod forbid this?

This is for a game that does allow mods, and which both licenses are already acceptable on the community.

I tried looking thru the licensing guidelines at the CC site, but I really haven't found a description that lets me know how can I sub-license or re-license content that is already CC licensed in a DIFFERENT license.

答:
The key part of CC-BY-SA of interest to you can be found in Section 2a5B of the legalease.

No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.

Quite simply said, by adding the 'NC' to your license you are imposing additional or different terms or conditions on the licensed material of which yours is a derivative work.

Similarly, this is again covered in Section 3b1 and 3b3

The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License.

You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.

That is the legalese part, the plain english can be seen in the CC-BY-SA summary page:

No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits.

You may say "wait, there's that comparable license" part, and if you read the Compatible Licenses from Creative Commons you will note that BY-SA and BY-NC-SA are not listed under each other's compatible licenses which is a simple "nope" to that line of reasoning.  This is again covered in the ShareAline Compatibility page from the FAQ.

Title: Licensing: CC-BY-SA to CC-BY-NC-SA


问:
Encapsulation: Should all properties be private and protected?
After learning about encapsulation in OOP, I started to use only protected and private properties, share data via accessors and change properties via mutators.

Right now, I'm afraid of declaring public properties.

Is it good to keep everything private and protected or is there some cases where I need to use public properties?

答:
If you don't need control over a data/property you are exposing, you can use public property with no problem.

For all other cases (like if it's a property with only in-class use or if you want to expose a property on which you want to keep read/write control), it's better to keep them private and some time protected if you plan for your class to be inherited


问:
The better way to ask for input?
I am wondering which is the best way to go with java code. I need to create a class with simple prompts for input.. I have tried using both classes and cannot work out the particular benefits for each. Is this because I am still in the early stages of programming or are there situations that will occur as it becomes more complex??

```<code>import java.util.Scanner;

public class myClass
{
    Scanner stdin = new Scanner(System.in);

    public String getInput(String prompt)
    {
        System.out.print(prompt);
        return stdin.nextLine();
    }

}
</code>```

... or

```<code>import java.io.*;

public class myClass
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Input something: ");
        String name = stdin.readLine();
    }
}
</code>```

I know these examples are showing different methods within these classes, but thought this might serve well for the discussion.

I'm really not sure which site is the best to ask this on.

答:
Simply reading System.in with BufferedReader, you end up writing a few lines of boilerplate code.

Moving up to Scanner, as suggested in Neil's answer, makes it easier to pull data of various types out of the stream.

Personally, when a command-line interface is really the best choice (which includes any time it's a stated requirement), I like to use System.console(). It's not always available (for example, when running inside some IDEs), but when it is, it offers useful things like readPassword() which prevents the user's input from being echoed back to the screen, and it makes it so that you can read from and write to the console using the same object.  It's really designed around the typical use case for command line tools that require user interaction.

Using System.console() doesn't explicitly conflict with Scanner:

```<code>Console console = System.console();
String name = console.readLine("Please enter your name: ");
Scanner ageScanner = new Scanner(console.readLine("How old are you? ");
int age = ageScanner.nextInt();
</code>```

They don't quite play perfectly together in this way, since you have to instantiate a new Scanner for each line.  Console does offer access to a Reader, which you can use to instantiate a Scanner:

```<code>Console console = System.console();
String name = console.readLine("Please enter your name: ");
Scanner consoleScanner = new Scanner(console.reader());
int age = consoleScanner.nextInt();
</code>```

(Disclaimer: I haven't tried the above code, and I'm not exactly sure how things will behave if you use console.readLine() intermixed with usages of a Scanner made from console.reader().  For clarity and consistency, it might be wise to choose one method and stick to it.)

Sticking with this example, I'd be more likely to write:

```<code>Console console = System.console();
String name = console.readLine("Please enter your name: ");
int age = Integer.parseInt(console.readLine("How old are you? ");
</code>```

Depending on your needs, you may find that one, the other, or both are best suited to your needs. Generally, I find that Scanner is better suited to reading a file with a known format, and Console is better suited to interactive user input, because Scanner really shines when you have multiple tokens per line of input.  Asking a user to enter that sort of input interactively is probably not going to result in the best experience.

JavaDoc: java.io.Console

Related question: Java: How to get input from System.console()

Title: The better way to ask for input?

Body:
Simply reading System.in with BufferedReader, you end up writing a few lines of boilerplate code.

Moving up to Scanner, as suggested in Neil's answer, makes it easier to pull data of various types out of the stream.

Personally, when a command-line interface is really the best choice (which includes any time it's a stated requirement), I like to use System.console(). It's not always available (for example, when running inside some IDEs), but when it is, it offers useful things like readPassword() which prevents the user's input from being echoed back to the screen, and it makes it so that you can read from and write to the console using the same object.  It's really designed around the typical use case for command line tools that require user interaction.

Using System.console() doesn't explicitly conflict with Scanner:

Console console = System.console();
String name = console.readLine("Please enter your name: ");
Scanner ageScanner = new Scanner(console.readLine("How old are you? ");
int age = ageScanner.nextInt();

They don't quite play perfectly together in this way, since you have to instantiate a new Scanner for each line.  Console does offer access to a Reader, which you can use to instantiate a Scanner:

Console console = System.console();
String name = console.readLine("Please enter your name: ");
Scanner consoleScanner = new Scanner(console.reader());
int age = consoleScanner.nextInt();

(Disclaimer: I haven't tried the above code, and I'm not exactly sure how things will behave if you use console.readLine() intermixed with usages of a Scanner made from console.reader().  For clarity and consistency, it might be wise to choose one method and stick to it.)

Sticking with this example, I'd be more likely to write:

Console console = System.console();
String name = console.readLine("Please enter your name: ");
int age = Integer.parseInt(console.readLine("How old are you? ");

Depending on your needs, you may find that one, the other, or both are best suited to your needs. Generally, I find that Scanner is better suited to reading a file with a known format, and Console is better suited to interactive user input, because Scanner really shines when you have multiple tokens per line of input.  Asking a user to enter that sort of input interactively is probably not going to result in the best experience.

JavaDoc: java.io.Console

Related question: Java: How to get input from System.console()


问:
How to use multiple programming languages together in the same program?
Such a simple question, but I have not found a reasonable answer to this.

I currently program in Python, an interpreted language. I always hear of people using multiple languages in the same program? Then I hear them using scripting languages; Can someone on here please in plain english explain to me the difference between what I know as programming languages and scripts, and how on Earth do people use multiple languages together. That just does not make any sense.

How can someone use Javascript, PHP, and ASP together. Or program a game in C/C++ and use python as scripts? It just doesn't make sense to me, they are different languages for a reason, i assume, so how do they play a role with one another?

答:
In many cases, when you see multiple languages used together, you will find that one is a compiled language and the other is a scripting language.

The compiled language is typically C/C++, but can be many other languages (Haskell, Erlang, Java, etc). The compiled language provides the base application. The base provides an interface to the underlying operating system as well as the foundation for the work to be done by the application. The application will often provide lower level functionality that makes it easier to develop using the scripting interface.

The scripting language is most often used to provide customization for the application. The customization can be part of the application provided by the vendor for their own convenience or the scripting interface can provide customization for the end user.

Many times, the script interface will provide almost a Domain Specific Language by providing useful functions and high level interface specific for the application, making it more easily customized.

A couple of well known examples. Emacs is written in C and customized using Emacs Lisp. TextMate is a compiled application customized using Ruby. Atom is a new text editor that is written in JavaScript to run on Node. Atom is more indirect. The application is (nearly?) all JavaScript while Node.js uses V8 which is written in C++. World of Warcraft has a scripting interface that uses Lua.

As a personal example, I worked on a brand-able installer where the base code was Objective-C/C++ in order to access UI elements on MacOS with customization using AppleScript. The AppleScript interface was used only by us in order to brand the application for each customer.

As others have said, use the right language for the right application.


问:
How to explain DependencyProperty using real world analogy?

How to explain DependencyProperty using real world analogy?

Why is it needed?

答:
From an answer to my post on StackOverflow by Kent Boogart:

In order for a property to be the target of a binding, that property must be a dependency property. WPF (and Silverlight) use dependency properties as a means for tracking changes, supporting value precedence (for animations and the like), and a bunch of other useful things. Note that I said "target". The source of a binding can be any old object that supports change notification.

This small tidbit of knowledge has really helped me out.  So use it if you want to databind to properties in your custom UserControls.


问:
Is embedding data in a executable considered a good practice?
Embedding data (such as images) in a executable seems to have a few advantages, like easier distribution of the executable and easier compatibility with different OSes.

But, is it a good practice? More specifically, how does the OS deals with a big executable? Would it be using much more RAM than needed?

答:
For embedding data files directly into an executable, there's several things to consider.

If the data isn't needed, will it be loaded? If your program always needs the data then the answer is "no". Also, for most OSs the executable file is memory mapped (where parts aren't loaded until they're used) so the answer may be "no" anyway. If the answer is "yes" then embedding the data files directly into the executable may increase startup time and waste RAM.

Will the data be needed temporarily (e.g. an image that's only shown when the application is starting)? In this case you want to free the memory when you no longer need it, and it can be hard/complicated to free part of the executable file.

Is there's an executable file size limit? For example, maybe it needs to work on some sort of 32-bit system where there's a 2 GiB executable file size limit, and the data you're embedding simply won't fit.

How well do your tools handle it? For some tools it's extremely easy to insert arbitrary binary files "as is" into an executable or object file (e.g. NASM's incbin or GAS's .incbin directive). For other tools it can be a pain in the neck (e.g. converting it to an array of bytes you can include as source code just so the compiler can convert it back into binary).

How hard should it be for people to modify/change the data? This can go both ways - maybe you want to make it easy for other project members (e.g. artists) to change the file and embedding it is a disadvantage; but maybe you want to make it hard for end users to change the file and embedding it is an advantage.

How hard is it to actually use the embedded data? For some cases (e.g. libraries that expect a file name) embedding the data might cause significant problem.

Will you have some sort of "auto-updater"? If you will, then it'd be more efficient to have multiple smaller files that can each be updated independently, rather than one large file where you can't update part of it and have to replace/update the entire file.


问:
Is static typing worth the trade-offs?
I began coding in in Python primarily where there is no type safety, then moved to C# and Java where there is. I found that I could work a bit more quickly and with less headaches in Python, but then again, my C# and Java apps are at much higher level of complexity so I have never given Python a true stress test I suppose.

The Java and C# camps make it sound like without the type safety in place, most people would be running into all sorts of horrible bugs left an right and it would be more trouble than its worth.

This is not a language comparison, so please do not address issues like compiled vs interpreted. Is type safety worth the hit to speed of development and flexibilty? WHY?

to the people who wanted an example of the opinion that dynamic typing is faster:

"Use a dynamically typed language during development. It gives you faster feedback, turn-around time, and development speed." -
     http://blog.jayway.com/2010/04/14/static-typing-is-the-root-of-all-evil/

答:
This is just my own opinion, but no, I don't think that type safety is worth it. Not even for a second.

I've been a developer for long time. Starting off with c++, c#, then moved to javascript (frontend and backend via node.js). Since I've been developing in javascript my productivity has sky-rocketed, to the point that I actually get aggravated using type-based languages. I'm also against compiling, I want everything to be in run-time now. Interpreted languages is really where I found my love for programming.

As far as types, I just don't see any benefits. I see types now the same way I see memory management. Completely unnecessary. The languages of tomorrow should completely shield the developer from knowing anything about types. The computer should understand types and leave the developer out of it.

Here's an example. I was just using Swift (Apple's new language) hoping it'd actually live up to its name a day ago and tried to do: var n = 1/2 didn't work. I was like, what's going on here. and then sadly realized I had to do var n: Float = 1/2. This reminded me how much I hate type systems and how much of an unnecessary aggravation they are.

I'd even go another mile to say that I don't even want user defined types (such as Classes). I don't want types at all. All I want is var and objects. Where any object can be used as any object. And objects are dynamic and constantly changing. Where it becomes a runtime issue as to what works and what doesn't.

Developers love to say how loosely typed languages aren't good for big projects. But I'd say it's the opposite. Strongly typed languages are horrendous for large projects. And if you say javascript doesn't work for big projects, ask Uber a 40billion+ company that runs all it's backend on node.js/javascript, or Facebook that started with PHP.

As far as statically typed languages it's not good for today's quick iterations. here's a simple example, you have 10 developers working on a .net project with a continuous integration server, one developer submits a mistake and the entire build is broken, even though the 10 developers are working on different things they are now all stopped and waiting for the offending developer to correct his mistake. Talk about efficient huh? Type system / static languages are interdependent in that way and make your code interdependent. However, script files are never interdependent. If there's a problem with one of the scripts it doesn't halt production, all the problems you'd see are left to the runtime. And the runtime never stops. It never breaks. It might produce wrong output but it doesn't just halt the entire process the way type systems do.

Title: Is static typing worth the trade-offs?


问:
Non-Object Oriented Programming in Object Oriented Language
Recently I was assigned a task of creating a calculator with functions addition, subtraction, multiplication, division and power using Object Oriented Programming. I successfully completed this task. However afterwards I reprogrammed the whole program without using Object Oriented technique/method.

The thing I noticed that my code length was reduced quite significantly and it was quite understandable. So my question here is when should I use Object Oriented Programming? Is it okay to create programs without Object Orientation in Object Oriented Language? Kindly help me out on this one.

PS: I am not asking here to tell me merits of Object Oriented Programming over procedural programming.

答:
How do professional programmers make judgement call on whether to go
  for OOP or not? It would be really helpful for me.

For me, there are two decision points. First, sometimes it will be obvious at the beginning. There will be lots of similar types that all share common methods that differ widely in their implementation details. For example, I was building a workflow system, and I needed the ability to implement arbitrary tasks. To run the task, I implemented a base class that each task inherited from, with an Execute() abstract method. The inheriting classes supplied the implementation, but the workflow system could begin the execution without knowing anything about what kind of task was being run.

Most projects aren't that clear-cut though. The second decision point is when a subset of the project has grown into a huge tangle of if-then statements or switch-case statements, and especially when those if-then statements require a lot of setup code to run correctly. I feel myself starting to lose the logic of what I'm trying to accomplish, and the code starts to feel fragile. At that point, it is usually a sign that it is time to refactor the code into base classes with specific implementations.

A big part of switching to an object-oriented style as opposed to a functional style is converting if-then statements into "run this action" statements. Instead of a huge set of if-then statements, you just tell the code to run its action. Which action is actually run depends on the implementation you supplied.

For example, here's the functional style in C#-style pseudocode:

```<code>if ( action == "email" ) {
    callEmailFunction(userInfo);
}
else if ( action == "sms" ) {
    callSmsFunction(userInfo);
}
else if ( action == "web" ) {
    endpoint = "http://127.0.0.1/confirm";
    confirmWeb(endpoint, userinfo);
}
...
</code>```

But maybe you could rewrite that to something like this:

```<code>interface IConfirmable {
    void Confirm(UserInfo userinfo);
}

public class ConfirmEmail : IConfirmable {
    public void Confirm(UserInfo userinfo) {
        // do the appropriate thing to confirm via email
    }
}

public class ConfirmSms : IConfirmable {
    public void Confirm(UserInfo userinfo) {
        // do the appropriate thing to confirm via email
    }
}

public class ConfirmWeb : IConfirmable {
    // this is a constructor
    public ConfirmWeb(string endpoint) {
        ...
    }

    public void Confirm(UserInfo userinfo) {
        // do the appropriate thing to confirm via web
    }
}
</code>```

And then the code itself:

```<code>// An implementation that decides which implementation of the base class to use
// This replaces the if-then statements in the functional programmming.
IConfirmable confirmer = ConfirmerFactory.GetConfirmer();

// get the userinfo however you get it,
// which would be the same way you get it in the functional example.
UserInfo userinfo = ...;

// perform the action.
confirmer.Confirm(userinfo);
</code>```

Now, when there is very little code inside the if-then, this looks like a lot of work to get no benefit. And when there is very little code in the if-then, that is correct: that's a lot of work for code that is harder to understand.

But the object-oriented style really shines when you have more than one action than just the Confirm() method that needs to be performed. Maybe you have an initialization routine, three or more action methods that can be run, and a Cleanup() method. The base algorithm is identical, except it makes its calls into the appropriate objects that implement a common base class. Now you start to see a real benefit to the object oriented style: the base algorithm is much easier to read than if it was checking if-then statements at every step of the way.

Body:
How do professional programmers make judgement call on whether to go
  for OOP or not? It would be really helpful for me.

For me, there are two decision points. First, sometimes it will be obvious at the beginning. There will be lots of similar types that all share common methods that differ widely in their implementation details. For example, I was building a workflow system, and I needed the ability to implement arbitrary tasks. To run the task, I implemented a base class that each task inherited from, with an Execute() abstract method. The inheriting classes supplied the implementation, but the workflow system could begin the execution without knowing anything about what kind of task was being run.

Most projects aren't that clear-cut though. The second decision point is when a subset of the project has grown into a huge tangle of if-then statements or switch-case statements, and especially when those if-then statements require a lot of setup code to run correctly. I feel myself starting to lose the logic of what I'm trying to accomplish, and the code starts to feel fragile. At that point, it is usually a sign that it is time to refactor the code into base classes with specific implementations.

A big part of switching to an object-oriented style as opposed to a functional style is converting if-then statements into "run this action" statements. Instead of a huge set of if-then statements, you just tell the code to run its action. Which action is actually run depends on the implementation you supplied.

For example, here's the functional style in C#-style pseudocode:

if ( action == "email" ) {
    callEmailFunction(userInfo);
}
else if ( action == "sms" ) {
    callSmsFunction(userInfo);
}
else if ( action == "web" ) {
    endpoint = "http://127.0.0.1/confirm";
    confirmWeb(endpoint, userinfo);
}
...

But maybe you could rewrite that to something like this:

interface IConfirmable {
    void Confirm(UserInfo userinfo);
}

public class ConfirmEmail : IConfirmable {
    public void Confirm(UserInfo userinfo) {
        // do the appropriate thing to confirm via email
    }
}

public class ConfirmSms : IConfirmable {
    public void Confirm(UserInfo userinfo) {
        // do the appropriate thing to confirm via email
    }
}

public class ConfirmWeb : IConfirmable {
    // this is a constructor
    public ConfirmWeb(string endpoint) {
        ...
    }

    public void Confirm(UserInfo userinfo) {
        // do the appropriate thing to confirm via web
    }
}

And then the code itself:

// An implementation that decides which implementation of the base class to use
// This replaces the if-then statements in the functional programmming.
IConfirmable confirmer = ConfirmerFactory.GetConfirmer();

// get the userinfo however you get it,
// which would be the same way you get it in the functional example.
UserInfo userinfo = ...;

// perform the action.
confirmer.Confirm(userinfo);

Now, when there is very little code inside the if-then, this looks like a lot of work to get no benefit. And when there is very little code in the if-then, that is correct: that's a lot of work for code that is harder to understand.

But the object-oriented style really shines when you have more than one action than just the Confirm() method that needs to be performed. Maybe you have an initialization routine, three or more action methods that can be run, and a Cleanup() method. The base algorithm is identical, except it makes its calls into the appropriate objects that implement a common base class. Now you start to see a real benefit to the object oriented style: the base algorithm is much easier to read than if it was checking if-then statements at every step of the way.


答:
C++ is not "just" an OO language, it is a multi-paradigm language. So it allows you to decide for or against OO programming, or to mix them both. Using OO techniques adds more structure to your program - from which you will benefit when your program reaches a certain size or complexity. This additional structure, however, comes for the price of additional lines of code. So for "small" programs the best way to go is often to implement them in a non-OO style first, and add more and more OO techniques later when the program starts to grow over the years (which will probably not happen to "exercise" programs, but is the typical life cycle for lots of business programs).

The tricky part is not to miss the point in time when the complexity of your program reaches the size which demands more structure. Otherwise you will end up with a huge pile of spaghetti code.

Title: Non-Object Oriented Programming in Object Oriented Language

Body:
Recently I was assigned a task of creating a calculator with functions addition, subtraction, multiplication, division and power using Object Oriented Programming. I successfully completed this task. However afterwards I reprogrammed the whole program without using Object Oriented technique/method.

The thing I noticed that my code length was reduced quite significantly and it was quite understandable. So my question here is when should I use Object Oriented Programming? Is it okay to create programs without Object Orientation in Object Oriented Language? Kindly help me out on this one.

PS: I am not asking here to tell me merits of Object Oriented Programming over procedural programming.


答:
Correlation, maybe.  But you have to dig still.

What if the candidate worked for the past 6 years at two different jobs.  Both of which locked down the environment and provided only IE as the available browser?

Of course, you will get used to it and start to prefer it.

But personally, there are a few things that will start to drop you to a thumbs down in my book.  The tools you use certainly indicate your experience as well as the lack of use of tools.  If you haven't tried and have an opinion on every free IDE (as one example) out there, then hit the road.

Title: Is there a useful correlation between choice of web-browser/search engine and good quality programmers?

Body:
After a round of interviews earlier this year, which included some practical questions with access to a computer, I noticed that, at least for the applicants we were seeing, there was a high inverse correlation between quality of applicant and the explicit choice of Bing/IE as the stack for search/browsing the web. That is, a large number of applicants specifically searched for IE to use as a browser when browsing the web, and specifically used Bing as the search engine (even typing in Bing in the Google search box, before starting a search)

Is this just an outlier, a fluke, or is there some sort of information I can obtain from this observation? So far, my best candidates are:

Yes, there is a high correlation between good programmers and choice of web browser/search engine

There is some training program, or community, which advises using IE/Bing during interviews, and I just happened to run into a poor selection from that group

Something else is going on, that I don't know about, but someone here might know.

So, to repeat, the question is: is there more than coincidence at work here, and, if there is, what's going on?


答:
I believe it is effect of two things:

Many programmers are not part of the "community". They don't read blogs, they don't frequent SO, they don't watch talks, etc.. That means they have no exposition to the new techniques and paradigms above what they learned in school. And they don't want to.

On the other hand, managers at least want to learn new things. They want to learn new processes and methodologies. It is just that they prefer learning the management part instead of technical part.

Case in point: Scrum. Scrum is majorly a management methodology. It doesn't talk about TDD, pair programming, refactoring, etc.. It is mostly managers who take the "Scrum Master" certifications. Compare that to the Extreme Programming, which was made by developers for developers and contains both management and technical aspects. It can be said that Scrum is just management subset of Extreme Programming.

And in the end, it is still managers who have the last world. Not developers. So when it comes to solving problems, it is management solution that is chosen. And this simply makes developers believe that those kind of solutions are the right ones.

Title: Is there a stronger stress on management than on technical education in recent years?

Body:
In my working environment, over the past few years I have observed an increasing stress on developer management and self-management over technical education.

For example, at work I hear lots of discussions about software development processes, about ways to handle software specifications, e.g. through automatic tests, and so on. I hear less discussions about programming concepts / techniques like data structures, lazy evaluation, memoization, and so on.

To give another example, if I asked a colleague how he would manage the complexity of a certain problem, I would expect that he'd indicate me some solution approach (try to solve a subproblem first, identify subtasks) instead of suggesting a programming abstraction (try using pattern X).

Is it just something specific to my working environment or there is a general trend towards management / work organization and away from the more conceptual aspects of programming?

To make my question specific (and answerable), are there any authors or modern schools of thought that consider organizational aspects more important than educational ones for improving developer productivity?


答: Yes, it is perfectly normal to use old style code, provided the scope of your project is well known or is limited. If you plan on extending your program or project OOP is one way to go, because you can maintain and extend your code seamlessly, on the other hand  if you planned it and have come to a conclusion that you are never going to plan extensibility of the project you make then writing code without OOP would suffice. It doesn't mean if you use non OOP approach you can never upgrade your project but then it would be a tedious thing to do. OOP is to help us visualize our concept as though it were a real life organism because we understand those better than anything else.</p>


问:
JSP without .jsp-files?
I have a little project (a CMS) that was developed using .jsp-files in 2006. I moved in 2011 to JSF and had only one .jsp-file for the frontend.

In 2014 I integrated the backend into the frontend using JSON and kicked all .jsp-files. I only use servlets now to build JSON-Answers, AJAX-Answers for XHTML and binary streams servlets for binary data. No .jsp-files anymore.

JSP means Java Server Pages and I don't know if this means I must use .jsp-files(!) or does it mean I also can serve XHTML-Pages via Java and transport them via AJAX.

After all, can I say in the handbook it uses JSP anymore?

答:
First off, I don't see anything wrong at all in developing a CMS in Java.  As you point out, Java server hosting is no longer hard to find and expensive as it once was. Java servers also in my experience tend to be more responsive than similar servers written in, say, PHP. Yes, Java isn't trendy like Ruby on Rails or node, but trendiness isn't exactly the best way to pick a development platform.

As to your primary question, I wouldn't call it a JSP solution. People are familiar enough with the more accurate term "Java Servlets" for that to be an appropriate term, and some will even prefer it (I've seen sites kludged together with .jsp files doing jobs entirely inappropriate for them before now, and seeing something described as a JSP application makes me worry that it might be one of them).

Title: JSP without .jsp-files?


答:
I like Dave's answer, but I will say that this is how I usually think about DependencyProperties, at least with Silverlight (I think WPF is similar):

If you want to create something that can be target of a binding, you want to create a class that implements INotifyPropertyChanged.

If you want to create something that you can define in XAML and be bound to something, you want to create a derivative of DependencyObject with DependencyProperties.

Gaining that understanding was a turning point in my ability to design things in Silverlight appropriately.

Body:
How to explain DependencyProperty using real world analogy?

Why is it needed?


问:
A very simple database system with JSON
If we need to store some data in a database, but without the need of advanced SQL features, can we use this scheme (written here in Javascript / node.js) :

```<code>// the DB will be in RAM !
var myDb = {};
// read DB from disk if file exists
try { myDb = JSON.parse(fs.readFileSync(DBFILENAME)); } catch(e) { }
 // serialize to disk every minute or when process terminates
function serialize() { fs.writeFile('./myDb.json', JSON.stringify(myDb)); }
setInterval(serialize, 60 * 1000);
process.on('SIGTERM', serialize); process.on('SIGINT', serialize);

myDb['record1'] = 'foo';
myDb['record2'] = 'bar';
// ...
</code>```

See the longer version here as a gist (8 lines of code).

1) Does this DB practice have a name? Is it really so bad? Is it possible to use such a 10-lines-of-code DB system, even in production of websites that have a < 1 GB database ?

2) Scalability: until which size would this system work without performance problems?

i.e. would it work until 2GB of data on a a normal Linux server with 4GB RAM? Or would there be real performance problems?

Note: a minute seems enough to write a 2GB data to disk... Of course I admit it is 100% non-optimized, we could add diff feature between n-1th and nth writing to disk...

3) Search: can I use ready-to-use tools to do some search in such a "simple" database? Lucene, ElasticSearch, Sphinx, etc. something else?

答:
Nothing is wrong with this for development.  If it has a name, I suppose it would be a mock database.  It is not uncommon to create a mock database that can emulate very basic functionality.  You have the added advantage that you start from a scratch database each and everytime, thus you know that your program would work also for a potential empty nosql database for the same reason.

However this is not a reasonable permanent solution by any means.

Most programmers, due to the small overhead, will simply go ahead and make it work with a nosql database.  It may take slightly longer, you are also programming directly to work in production and not being forced to adapt your program and test it beforehand.

Scalability is a non-issue because you're always working in development.  If you crash your own computer, it is not that big of a deal.  The limit of such a database would be only that of your RAM (or the RAM of the computer running the server), however I think you'd find that you'll find that the program gets very slow before you even reach the point when your program will crash.

Perhaps you could adapt some searching mechanism for the mock database, but if you're going to go through the trouble, just go ahead and use a proper nosql database.  If you literally lose more than 1 hour working on this mock database, then you've wasted time.

Title: A very simple database system with JSON


问:
Why is *declaration* of data and functions necessary in C language, when the definition is written at the end of the source code?
Consider the following "C" code:

```<code>#include<stdio.h>
main()
{
  printf("func:%d",Func_i());
}

Func_i()
{
  int i=3;
  return i;
}
</code>```

Func_i() is defined at the end of the source code and no declaration is provide before its use in main(). At the very time when the compiler sees Func_i() in main(), it comes out of the main() and finds out Func_i(). The compiler somehow finds the value returned by Func_i()and gives it to printf(). I also know that the compiler cannot find the return type of Func_i(). It, by default takes(guesses?) the return type of Func_i() to be int. That is if the code had float Func_i() then the compiler would give the error: Conflicting types for Func_i().

From the above discussion we see that:

The compiler can find the value returned by Func_i().

If the compiler can find the value returned by Func_i() by coming out of the main() and searching down the source code, then why can't it find the type of Func_i(), which is explicitly mentioned.

The compiler must know that Func_i() is of type float--that's why it gives the error of conflicting types.

If the compiler knows that Func_i is of type float, then why does it still assume Func_i() to be of type int, and gives the error of conflicting types? Why don't it forcefully make Func_i() to be of type float.

I've the same doubt with the variable declaration. Consider the following "C" code:

```<code>#include<stdio.h>
main()
{
  /* [extern int Data_i;]--omitted the declaration */
  printf("func:%d and Var:%d",Func_i(),Data_i);
}

 Func_i()
{
  int i=3;
  return i;
}
int Data_i=4;
</code>```

The compiler gives the error: 'Data_i' undeclared(first use in this function).

When the compiler sees Func_i(), it goes down to the source code to find the value returned by Func_(). Why can't the compiler do the same for the variable Data_i?

Edit:

I don't know the details of the inner working of compiler, assembler, processor etc. The basic idea of my question is that if I tell(write) the return-value of the function in the source code at last, after the use of that function then the "C" language allows the computer to find that value without giving any error. Now why can't the computer find the type similarly. Why can't the type of Data_i be found as Func_i()'s return value was found. Even if I use the extern data-type identifier; statement, I am not telling the value to be returned by that identifier(function/variable). If the computer can find that value then why can't it find the type. Why do we need the forward declaration at all?

Thank you.

答:
First, you programs are valid for the C90 standard, but not for those following. implicit int (allowing to declare a function without giving its return type), and implicit declaration of functions (allowing to use a function without declaring it) are no more valid.

Second, that doesn't work as you think.

Result type are optional in C90, not giving one means an int result.  That it is also true for variable declaration (but you have to give a storage class, static or extern).

What the compiler does when seeing the Func_i is called without a previous declaration, is assuming that there is a declaration

```<code>extern int Func_i();
</code>```

it doesn't look further in the code to see how effectively Func_i is declared.  If Func_i wasn't declared or defined, the compiler would not change its behavior when compiling main.  The implicit declaration is only for function, there is none for variable.

Note that the empty parameter list in the declaration doesn't mean the function doesn't take parameters (you need to specify (void) for that), it does mean that the compiler doesn't have to check the types of the parameters and will the same implicit conversions that are applied to arguments passed to variadic functions.

Body:
First, you programs are valid for the C90 standard, but not for those following. implicit int (allowing to declare a function without giving its return type), and implicit declaration of functions (allowing to use a function without declaring it) are no more valid.

Second, that doesn't work as you think.

Result type are optional in C90, not giving one means an int result.  That it is also true for variable declaration (but you have to give a storage class, static or extern).

What the compiler does when seeing the Func_i is called without a previous declaration, is assuming that there is a declaration

extern int Func_i();

it doesn't look further in the code to see how effectively Func_i is declared.  If Func_i wasn't declared or defined, the compiler would not change its behavior when compiling main.  The implicit declaration is only for function, there is none for variable.

Note that the empty parameter list in the declaration doesn't mean the function doesn't take parameters (you need to specify (void) for that), it does mean that the compiler doesn't have to check the types of the parameters and will the same implicit conversions that are applied to arguments passed to variadic functions.


答:
A design constraint of the C language was that it was supposed to be compiled by a single-pass compiler, which makes it suitable for very memory-constrained systems. Therefore, the compiler knows at any point only about stuff that was mentioned before. The compiler can't skip forward in the source to find a function declaration and then go back to compile a call to that function. Therefore, all symbols ought to be declared before they are used. You can pre-declare a function like

```<code>int Func_i();
</code>```

at the top or in a header file to help the compiler.

In your examples, you use two dubious features of the C language that should be avoided:

If a function is used before it was properly declared, this is used as an “implicit declaration”. The compiler uses the immediate context to figure out the function signature. The compiler will not scan through the rest of the code to figure out what the real declaration is.

If something is declared without a type, the type is taken to be int. This is e.g. the case for static variables or function return types.

So in printf("func:%d",Func_i()), we have an implicit declaration int Func_i(). When the compiler reaches the function definition Func_i() { ... }, this is compatible with the type. But if you wrote float Func_i() { ... } at this point, you have the implicity declared int Func_i() and the explicitly declared float Func_i(). Since the two declarations don't match, the compiler gives you an error.

Clearing up some misconceptions

The compiler does not find the value returned by Func_i. The absence of an explicit type means that the return type is int by default. Even if you do this:

```<code>Func_i() {
    float f = 42.3;
    return f;
}
</code>```

then the type will be int Func_i(), and the return value will be silently truncated!

The compiler eventually gets to know the real type of Func_i, but it does not know the real type during the implicit declaration. Only when it later reaches the real declaration can it find out whether the implicitly declared type was correct. But at that point, the assembly for the function call might already have been written and can't be changed in the C compilation model.

Title: Why is *declaration* of data and functions necessary in C language, when the definition is written at the end of the source code?

Body:
Consider the following "C" code:

```<code>#include<stdio.h>
main()
{
  printf("func:%d",Func_i());
}

Func_i()
{
  int i=3;
  return i;
}
</code>```

Func_i() is defined at the end of the source code and no declaration is provide before its use in main(). At the very time when the compiler sees Func_i() in main(), it comes out of the main() and finds out Func_i(). The compiler somehow finds the value returned by Func_i()and gives it to printf(). I also know that the compiler cannot find the return type of Func_i(). It, by default takes(guesses?) the return type of Func_i() to be int. That is if the code had float Func_i() then the compiler would give the error: Conflicting types for Func_i().

From the above discussion we see that:

The compiler can find the value returned by Func_i().

If the compiler can find the value returned by Func_i() by coming out of the main() and searching down the source code, then why can't it find the type of Func_i(), which is explicitly mentioned.

The compiler must know that Func_i() is of type float--that's why it gives the error of conflicting types.

If the compiler knows that Func_i is of type float, then why does it still assume Func_i() to be of type int, and gives the error of conflicting types? Why don't it forcefully make Func_i() to be of type float.

I've the same doubt with the variable declaration. Consider the following "C" code:

```<code>#include<stdio.h>
main()
{
  /* [extern int Data_i;]--omitted the declaration */
  printf("func:%d and Var:%d",Func_i(),Data_i);
}

 Func_i()
{
  int i=3;
  return i;
}
int Data_i=4;
</code>```

The compiler gives the error: 'Data_i' undeclared(first use in this function).

When the compiler sees Func_i(), it goes down to the source code to find the value returned by Func_(). Why can't the compiler do the same for the variable Data_i?

Edit:

I don't know the details of the inner working of compiler, assembler, processor etc. The basic idea of my question is that if I tell(write) the return-value of the function in the source code at last, after the use of that function then the "C" language allows the computer to find that value without giving any error. Now why can't the computer find the type similarly. Why can't the type of Data_i be found as Func_i()'s return value was found. Even if I use the extern data-type identifier; statement, I am not telling the value to be returned by that identifier(function/variable). If the computer can find that value then why can't it find the type. Why do we need the forward declaration at all?

Thank you.

Body:
A design constraint of the C language was that it was supposed to be compiled by a single-pass compiler, which makes it suitable for very memory-constrained systems. Therefore, the compiler knows at any point only about stuff that was mentioned before. The compiler can't skip forward in the source to find a function declaration and then go back to compile a call to that function. Therefore, all symbols ought to be declared before they are used. You can pre-declare a function like

int Func_i();

at the top or in a header file to help the compiler.

In your examples, you use two dubious features of the C language that should be avoided:

If a function is used before it was properly declared, this is used as an “implicit declaration”. The compiler uses the immediate context to figure out the function signature. The compiler will not scan through the rest of the code to figure out what the real declaration is.

If something is declared without a type, the type is taken to be int. This is e.g. the case for static variables or function return types.

So in printf("func:%d",Func_i()), we have an implicit declaration int Func_i(). When the compiler reaches the function definition Func_i() { ... }, this is compatible with the type. But if you wrote float Func_i() { ... } at this point, you have the implicity declared int Func_i() and the explicitly declared float Func_i(). Since the two declarations don't match, the compiler gives you an error.

Clearing up some misconceptions

The compiler does not find the value returned by Func_i. The absence of an explicit type means that the return type is int by default. Even if you do this:

Func_i() {
    float f = 42.3;
    return f;
}

then the type will be int Func_i(), and the return value will be silently truncated!

The compiler eventually gets to know the real type of Func_i, but it does not know the real type during the implicit declaration. Only when it later reaches the real declaration can it find out whether the implicitly declared type was correct. But at that point, the assembly for the function call might already have been written and can't be changed in the C compilation model.


答:
C and a number of other languages which require declarations were designed in an era when processor time and memory were expensive. The development of C and Unix went hand in hand for quite some time, and the latter didn't have virtual memory until 3BSD appeared in 1979.  Without the extra room to work, compilers tended to be single-pass affairs because they didn't require the ability to keep some representation of the entire file in memory all at once.

Single-pass compilers are, like us, saddled with an inability to see into the future.  This means the only things they can know for sure are what they've been told explicitly before the line of code being compiled.  It's plain to either of us that Func_i() is declared later in the source file, but the compiler, which operates on a small chunk of code at a time, has no clue it's coming.

In early C (AT&T, K&R, C89), use of a function foo() before declaration resulted in a de facto or implicit declaration of int foo().  Your example works works when Func_i() is declared int because it matches what the compiler declared on your behalf.  Changing it to any other type will result in a conflict because it no longer matches what the compiler chose in the absence of an explicit declaration.  This behavior was removed in C99, where use of an undeclared function became an error.

So what about return types?

The calling convention for object code in most environments requires knowing only the address of the function being called, which is relatively easy for compilers and linkers to deal with.  Execution jumps to the start of the function and comes back when it returns.  Anything else, notably arrangements of passing arguments and a return value, is determined entirely by the caller and callee in an arrangement called a calling convention.  As long as both share the same set of conventions, it becomes possible for a program to call functions in other object files whether they were compiled in any language that shares those conventions.  (In scientific computing, you run into a lot of C calling FORTRAN and vice versa, and the ability to do that comes from having a calling convention.)

One other feature of early C was that prototypes as we know them now didn't exist.  You could declare a function's return type (e.g., int foo()), but not its arguments (i.e., int foo(int bar) was not an option).  This existed because, as outlined above, the program always stuck to a calling convention that could be determined by the arguments.  If you called a function with the wrong type of arguments, it was a garbage in, garbage out situation.

Because object code has the notion of a return but not a return type, a compiler has to know the return type to deal with the value returned.  When you're running machine instructions, it's all just bits and the processor doesn't care whether the memory where you're trying to compare a double actually has an int in it.  It just does what you ask, and if you break it, you own both pieces.

Consider these bits of code:

```<code>double foo();         double foo();
double x;             int x;
x = foo();            x = foo();
</code>```

The code on the left compiles down to a call to foo() followed by copying the result provided via the call/return convention into wherever x is stored.  That's the easy case.

The code on the right shows a type conversion and is why compilers need to know a function's return type.  Floating-point numbers can't be dumped into memory where other code will expect to see an int because there's no magic conversion that takes place.  If the end result has to be an integer, there have to be instructions that guide the processor to make the conversion before storage.  Without knowing the return type of foo() ahead of time, the compiler would have no idea that conversion code is necessary.

Multi-pass compilers enable all sorts of things, one of which is the ability to declare variables, functions and methods after they're first used.  This means that when the compiler gets around to compiling the code, it has already seen the future and knows what to do.  Java, for example, mandates multi-pass by virtue of the fact that its syntax allows declaration after use.

Body:
C and a number of other languages which require declarations were designed in an era when processor time and memory were expensive. The development of C and Unix went hand in hand for quite some time, and the latter didn't have virtual memory until 3BSD appeared in 1979.  Without the extra room to work, compilers tended to be single-pass affairs because they didn't require the ability to keep some representation of the entire file in memory all at once.

Single-pass compilers are, like us, saddled with an inability to see into the future.  This means the only things they can know for sure are what they've been told explicitly before the line of code being compiled.  It's plain to either of us that Func_i() is declared later in the source file, but the compiler, which operates on a small chunk of code at a time, has no clue it's coming.

In early C (AT&T, K&R, C89), use of a function foo() before declaration resulted in a de facto or implicit declaration of int foo().  Your example works works when Func_i() is declared int because it matches what the compiler declared on your behalf.  Changing it to any other type will result in a conflict because it no longer matches what the compiler chose in the absence of an explicit declaration.  This behavior was removed in C99, where use of an undeclared function became an error.

So what about return types?

The calling convention for object code in most environments requires knowing only the address of the function being called, which is relatively easy for compilers and linkers to deal with.  Execution jumps to the start of the function and comes back when it returns.  Anything else, notably arrangements of passing arguments and a return value, is determined entirely by the caller and callee in an arrangement called a calling convention.  As long as both share the same set of conventions, it becomes possible for a program to call functions in other object files whether they were compiled in any language that shares those conventions.  (In scientific computing, you run into a lot of C calling FORTRAN and vice versa, and the ability to do that comes from having a calling convention.)

One other feature of early C was that prototypes as we know them now didn't exist.  You could declare a function's return type (e.g., int foo()), but not its arguments (i.e., int foo(int bar) was not an option).  This existed because, as outlined above, the program always stuck to a calling convention that could be determined by the arguments.  If you called a function with the wrong type of arguments, it was a garbage in, garbage out situation.

Because object code has the notion of a return but not a return type, a compiler has to know the return type to deal with the value returned.  When you're running machine instructions, it's all just bits and the processor doesn't care whether the memory where you're trying to compare a double actually has an int in it.  It just does what you ask, and if you break it, you own both pieces.

Consider these bits of code:

double foo();         double foo();
double x;             int x;
x = foo();            x = foo();

The code on the left compiles down to a call to foo() followed by copying the result provided via the call/return convention into wherever x is stored.  That's the easy case.

The code on the right shows a type conversion and is why compilers need to know a function's return type.  Floating-point numbers can't be dumped into memory where other code will expect to see an int because there's no magic conversion that takes place.  If the end result has to be an integer, there have to be instructions that guide the processor to make the conversion before storage.  Without knowing the return type of foo() ahead of time, the compiler would have no idea that conversion code is necessary.

Multi-pass compilers enable all sorts of things, one of which is the ability to declare variables, functions and methods after they're first used.  This means that when the compiler gets around to compiling the code, it has already seen the future and knows what to do.  Java, for example, mandates multi-pass by virtue of the fact that its syntax allows declaration after use.


问:
Help, team members out of tasks want to start with future sprints topics
I have this problem, a team with 4 members working under scrum, with specific skills each one of them:

Person A) DBA with reporting skills

Person B) DBA with stored procedure skills and a very deep knowledge of the business

Person C) Developer

Person D) Tester

Problem 1

Right now, we're at the end of sprint 6, Person A has ran out of tasks, and he wants to start working on sprint 7 issues. I have explained to the whole team that we must focus on finish sprint 6 functionalities, and not to think about independent tasks, but it is not being really accepted. On despite off they team is not working on sprint 7, they're not really convinced about it.

Problem 2

We will have the sprint 7 planning meeting on wednesday, and the team wants to talk separately to the PO in order to ask him questions about the User Stories, Person C argues that listening to "person A" talk with the PO is a waste of time for him, and he prefers to start working in other tasks that he knows he can start working and has enough information

What I understand so far is that the team should not start with tasks belonging to a different sprint because it would lead to lose the focus on the current sprint goal, the whole team should be involved on getting the work done as a team and not as separate members. We're not playing tetris trying to accommodate tasks as if they were shapes that could be arranged, we're delivering a specific set of functionalities.

I want to convince them, but I'm running out of arguments and I need help to get the team back in focus.

Am I wrong about it?
Any advice?

答:
When we started practicing scrum, we kind of dropped our specialisms and individual projects, instead we started working as one team. While I am more of an expert in Unity3D and C# and we have another team member who is more skilled with Node.js (etc), we ensure that we are spreading the knowledge of the projects.

One thing agile and scrum are in favour of, is spreading knowledge in the team. If you only have one person that can make changes to the database due to their knowledge then what do you do when that person is away and your PO wants you to make changes? As well as this, agile is about keeping things open. If just one person works on a project, you get worse code and a worse project than if all of the team takes part in it.

In scrum, if one team member finishes a task, they pick up another one. By the sounds if it, your team is still stuck trying to manage their own projects and their own tasks. To me this seems to be fighting against what scrum is trying to do for your team.

I.E.: I may not be fantastic at Node.js and it may take me longer, I may even choose to pick up mostly Unity or C# work as I feel more comfortable with it. But if all the tasks in that area are complete and there are still outstanding tasks in the sprint, I pick up what's left. I don't get to just pack up and go home, or start on new backlog issues.

Scrum intentionally spreads the knowledge and stops things being "my project",  "his area" or "her task". Everything becomes the "teams", if a task isn't done by the end of the sprint then the team has failed at completing that task. No single individual is responsible for it, everyone is.

I think your team need to get their heads around the idea that every project is the teams project and if there are things to be done, anyone can picks them up. So in this case Person A should be picking up any more out standing tasks still on the sprint. This is also the reason that all persons are involved in sprint planning meetings (for estimation and such). It ensures quality and makes sure that the team is moving as a team.


问:
How do you unit test a function that clears properties?
I have a very common function that I have always unit tested in the same way, but I'm wondering if there is a better solution or if it's even possible a code smell is involved. It seems like a very simple case but I have a function that clears the properties of the object. Working in JavaScript, here is a simple example:

```<code>function Dog(name, owner) {
  this.name = name;
  this.owner = owner;

  this.reset = function() {
    this.name = '';
    this.owner = '';
  };
}

var puppy = new Dog('Max', 'Timmy');
console.log(puppy.name)  // logs "Max"
puppy.reset();
console.log(puppy.name)  // logs ""
</code>```

I would normally unit test by setting the properties, calling the clear function, and then asserting that the properties were indeed set back to the defaults or "cleared out". The reason I'm asking about such a simple solution is because of the dogma that unit tests should only have 1 assertion. I also think that a "reset" type function could get way out of hand when it is dealing with a large number of properties (i.e. an object that is meant to store a SPA's state).

I'm sure that I am over-thinking this but wanted to get some outside opinion/criticism for something I have been doing the same for many years. I just cannot possibly think of a better way to do this.

Another question could be, are unit tests surrounding a reset function necessary? To me they seem to almost just test the language implementation -- similar to a getter/setter property.

答:
You could add a function that returns the properties in their default state enclosed in an object and then another that returns their current state. Compare the returning values of each of those functions and assert accordingly.

In this particular example, you should be able to assert true that puppy.reset().getNameAndOwner() should be equal to puppy.getDefaultState(). (There's a link for Object comparison at the bottom of my post. Do NOT use == or ===)

See below

```<code>function Dog(name, owner) {
   this.name = name || '';
   this.owner = owner || '';

   this.reset = function() {
       this.name = '';
       this.owner = '';
   };

   this.getNameAndOwner = function() {
       var name = this.name
           owner = this.owner;
       return { name: name, owner: owner };
   }

   this.defaultState = function() {
       var emptyName = '',
           emptyOwner = '';
       return { name: emptyName, owner: emptyOwner };
   }
}
</code>```

How to compare objects:

Object comparison in JavaScript

How to determine equality for two JavaScript objects?

Body:
You could add a function that returns the properties in their default state enclosed in an object and then another that returns their current state. Compare the returning values of each of those functions and assert accordingly.

In this particular example, you should be able to assert true that puppy.reset().getNameAndOwner() should be equal to puppy.getDefaultState(). (There's a link for Object comparison at the bottom of my post. Do NOT use == or ===)

See below

function Dog(name, owner) {
   this.name = name || '';
   this.owner = owner || '';

   this.reset = function() {
       this.name = '';
       this.owner = '';
   };

   this.getNameAndOwner = function() {
       var name = this.name
           owner = this.owner;
       return { name: name, owner: owner };
   }

   this.defaultState = function() {
       var emptyName = '',
           emptyOwner = '';
       return { name: emptyName, owner: emptyOwner };
   }
}

How to compare objects:

Object comparison in JavaScript

How to determine equality for two JavaScript objects?


答:
You are over-thinking the "one assertion" rule/guideline.

The reason for the rule is that a test case should test only one "behaviour" of a class. By testing only one behaviour per test case, you make it much easier on yourself to pinpoint where an error got introduced when a test case starts failing.

The problem is that it is hard to tell when that basic rule of testing only one behaviour is being violated, also because people might disagree what falls under "one behaviour".

However, in the large majority of cases, the one behaviour that you want to test can be verified with a single assert statement. For that reason, the rule is being stated as "you shall have only a single assert".

For the minority of cases where a single, indivisible action of the class has multiple outputs and/or side effects (like your reset method), it is perfectly fine to have multiple assert statements. In fact, you are still asserting just one thing, namely that all properties have been cleared.

Title: How do you unit test a function that clears properties?

Body:
I have a very common function that I have always unit tested in the same way, but I'm wondering if there is a better solution or if it's even possible a code smell is involved. It seems like a very simple case but I have a function that clears the properties of the object. Working in JavaScript, here is a simple example:

```<code>function Dog(name, owner) {
  this.name = name;
  this.owner = owner;

  this.reset = function() {
    this.name = '';
    this.owner = '';
  };
}

var puppy = new Dog('Max', 'Timmy');
console.log(puppy.name)  // logs "Max"
puppy.reset();
console.log(puppy.name)  // logs ""
</code>```

I would normally unit test by setting the properties, calling the clear function, and then asserting that the properties were indeed set back to the defaults or "cleared out". The reason I'm asking about such a simple solution is because of the dogma that unit tests should only have 1 assertion. I also think that a "reset" type function could get way out of hand when it is dealing with a large number of properties (i.e. an object that is meant to store a SPA's state).

I'm sure that I am over-thinking this but wanted to get some outside opinion/criticism for something I have been doing the same for many years. I just cannot possibly think of a better way to do this.

Another question could be, are unit tests surrounding a reset function necessary? To me they seem to almost just test the language implementation -- similar to a getter/setter property.


问:
What is the "default" software license?
If I release some code and binaries, but I don't include any license at all with it, what are the legal terms that apply by default (in the US, where I am). I know that I automatically have copyright without doing anything, but what restrictions are there on it?

If I upload my code to github and announce it as a free download / contribute at will, then are people allowed to modify and close source my work? I haven't said that they cannot, as a GPL would, but I don't feel that it would by default be acceptable to steal my work either.

So what can and cannot people do with code that is freely available, but has absolutely no licensing terms attached?

答:
If you provide no license, then all restrictions come from copyright law.

IANAL, but this is how I understand US law.  If you want legal advice you can rely on, find somebody competent to give it in the jurisdiction you're interested in.

It is possible for the copyright holder or licensee (if permitted by the license) to distribute copies.  Therefore, if I have code with no license, put it on a web site, and say "Feel free to download this", you may download it.

Once downloaded legitimately, you have a legal copy.  You can make one backup copy, and use it as you like.  You can run it, since US copyright law allows all copies necessary to run legally acquired software.  You can, I believe, modify it for your own use (I can modify books I buy, after all).  You can transfer your copy to another person, provided you don't keep a copy on your own.  You can't legally run your copy on more than one machine at a time (although "machine" may be legally fuzzy here).

I don't know if you could keep downloading copies and selling them; ask a lawyer.

You would also have all "fair use" rights, but those are fairly limited, and apply on a case-by-case basis.

If you don't want people to use your software, don't offer it to them.  If you do want them to, come up with a license.  An OSI-certified Open Source license has the advantage that it's been vetted for problems, and there's a general understanding of what it means.

Title: What is the "default" software license?


答:
You wrote in a comment:

The execution is done line-by-line. The only way to find the value returned by Func_i() is to jump out of the main

That's a misconception: Execution isn't don line-by-line. Compilation is done line by line, and name resolution is done during compilation, and it only resolves names, not return values.

A helpful conceptual model is this: When the compiler reads the line:

```<code>  printf("func:%d",Func_i());
</code>```

it emits code equivalent to:

```<code>  1. call "function #2" and put the return value on the stack
  2. put the constant string "func:%d" on the stack
  3. call "function #1"
</code>```

The compiler also makes a note in some internal table that function #2 is a not yet declared function named Func_i, that takes an unspecified number of arguments and returns an int (the default).

Later, when it parses this:

```<code> int Func_i() { ...
</code>```

the compiler looks up Func_i in the table mentioned above and checks if the parameters and the return type match. If they don't, it stops with an error message. If they do, it adds the current address to the internal function table and goes on to the next line.

So, the compiler didn't "look" for Func_i when it parsed the first reference. It simply made a note in some table, the went on parsing the next line. And at the end of the file, it has an object file, and a list of jump addresses.

Later, the linker takes all this, and replaces all pointers to "function #2" with the actual jump address, so it emits something like:

```<code>  call 0x0001215 and put the result on the stack
  put constant ... on the stack
  call ...
...
[at offset 0x0001215 in the file, compiled result of Func_i]:
  put 3 on the stack
  return top of the stack
</code>```

Much later, when the executable file is run, the jump address is already resolved, and the computer can just jump to address 0x1215. No name lookup required.

Disclaimer: As I said, that's a conceptual model, and the real world is more complicated. Compilers and linkers do all kinds of crazy optimizations today. They even might "jump up an down" to look for Func_i, although I doubt it. But the C languages is defined in a way that you could write a super-simple compiler like that. So most of the time, it's a very useful model.

Body:
You wrote in a comment:

The execution is done line-by-line. The only way to find the value returned by Func_i() is to jump out of the main

That's a misconception: Execution isn't don line-by-line. Compilation is done line by line, and name resolution is done during compilation, and it only resolves names, not return values.

A helpful conceptual model is this: When the compiler reads the line:

  printf("func:%d",Func_i());

it emits code equivalent to:

  1. call "function #2" and put the return value on the stack
  2. put the constant string "func:%d" on the stack
  3. call "function #1"

The compiler also makes a note in some internal table that function #2 is a not yet declared function named Func_i, that takes an unspecified number of arguments and returns an int (the default).

Later, when it parses this:

 int Func_i() { ...

the compiler looks up Func_i in the table mentioned above and checks if the parameters and the return type match. If they don't, it stops with an error message. If they do, it adds the current address to the internal function table and goes on to the next line.

So, the compiler didn't "look" for Func_i when it parsed the first reference. It simply made a note in some table, the went on parsing the next line. And at the end of the file, it has an object file, and a list of jump addresses.

Later, the linker takes all this, and replaces all pointers to "function #2" with the actual jump address, so it emits something like:

  call 0x0001215 and put the result on the stack
  put constant ... on the stack
  call ...
...
[at offset 0x0001215 in the file, compiled result of Func_i]:
  put 3 on the stack
  return top of the stack

Much later, when the executable file is run, the jump address is already resolved, and the computer can just jump to address 0x1215. No name lookup required.

Disclaimer: As I said, that's a conceptual model, and the real world is more complicated. Compilers and linkers do all kinds of crazy optimizations today. They even might "jump up an down" to look for Func_i, although I doubt it. But the C languages is defined in a way that you could write a super-simple compiler like that. So most of the time, it's a very useful model.


答:
Unit tests should cover logic, and as a matter of fact, reset doesn't contain any logic - there is no ifs, no switches, no loops in it - basically, no conditional statements of any type.

And yes, it means that testing it sort of boils down to testing JavaScript as such, as you say. Set a, b, and c to empty strings! Have a, b and c been set to empty strings? Good. Good JavaScript!

So, given there's no logic, why would we want unit test coverage here at all?

I guess we'd wish to have it in order to protect ourselves against the scenario in which you're adding another property to the class, but then forget to reset it in your reset function.

The problem here is that you would also have to update your unit test to reveal this bug, and if you forgot about updating your reset function, it stands to reason you would have failed to update testReset, too.

Or your little special function that returns all the contents of your singleton, nicely packed for testing purposes.

One possible alternative would be to use reflection (in case of JavaScript, it's just iterating over properties of course) for resetting all properties in existence, and then only unit test it as a universal utility, even on an arbitrary stub class.

Of course you're likely to get into more problems if you want to actually preserve the value of some of your properties rather than wipe everything clean.

All in all, it's a difficult task because that's a singleton you have to reset. Singletons are notoriously bad for testability.

Misko Hevery devoted a series of articles and presentations to that. See:

Root cause of singletons (article)

Singletons are pathological liers (article)

The Clean Code Talks - "Global State and Singletons" (video)


答:
An alternative approach is two tests, one for each component of your reset function. Or more, if you have more. These would be pretty simple to create.

A key point of tests is to know what is failing when something fails. If you test the "reset" method and it fails you want to know what failed. While not super important in your example, other situations like this might be much less clear which part is failing.

By testing each individual variable, as long as your workflow is writing a failing test when you add new variables, say Breed to your dog, you will be forced to add Breed to the reset function because you immediately have a failing test.