问:
is JS a gradually typed language?
I was researching on statically typed and dynamically typed concepts and found out there is another type system called gradually typed.

From wikipedia

Gradual typing is a type system in which variables may be typed either at compile-time (static typing) or at run-time (dynamic typing), allowing software developers to choose either type paradigm as appropriate, from within a single language.

In particular, gradual typing uses a special type named dynamic to represent statically-unknown types and gradual typing replaces the notion of type equality with a new relation called consistency (aka. compatibility) that relates the dynamic type to every other type. The consistency relation is symmetric but not transitive

If I understand those concepts correctly, "Javascript" is a gradually typed language. Am I correct?

答:
Mixing static and dynamic typing is still very much an open research issue with several competing approaches, including but not limited to Jeremy Siek's Gradual Typing (which you mentioned), Quasi-Static Typing, Soft Typing, Hybrid Typing (Flanagan), Optional Static Typing (championed for example by Gilad Bracha), Blame Calculus (Wadler and Findler), Coercion Calculus (Henglein), Contracts (Findler and Felleisen), Manifest Contracts (Greenberg, Pierce, and Weirich) and many more.

ECMAScript / JavaScript is not gradually typed. It would be stupid to add something that is still an open research problem to a production language such as ECMAScript. A language design committee is not the place to do cutting-edge research.

Actually, the ECMAScript committee tried to do cutting-edge research by mixing static and dynamic typing in ECMAScript 4 … and that was a spectacular failure.

ECMAScript / JavaScript are dynamically typed. There are no static types, nor is there syntax for type annotations.

Title: is JS a gradually typed language?


问:
Is there a benefit in compiling your code as you go along?
I recently had a job interview in which they gave me an hour to write some real code.  It wasn't a huge amount, probably less than 100 lines.  After about 45 minutes, I compiled, ran it, and got it to work.  I may have spent 5-10 minutes working out compile errors and a couple minor bugs, but overall it was very smooth.  (Incidentally, I did get an offer from them.)

However, what puzzled me was that after I handed over the completed code, the interviewer told me that the only thing I did wrong was "not compiling as I go along".  I asked him what the difference is, and he said "what would you have done if you finished the code and it didn't compile in time".

In my understanding that's an invalid argument, because "getting code to compile" for a given length of code generally involves fixing a constant number of compile errors and takes a fairly constant amount of time, which should be the same whether you do it after you finish writing the code, or if you interleave it with your coding time.  If anything, interrupting your coding to search for missing semicolons would probably be detrimental to your efficiency.  Except in extreme circumstances when I'm experimenting with obscurities around edge-cases on things like virtual functions in derived classes, etc. it seems reasonable to expect that code written by a an experienced developer will compile, minus the occasional typing error, and even if it doesn't, it's not as if I would have to rewrite a portion of the code in order to fix the compile error.

In another similar incident, I was given an incomplete codebase in an interview, and asked to finish it and make necessary modifications to get it running.  I started by reading through the existing code, and then after a few minutes (even before I had finished looking at the code), the interviewer told me that's enough.  When I asked him what he would have done (i.e. "what did I do wrong"), he told me that he would have started by immediately getting the code to compile.

Why is that even relevant?  In my opinion and in my experience, whether or not a piece of code compiles is essentially random, involving things like whether or not semicolons are missing, and has little to do with the correctness of the underlying program.  (To me, focusing on compiling is like running an article through a spell-check without proofreading to check the grammar.)

If you give me a piece of incomplete code, the first thing I do will be to read it.  I won't even try to compile it until I know what the code is doing and I know the algorithm is correct.

Anyway, these have been just a couple recent incidents, but in general I've heard many developers talk about compiling their code as they go along, and yet nobody has been able to tell me the benefit of doing so.  I understand the benefits of testing your code as you go along, but why compiling?

So my question is this: Is there something I missed?  Is there actually a benefit to compiling as you go along?  Or is this some sort of myth propagated by the software community that you must compile your code frequently?

答:
Is there actually a benefit to compiling as you go along?

There is. It gives you a shorter feedback loop - which in general, when designing (UI, writing software, visual design etc...) is a good thing.

A short feedback loop means you can quickly fix errors early on, before they become more expensive to fix.

To borrow your example, say you were coding in a C-like language and forgot a } somewhere in the middle of the program.

If you compile just after you finish writing the statement, you can be quite certain you have just introduced the compilation error and can fix it there and then, within seconds.

If you don't, however, you would have to spend a good amount of time reading the code, looking for the exact position that the } is and making sure, once you have located the error that the fix is indeed what was intended. This would take place a while after you left that bit of code. It wouldn't be as crystal clear as during the moment you wrote it.

Now, yes, the end result is the same, but you wasted a good amount of time on syntactical issues that the compiler is there to help you with - an amount of time that could be significantly shorter if you compiled as you went along.

ContentLicense: CC BY-SA 3.0


问:
Is modifying an incoming parameter an antipattern?
I am programming in Java, and I always make converters sort of like this:

```<code>public OtherObject MyObject2OtherObject(MyObject mo){
    ... Do the conversion
    return otherObject;
}
</code>```

At the new workplace the pattern is:

```<code>public void MyObject2OtherObject(MyObject mo, OtherObject oo){
    ... Do the conversion
}
</code>```

For me it is a little bit smelly, as I got used to not to change the incoming parameters. Is this incoming parameter alteration an antipattern or is it OK? Does it have some serious drawbacks?

答: I don't think those are two equivalent pieces of code. In first case, you have to create the otherObject. You can modify existing instance in the second. Both have it's uses. Code smell would be preferring one over another.


答:
Quoting Robert C. Martin's famous book "Clean Code":

Output arguments should be avoided

Functions should have a small numbers of arguments

The second pattern violates both rules, particularly the "output argument" one. In this sense it is worse than the first pattern.

Title: Is modifying an incoming parameter an antipattern?

Body:
I am programming in Java, and I always make converters sort of like this:

```<code>public OtherObject MyObject2OtherObject(MyObject mo){
    ... Do the conversion
    return otherObject;
}
</code>```

At the new workplace the pattern is:

```<code>public void MyObject2OtherObject(MyObject mo, OtherObject oo){
    ... Do the conversion
}
</code>```

For me it is a little bit smelly, as I got used to not to change the incoming parameters. Is this incoming parameter alteration an antipattern or is it OK? Does it have some serious drawbacks?


问:
Is it possible to have a single code base for a desktop GUI and a web application?
The required user interface is fairly simple; basically, two tables that "interact with each other", e.g. certain rows in one table get highlighted when a row in the other is clicked, plus maybe a panel with charts.

Is it possible to have a (largely) single code base for a desktop app and a web app implementing this interface? For a few reasons, it would be good to have both versions, but I would hate to implement the GUI twice.

The details of my particular case are as follows:

This is an academic research problem, so I don't have strict constraints in terms of tools and the coding style (or users!). On the other hand, I do have quite some time constraints.

It has to run on bare JVM, but any language/framework would be welcome (Java, Groovy, Scala, Clojure, etc.).

There is no persistent state, i.e. no strict need in a shared DB or any server part whatsoever.

I would be willing to go through some design hoops to make it work (by design hoops I mean some unconventional application architecture).

Is it completely crazy to even think about something like that? If no, what would be the tools to pull it off?

答: It's possible through RAP with a single code base to develop a Web application which can be also installed as a Desktop application. Here is the link - http://eclipse.org/rap/</p>


答:
The advantage of the second pattern is that it forces the caller to take ownership and responsibility for the created object. There is no question whether or not the method created the object or got it from a reusable pool.
The caller knows that they are responsible for the lifetime and disposal of the new object.

The disadvantages of this method are:

Can not be used as a factory method, the caller must know the exact subtype of OtherObject it needs and construct it in advance.

Can not be used with objects that require parameters in their constructor if those parameters come from MyObject. OtherObject must be constructable without knowing about MyObject.

The answer is based on my experience in c#, I hope the logic translates to Java.


答:
So my question is this: Is there something I missed?

Yes: your mind is not a compiler. While a compiler can make n context switches per second, your mind cannot. The number of context switches your mind can make in a day depends on a number of factors like experience/familiarity with code base, how mentally immersed you are in the code, how clean the code is, how complex is the problem you are tackling, how tired you are, if you are frequently interrupted or in a noisy environment and so on.

Compiling a code base (all at the same time), for the first time (think "project with 20 files") will force you to switch context from what you are thinking about (e.g. "this value is set to 5 here, then in the for loop blablabla, and the complex algorithm yields the correct value on return") to a compilation problem that is completely unrelated to what you are thinking about (different file/module/function/pre-conditions/syntax/variable names, preconditions etc).

The more code you compile at once, the more context switching your mind has to make. This is not a problem for a small code base, when all the code you wrote is whatever you wrote in one hour. It is a big problem though, when working in an existing code base, with multiple (and many times undocumented) interdependencies.

Is there actually a benefit to compiling as you go along?

You minimize the context switches your mind has to make, allowing you to focus more on the impact and side effects of the changes you make. It also makes you less tired (and less prone to mistakes) and increases the quality of your output (i.e. you can guarantee minimized side effects easier when you change and compile one file at a time, than when you compile and change ten).

If you compile in very short iterations (this assumes the compilation process is optimized to take a short time) it is possible to fix compilation errors without getting out of "the zone".

Or is this some sort of myth propagated by the software community that you must compile your code frequently?

It is propagated by the software comunity as well, but it has good reasons behind it.

In my understanding that's an invalid argument, because "getting code to compile" for a given length of code generally involves fixing a constant number of compile errors and takes a fairly constant amount of time

It sounds to me like you have little (to no) experience, in maintenance of medium to large legacy code bases (hundreds or thousands of source files). This is where this attitude (i.e. "compile as you go") will help the most, and this is where you form this kind of habit.

I would imagine that the people who inteviewed you drew a similar conclusion ("you have little to no experience in large code bases").

Title: Is there a benefit in compiling your code as you go along?

Body:
I recently had a job interview in which they gave me an hour to write some real code.  It wasn't a huge amount, probably less than 100 lines.  After about 45 minutes, I compiled, ran it, and got it to work.  I may have spent 5-10 minutes working out compile errors and a couple minor bugs, but overall it was very smooth.  (Incidentally, I did get an offer from them.)

However, what puzzled me was that after I handed over the completed code, the interviewer told me that the only thing I did wrong was "not compiling as I go along".  I asked him what the difference is, and he said "what would you have done if you finished the code and it didn't compile in time".

In my understanding that's an invalid argument, because "getting code to compile" for a given length of code generally involves fixing a constant number of compile errors and takes a fairly constant amount of time, which should be the same whether you do it after you finish writing the code, or if you interleave it with your coding time.  If anything, interrupting your coding to search for missing semicolons would probably be detrimental to your efficiency.  Except in extreme circumstances when I'm experimenting with obscurities around edge-cases on things like virtual functions in derived classes, etc. it seems reasonable to expect that code written by a an experienced developer will compile, minus the occasional typing error, and even if it doesn't, it's not as if I would have to rewrite a portion of the code in order to fix the compile error.

In another similar incident, I was given an incomplete codebase in an interview, and asked to finish it and make necessary modifications to get it running.  I started by reading through the existing code, and then after a few minutes (even before I had finished looking at the code), the interviewer told me that's enough.  When I asked him what he would have done (i.e. "what did I do wrong"), he told me that he would have started by immediately getting the code to compile.

Why is that even relevant?  In my opinion and in my experience, whether or not a piece of code compiles is essentially random, involving things like whether or not semicolons are missing, and has little to do with the correctness of the underlying program.  (To me, focusing on compiling is like running an article through a spell-check without proofreading to check the grammar.)

If you give me a piece of incomplete code, the first thing I do will be to read it.  I won't even try to compile it until I know what the code is doing and I know the algorithm is correct.

Anyway, these have been just a couple recent incidents, but in general I've heard many developers talk about compiling their code as they go along, and yet nobody has been able to tell me the benefit of doing so.  I understand the benefits of testing your code as you go along, but why compiling?

So my question is this: Is there something I missed?  Is there actually a benefit to compiling as you go along?  Or is this some sort of myth propagated by the software community that you must compile your code frequently?


答:
Compiling is a form of test, especially in languages which make extensive use of types such as Haskell or ML. In other languages it's a syntactic scan that tells you little.

Having said that, "compile as you go" seems to me a very situational habit. You could equally well be marked down for being "twitchy" for compiling more frequently than the interviewer's personal prejudice. It sounds like nitpicking; nobody likes to admit that an interviewee has aced the test; it tips the scales of the salary negotiation.

Not all build systems are fast. I worked on a (C++) project where Make would spend 30 seconds just stat'ting everything to determine whether it needed to build or not, and most files would take a couple of minutes to build if you had made changes. We were reluctant to do this more frequently than every 10-15 minutes. Someone will no doubt supply an anecdote of when compiling involved taking your deck of punch cards and carrying them to a different building ...

Compile when you feel you've done a complete conceptual unit in your head and are ready to have it validated. Once a minute or once a week depending on the workflow.


问:
Best way of storing a small number of user credentials
I'm working on a messaging application, based on a server/client architecture.
Now I am thinking about the way how to store the user credentials.
It's not a huge number, just about 20 entries with their User-IDs, Usernames and hashed passwords.

Storing it with a SQL Server in my opinion is overkill.
Is it better to store it in sort of a text file or in a SQLite database file?
These methods would keep the server portable and the installation simple.

And is password hashing enough to keep the passwords secret?

What is the best way to handle this?

答:
You can take the file approach as long as you acknowledge and understand all the implications of this. There are many applications that do this. For example adding/editing a user will possible require a re-configure/re-start of your application and the involvement of an admin. Depending on how your application will be used that could be too slow or perfectly fine.

If you do continue with the file approach it will probably be more efficient to load that into memory at the app boot time. If you don't want to restart the app when you change the config file you could add a monitor on the file to track changes and force a reload.

Hashing passwords should be fine as long as you salt them and use a proper hashing algorithm. Have a look at BCrypt.


答:
If you only need to cater for such a small amount of users, you could also consider delegating credential storing to some other service, such as Google or Facebook. This is usually preferred since the user needs to remember one less set of credentials and you have one less thing to worry about.

That being said, this could be problematic if you want to run your application offline (intranet). In that case, I would go to an SQLLite approach. This would also allow your application to scale up to a certain extent, and if you would need to move to a more robust SQL server, you would already have the data in the format required, so the migration would not be that much of a headache.

Lastly, when it comes to storing passwords, if you really must do it yourself, I would recommend using salted hashes to store your database. You should find plenty of examples online to do it with your technology of choice.

Title: Best way of storing a small number of user credentials

Body:
I'm working on a messaging application, based on a server/client architecture.
Now I am thinking about the way how to store the user credentials.
It's not a huge number, just about 20 entries with their User-IDs, Usernames and hashed passwords.

Storing it with a SQL Server in my opinion is overkill.
Is it better to store it in sort of a text file or in a SQLite database file?
These methods would keep the server portable and the installation simple.

And is password hashing enough to keep the passwords secret?

What is the best way to handle this?


问:
Understanding how variable assignment works
When I started learning C programming a few years ago, my tutor taught me similar to most of the tutors around the world. She said me the very basic things like any int datatype is of 2 bytes memory. If the following is my code,

```<code>#include"stdio.h"
#include"conio.h"
void main()
{
    clrscr();
    int i,n;
    n = 0;
    for(i=0;i<3;i++)
        n = n + i;
    printf("%d",n); //obviously it prints 3
    getch();
}
</code>```

she will explain like what I have written below. Here my teacher starts off her class yet again. . .

Listen students. Here we have two integer values. So let us draw two boxes each of 2 bytes memory.The first box be the memory space of i and the second box be that of n. At n = 0; 0 gets stored into the box n. As the control gets into the loop, 0 gets stored into the box i intially.

0 0

Now the condition is checked. i < 3. Condition gets true. So now the value of n changes from 0 to n+i i.e., 0+0=0. The first iteration then ends after the increment statement. Now i gets incremented to 1. So our picture becomes like this.

1 0

And now i < 3 again. Condtion gets true. n changes from 0 to n + i i.e., 0+1=1. Don't forget the increment my dears. Only then our iteration gets completed. i++ makes our i to 2 now. And the picture will now look like

2 1

She will go on similarly step by step and will complete when both the boxes get 3, 3 values.

So thats it kids. After we get our boxes like this

3 3

the value of n gets printed on the screen.

3

By that time, I was merely like a kid nodding its head when a teacher claims earth as a  circular mass. I never asked her any questions. I felt logically she was perfect. But now I am plentiful of queries. If there is a statement like n = n + i;, won't there be a conflict as both the destination space and the operation space is the same n box? Will the operations be done with the help of any default temporary space for calculations? What will happen if I use a recursive code like the following snippet.

```<code>int factorial(int n)
{
    if(n < 2)
    {
        return n;
    }
    else
    {
        n = n * factorial(n - 1);
        return n;
    }
}
</code>```

How could it be possible to use a single n box as my tutor taught? Won't a new n box be created whenever factorial(n - 1) is called? If I am right, how could the computer know which n box value to be returned? Somebody help me please. I am pulling of hairs from ma head!

答:
The = in C does not mean mathematical equality. For mathematical equality, in C you could write, for example:

```<code>n == n + i
</code>```

This is a logical expression whose value will be true when the value of i is zero, and false at any other time.

The expression n = n + i means, "Modify n so that the new value of n will equal the sum of i added to the old value of n." In some other computer languages this operation is given a symbol different from =; for example, := or <-. It just so happens, however, that in C the symbol for this operation is =.

In the case where you call factorial(n - 1) from within the factorial function, the computer uses an area of memory called the "stack". Within the stack, there may be many "frames". Each frame contains all the little boxes of memory that the computer has allocated for the use of just one invocation of a function. The first time you call factorial, a stack frame is allocated and a box for the variable n is created there. When that invocation of factorial calls factorial(n - 1), a new stack frame is created and a new box for the variable n is created. So there are now two stack frames, each of which contains a box named n. Since at this point the first invocation of the function hasn't actually executed the = operation yet (because it has to finish evaluating factorial(n - 1) first), the n box in its stack frame still contains the same value you originally passed to that function. The n box in the second stack frame contains a value that is (initially) 1 less than the value in the first frame's n box.

Of course, that assumes you are able to compile the program so that the computer will execute any of it.

Body:
The = in C does not mean mathematical equality. For mathematical equality, in C you could write, for example:

n == n + i

This is a logical expression whose value will be true when the value of i is zero, and false at any other time.

The expression n = n + i means, "Modify n so that the new value of n will equal the sum of i added to the old value of n." In some other computer languages this operation is given a symbol different from =; for example, := or <-. It just so happens, however, that in C the symbol for this operation is =.

In the case where you call factorial(n - 1) from within the factorial function, the computer uses an area of memory called the "stack". Within the stack, there may be many "frames". Each frame contains all the little boxes of memory that the computer has allocated for the use of just one invocation of a function. The first time you call factorial, a stack frame is allocated and a box for the variable n is created there. When that invocation of factorial calls factorial(n - 1), a new stack frame is created and a new box for the variable n is created. So there are now two stack frames, each of which contains a box named n. Since at this point the first invocation of the function hasn't actually executed the = operation yet (because it has to finish evaluating factorial(n - 1) first), the n box in its stack frame still contains the same value you originally passed to that function. The n box in the second stack frame contains a value that is (initially) 1 less than the value in the first frame's n box.

Of course, that assumes you are able to compile the program so that the computer will execute any of it.


问:
Is BSD license compatible with Apache?
Can I develop a BSD-licensed software that extends an Apache-licensed software (and vice-versa)?</p>

答:
Here is very useful site:

Easily to compare different types of licenses.

And Choose A License

In your case:
apache-2.0 and BSD.

In both of them you must:

Include copyright

But in Apache, unlike BSD you must:

Include License

State Changes

Include Notice

UPD

This info taken from tldrlegal.com

And as they notice:

This is only a short summary of the Full Text. No information on TLDRLegal is legal advice.

Please, see discussion in comments with @DmitryAlexandrov for more info.

ContentLicense: CC BY-SA 2.5

Title: Is BSD license compatible with Apache?


问:
How to store Role Based Access rights in web application?
Currently working on a web based CRM type system that deals with various Modules such as Companies, Contacts, Projects, Sub Projects, etc.  A typical CRM type system (asp.net web form, C#, SQL Server backend).  We plan to implement role based security so that basically a user can have one or more roles.

Roles would be broken down by first the module type such as:

-Company

-Contact

And then by the actions for that module for instance each module would end up with a table such as this:

```<code>Role1 Example:

    Module   Create  Edit        Delete   View
    Company   Yes    Owner Only    No     Yes
    Contact   Yes    Yes           Yes    Yes
</code>```

In the above case Role1 has two module types (Company, and Contact).  For company, the person assigned to this role can create companies, can view companies, can only edit records he/she created and cannot delete.  For this same role for the module contact this user can create contacts, edit contacts, delete contacts, and view contacts (full rights basically).

I am wondering is it best upon coming into the system to session the user's role with something like a:

List<Role> roles;

Where the Role class would have some sort of List<Module> modules; (can contain Company, Contact, etc.).?  Something to the effect of:

```<code>class Role{
string name;
string desc;
List<Module> modules;
}
</code>```

And the module action class would have a set of actions (Create, Edit, Delete, etc.) for each module:

```<code>class ModuleActions{
List<Action> actions;
}
</code>```

And the action has a value of whether the user can perform the right:

```<code>class Action{
string right;
}
</code>```

Just a rough idea, I know the action could be an enum and the ModuleAction can probably be eliminated with a List<x, y>.  My main question is what would be the best way to store this information in this type of application: Should I store it in the User Session state (I have a session class where I manage things related to the user).  I generally load this during the initial loading of the application (global.asax).  I can simply tack onto this session.

Or should this be loaded at the page load event of each module (page load of company etc..).  I eventually need to be able to hide / unhide various buttons / divs based on the user's role and that is what got me thinking to load this via session.

Any examples or points would be great.

答:
There should be very little overhead associated with getting the user permissions on page load, so do that.  Don't use the session to store much of anything.  This will allow permissions to be dynamically changed by admins (so that the user won't have to login again).

Rather than develop a detailed role infrastructure, why not consider something simpler like assigning permission tags to a user -- e.g. company:create, company:edit, etc.  These can be interpreted exactly as your current infrastructure would; however, this will permit some additional flexibility with allowing permissions to be assigned to more discrete actions (e.g. not just the CRUD operations).

Lastly, whatever permissions are granted in the client must also be verified on the server when the user submits his action.  We can't simply trust the client.  So whether on the client or on the server you'll check a user's permission tags and do the right thing.  On the client side this might mean changing the interface.  On the server side this might mean rejecting a transaction where it appears the user somehow circumvented our permissions (e.g. attempted to create a company where this was disallowed).


答:
There are merits to compiling as you go. But I very much agree that staying on task is an OK coding strategy.

The most significant benefit to incremental compiling is the mentality many get in if they wait for the end to compile and test: we're more concerned at the end in getting the code to run than anything else at that point. We say "Oh, just need to add this bracket so the compiler stops complaining" or "oh just need to capitalize this" without thinking if there is an underlying semantic error that this syntax error hides. I really do find syntactical errors often nest themselves in semantic errors (the converse not true).

As an example, say I changed a variable's meaning and as a result, changed its name. The name change generates a syntax error later on in the code but if I just please the complier by correcting the name, I've ignored why that error came into existence.


答:
I understand the benefits of testing your code as you go along, but why compiling?

But how will you test your code as you go along when you don't compile accordingly?

The extreme case is test-driven development (TDD). It is obvious that TDD does not work with your strategy, since TDD means extremely short cycles of write-test, compile (should fail), write-code, compile again, run-test, fix-bugs, compile again, refactor, compile-again, run-test, and-so-on...

So not everyone does TDD, at least not always (me too, I admit). With your current strategy, you will never have a chance to even try TDD. But even when you are not doing TDD, it is IMHO extremly helpful to test your code more regular - which is not possible when you don't compile it regularly. And when your test fails, you have running to debug it (which can help you to understand why the nice looking algorithm you have written some minutes before does not behave so nice as you thought it should do). And the more code you write without compiling, the more code you write without testing, so the more likely it will happen that you run into a case where you cannot predict that the time to fix the problem is "O(1)", as you wrote.


答:
The second idiom can be faster, because caller can reuse one variable over long loop, instead of each iteration creating new instance.

I would not generally use it, but eg. in game programing it has its place.
For example look at JavaMonkey's Vector3f lot of operations allows to pass instance that should be modified and returned as result.


答:
I actually agree with you that compiler errors should be no big deal for an experienced developer.  I don't think the cost of fixing them increases significantly enough over time to worry about.  If it were possible to postpone fixing all the compiler errors until just before a push, I would do so, as it would present a much smaller and more consolidated interruption.

Unfortunately, finding compiler errors isn't the only thing compilers do.  At the risk of stating the obvious, compiling is required to run your program, and running your program is required to find all the more complex, subtle, and interesting runtime bugs that even experienced developers create.  And those types of bugs are more difficult and therefore more expensive to fix the longer you postpone debugging them, because they can build on or mask each other.

However, I wouldn't necessarily mark someone down in an interview exercise for postponing compiling until the very end.  Interview exercises tend to be very straightforward, and experienced developers usually know their limits.  The more confident you are about what you wrote, the longer you will go between compiles.  That's just human nature.

In order to not mark you down for it, the confidence would have to be justified, though.  If you had spent 45 minutes writing something without compiling, then required another 45 minutes to debug it, I would have weighed that heavily against you.


答:
Given the loose semantics -- myObjectToOtherObject could equally mean that you move some data from the first object to the second or that you convert it entirely anew, the second method seems more adequate.

However, if the method name were Convert (which it should be if we look at the "... do the conversion" part), I'd say the second method wouldn't make any sense. You don't convert a value into another value that already exists, IMO.


答:
No, it's not unreasonable to hold off compiling until you've done a sufficient amount of code (and a 'sufficient amount' depends on the coder and the code being written).

For example, if you're an awesome coder who takes his time to get it right, and you're not writing massive amounts or convoluted code, then compiling regularly is a waste, and probably a distraction too. If you're not, then compiling every function can be a good thing. It depends on the person.

As a counter-example, imagine you're writing JavaScript code - there is no compiler. Instead (given the nature of most JavaScript code) you would run the program (or refresh the page) to see the results of your coding. Now, you cannot do that until you're written enough code to make sense. As a result, JavaScript developers tend to "compile" as often as they can, which isn't necessarily very often.

In short, there's no correct answer here - the interviewer isn't wrong, but neither are you. Do what makes you productive and forget what anyone tells you you're supposed to do. There are much more important factors about coding than your tendency to hit F7 regularly (or not) is of absolutely no consequence.


答:
The simplest way would be to implement it using web technologies (eg HTML controls) so that it can be displayed as a web page easily, and then create a desktop app that uses the same html pages only wrapped as a 'executable'.

To create a desktop application you can either view the web page in an embedded browser in an application that exists solely to show the browser in a window, or you can use something like Microsoft's HTA system that presents web pages as desktop-style windows.

The only other alternative is Wt. This is a system that takes a Qt based GUI application and rewrites the drawing mechanism from the usual desktop controls into html controls on a web page. Its pretty cool considering most applications go the other way round. IIRC its very transparent in that you only need to change a line or two of your original code. Qt is not java though, so I'm only pointing it out for completeness, its still pretty cool though :)

Title: Is it possible to have a single code base for a desktop GUI and a web application?

Body:
The required user interface is fairly simple; basically, two tables that "interact with each other", e.g. certain rows in one table get highlighted when a row in the other is clicked, plus maybe a panel with charts.

Is it possible to have a (largely) single code base for a desktop app and a web app implementing this interface? For a few reasons, it would be good to have both versions, but I would hate to implement the GUI twice.

The details of my particular case are as follows:

This is an academic research problem, so I don't have strict constraints in terms of tools and the coding style (or users!). On the other hand, I do have quite some time constraints.

It has to run on bare JVM, but any language/framework would be welcome (Java, Groovy, Scala, Clojure, etc.).

There is no persistent state, i.e. no strict need in a shared DB or any server part whatsoever.

I would be willing to go through some design hoops to make it work (by design hoops I mean some unconventional application architecture).

Is it completely crazy to even think about something like that? If no, what would be the tools to pull it off?


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Knowledge is knowledge. And viceversa.

From a T-shirt.

LastEditorDisplayName: Roger Pate


问:
MVC for our application?
There are some issues about how to manage our program designs and programming styles. I was assigned to find a solution to write reusable code - though, the programming team does not follow the rules.

I would rather use MVC to perform a well structured programming style. I found out that a blueprint for next works requires a bunch of experts. The thing is that I have to do it all myself. And the worse part is that I have to use a general MVC platform.

I need your helps and suggestions for:

Is there a way that I can write a document for MVC - to use it in our design in Java?

How can I represent it?

How much work does it need?

How can I connect the Model, the View, and the controller parts together?

答:
MVC is just a design pattern - it's not a silver bullet.

Ask yourself:  Are you actually designing a UI?

There are lots of MVC frameworks out there, don't re-invent the wheel!

UML is typically used to represent the MVC structure - there's a million generic diagrams out there already

Title: MVC for our application?


问:
Is there a downside to using AggressiveInlining on simple properties?
I bet I could answer that myself if I knew more about tools to analyze how C#/JIT behaves but since I don't, please bear with me asking.

I have simple code like this :

```<code>    private SqlMetaData[] meta;

    private SqlMetaData[] Meta
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        get
        {
            return this.meta;
        }
    }
</code>```

As you can see I put AggressiveInlining because I feel like it should be inlined.

I think. There's no guarantee the JIT would inline it otherwise. Am I wrong?

Could doing this kind of thing hurt the performance/stability/anything?

答:
Compilers are smart beasts. Usually, they'll automatically squeeze out as much performance as they can from anywhere they can.

Trying to outsmart the compiler doesn't usually make a big difference, and has a lot of chances to backfire. For instance, inlining makes your program bigger as it duplicates the code everywhere. If your function is used in a lot of places throughout the code, it might actually be detrimential as pointed out @CodesInChaos. If it is obvious the function should be inlined, you can bet the compiler will do so.

In case of hesitation, you can still do both and compare if there is any performance gain, that's the only certain way to now. But my bet is the difference will be neglegible, the source code will just be "noisier".

ContentLicense: CC BY-SA 4.0


问:
Is there any benefit to just artificially reducing WIP in a Kanban system?
So imagine this scenario:

There is only 1 developer, who also is the bottleneck (testers, etc are busy on other contracts).
There is a nontrivial backlog of tickets, most of which are blocked for not being reproducible, unintelligible requirements, unsolvable (with current ideas, staff and technologies).

Is there any particular benefit to creating a system that parcels out the tickets to the sole developer one or two at a time?  The system so far has immediately created slack on account of delays in assigning new tickets after current tickets are worked. When blocked tickets are assigned, they now sit on the developer's desk blocked until they are moved back to unassigned tickets.

Are there any benefits to this "artificial low-WIP" system and how could/should it have been implemented?

答:
It would look to me that you want to implement a Pull mechanism - so that the developer self-assigns new unblocked tickets to himself/ herself as soon as he is done with the ones he is working on, instead of someone else assigning tickets to him.  That way, he remains occupied and focuses on finishing what he started and taking up new work when he is ready for it.

Also, if something he is working on needs to blocked for any of the reasons you mentioned, he should block it so that it is visible to him as well as to others in the team - so they can all pitch in to help resolve the block and help close the ticket successfully. They should ideally not be moved back to backlog (unassigned status) since there must have been good reason to pick it up in the first place.  Only in exceptional cases should blocked tickets be moved back to backlog.

A formal WIP limit ensures that in-process tickets (including blocked ones) get dealt BEFORE others get taken up - and over a period of time, ensures that work flows from Backlog to Completion, instead of remaining in the system for prolonged periods of time.


答:
You are right - there is no way to guarantee that the method would be inlined - MSDN MethodImplOptions Enumeration, SO MethodImplOptions.AggressiveInlining vs TargetedPatchingOptOut.

Programmers are more intelligent than a compiler, but we work on a higher level and our optimizations are products of one man's work - our own. Jitter sees what's going during the execution. It can analyze both the execution flow and the code according to the knowledge put into it by its designers. You can know your program better, but they know better the CLR. And who will be more correct in his optimizations? We don't know for sure.

That's why you should test any optimization you make. Even if it is very simple. And take into account that the environment may change and your optimization or disoptimization can have quite an unexpected result.

Title: Is there a downside to using AggressiveInlining on simple properties?

Body:
I bet I could answer that myself if I knew more about tools to analyze how C#/JIT behaves but since I don't, please bear with me asking.

I have simple code like this :

```<code>    private SqlMetaData[] meta;

    private SqlMetaData[] Meta
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        get
        {
            return this.meta;
        }
    }
</code>```

As you can see I put AggressiveInlining because I feel like it should be inlined.

I think. There's no guarantee the JIT would inline it otherwise. Am I wrong?

Could doing this kind of thing hurt the performance/stability/anything?


答:
The idea behind limiting the WIP count in kanban is to provide everyone the opportunity to properly focus on the few items assigned to them and to progress those items to the next stage as efficiently as possible.

The problem with just piling all the work on that one developer is that the typical reactions are

Try to work on "everything" at the same time, thereby losing efficiency in the context switches between issues

Becoming overwhelmed by the amount of work and losing focus as a result of that.

Both have the end result that the developer becomes more of a bottleneck.

The biggest flaw in your implementation is that "unworkable" items get assigned to the developer, who then spends valuable time investigating the issue, only to come to the conclusion that he still doesn't understand it or can't do anything about it.

The biggest improvements can be made by ensuring that blocked issues don't get assigned to the developer.

Issues that can't be solved within the current system constraints should either be closed as "Won't Fix", or should be put in a special 'Hold' status.

Unclear issues/requirements should be assigned to the originator (or someone who can act on behalf of the originator) for clarification. It is the responsibility of everybody involved to avoid that these issues start bouncing back-and-forth.

Issues that can't be reproduced should be assigned to a tester for reproduction and a description on how to reproduce. If it is really a one-off, it should be prioritized accordingly.

The system should allow some level of cherry-picking for the developer in the issues he wants to take up. After working on some very hard issues, it is nice to get rid of some low hanging fruit to get the backlog down a bit and give your brain a bit of rest at the same time.

Title: Is there any benefit to just artificially reducing WIP in a Kanban system?

Body:
So imagine this scenario:

There is only 1 developer, who also is the bottleneck (testers, etc are busy on other contracts).
There is a nontrivial backlog of tickets, most of which are blocked for not being reproducible, unintelligible requirements, unsolvable (with current ideas, staff and technologies).

Is there any particular benefit to creating a system that parcels out the tickets to the sole developer one or two at a time?  The system so far has immediately created slack on account of delays in assigning new tickets after current tickets are worked. When blocked tickets are assigned, they now sit on the developer's desk blocked until they are moved back to unassigned tickets.

Are there any benefits to this "artificial low-WIP" system and how could/should it have been implemented?


答:
It's not an antipattern, it's a bad practice.

The difference between an antipattern and a mere bad practice is here: anti-pattern definition.

The new workplace style you show is a bad practice, vestigial or pre-OOP times, according to  Uncle Bob's Clean Code.

Arguments are most naturally interpreted as inputs to a function.

Anything that forces you to check the function signature is equivalent
to a double-take. It’s a cognitive break and should be avoided. In the
days before object oriented programming it was sometimes necessary to
have output arguments. However, much of the need for output arguments
disappears in OO languages


问:
Web app that runs other applications?
I am trying to write a web application that interacts with a service that would run scripts at the system level. Something like a website that you can schedule a job, the service will run the job with the given inputs, write the outputs to a database, and inform the website of its status.

A few questions:

How is this typically done? Do I write to a "JOBS_QUEUED" table in my database and have the service check that? How can I pass a "% done" back to the web page? Is there a name for this type of thing?

Not sure if it matters, but I am working with Ruby on Rails right now.

答:
There are many ways this could be done. One way I have seen it done:

A web application adds a record to a job queue. The new job ID is saved in the user's web session, to make it easier to find the jobs of the user.

Another background process periodically scans the table for new jobs that have not yet been started. When it finds such a job, it then starts processing it.

The web user can see the progress of their job by refreshing a page which runs a query using the saved job ID. In this case, progress is just the name of the current status, there's no "% complete". That could been done with AJAX, but it's not.

If you have very specific questions about doing this in Rails, it might be better to ask those questions on Stackoverflow.

Title: Web app that runs other applications?


答:
MVC is a good pattern for this, but its the V part "View" that isn't reusable from platform to platform.

The code for modifying the document of a webpage on the clientside without postback is javascript, that is non-negotiable.

The code for modifying controls in a native/jvm form application for example, is not javascript.

So for the presentation part the answer is no, not really. Not for traditional webpage and native/java forms.

The MVC pattern though can make most of your real code reusable, with only the display and view interaction needing to be platform specific.


问:
Why are data constructors with the same name disallowed in different type constructors?
The following declaration gives an error:

```<code>type Vec2d = (Float, Float)
type Vec3d = (Float, Float, Float)
-- Rect x y defines a rectangle spanning from (0,0) to (x,y)
data Obj2d = Rect Float Float
           | Translate Vec2d Obj2d
-- Cuboid x y z defines a cuboid spanning from (0,0,0) to (x,y,z)
data Obj3d = Cuboid Float Float Float
           | Translate Vec3d Obj3d
</code>```

namely Multiple declarations of 'Translate'.

Now, I wonder why this limitation was introduced?

If the limitation were not there, one could write

Translate (1, 1) Rect 2 2
and
Translate (1, 2, 3) Cuboid 1 1 1, which sounds natural.

I don't (immediately) see how this could result in a parsing problem bidding to disallow using the same name, the type could be inferred by the argument (Rect 2 2 is an Obj2d, Cuboid 1 1 1 is an Obj3d).

I'm sure there is a good reason the language designers chose to disallow using the same name for data constructors of different types, but I'd like to learn: why, when it's not obviously necessary?

(And type disambiguation is the bread-and-butter business of Haskell!)

答:
That's because data constructors are just functions, and function overloading is not allowed in Haskell. It might be more clear if you use GADT syntax to define your types:

```<code>{-# LANGUAGE GADTs #-}
data Obj2d where
    Rect :: Float -> Float -> Obj2d   -- a function from floats to obj2d's
    Translate :: Vec2d -> Obj2d       -- a function from vec2d's to Obj2d's
</code>```

I believe they (the GHC devs) are working on possible solutions to this problem involving introducing a new type class for all types that share the same data constructor, or something similar. So stay tuned, a solution to your problem may be coming soon! (I hope)

Body:
That's because data constructors are just functions, and function overloading is not allowed in Haskell. It might be more clear if you use GADT syntax to define your types:

{-# LANGUAGE GADTs #-}
data Obj2d where
    Rect :: Float -> Float -> Obj2d   -- a function from floats to obj2d's
    Translate :: Vec2d -> Obj2d       -- a function from vec2d's to Obj2d's

I believe they (the GHC devs) are working on possible solutions to this problem involving introducing a new type class for all types that share the same data constructor, or something similar. So stay tuned, a solution to your problem may be coming soon! (I hope)


问:
Application qos involving priority and bandwidth
Our manager wants us to do applicaiton qos which is quite different from the well-known system qos. We have many services of three types, they have priorites, the manager wants to suspend low priority services requests when there are not enough bandwidth for high priority services. But if the high priority services requests decrease, the bandwidth for low priority services should increase and low priority service requests are allowed again.

There should be an algorithm involving priority and bandwidth. I don't know how to design the algorithm, can anyone assist in getting this right?

All these services are within a same process. We are setting the maximum bandwidth for the three types of services via ports of services via TC (TC is the linux qos tool whose name means traffic control).

答:
There are companies who do application QoS for living (Exinda, Riverbed, etc..) and it is not a job that can be completed by a single person if you need a reliable system. Having said that if you still want to go ahead and implement a cheaper solution, TC in linux is a good place to start this will allow you to throttle traffic. IPtables can be used to create rules to mark the traffic with a mark and route packets to different TC buckets based on the mark.I cannot give more specific answers as to configuration of iptable rules and tc without more information about your network and type of applications you are trying to prioritize.

In terms of queuing there are many generic algorithms like FIFO,HTB.

You might be able to get away with the simple bash scripts if you are trying to prioritize just generic traffic like HTTP, FTP or ports as you are trying to do.

If you are looking to for a more sophisticated system that can detect different types of web applications you might have to take a look at some sort deep packet inspection tool(most of them have to be purchased).If you have a decent firewalls in your premise they might also have some QoS capabilities.

My point is it is a very humongous task to build a QoS system in large scheme of things,But if you can give more specific input on what you are trying to achieve some one might be able to help you.

Disclaimer: I work with Exinda.


答:
With a good development environment I see little reason to compile unless you're actually planning to test code.  The background syntax checking tools catch most everything that the interviewer seems to be talking about, although I will admit there are still a few cases (involving changes that propagate across files) that aren't always fully identified.

That being said, I will try to compile and run pretty much the smallest unit of code that can actually produce an outcome.  Half an hour ago I was creating a means of printing some search results and I did half a dozen test prints (to .pdf, not paper) making changes to the result to make it look better--a rate of about 1 compile per 10 lines.


答:
A browser is a desktop application, its very easy to pack your war with and embebed server (with jetty its really easy), this way you can run your app in a stand-alone machine.

If you want two versions, web and desktop, its because one of this versions gives things to your users that the other versions cannot give, if you are thinking in a "automatic" way of having the two GUI's its because you are thinking in having basically the same app in the browser and in the desktop version, ¿why you are thinking in wasting your time for building the same thing twice?

In resume, the problem its not thinking in an automatic way of having two guis, the real problem its thinking in why do you want this two versions in the first place.


问:
Why GPL was made so that it requires open application code yet not open pipe of compiled applications?
Say we have a GPL library (CGAL for example). We have a big tasks chain like pipes modeling and testing. We would love to use library for our indoors application yet we must open sources... so we make a minimal application that takes arguments and files in, and returns files and data out. And is being used like closedSourceApp > GPLApp > closedSourceApp.

And all interesting/relevant parts are excluded from GPL app. At the same time GPL library is not used at its full potential and does not get integrated into bigger applications.

So the question is what reasons were behind GPL license idea to force project new code to live under it?

答:
The Free Software Foundation (FSF) already explains their motivations pretty well.  Their goal is to give users freedom.  Freedom to modify the source code of the programs they use as they see fit, freedom to distribute their modifications to others.

The only way users can get that freedom is if they have access to your source code.  The GPL therefore requires that, if you use a library that is so licensed, you must also make your source code available.

The way FSF defines usage is by a concept called "derived works."  If you link a library into your application, and that library is a substantial part of your application's functionality (i.e. your application won't work without it), the GPL considers that a derived work, and you must open your source.

If, instead, you connect to a GPL application at arm's length, and your application will work without the GPL application, then the GPL considers them two different applications, and you don't have to open the source code for your application.


答:
I think there is more than a little professional snobbery here. The implication seems to be "if you've never had the need to compile regularly then you've never worked with anything that complicated - go get some more experience and come back when you've learned to work exactly the way we do."

But obviously there is another side to this. Some projects take an age to compile. I've worked with frameworks that take 30 minutes or more to compile after even minor edits.  Heaven help you if you ever need to edit a header file. Full recompilations are typically done overnight, and if you're relying on the compiler to catch your mistakes there are still rare errors that won't be detected during a partial build. You just don't re-compile every 5 minutes under these conditions - unless you're feeling lazy.

The compiler cannot help you with logical or semantic errors and syntax errors really aren't so hard to avoid that spending half of your day compiling becomes worthwhile. Of course, you'll make the occasional typo, but I'm going to assume you can both touch-type and read. If you have the freedom to choose, use a coding style that makes good use of layout to visually highlight errors and you'll never drop a brace, bracket or semicolon ever again. It takes a little practice and a little more discipline than most are used to, but it is possible. I can write code for a couple of hours at a time, in a plain text editor, and compile it first time better than nine times out of ten. Sure, I could compile more often, but I can't remember the last time I had an error that would have been easier to correct as a result.

If you aren't a fan of constant recompilation, you're in good company. Here's Donald Knuth:

As to your real question, the idea of immediate compilation and "unit
  tests" appeals to me only rarely, when I’m feeling my way in a totally
  unknown environment and need feedback about what works and what
  doesn’t. Otherwise, lots of time is wasted on activities that I simply
  never need to perform or even think about.

All of that being said... if you're working in a context where compilation is a free action, why wouldn't you? At home, on personal projects, I hit ctrl-S about once every 30 seconds and the "compile" shortcut nearly as often, in an IDE that constantly runs the code through the compiler's front end to provide real-time error highlighting. Why pass up a free lunch?


问:
Setting global parameters: is this a reasonable use of const_cast and volatile?
I have a program that I run repeatedly with various parameter sets. Different parameters are used in different parts of the program (including different source files). The same parameter may also be used in different places. However, all parameters are constant during run-time after they have been set.

I discovered very quickly that declaring the parameters locally does not make sense (it involves having to remember where every parameter is defined, etc.), so I resorted to using a params.h where I declared and defined all the parameters: const int Param1 = 42;, etc.

The downside of this is that I have to recompile every time I change a parameter. So  I'm thinking of using the method below. It relies on usingvolatile and const_cast, which is normally considered "dirty", but it ensures once the parameters have been set in main, they are not accidentally changed anywhere else in the program.

I'm wondering whether people think this is OK, because eventually I want to open-source my code.

In params.h:

```<code>namespace Params
{
extern volatile const int Param1;
// etc.
}
</code>```

In main.cpp:

```<code>#include "params.h"

volatile const int Params::Param1 = 0;

int main(int argc, char* argv[])
{
    int* const pParam1 = const_cast<int*>(Params::Param1);
    *pParam1 = // Get value from argv[] or some config.ini file.
    // etc.
}
</code>```

答:
You should read your parameters from a configuration file when the program starts.
You can pass the file name on the command line.  See this answer for information on using boost::property_tree to read a parameter file.</p>


答:
In larger projects, with several subroutines, you want to test these parts, before using them in the larger scheme, since it is way easier to debug if you know certain parts already work.

In order to test these smaller pieces, you need to compile.

It might be that the interviewer confuses this situation with a small program that is not designed in this manner.


答:
The one important thing about compiling often, missing from other answers as far as I can see is this: if you compile rarely and get a large amount of compiler errors, most of those are meaningless, because they are generated by the first error. It could be because you had wrong type, or typo, or plain syntax error which makes some declaration invalid.

You could always just fix the first one, recompile, fix the next remaining one, and so on, but with large code base this can be slow. But if you try to skim through the long list of compiler errors and spot errors which are independent, then you spend a lot of time reading irrelevant messages, or navigating code from secondary error spot to actual cause.

Another thing going for regular builds is, nothing stops you from starting to compile as soon as you have a complete block of code written, which should compile. You can then continue writing more code while compilation goes on, just as long as you don't save the new edits until compilation finishes. So there's practically no time wasted on waiting for build. If you wait until you have written everything you are going to write at that time, you then have to wait for compilation without nothing to do. This is basically the manual version of what modern IDEs can do in the background automatically.


问:
Object identification in Python
In learning Python, I found that when two "names" (or "variables") are assigned to the same value, both of them point to the same memory address. For example

```<code>>>> a = 10
>>> b = 10
>>> a is b
True
</code>```

My question is, when assigning b, how does Python figure out that a 10 object already exists?

One way might be to create the new object for b, scan pre-existing objects in memory to find a duplicate and, if found, point b to it. This sounds expensive, and tricky for more complex objects.

答:
It just keeps a cache of small integer instances.

```<code>>>> a = 58435
>>> b = 58435
>>> a is b
False
</code>```

Precisely how small is easy to determine manually for your implementation. Mine caches −5 to 256.

Title: Object identification in Python

Body:
It just keeps a cache of small integer instances.

>>> a = 58435
>>> b = 58435
>>> a is b
False

Precisely how small is easy to determine manually for your implementation. Mine caches −5 to 256.


问:
What happens if you're unable to solve a problem?
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?

答:
My experience is that a fresh graduate is not thrown into the deep.
Instead, you will likely be part of a team that also includes experienced developers.

My advice would be: make use of them. When you are unsure how to tackle a problem, or if you want to know if your solution is going in the right direction, discuss this with them. And if you feel you are stuck somewhere, grab one of the experienced guys and explain your problem and ask for help.

Most often, just explaining your problem will reveal a solution and explaining your solution may equally reveal flaws in it.


问:
Is duplicate syntax for defining named functions a bad language design decision?
I am modelling a programming language for fun, and the syntax is heavily influenced by Scala - specifically function definitions.

I have encountered a design problem because my language does not differentiate between functions defined via the def syntax (class methods) and anonymous functions assigned to values (created using =>) - it removes the differences in both implementation and behaviour.

The result is that the following two definitions mean the same thing:

```<code>def square(x: Int) = x*x

val square = (x: Int) => x*x
</code>```

There is no reason for the latter form (immediate anonymous function assignment) to be used in any normal situation - it's simply possible to use it instead of the def form.

Would having such duplicate syntax for defining named functions hurt the orthogonality of the language or some other design aspect?

I prefer this solution because it allows for short and intuitive definitions of methods and named functions (via def), and short definitions of anonymous functions (using =>).

Edit: Scala does differentiate between the two - anonymous functions are not the same as methods defined with def in Scala. The differences are relatively subtle though - see the posts I linked before.

答:
I've found a fundamental difference between lambdas and def methods in Scala - that I am still not sure whether I want to implement. I have to do further research on it and then I'll report back on my decision.

Essentially, only methods can return - and when the keyword is used from a lambda, it actually returns from the encompassing method.

As I've said, I'm not sure whether I want this. But it could be justification enough for this syntax. Or maybe too dangerous because subtle differences can unexpectedly cause harm.

Details


答:
is operator is not the same as ==.

While == checks the value of object, is checks identity of it using it's memory address.

As mentioned before ints from -5 to 256 (inclusive) are special (small) and Python will not recreate those objects. Ints from outside that range will be new objects every time so is will return True only if they are the same exact object.

That happens also to: chars, empty strings and some other strings - that looks like Python identifiers.

(I think that bytes as well, but I'm not sure).

If you want to read more, please take a look the fallowing post: http://mrfuxi.github.io/blog/python-gotchas/

Title: Object identification in Python

Body:
In learning Python, I found that when two "names" (or "variables") are assigned to the same value, both of them point to the same memory address. For example

```<code>>>> a = 10
>>> b = 10
>>> a is b
True
</code>```

My question is, when assigning b, how does Python figure out that a 10 object already exists?

One way might be to create the new object for b, scan pre-existing objects in memory to find a duplicate and, if found, point b to it. This sounds expensive, and tricky for more complex objects.


问:
Modifying the MIT license for modified source code?
I have made a large number of modifications to some MIT-licensed source code to tailor it to the requirements of my project. Since this is JavaScript (for a website) the minified source code is naturally attainable by anyone viewing the site.

Whilst I am happy for people to use the source code under the terms of the MIT license, I feel that the body text of the license may lead to confusion since this is a highly modified version.

Is it acceptable to amend the license text? What is the correct etiquette ?

Original Text:

```<code>The MIT License (MIT)

Copyright (c) 2009 - 2014 Adriana Palazova
http://www.adipalaz.com

...
</code>```

Full license in question (for a jQuery accordion control): http://www.adipalaz.com/docs/mit-license.txt

Proposed Change:

Add my name to the copyright notice in the MIT license:

```<code>The MIT License (MIT)

Copyright (c) 2009 - 2014 Adriana Palazova, 2014 {{My Name Here}}
http://www.adipalaz.com

...
</code>```

And then change the header in the minified JavaScript file to the following:

```<code>/*!
 * Nested Accordion (Modified by {{My Name Here}})
 * Copyright (c) 2009, 2010, 2011, 2012, 2013 Adriana Palazova
 * Copyright (c) 2014 {{My Name Here}}
 * Licensed under the MIT (http://{{My URL Here}}/mit-license.txt) license.
 */
</code>```

答:
Yes, what you're proposing with an additional copyright line would be fine.

Remember that copyright != licensing.

The license is the permissions others have in using a given work.

The copyright indicates who owns the intellectual property associated with creating the work.

In this case, you have made non-trivial modifications to the project so you are allowed to assert copyright over the work for the portions you modified.


问:
Is modifying an incoming parameter an antipattern?
I am programming in Java, and I always make converters sort of like this:

```<code>public OtherObject MyObject2OtherObject(MyObject mo){
    ... Do the conversion
    return otherObject;
}
</code>```

At the new workplace the pattern is:

```<code>public void MyObject2OtherObject(MyObject mo, OtherObject oo){
    ... Do the conversion
}
</code>```

For me it is a little bit smelly, as I got used to not to change the incoming parameters. Is this incoming parameter alteration an antipattern or is it OK? Does it have some serious drawbacks?

答:
It really does depend on the language.

In Java the second form may be an anti-pattern, but some languages treat parameter passing differently. In Ada and VHDL for example, instead of pass by value or by reference, parameters can have modes in, out, or in out.

It is an error to modify an in parameter or read an out parameter, but any changes to an in out parameter are passed back to the caller.

So the two forms in Ada (these are also legal VHDL) are

```<code>function MyObject2OtherObject(mo : in MyObject) return OtherObject is
begin
    ... Do the conversion
    return otherObject;
end MyObject2OtherObject;
</code>```

and

```<code>procedure MyObject2OtherObject(mo : in MyObject; oo : out OtherObject) is
begin
    ... Do the conversion
    oo := ... the conversion result;
end MyObject2OtherObject;
</code>```

Both have their uses; a procedure can return multiple values in multiple Out parameters while a function can only return a single result. Because the purpose of the second parameter is clearly stated in the procedure declaration there can be no objection to this form. I tend to prefer the function for readability. but there will be cases where the procedure is better, e.g. where the caller has already created the object.

Body:
It really does depend on the language.

In Java the second form may be an anti-pattern, but some languages treat parameter passing differently. In Ada and VHDL for example, instead of pass by value or by reference, parameters can have modes in, out, or in out.

It is an error to modify an in parameter or read an out parameter, but any changes to an in out parameter are passed back to the caller.

So the two forms in Ada (these are also legal VHDL) are

function MyObject2OtherObject(mo : in MyObject) return OtherObject is
begin
    ... Do the conversion
    return otherObject;
end MyObject2OtherObject;

and

procedure MyObject2OtherObject(mo : in MyObject; oo : out OtherObject) is
begin
    ... Do the conversion
    oo := ... the conversion result;
end MyObject2OtherObject;

Both have their uses; a procedure can return multiple values in multiple Out parameters while a function can only return a single result. Because the purpose of the second parameter is clearly stated in the procedure declaration there can be no objection to this form. I tend to prefer the function for readability. but there will be cases where the procedure is better, e.g. where the caller has already created the object.


问:
How often should a manager meet with his subordinate who is a team leader?
Ours is a software concern and we have a team structured like so: manager->team leads->team members. We are following the agile programming model and trying to develop a product in a collaborative fashion. We have daily morning meetings with team members and their team leads to discuss progress and issues.

When it comes to TL->Manager, most of the time they do not have items to discuss on a daily basis since TL goals would be for weekly plan and such. Most of the time, we just discuss about resources and it is less technical. I just want suggestions on how the manager & team lead interaction should be and whether the current system we have is fine. Please share your thoughts or ideas.

答:
As often as is needed.  Some projects - those where requirements might be fluid or political reasons mean that regular updates are critical - require more on-going communication than others.

As a minimum I'd suggest that it would be a very odd week in which some meeting / discussion (possibly informal or in passing) wasn't needed.

Similarly I'd suggest any sort of regular daily meeting lasting longer than a few minutes would almost certainly be over the top.

Things to think about:

Regular meetings can benefit all parties - if you know when they're going to be you can plan round them and if a PM / Team Lead knows when he's getting his next update he's less likely to pester.

If you have a meeting make it clear what the purpose of the meeting is so people can prepare and/or opt out (though they should always give a reason why they're opting out, not just that they don't want to be there - though that is a useful sign that the meeting isnt' being seen as productive that you might want to look at).

Often the meeting time is more intrusive than the meeting length.  11am and 3pm are dreadful times for meetings as the break up the productive stretch morning or afternoon.  First thing or last thing are often better (or first thing in the afternoon).

You can cover off a lot of what's covered in meetings in e-mail.  Outline a template for regular updates (and timings).  This allows the programmer / team leads to adjust the timing of the updates to their own schedule.

The more people in a meeting the longer it will go on and the greater the proportion of time that is wasted.

Face to face meetings to achieve things that other communications find difficult.  Whatever you do have some - just keep them small and focused.


问:
Is it bad to use the same class or idiom names as in a third-party API that you're using?
FlashPunk is a third-party graphics API for simple game development in AS3, and they take what are effectively sprites or display objects of some sort and refer to them as "Entities".  Entity is the actual class name, and it's the predominant class to use to animate something such as a character moving on the screen.

There's a bit of a convention right now in which you refer to things like barriers, enemies, characters, etc. as "entities".  So that being said, if you're using FlashPunk for your graphics, is it bad to create a base class to represent such things and name it Entity as well?  (In particular, does this violate a widely-held coding convention?)

Obviously it would be in a different package, and most people would probably separate the graphics from the game's actual state, so there's not a lot of overlap there.  It's just using the same title.

What about scenarios like this in general with programming?  Is there a particular convention?

答:
Naming collisions are bound to happen when using third-party libraries because naming objects is not an easy thing to do and there are not many elegant names one can assign to objects to give them representative meaning. With that said, if you won't have many of these collisions that would cause much confusion to anyone reading/using your code, then use the same names. My suggestion is to avoid naming collisions as much as possible.

For your particular example, instead of using the name Entity, you could use EntityBase.


答:
Don't use volatile const, it sounds like nonsense! Instead, use a class/struct and initialize all variables in the constructor. You can still use const.

Params.h:

```<code>struct ConfigParams {

    const int param1;
    const int param2;
    // ...

    // Define a constructor that will load stuff from a configuration file.
    // Tune this to meet your needs, such as parsing the data from a startup command line.
    ConfigParams(const std::string & configFileName);
};

// The global that you will use to fetch the configurations during runtime.
extern const ConfigParams configParams;
</code>```

Params.cpp:

```<code>// Declare the global configuration data table:
const ConfigParams configParams("app_configs.ini");

// The constructor:
ConfigParams::ConfigParams(const std::string & configFileName)
    : param1(getConfigFromFile(configFileName, "param1"))
    , param2(getConfigFromFile(configFileName, "param2"))
    // and so on ...
{
}

// And this function would open the file and lookup the requested parameter key, returning its value:
int getConfigFromFile(const std::string & configFileName, const std::string & key)
{
    // TODO...
}
</code>```

Title: Setting global parameters: is this a reasonable use of const_cast and volatile?

Body:
I have a program that I run repeatedly with various parameter sets. Different parameters are used in different parts of the program (including different source files). The same parameter may also be used in different places. However, all parameters are constant during run-time after they have been set.

I discovered very quickly that declaring the parameters locally does not make sense (it involves having to remember where every parameter is defined, etc.), so I resorted to using a params.h where I declared and defined all the parameters: const int Param1 = 42;, etc.

The downside of this is that I have to recompile every time I change a parameter. So  I'm thinking of using the method below. It relies on usingvolatile and const_cast, which is normally considered "dirty", but it ensures once the parameters have been set in main, they are not accidentally changed anywhere else in the program.

I'm wondering whether people think this is OK, because eventually I want to open-source my code.

In params.h:

```<code>namespace Params
{
extern volatile const int Param1;
// etc.
}
</code>```

In main.cpp:

```<code>#include "params.h"

volatile const int Params::Param1 = 0;

int main(int argc, char* argv[])
{
    int* const pParam1 = const_cast<int*>(Params::Param1);
    *pParam1 = // Get value from argv[] or some config.ini file.
    // etc.
}
</code>```

Body:
Don't use volatile const, it sounds like nonsense! Instead, use a class/struct and initialize all variables in the constructor. You can still use const.

Params.h:

struct ConfigParams {

    const int param1;
    const int param2;
    // ...

    // Define a constructor that will load stuff from a configuration file.
    // Tune this to meet your needs, such as parsing the data from a startup command line.
    ConfigParams(const std::string & configFileName);
};

// The global that you will use to fetch the configurations during runtime.
extern const ConfigParams configParams;

Params.cpp:

// Declare the global configuration data table:
const ConfigParams configParams("app_configs.ini");

// The constructor:
ConfigParams::ConfigParams(const std::string & configFileName)
    : param1(getConfigFromFile(configFileName, "param1"))
    , param2(getConfigFromFile(configFileName, "param2"))
    // and so on ...
{
}

// And this function would open the file and lookup the requested parameter key, returning its value:
int getConfigFromFile(const std::string & configFileName, const std::string & key)
{
    // TODO...
}


问:
How do people make money by writing programming languages?
Why will anyone even attempt to write a programming language?

It seems to be a tedious task and the alternative (simply using an existing language) seems to make much more economical sense.

Microsoft may hire people to write .NET because they have too much spare money to burn. But why will anyone else write a language if they aren't paid for it?

答:
To increase the creativity. Also for reputation. Writing the Programming Language not only boost your creativity but also change the way you think and makes you the smartest person in the crew.

Writing more and more programs gives the new way solve the problem and makes your mind broad.


答:
It does indeed seem smelly, and without seeing more context it's impossible to say for sure. There could be two reasons for doing this, although there are alternatives for both.

First, it's a concise way of implementing partial conversion, or leaving the result with default values if conversion fails. That is, you might have this:

```<code>public void ConvertFoo(Foo from, Foo to) {
    if (can't convert) {
        return;
    }
    ...
}

Foo a;
Foo b = DefaultFoo();
ConvertFoo(a, b);
// If conversion fails, b is unchanged
</code>```

Of course, usually this is handled using exceptions. However, even if exceptions need to be avoided for whatever reason, there's a better way to do this - the TryParse pattern being one option.

Another reason is that it could be for purely consistency reasons, for example it's part of a public API where this method is used for all conversion functions for whatever reason (such as other conversion functions having multiple outputs).

Java's not great at dealing with multiple outputs - it can't have output-only parameters like some languages, or have multiple return values like others - but even still, you could use return objects.

The consistency reason is rather lame but sadly it may be the most common.

Perhaps the style cops at your workplace (or your codebase) come from a non-Java background and have been reluctant to change.

Your code may have been a port from a language where this style is more idiomatic.

Your organisation may need to maintain API consistency across different languages, and this was the lowest-common-denominator style (it's daft but it happens even for Google).

Or perhaps the style made more sense in the distant past and morphed into its current form (for example, it could have been the TryParse pattern but some well-intentioned predecessor removed the return value after discovering that nobody checked it at all).

Body:
It does indeed seem smelly, and without seeing more context it's impossible to say for sure. There could be two reasons for doing this, although there are alternatives for both.

First, it's a concise way of implementing partial conversion, or leaving the result with default values if conversion fails. That is, you might have this:

public void ConvertFoo(Foo from, Foo to) {
    if (can't convert) {
        return;
    }
    ...
}

Foo a;
Foo b = DefaultFoo();
ConvertFoo(a, b);
// If conversion fails, b is unchanged

Of course, usually this is handled using exceptions. However, even if exceptions need to be avoided for whatever reason, there's a better way to do this - the TryParse pattern being one option.

Another reason is that it could be for purely consistency reasons, for example it's part of a public API where this method is used for all conversion functions for whatever reason (such as other conversion functions having multiple outputs).

Java's not great at dealing with multiple outputs - it can't have output-only parameters like some languages, or have multiple return values like others - but even still, you could use return objects.

The consistency reason is rather lame but sadly it may be the most common.

Perhaps the style cops at your workplace (or your codebase) come from a non-Java background and have been reluctant to change.

Your code may have been a port from a language where this style is more idiomatic.

Your organisation may need to maintain API consistency across different languages, and this was the lowest-common-denominator style (it's daft but it happens even for Google).

Or perhaps the style made more sense in the distant past and morphed into its current form (for example, it could have been the TryParse pattern but some well-intentioned predecessor removed the return value after discovering that nobody checked it at all).


答:
The primary problem I see with this is that talking about your code you're going to get a lot of "which Entity do you mean?" questions.

Most modern computer languages (and many older ones) provide name scoping to avoid this problem, but English is older than any of them and all it has is weak context hinting. Which means that if you go down this path you're going to add a lot of qualifiers to your discussions to disambiguate the ambiguity you've added.

Much better would be to call your "root descendant" or wrapper class something else. Sprite is possibly a good name.

Title: Is it bad to use the same class or idiom names as in a third-party API that you're using?

Body:
FlashPunk is a third-party graphics API for simple game development in AS3, and they take what are effectively sprites or display objects of some sort and refer to them as "Entities".  Entity is the actual class name, and it's the predominant class to use to animate something such as a character moving on the screen.

There's a bit of a convention right now in which you refer to things like barriers, enemies, characters, etc. as "entities".  So that being said, if you're using FlashPunk for your graphics, is it bad to create a base class to represent such things and name it Entity as well?  (In particular, does this violate a widely-held coding convention?)

Obviously it would be in a different package, and most people would probably separate the graphics from the game's actual state, so there's not a lot of overlap there.  It's just using the same title.

What about scenarios like this in general with programming?  Is there a particular convention?


问:
Standard ways of revoking user access to a site
I'm in the process of building a .NET MVC website where a requirement is that admin users should be able to lock accounts to not only prevent future log-ins but to also immediately revoke access to the site for a given authenticated user.

Locking the account is easy, but is there an established method of preventing access immediately in this type of scenario. Is it a case of checking on each request whether the requester's account is locked in the db and then clearing the authentication cookie if required?

I'd appreciate any pointers anyone has.

答:
A method that I have used is to allow Admins to effectively assign discontinued users to a role marking those users as such.  The role can be called whatever you like, such as "Disabled", while active users would be assigned to a role of "Active".

Then I just prevent access via the Authorize annotation at the Controller(s) level:

[Authorize(Roles = "Active")]


问:
How to store Role Based Access rights in web application?
Currently working on a web based CRM type system that deals with various Modules such as Companies, Contacts, Projects, Sub Projects, etc.  A typical CRM type system (asp.net web form, C#, SQL Server backend).  We plan to implement role based security so that basically a user can have one or more roles.

Roles would be broken down by first the module type such as:

-Company

-Contact

And then by the actions for that module for instance each module would end up with a table such as this:

```<code>Role1 Example:

    Module   Create  Edit        Delete   View
    Company   Yes    Owner Only    No     Yes
    Contact   Yes    Yes           Yes    Yes
</code>```

In the above case Role1 has two module types (Company, and Contact).  For company, the person assigned to this role can create companies, can view companies, can only edit records he/she created and cannot delete.  For this same role for the module contact this user can create contacts, edit contacts, delete contacts, and view contacts (full rights basically).

I am wondering is it best upon coming into the system to session the user's role with something like a:

List<Role> roles;

Where the Role class would have some sort of List<Module> modules; (can contain Company, Contact, etc.).?  Something to the effect of:

```<code>class Role{
string name;
string desc;
List<Module> modules;
}
</code>```

And the module action class would have a set of actions (Create, Edit, Delete, etc.) for each module:

```<code>class ModuleActions{
List<Action> actions;
}
</code>```

And the action has a value of whether the user can perform the right:

```<code>class Action{
string right;
}
</code>```

Just a rough idea, I know the action could be an enum and the ModuleAction can probably be eliminated with a List<x, y>.  My main question is what would be the best way to store this information in this type of application: Should I store it in the User Session state (I have a session class where I manage things related to the user).  I generally load this during the initial loading of the application (global.asax).  I can simply tack onto this session.

Or should this be loaded at the page load event of each module (page load of company etc..).  I eventually need to be able to hide / unhide various buttons / divs based on the user's role and that is what got me thinking to load this via session.

Any examples or points would be great.

答:
I think it would be best to store a List<Action> in the session. Resolve this list based on the roles the user has at the beginning of the session.

Unless permissions change often, it is enough that the user permissions are updated on each login.

On a sidenote, I would not design it so that Role has a List<Module> but instead a List<Action>.


问:
Project based prefix for class names
My project leader uses project based prefixes for class names, lets say projects name ABC, he create User class name as ABCUser. and he says he do this becasuse if he wants to make User.aspx Users get mixed. so I told him why not use namespace (Entity.User ie.) to make it specific but he against it. I would like to hear from you guys' opinion on this subject.

We code c#.net and using visual studio for projects.

答:
I currently work on a large project where every class is prefixed with the project name. Strangely it helps quite a lot, if you have a file, you can find the class very easily.

Now I imagine this doesn't help much if you have a dozen or two files, but when you have many hundred... things are different. So its not a bad idea per-se, and it won't hurt you to have such a standard.

That said, there are other ways to skin cats. so a namespace for each project and keeping your files organised in some other way to ensure you can quickly determine which part of the project a particular file comes from would work too.

I wouldn't complain particularly. One name is as good as another, so what if its called ABCUser or ABC.User. Sometimes trivial standards like this are not worth the hassle of worrying about. Save your powder for bracket placement and #region usage.

Title: Project based prefix for class names