答:
HTTPS secures the communication channel against eavesdropping: that is, any man-in-the-middle who could otherwise read your traffic without either side noticing will now see nothing but encrypted data, and the encryption is done in a way that it can only be undone either by getting at the server's private key, or by attacking the encryption algorithm itself. Additionally, HTTPS makes sure that the server you're talking to is actually the correct one: the certificate specifically points to a domain name (e.g. acme.com), and the server authenticates itself through the certificate; this way, when someone hijacks your DNS and points acme.com to their own server, they won't have a valid certificate to serve, and the authentication will fail (this is what happens when your browser throws a huge warning sign in your face).

Now, when you log into a website, the server has to know who you are on subsequent requests, and the way this is usually (well, practically always) done is through a session cookie. This cookie is set once at login, and then sent back to the server on every request. Now consider what happens when such a request is not encrypted: an eavesdropper can read it, including the Cookie header, extract the cookie, and take over your login. You don't want that.

Technically speaking, only sensitive requests have to contain the cookie and run over a secure connection, but mixing secure and non-secure requests within one document leads to a whole cornucopia of other issues, and it's just too difficult to get right that the general consensus is that it's better (easier and more reliable) to just serve everything over HTTPS, including scripts, images, stylesheets, AJAX requests, and anything else you can think of.

Another thing to keep in mind: The Cookie RFC specifies two flags you can set on a cookie: SECURE and HTTP_ONLY. For session cookies, you should always set both, and here's why:

SECURE instructs the browser to never send the cookie over an insecure connection. When you set it, an attacker won't be able to trick the browser into sending it over an untrusted (and potentially hijacked) connection, which removes an entire class of attack angles from the scene. Similarly, if you missed a spot and your application accidentally sends plain HTTP requests from an HTTPS context, an eavesdropper might still see the cookie without this flag, but with it, the browser will simply silently exclude the cookie from the request. Not all browsers honor this flag, so you still need all the other precautions, but the recent mainstream ones all do.

HTTP_ONLY means the cookie is not accessible from within JavaScript, not even read-only. This prevents combinations of XSS and Session Hijacking attacks, where an attacker uses XSS to plant JavaScript which then reads the session cookie and sends it back home. With the HTTP_ONLY flag, the cookie will be invisible to the JavaScript, so the attack won't work.

Title: Do logged in users need to browse a site over https?

Body:
I've never thought it was necessary, but a client has requested that all webpages served to logged in users be delivered over HTTPS.

Aside from the implementation standpoint, which I don't think I'm going to pursue is there any real reason for this request ?

For clarity, the login / logout process, account settings, registration preferences and all user related scripts are served over https. but I can't see the point in my news articles, press releases, events etc... being served in this manner? Am I missing something ?


问:
How do you avoid working on the wrong branch?
Being careful is usually enough to prevent problems, but sometimes I need to double check the branch I'm working on (e.g. "hmm... I'm in the dev branch, right?") by checking the source control path of a random file.

In looking for an easier way, I thought of naming the solution files accordingly  (e.g. MySolution_Dev.sln) but with different file names in each branch, I can't merge the solution files.

It's not that big of a deal but are there any methods or "small tricks" you use to quickly ensure you're in the correct branch?  I'm using Visual Studio 2010 with TFS 2008.

答:
I am using this
http://visualstudiogallery.msdn.microsoft.com/f3f23845-5b1e-4811-882f-60b7181fa6d6

Updates your title to for example:

Development\myproject

or

Main\myproject

or

Release\myproject

Hope it helps

ContentLicense: CC BY-SA 3.0


问:
Unit test SHA256 wrapper queries
I have the following SHA256 wrapper.

```<code>    public static string SHA256(string plainText)
    {
        StringBuilder sb = new StringBuilder();

        SHA256CryptoServiceProvider provider = new SHA256CryptoServiceProvider();
        var hashedBytes = provider.ComputeHash(Encoding.UTF8.GetBytes(plainText));

        for (int i = 0; i < hashedBytes.Length; i++)
        {
            sb.Append(hashedBytes[i].ToString("x2").ToLower());
        }

        return sb.ToString();
    }
</code>```

Do I want to be testing it? If so, what do you recommend?

My thought process is as follows:

What logic is there here.

The answer is my for loop and ToString("x2") so from my understanding I want to be testing this part?

I can assume Encoding.UTF8.GetBytes(plainText) works. Correct assumption?
I can assume SHA256CryptoServiceProvider.ComputeHash() works. Correct assumption?

I want to be only testing my logic. In this case is limited to the printing of hex encoded hash. Correct?

Thanks.

EDIT:

Update method based on MainMa's excellent answer:

```<code>    /// <summary>
    /// Returns a SHA256 hash of the plain text.
    /// </summary>
    /// <param name="plainText">The pain text.</param>
    /// <returns>The hash.</returns>
    public static string SHA256(string plainText)
    {
        if (string.IsNullOrWhiteSpace(plainText)) throw new ArgumentNullException("The plain text cannot be empty.");

        StringBuilder sb = new StringBuilder();

        Byte[] hashedBytes;
        using (SHA256CryptoServiceProvider sha256Provider = new SHA256CryptoServiceProvider())
        {
            hashedBytes = sha256Provider.ComputeHash(Encoding.UTF8.GetBytes(plainText));
        }

        foreach(Byte b in hashedBytes)
        {
            sb.Append(b.ToString("x2").ToLower(CultureInfo.InvariantCulture));
        }

        return sb.ToString();
    }
</code>```

答:
Note: a more detailed discussion of the code is available at my website. It covers nearly all the points covered here, and shows, step by step, how this piece of code can be refactored into a piece of reliable software.

First, you may want to test the edge cases.

What if plainText is null? You don't check the inputs. Is this intentional, i.e. you rely on GetBytes to throw ArgumentNullException in your place? Is this a mistake?

What if plainText is long, and by long, I mean the maximum allowed by Windows? This is a complicated case, since unit testing it is not obvious (including in terms of performance and memory consumption: nobody wants their unit tests taking all memory available), but you still should consider it.

Hint: the easiest and fastest way to handle this case is to specify the maximum supported length in the product requirements, and then enforce this limit at input validation step.

What if plainText is an empty string?

What if you are calling the method plenty of times? You don't dispose SHA256CryptoServiceProvider, despite the fact that you should, which means that sooner or later, it will fail more or less unpredictably. This is another case where unit testing is complicated/practically impossible.

Second, you're right, you can rely on the methods from .NET Framework and assume they are correctly implemented. This means that you have to test your logic and the way you use those methods:

Write a simple test which calls the method with "Hello World!" as input. Take any non-.NET language: JavaScript, Python, whatever. Compute the SHA256 hash with this language and hardcode the result in your unit test. Compare.

Analyse your code (note: in TDD, you don't do that: you write tests from the use cases, not the actual code). Such analysis should give you the overall view of the flow: where are the conditions, how do you exit the loops, are there guard clauses, etc. The actual flow is easy: a sequence of calls to different methods, then a for. Aside the missing using, the sequence of calls can create a risk of using a variable while it is null. For example:

```<code>var product = this.GetProductById(productId);
var category = product.GetCategory();
</code>```

is wrong, unless there is a guarantee that GetProductById cannot return null. The previous piece of code should have been:

```<code>var product = this.GetProductById(productId);
if (product == null)
{
    // Handle the situation and either throw an exception or prematurely return/break.
}

var category = product.GetCategory();
</code>```

or:

```<code>var product = this.GetProductById(productId);
Debug.Assert(
    product != null,
    "The null result is unexpected from ProductsManager.GetProductById method.");

var category = product.GetCategory();
</code>```

or:

```<code>var product = this.GetProductById(productId);
Contract.Assume(product != null);
var category = product.GetCategory();
</code>```

In your case, there are only constructors, so you don't have to care about null references.

for that you erroneously use (it should have been foreach) is another point to consider. Is the loop made correctly? Do you have to do i < hashedBytes.Length or i <= hashedBytes.Length? When you access the hashedBytes by index, are you sure that the index is never out of range? Could the length be bigger than int.MaxValue? What would happen?

Finally, you're using both byte.ToString and ToLower without specifying the culture. Since you don't say neither that you're expecting the InvariantCulture to be used, it may indicate that you simply forgot to clearly indicate your intent. Both methods use the current culture. This means that you have also to unit test cases where the current culture is not en-US, since the final result of your SHA256 method depends on it (or use formal methods to show that the result would be the same for any culture).

Moreover, byte.ToString("x2") already produces a lowercase string. Converting a lowercase string to lowercase is not needed. Always get rid of the code you don't need.

Conclusion:

Your assumption that you can rely on methods from .NET Framework is true. However, the way you use them should be unit tested. As you can see, in this very short method with simple logic,

there is a potential severe bug which will appear sooner or later when somebody will start to modify this method.

by not disposing objects properly, created a bug which will be very hard to debug later,

made it error prone by wrongly using for when foreach was expected,

made it potentially vulnerable by not checking your inputs (while this is a public method),

made it difficult to guess which exceptions may be thrown by this method,

made its behavior very random when it comes to edge cases (strings too long, null, etc.)

You could have avoided few of those issues with severe testing, but testing alone is not enough. Using other techniques, such as informal code reviews or static checking should be systematic and cover if not all, at least most non-CRUD code you write.

Title: Unit test SHA256 wrapper queries

Body:
Note: a more detailed discussion of the code is available at my website. It covers nearly all the points covered here, and shows, step by step, how this piece of code can be refactored into a piece of reliable software.

First, you may want to test the edge cases.

What if plainText is null? You don't check the inputs. Is this intentional, i.e. you rely on GetBytes to throw ArgumentNullException in your place? Is this a mistake?

What if plainText is long, and by long, I mean the maximum allowed by Windows? This is a complicated case, since unit testing it is not obvious (including in terms of performance and memory consumption: nobody wants their unit tests taking all memory available), but you still should consider it.

Hint: the easiest and fastest way to handle this case is to specify the maximum supported length in the product requirements, and then enforce this limit at input validation step.

What if plainText is an empty string?

What if you are calling the method plenty of times? You don't dispose SHA256CryptoServiceProvider, despite the fact that you should, which means that sooner or later, it will fail more or less unpredictably. This is another case where unit testing is complicated/practically impossible.

Second, you're right, you can rely on the methods from .NET Framework and assume they are correctly implemented. This means that you have to test your logic and the way you use those methods:

Write a simple test which calls the method with "Hello World!" as input. Take any non-.NET language: JavaScript, Python, whatever. Compute the SHA256 hash with this language and hardcode the result in your unit test. Compare.

Analyse your code (note: in TDD, you don't do that: you write tests from the use cases, not the actual code). Such analysis should give you the overall view of the flow: where are the conditions, how do you exit the loops, are there guard clauses, etc. The actual flow is easy: a sequence of calls to different methods, then a for. Aside the missing using, the sequence of calls can create a risk of using a variable while it is null. For example:

var product = this.GetProductById(productId);
var category = product.GetCategory();

is wrong, unless there is a guarantee that GetProductById cannot return null. The previous piece of code should have been:

var product = this.GetProductById(productId);
if (product == null)
{
    // Handle the situation and either throw an exception or prematurely return/break.
}

var category = product.GetCategory();

or:

var product = this.GetProductById(productId);
Debug.Assert(
    product != null,
    "The null result is unexpected from ProductsManager.GetProductById method.");

var category = product.GetCategory();

or:

var product = this.GetProductById(productId);
Contract.Assume(product != null);
var category = product.GetCategory();

In your case, there are only constructors, so you don't have to care about null references.

for that you erroneously use (it should have been foreach) is another point to consider. Is the loop made correctly? Do you have to do i < hashedBytes.Length or i <= hashedBytes.Length? When you access the hashedBytes by index, are you sure that the index is never out of range? Could the length be bigger than int.MaxValue? What would happen?

Finally, you're using both byte.ToString and ToLower without specifying the culture. Since you don't say neither that you're expecting the InvariantCulture to be used, it may indicate that you simply forgot to clearly indicate your intent. Both methods use the current culture. This means that you have also to unit test cases where the current culture is not en-US, since the final result of your SHA256 method depends on it (or use formal methods to show that the result would be the same for any culture).

Moreover, byte.ToString("x2") already produces a lowercase string. Converting a lowercase string to lowercase is not needed. Always get rid of the code you don't need.

Conclusion:

Your assumption that you can rely on methods from .NET Framework is true. However, the way you use them should be unit tested. As you can see, in this very short method with simple logic,

there is a potential severe bug which will appear sooner or later when somebody will start to modify this method.

by not disposing objects properly, created a bug which will be very hard to debug later,

made it error prone by wrongly using for when foreach was expected,

made it potentially vulnerable by not checking your inputs (while this is a public method),

made it difficult to guess which exceptions may be thrown by this method,

made its behavior very random when it comes to edge cases (strings too long, null, etc.)

You could have avoided few of those issues with severe testing, but testing alone is not enough. Using other techniques, such as informal code reviews or static checking should be systematic and cover if not all, at least most non-CRUD code you write.


问:
How to familiarize myself with Python
I'm a Python beginner. I started programming with Python 1.5 months back.

I downloaded the Python docs and read some parts of the tutorial. I have been programming on codechef.com and solving problems of projecteuler. I am thinking of reading Introduction to algorithms and following this course on MIT opencourse ware as I haven't improved much in programming and I am wasting a lot of time thinking just what should I do when faced with any programming problem.

But I think that I still don't know the correct way to learn the language itself. Should I start with the library reference or continue with the Python tutorial? Is learning algorithms useful for languages such as C and not so much for Python as it has "batteries included"?

Are there some other resources for familiarization with the language and in general for learning to solve programming problems? Or do I need to just devote some more time?

答:
First of all, learning algorithms is orthogonal to learning any particular programming language, and spending time on algorithms is never wasted - in short, better knowledge of all sorts of algorithms makes you a better programmer overall, period.

Apart from that, you seem to be struggling with two independent problems: learning Python, and learning programming. How you approach learning both is highly dependent on where you stand regarding either, as well as what does and doesn't work for you.

That said, I've found the following approach works well when learning a new technology:

Do a bit of preliminary reading: the wikipedia page, the project homepage, the official documentation; get an idea what it is about and how the community ticks.

Install the toolchain, find a good introductory tutorial that matches your style, and play around with it. Make a few super-tiny programs, something that is sort of kind of useful, but most importantly, something you can finish in about an hour or so. Also make sure you have a complete authoritative reference guide at hand.

Once you get the hang of the language basics, you should have a rough idea of what the language is good at and what not. Pick a project that the language is very suitable for, and start working on it. Get in touch with the community: they'll provide you with invaluable insights and tips.

Throw away your first project and start from scratch. Really. The first project you build in any language is usually crap; that's fine, you did it for the learning experience, and you'll get half of it wrong. This is why you do it again, but this time, you do it better and more in line with the language's accepted conventions, standards and idiosyncrasies.

Practice, practice, practice. Keep in touch with the community. Experiment. Read other people's code. Have others read your code. Keep an eye on new developments. And most of all, have fun.

Just like with natural languages, my experience is that nothing beats actual hands-on real-world exposure. You will never learn it if you don't use it a lot.

Title: How to familiarize myself with Python


问:
Should I be worried about overengineering programming assignments given during interview process?
I recently had a phone interview with a company. After that phone interview, I was told to complete a short programming assignment (a small program; shouldn't take more than three hours). I'm only directly instructed to complete the assignment and turn in the code. I was given complete freedom to use any language I wished and was not told exactly how to turn in the code.

Immediately I planned on throwing it on Github, writing a test suite for it, using Travis-CI (free continuous integration for public Github repositories) to run the test suites, and using CMake to build the Linux makefiles for Travis-CI. That way, not only can I demonstrate that I understand how to use Git, CMake, Travis-CI, and how to write tests, but I can also simply link to the Travis-CI page so they can see the output of the tests. I figured that'd make it a tiny bit more convenient for the interviewer.

Since I know those technologies well, it would add essentially no time to the assignment.

However, I'm a bit worried that doing all this for a relatively simple task would look bad. Although it wouldn't add much more time at all for me, I don't want them thinking I spend too much time on things that should be simple.

答:
I think that your approach is neither good nor bad per se. I would ask the interviewer if it's ok to use Github and the other tools. As @Izkata pointed out in the comments, you are making your solution public.

As an interviewer, I known there's usually no harm in the candidate trying to clarify a few things. Also, asking one or two questions can be a good sign, as you don't rush to do things that you didn't understand.

Remember, though, that the most important thing is that the problem is solved, and solved well. In that regard, everybody agrees that a test suite helps. But, for that, maybe you just need to send a couple of test classes together with your project/solution.


问:
Generic and type safe I/O model in any language
I am looking for an I/O model, in any programming language, that is generic and type safe.

By genericity, I mean there should not be separate functions for performing the same operations on different devices (read_file, read_socket, read_terminal). Instead, a single read operation works on all read-able devices, a single write operation works on all write-able devices, and so on.

By type safety, I mean operations that do not make sense should not even be expressible in first place. Using the read operation on a non-read-able device ought to cause a type error at compile time, similarly for using the write operation on a non-write-able device, and so on.

Is there any generic and type safe I/O model?

答:
Having thought some more about this, I think that it can be proved that it is not possible to deal with seekability entirely by compile time type checking.

In Linux / Unix there are things called "named sockets" that exist in the file system and can be opened in the same way as other objects in the file system.  The catch is that they are no seekable.  And there are "device files" that have the same property; e.g. "/dev/tty" or "/dev/null".

An IO library needs to be able to create an input or output stream for an object using a filename or pathname supplied as a string; i.e. a runtime value.  (If you can't do that, the language has "limited utility".)

The "open" method therefore needs to be able to cope with the cases that it could be asked to open a seekable object or a non-seekable object ... and that it won't know which is the case until it has tried it.

This means that even if you were to design a set of APIs that distinguished between seekable and non-seekable streams, there would still need to be a runtime test to determine if a specific file could be opened as a seekable (or non-seekable) stream.

In short, it is not possible deal with this entirely via static typing.

UPDATE

Mat Fennwick commented thus:

Perhaps I'm missing something, but it seems to me that your example could be handled with an algebraic sum type, à la Haskell. Is that not the case?

Yes, I think that you could express different flavours of stream using algebraic sum types.  But I don't see how this is going to give you a compilation error if you:

open a stream based on a pathname, then

try to do a seek on a non-seekable stream.

You'd end up having to do a switch to discriminate the seekable and non-seekable cases, and deal with the possibility that you've got the wrong kind of stream.

Now you could design the APIs to minimize the runtime checking.  But my feeling is that that comes at a cost.  And the cost is that the classes that use the APIs get more complicated.  For instance, whenever you pass a stream object you have to think whether you need to declare the method to require a seekable or non-seekable stream parameter.  (And you can't just say "either" all of the time and use a common supertype ... because then you need a typecast at the point where the stream needs to be seekable and your compiler can no longer detect the real problem.)

The other problem with mapping (effectively) runtime properties to compile time types / interfaces is that it gets messy when you've got multiple; e.g. imagine if you had types / interfaces for seekability, readability, writability, deletability and so on.  You end up with a combinatorial explosion of the leaf classes.

Finally, if this was a good idea, you would have thought that some would have tried it, shown it to be a good idea, and convinced someone to add it to a mainstream programming language.  AFAIK, the last step hasn't happened.  OK, that is not proof that it won't work ... but the absence is pretty convincing.


问:
Python GUI and MVC - get variable from other module
I am trying to split my code into different layers:
GUI, reading the GUI, creating input, calculating the model, interpreting data, creating view, sending the view to the GUI.
Somebody told me about MVC and I would like to try to build my program that way. But I'm a little confused about how to exchange information between those modules. I'm running into problems with undefined global names and so forth.
My model is written in matlab and consists of a simulation. The GUI is supposed to present the data in plots.

My actual problem is: how to connect the different modules/classes/files to each other if they are supposed to be as independent as possible?

For example: I'm creating a GUI in one file, like this:

```<code># userinterface.py

class Userinterface(object):
    def __init__(self, controller):
        self.controller = controller
        self.buildGUI()
        return

    def buildGUI():
        # build lots of widgets and stuff
        widget = tk.Thewidget(options=values, command=self.controller.onclick)
</code>```

And call it my interface. In order to keep this file nice and clean, I would like to define all functions to handle button clicks and read fields in another file and I guess this is what you would call the controller part:

```<code># main.py
    import userinterface as gui

    class Controls(object):
        def onclick(self):
            # read values from widgets and do stuff
            var1 = GUI.widget_entry.get()
            # Call some other function with var1 etc.

if __name__ == '__main__':
    GUI_controls = Controls()
    GUI = gui.UserInterface(GUI_controls)
</code>```

But how do I do to connect these two? In my example above, I'm handing over an instance of my Controls object. But then I read about Events too or Inheritance or subclasses.

I'm rather new to programming and started all this 2 months ago, so I'm struggling sorting all these theories.

If somebody could point out to me what the way of communication between my modules/files should be and what such a meeting-point looks like. Or just give me a link that I can study (like Javier did, although I'll have to read this thing more than once)

答:
You're on the right track. The controller is what binds the app together, so passing it around to the various view and model classes is fine.

However, don't think that just because you have a controller, all widgets must use that controller for everything. For instance, I wouldn't put the onclick method in the controller. The controller should be for routing business logic, but what you're doing is mostly specific to the GUI.

I think a good general rule of thumb is that GUI events and callbacks should be within the GUI module. They then call the controller when interfacing with business logic. Fetching a string from the GUI itself is not business logic.

So, instead of:

```<code># GUI module
button = Button(..., command=controller.on_click)

# Controller module
def on_click():
    var1 = GUI.widget_entry.get()
    self.do_something(var1)
</code>```

I would do this:

```<code># GUI module
button = Button(..., command=on_click)
def on_click():
    var1 = widget_entry.get()
    controller.do_something(var1)
</code>```

With the above, the controller doesn't need to know what widgets are part of the GUI. All it does is provide an interface through which the GUI can request services.

If you prefer to keep the on_click in the controller, that's possible too, and not completely unreasonable. However, instead of building in knowledge of the GUI widgets into the controller, give the GUI an interface that the controller can use.

For example, instead of doing GUI.widget_entry.get(), the controller would call an accessor such as GUI.get_entry_widget_value(). That allows you to refactor the GUI without having to change the controller. If you move the entry to the_widget_entry instead of widget_entry, the controller can be completely unaware and still function properly.

Body:
You're on the right track. The controller is what binds the app together, so passing it around to the various view and model classes is fine.

However, don't think that just because you have a controller, all widgets must use that controller for everything. For instance, I wouldn't put the onclick method in the controller. The controller should be for routing business logic, but what you're doing is mostly specific to the GUI.

I think a good general rule of thumb is that GUI events and callbacks should be within the GUI module. They then call the controller when interfacing with business logic. Fetching a string from the GUI itself is not business logic.

So, instead of:

# GUI module
button = Button(..., command=controller.on_click)

# Controller module
def on_click():
    var1 = GUI.widget_entry.get()
    self.do_something(var1)

I would do this:

# GUI module
button = Button(..., command=on_click)
def on_click():
    var1 = widget_entry.get()
    controller.do_something(var1)

With the above, the controller doesn't need to know what widgets are part of the GUI. All it does is provide an interface through which the GUI can request services.

If you prefer to keep the on_click in the controller, that's possible too, and not completely unreasonable. However, instead of building in knowledge of the GUI widgets into the controller, give the GUI an interface that the controller can use.

For example, instead of doing GUI.widget_entry.get(), the controller would call an accessor such as GUI.get_entry_widget_value(). That allows you to refactor the GUI without having to change the controller. If you move the entry to the_widget_entry instead of widget_entry, the controller can be completely unaware and still function properly.


问:
Are the technologies used in an application part of the architecture, or do they represent implementation/detailed design details?
When designing and writing documentation for a project an architecture needs to be clearly defined: what are the high-level modules of the system, what are their responsibilities, how do they communicate with each other, what protocols are used etc. But in this list, should the concrete technologies be specified or this is actually an implementation detail and need to be specified at a lower level?

For example, consider a distributed application that has two modules which communicate asynchronously via AMQP protocol, mediated by a message broker. The fact that these modules use the Spring AMQP library for sending and receiving messages is a fact that needs to be specified in the architecture or is a lower-level detailed design/implementation detail?

答:
It depends - for one thing, the definition of architecture is pretty fuzzy: The SEI gives probably more than 100 definitions of the term, though the one I personally use most often is Chris Verhoef's:

Architecture is that which is hardest to change.

Under this definition, it's easier to characterize architecture by looking backwards on an existing system than by looking forwards while the system is being designed. It can still be used during design, IMO. You could say that a technology choice can be considered architectural when you have designed large parts of the system in such a way that they are tightly coupled to your technology. (For example, choice of programming language is extremely likely to be an architectural decision.)


问:
Is sticking to one language on a particular project a good practice?
I'm developing a pipeline for processing text that will go into production. The question I keep asking myself is: should I stick to one language for the project when I'm looking for a tool to do a particular task (e.g. NLTK, PDFMiner, CLD, CRFsuite, etc.)?

Or is it OK to mix and match languages on the project?  So I pick the best tool regardless of what language it's written in (e.g. OpenNLP, ParsCit, poppler, CFR++, etc.) and warp (wrap) my code around it?

Note, I am not asking about should a developer stick to just one language for their career.

答:
I have found that large multi-programmer, multi-year projects are best served with a single language, while small, one-person projects are best served with a "whatever works" policy.

The issue is maintenance and bringing in new programmers. If you have a large project that spans many years, then you have a significant investment in the code base. When you recruit people you can recruit people who know the single technology that your project uses. Programmers that don't know it, can learn it.  If you have a project that uses 10 different technologies, each of which is best at what it does, you'll have a situation where some programmers can't work on some parts, or else you'll only be able to hire people that know all of the core technologies.

If you have a small project, then the only technologies it uses will be those known to the solo-developer. This is a mess to maintain over time. Chance are, though, that you won't need to maintain it.

We had a project that grew from a small one to a big one. At year 4 we realized that we had written code in C++, Java, Python, Perl and SQL. We used every interprocess communication system available in Unix. We found it nearly impossible to hire people and, when we did, they couldn't work on the majority of our code base.  Things did not work out well.


问:
Implementation details of database synchronisation API
I want to achieve a database synchronisation between my server database and a client application. The server would run MySQL and the applications may run different database technologies, their implementation isn't important.

I have a MySQL database online and web accessible via an API I wrote in PHP (just a detail).

My client application ships with a copy of the online data. As time passes my goal is to check for any changes in the online database and make these updates available to the client app via an API call, by sending a date to an API endpoint corresponding to the last date the app was updated, the response would be a JSON filled with all new objects and updated objects, and delete IDs, this makes possible to update the local store appropriately.

Essentially I want to do this: http://dbconvert.com/synchronization.php

My question is about the implementation details.

Would I need to add a column to my database tables with a "last modified" date?

Since the client app could be very out of date if it's been offline for a long time, does that also mean I shouldn't delete data from the online database but instead have another column called "delete" set to 1 and a modified date updated appropriately?

Would my SQL query simply check for all data with a modified date superior then the date passed into the API request by the client?

I feel like there's a lot more to it then having a ton of dates everywhere. And also, worry that I will need to persist a lot of old data in order to ensure that old versions of the client app always have the opportunity to delete parts of their data when they are able to sync.

答:
There are different ways to do it but in general you have 2 choices:

Rough imports: overwrite what you have with the new data coming in. So a full new import of the data.

or the alternative:

Track changes:
Don't just use a modified date field but really track all changes. Then let the changes be downloadable with a from date. So, the client asks for all changes since the last time it asked. Then it will apply all changes and you can handle the arising conflicts.


问:
Implementing MVC pattern in SWT application
I am developing an SWT application (it's basically an Eclipse plugin, so I need to use SWT). Currently my design is as follows:

Model: In model, I have POJOs which represents the actual fields in views.

View: It is a dumb layer, it contains just UI and contains no logic (not even event handlers)

Controller: It acts as a mediator b/w those two layers. Also it is responsible for creating view layer, handling events etc.

Basically I have created all of the controls in view as a static like this public static Button btnLogin and in controller I have a code like this:

```<code>public void createLoginView(Composite comp) {
    LoginFormView.createView(comp);  //This createView method is in view layer ie LoginFormView
    LoginFormView.btnLogin.addSelectionListener(new SelectionListener() {
        //Code goes here
    });
}
</code>```

Similalrly I have done for other views and controls. So that in main class and other classes I am calling just createLoginView of controller. I am doing similar thing for other views.

So my question, is what I am doing is correct? Is this design good? Or I should have followed any other approach. Since I am new to SWT and Eclipse plugin development (basically I am Java EE developer having 4+ years of exp). Any tips/pointers would be appreciated.

答:
The MVC Design Pattern that you implemented is definitely good, but I would also encourage you to implement the OOPs in it. It would only then serve your purpose better.

Here are few links, which should help you understand it better;

N-Layer Architecture

OOPS


问:
URL Naming Convention with Repetitive Letter
What is a good practice to name an URL if it contains repetitive letters. For example, /info/foossite

The two s looks kind of odd and if this was access point for a Web-Service, this could lead into misspelling. In most programming languages, we have Camel notation. However, as URLs are case insensitive, we don't have that luxury here.

So, what is the best practice in this regard?

答: I dont think its a big deal to have duplicated letters.  But if you are concerned it will cause confusion or misspellings, you might use a dash in between the words, like /info/foos-site.

ContentLicense: CC BY-SA 4.0


问:
Is the “jQuery programming style” a kind of Reactive programming?
jQuery is a Javascript library and framework, but when we are programming
with jQuery into DOM problems/solutions,
we can practice a style quite different of programming... We can read about jQuery at Wikipedia,

The set of jQuery core features — DOM element selections, traversal and manipulation —, enabled by its selector engine (...), created a new "programming style", fusing algorithms and DOM-data-structures

This question is similar to the "subquestion-3" of this question
but not so generic. The focus here is about this new kind of "programming style"... So, the question:

Is the "jQuery programming style in DOM context" a new paradign? Or it is more one example of reactive programming (not "cell-oriented" but "DOM-node oriented") or another one?

We have no "standard taxonomy of paradigms", so, please, in your answer, indicate also your "best choice for Wikipedia Paradign".

Example: if you understand that "jQuery programming DOM" is like "awk filtering data", your choice can be event-driven.

答:
If there is a paradigm in use in jQuery, it is functional programming, with some Fluent Interface sprinkled in for good measure.  It is the fluent interface pattern that provides for the method chaining capability.

Beyond that, it's simply clever and deliberate application of an API.  Under the hood, there's a lot of jiggery going on to insure cross-browser compatibility, but the foundational ideas behind jQuery are relatively simple.  Just goes to show you how useful a well-designed API can be.


问:
Can web apps allow fast data-typists to "type-ahead"?
In some data entry contexts, I've seen data typists, type really fast and know so well the app they use, and have a mechanic quality in their work so that they can "type ahead", ie continue typing and "tab-bing" and "enter-ing" faster than the display updates, so that in many occasions they are typing in the data for the next form before it draws itself. Then when this next entry form appears, their keystrokes fill the text boxes and they continue typing, selecting etc.

In contexts like this, this speed is desirable, since this persons are really productive.

I think this "type ahead of time" is only possible in desktop apps, but I may be wrong.

My question is whether this way of handling the keyboard buffer (which in desktop apps require no extra programming) is achievable in web apps, or is this impossible because of the way web apps work, handle sessions, etc (network latency and the overhead of generating new web pages ) ?

Edit: By "type ahead" I mean "keyboard type ahead" (typing faster than the next entry form can load), not suggets-as-you-type-like-google type ahead.

Typeahead is a feature of computers and software (and some
  typewriters) that enables users to continue typing regardless of
  program or computer operation—the user may type in whatever speed he
  or she desires, and if the receiving software is busy at the time it
  will be called to handle this later. Often this means that keystrokes
  entered will not be displayed on the screen immediately. This
  programming technique for handling user what is known as a keyboard
  buffer.

答:
Keyboard type-ahead is already incorporated in web apps.  The operating system does not distinguish between desktop apps and web apps, in that sense.

The real impediments to making web applications efficient are:

Network latency; i.e. how long it takes to send data over the Internet, and

The time it takes to generate new web pages to get to the next step in the business process.

These can be remedied, for the most part, by building web applications that use HTML5 to give the look, feel and impression of desktop applications, or by putting the whole form on a single web page.  Then, all the user has to wait for is the application to save the data that the user has typed in.


答:
GrandmasterB's solution is sufficient, but I present an alternative if you're using a RESTful web service.  The whole point behind being RESTful is to make a URL read intuitively.  The first part of the URL is the subject of the pages.

In other words in the URL:

http://www.host.com/books/1

books would be the subject.  However, there's no reason why you shouldn't be able to have URLs like:

http://www.host.com/foos/site/1

So long as it makes sense that they're separate words  (i.e. please don't make URLs like http://www.host.com/book/keeper/1), I wouldn't have any problems doing it this way.

Title: URL Naming Convention with Repetitive Letter

Body:
What is a good practice to name an URL if it contains repetitive letters. For example, /info/foossite

The two s looks kind of odd and if this was access point for a Web-Service, this could lead into misspelling. In most programming languages, we have Camel notation. However, as URLs are case insensitive, we don't have that luxury here.

So, what is the best practice in this regard?


问:
Advanced Search Stored procedure
So I am working on an MVC ASP.NET web application which centers around lots of data and data manipulation.

PROBLEM OVERVIEW:
We have an advanced search with 25 different filter criteria. I am using a stored procedure for this search. The stored procedure takes in parameters, filter for specific objects, and calculates return data from those objects. It queries large tables 14 millions records on some table, filtering and temp tables helped alleviate some of the bottle necks for those queries.

ISSUE:
The stored procedure used to take 1 min to run, which creates a timeout returning 0 results to the browser. I rewrote the procedure and got it down to 21 secs so the timeout does not occur. This ONLY occurs this slow the FIRST time the search is run, after that it takes like 5 secs.

I am wondering should I take a different approach to this problem, should I worry about this type of performance issue if it does not timeout?

答:
No, you don't need to worry about a problem that isn't occurring.  If your query isn't timing out or running unacceptably slow, you can allocate your time elsewhere.

If you are allowing very complex queries, the question of why you are not allowing slightly sanitized SQL arises.  And if you allow arbitrary select statements, then how you handle timeouts and errors and cancellations becomes more important than the performance of your gui-sourced sql.

I've seen and worked with web apps that don't allow direct sql even for competent users, and the results have always been disappointing.  Empowerment lets you handle the edge cases from a design perspective, and focus your attention on where it can get the most benefit instead of doing a user's work for them all the time.

Title: Advanced Search Stored procedure


问:
How do you educate your customers?
Customers need some education because they think different. Customers think:

changes are not a problem in any time of the project

details are not important (exceptions even less)

time does not cost money (they have a fix price agreed)

one sentence in the specification can be extended/read freely to fit the actual needs - and this does not affect the contract. (here we see often the "common sense" discussion - example: "Of course we need a invoice management screen when we talk about accounting managment - this is common sense!")

the list goes on...

The main problem is that customer (no matter if external or internal/department) do not want or can not understand. It took me many years to understand software creation process and I am still learning, so how can they in just a few months.

What is your experience, what is the best approach to educate customers?

答:
Educate the customer. I wish I'm not one of your customer ;)

Seriously, I understand your are in trouble, and you think the problem is the customer. Maybe it is, but it doesn't matter. Changing your customers is really hard, while changing the way your work with them is lot more easier.

The problem is that most customers are not aware of all implications of software development and you are not aware of their business in details.

Just one little thing:

changes are not a problem in any time of the project

"No matter how far you have gone on a wrong road, turn back." Turkish Proverb

I love that proverb, so when I can use it, I'm happy. Thanks for the opportunity ;)

Here are a couple of solutions:

You must provide the customer with the possibility to change his mind, because this will help him getting the right software that really fits its needs. He will eventually get more ideas while you are developing it.

Your are in a fixed price contract, so I guess you had to gather requirements, estimate them and put a price on each?

If you have to build a new thing, use the same process: you amend the fixed price contract with the extra requirements. Accept to remove requirements that will be useless (of you have not built them already of course).

Another approach would be to finish what has been negociated (less useless and not developed requirements) as version 1, and negociate a version 2 with its new ideas.

The second solution would be to create iteration in the development like in Scrum. I've no experience with this yet in fixed price project (because I don't do fixed projects anymore), so I don't know if it works or not. I seriously have lot of doubts Scrum (or Agile) is the solution to all software development projects, but maybe some of the practices described will help you.

ContentLicense: CC BY-SA 2.5

Title: How do you educate your customers?


答:
Java has "stream readers/writes", "byte readers/writes", "line readers/writes" that read from and write to "streams". A "stream" can be a file, a socket, an url, etc.

Also the language is type safe, strictly typed, compiled, etc. It yells at compile time if you attempt to do the wrong operation on the wrong type of stream.

Title: Generic and type safe I/O model in any language

Body:
I am looking for an I/O model, in any programming language, that is generic and type safe.

By genericity, I mean there should not be separate functions for performing the same operations on different devices (read_file, read_socket, read_terminal). Instead, a single read operation works on all read-able devices, a single write operation works on all write-able devices, and so on.

By type safety, I mean operations that do not make sense should not even be expressible in first place. Using the read operation on a non-read-able device ought to cause a type error at compile time, similarly for using the write operation on a non-write-able device, and so on.

Is there any generic and type safe I/O model?


问:
How to save during real-time collaboration
I want multiple users to edit same document. Problem I'm facing is when a new user joins, he might see an outdated document. How do I make sure that new users get most recent changes?

Some solutions I thought of:

Save on every change. I don't like this solution because it will slow things down on UI and put load on db.

When new user joins, trigger save on all other clients. After other clients saved, load document.   With this there can be inconsistency still.

Any other suggestions would be helpful.

UPDATE: After looking into suggested solution, Google Realtime API, I found out that:

Users of your app must have Google Drive and give you access to their drive. This could at best present awkward UI flow or prevent users who don't have Google Drive from using realtime feature.

All the sharing settings that are done on your side, have to be replicated for Google document.

UPDATE 2: To acoomplish the goal, I went with Google's Firebase

答:
I'd recommend 1 persistent copy of the document on the server. When a client connects to the server you issue an UPDATE command(s) to that client with all the changes.

Update WorkFlow

User causes triggering change ->  Client sends UPDATE to Server -> Server sends UPDATE to Clients

Viable triggers

User clicks Save

User completes a specific task

Finishes editing a cell

Finishes editing a sentence/paragraph/line

User clicks Undo

User presses Return key

User types a key (save on every change)

Update Implementation

I would suggest being able to re-create the document with a series of UPDATE commands so that the server stores each UPDATE and when a new client connects the client can be sent the series of updates and it itself can re-create the document to display to the user.  Also, you could alternatively have a SAVE command that is separate and have UPDATE be temporary changes that can be used for UNDO requests and have SAVE actually store it to be re-opened if the server is closed or all clients disconnect.


问:
C# Minimal SQL Database
I'm working on a small project (not production) where I'm needing to store enough data that something like a CSV would be inefficient to process and an SQL/MySQL server would be too much. Does .Net have any way to efficiently store several entries of data with the ability to query without having to manage and connect to a server rather loading and processing a single file.</p>

答:
There are a few alternatives, in no particular order:

All versions of (paid?) visual studio come with SQL Server Express installed. You can use that.

(Ugh) XML files

SQL Server CE (basically, local SQL via file)

SQLite

More ideas here: https://stackoverflow.com/questions/3639846/what-is-a-good-embedded-database-to-use-with-c

Title: C# Minimal SQL Database


问:
Minimal Refresh(F5) Web App Development
Although questions similar to this one has already been asked and I can perhaps assemble the answer for myself by reading  already posted materials. Still I am going ahead with the question, cause I feel it has elements of new flavor and I would like to see the views of others on how to tackle this.

I have developed several Web Applications of various scale. In some of them, I was only Developer, in another I led small teams and was part of a big team in another.

Most of these were developed using PHP. One of them used Kohana Framework, the rest were all developed using Raw PHP. The main difficulty that I faced in regards to speedy development was, whenever a small change was  done to fix a bug or modify a feature, I had to refresh my web browser, go through several pages until I reached the page which included the fix.

I would like to know, what should be the development approach so that I can test out my code without having to, or at least minimize the number of refreshes required to test out changes in code. Although, the concepts maybe applicable for developments of any nature,  for this question, let us stick to PHP and it's framework.

答:
You're going to have to refresh the page: PHP works on page generation. But you can automate the refreshes using a variety of different methods. Check out this article for four different ways:

Quick Tip: 4 Ways to Auto-Refresh your Browser when Designing new Sites

You'll also want to get into test-driven development. It'll automate the process of testing the same things over and over. For PHP, there's SimpleTest among other frameworks for TDD.

Title: Minimal Refresh(F5) Web App Development


答:
In addition to the options Sklivvz offered, don't be afraid to venture outside of the SQL realm and use an embedded object-oriented database engine, such as Sterling or DB4O. </p>

<p>They offer the advantages of being small and file-based, embeddable into your application, but are also very fast and easy to program to. </p>

Title: C# Minimal SQL Database

Body: I'm working on a small project (not production) where I'm needing to store enough data that something like a CSV would be inefficient to process and an SQL/MySQL server would be too much. Does .Net have any way to efficiently store several entries of data with the ability to query without having to manage and connect to a server rather loading and processing a single file.</p>

Body:
In addition to the options Sklivvz offered, don't be afraid to venture outside of the SQL realm and use an embedded object-oriented database engine, such as Sterling or DB4O.

They offer the advantages of being small and file-based, embeddable into your application, but are also very fast and easy to program to.


问:
unit testing variable state explicit tests in dynamically typed languages
I have heard that a desirable quality of unit tests is that they test for each scenario independently. I realised whilst writing tests today that when you compare a variable with another value in a statement like:

```<code>assertEquals("foo", otherObject.stringFoo);
</code>```

You are really testing three things:

The variable you are testing exists and is within scope.

The variable you are testing is the expected type.

The variable you are testing's value is what you expect it to be.

Which to me raises the question of whether you should test for each of these implicitly so that a test fail would occur on the specific line that tests for that problem:

```<code>assertTrue(stringFoo);
assertTrue(stringFoo.typeOf() == "String");
assertEquals("foo", otherObject.stringFoo);
</code>```

For example if the variable was an integer instead of a string the test case failure would be on line 2 which would give you more feedback on what went wrong.

Should you test for this kind of thing explicitly or am i overthinking this?

答:
It depends.
Quite probably you shouldn't use three tests for something as small as that, and rather use a debugger if it fails.
However, if you have reason to believe one of the 1st two cases would be a probable bug, by all means, put them in, if just as a remainder to check for all of them.</p>


答:
SQLite would be your best option.

As written on their site:

SQLite is a software library that implements a self-contained,
  serverless, zero-configuration, transactional SQL database engine.

Seems really what you're looking for!

There's even a Chocolatey package if you're too lazy to download and install it yourself!

Title: C# Minimal SQL Database


问:
How do I initialize a Scala map with more than 4 initial elements in Java?
For 4 or fewer elements, something like this works (or at least compiles):

```<code>import scala.collection.immutable.Map;

Map<String,String> HAI_MAP = new Map4<>("Hello", "World",
                                        "Happy", "Birthday",
                                        "Merry", "XMas",
                                        "Bye", "For Now");
</code>```

For a 5th element I could do this:

```<code>Map<String,String> b = HAI_MAP.$plus(new Tuple2<>("Later", "Aligator"));
</code>```

But I want to know how to initialize an immutable map with 5 or more elements and I'm flailing in Type-hell.

Partial Solution

I thought I'd figure this out quickly by compiling what I wanted in Scala, then decompiling the resultant class files.  Here's the scala:

```<code>object JavaMapTest {
  def main(args: Array[String]) = {
    val HAI_MAP = Map(("Hello", "World"),
                      ("Happy", "Birthday"),
                      ("Merry", "XMas"),
                      ("Bye", "For Now"),
                      ("Later", "Aligator"))
    println("My map is: " + HAI_MAP)
  }
}
</code>```

But the decompiler gave me something that has two periods in a row and thus won't compile (I don't think this is valid Java):

```<code>scala.collection.immutable.Map HAI_MAP =
        (scala.collection.immutable.Map)
        scala.Predef..MODULE$.Map().apply(scala.Predef..MODULE$.wrapRefArray(
                scala.Predef.wrapRefArray(
                        (Object[])new Tuple2[] {
                                new Tuple2("Hello", "World"),
                                new Tuple2("Happy", "Birthday"),
                                new Tuple2("Merry", "XMas"),
                                new Tuple2("Bye", "For Now"),
                                new Tuple2("Later", "Aligator") }));
</code>```

I'm really baffled by the two periods in this:

```<code>scala.Predef..MODULE$
</code>```

I asked about it on #java on Freenode and they said the .. looked like a decompiler bug.  It doesn't seem to want to compile, so I think they are probably right.  I'm running into it when I try to browse interfaces in IntelliJ and am just generally lost.

Based on my experimentation, the following is valid:

```<code>Tuple2[] x = new Tuple2[] { new Tuple2<String,String>("Hello", "World"),
                            new Tuple2<String,String>("Happy", "Birthday"),
                            new Tuple2<String,String>("Merry", "XMas"),
                            new Tuple2<String,String>("Bye", "For Now"),
                            new Tuple2<String,String>("Later", "Aligator") };

scala.collection.mutable.WrappedArray<Tuple2> y = scala.Predef.wrapRefArray(x);
</code>```

There is even a WrappedArray.toMap() method but the types of the signature are complicated and I'm running into the double-period problem there too when I try to research the interfaces from Java.

答:
The decompiler probably has problems in decompiling class names correctly that contain a $ symbol. The symbol you are searching for is named Predef$:

```<code>import scala.Predef;
import scala.Predef$;
import scala.Tuple2;
import scala.collection.immutable.Map;
import scala.collection.mutable.WrappedArray;

public class T {
  @SuppressWarnings({ "rawtypes", "unchecked" })
  public static void main(final String... args) {
    final Tuple2[] ts = { new Tuple2("a", "b") };
    final WrappedArray wa = Predef.wrapRefArray(ts);
    final Map<String, String> map = Predef$.MODULE$.Map().apply(wa);
    System.out.println(map);
  }
}
</code>```

Thus, I emphasize not to use a decompiler but the internal representation of the AST in scalac:

```<code>$ scala -print -e 'Map(("a", "b"))'
...
scala.this.Predef.Map().apply(
  scala.this.Predef.wrapRefArray(
    Array[Tuple2]{new Tuple2("a", "b")}.$asInstanceOf[Array[Object]]()));
...
</code>```

If you are interested in more information about how to work with the output of scalac then take a look at this question and its answers.

OwnerDisplayName: GlenPeterson

Body:
The decompiler probably has problems in decompiling class names correctly that contain a $ symbol. The symbol you are searching for is named Predef$:

import scala.Predef;
import scala.Predef$;
import scala.Tuple2;
import scala.collection.immutable.Map;
import scala.collection.mutable.WrappedArray;

public class T {
  @SuppressWarnings({ "rawtypes", "unchecked" })
  public static void main(final String... args) {
    final Tuple2[] ts = { new Tuple2("a", "b") };
    final WrappedArray wa = Predef.wrapRefArray(ts);
    final Map<String, String> map = Predef$.MODULE$.Map().apply(wa);
    System.out.println(map);
  }
}

Thus, I emphasize not to use a decompiler but the internal representation of the AST in scalac:

$ scala -print -e 'Map(("a", "b"))'
...
scala.this.Predef.Map().apply(
  scala.this.Predef.wrapRefArray(
    Array[Tuple2]{new Tuple2("a", "b")}.$asInstanceOf[Array[Object]]()));
...

If you are interested in more information about how to work with the output of scalac then take a look at this question and its answers.

OwnerDisplayName: sschaef


答:
How about this?</p>

```<code>java.util.Map<String, String> javaMap = new java.util.HashMap<String, String>();
javaMap.put("Hello", "World");
javaMap.put("Happy", "Birthday");
javaMap.put("Merry", "XMas");
javaMap.put("Bye", "For Now");
javaMap.put("Later", "Aligator");

scala.collection.Map<String, String> scalaMap = scala.collection.JavaConversions$.MODULE$.asMap(javaMap);
System.out.println(scalaMap);
</code>```

Title: How do I initialize a Scala map with more than 4 initial elements in Java?

Body:
For 4 or fewer elements, something like this works (or at least compiles):

```<code>import scala.collection.immutable.Map;

Map<String,String> HAI_MAP = new Map4<>("Hello", "World",
                                        "Happy", "Birthday",
                                        "Merry", "XMas",
                                        "Bye", "For Now");
</code>```

For a 5th element I could do this:

```<code>Map<String,String> b = HAI_MAP.$plus(new Tuple2<>("Later", "Aligator"));
</code>```

But I want to know how to initialize an immutable map with 5 or more elements and I'm flailing in Type-hell.

Partial Solution

I thought I'd figure this out quickly by compiling what I wanted in Scala, then decompiling the resultant class files.  Here's the scala:

```<code>object JavaMapTest {
  def main(args: Array[String]) = {
    val HAI_MAP = Map(("Hello", "World"),
                      ("Happy", "Birthday"),
                      ("Merry", "XMas"),
                      ("Bye", "For Now"),
                      ("Later", "Aligator"))
    println("My map is: " + HAI_MAP)
  }
}
</code>```

But the decompiler gave me something that has two periods in a row and thus won't compile (I don't think this is valid Java):

```<code>scala.collection.immutable.Map HAI_MAP =
        (scala.collection.immutable.Map)
        scala.Predef..MODULE$.Map().apply(scala.Predef..MODULE$.wrapRefArray(
                scala.Predef.wrapRefArray(
                        (Object[])new Tuple2[] {
                                new Tuple2("Hello", "World"),
                                new Tuple2("Happy", "Birthday"),
                                new Tuple2("Merry", "XMas"),
                                new Tuple2("Bye", "For Now"),
                                new Tuple2("Later", "Aligator") }));
</code>```

I'm really baffled by the two periods in this:

```<code>scala.Predef..MODULE$
</code>```

I asked about it on #java on Freenode and they said the .. looked like a decompiler bug.  It doesn't seem to want to compile, so I think they are probably right.  I'm running into it when I try to browse interfaces in IntelliJ and am just generally lost.

Based on my experimentation, the following is valid:

```<code>Tuple2[] x = new Tuple2[] { new Tuple2<String,String>("Hello", "World"),
                            new Tuple2<String,String>("Happy", "Birthday"),
                            new Tuple2<String,String>("Merry", "XMas"),
                            new Tuple2<String,String>("Bye", "For Now"),
                            new Tuple2<String,String>("Later", "Aligator") };

scala.collection.mutable.WrappedArray<Tuple2> y = scala.Predef.wrapRefArray(x);
</code>```

There is even a WrappedArray.toMap() method but the types of the signature are complicated and I'm running into the double-period problem there too when I try to research the interfaces from Java.

Body:
How about this?

java.util.Map<String, String> javaMap = new java.util.HashMap<String, String>();
javaMap.put("Hello", "World");
javaMap.put("Happy", "Birthday");
javaMap.put("Merry", "XMas");
javaMap.put("Bye", "For Now");
javaMap.put("Later", "Aligator");

scala.collection.Map<String, String> scalaMap = scala.collection.JavaConversions$.MODULE$.asMap(javaMap);
System.out.println(scalaMap);

OwnerDisplayName: Jean-Philippe Pellet


问:
Mono is frequently used to say "Yes, .NET is cross-platform". How valid is that claim?
In What would you choose for your project between .NET and Java at this point in time? I say that I would consider the "Will you always deploy to Windows?" the single most important technical decision to make up front in a new web project, and if the answer is "no", I would recommend Java instead of .NET.

A very common counter-argument is that "If we ever want to run on Linux/OS X/Whatever, we'll just run Mono"1, which is a very compelling argument on the surface, but I don't agree for several reasons.

OpenJDK and all the vendor supplied JVM's have passed the official Sun TCK ensuring things work correctly.  I am not aware of Mono passing a Microsoft TCK.

Mono trails the .NET releases.  What .NET-level is currently fully supported?

Does all GUI elements (WinForms?) work correctly in Mono?

Businesses may not want to depend on Open Source frameworks as the official plan B.

I am aware that with the new governance of Java by Oracle, the future is unsafe, but e.g. IBM provides JDK's for many platforms, including Linux.  They are just not open sourced.

So, under which circumstances is Mono a valid business strategy for .NET-applications?

1Mark H summarized it as: "If the claim is that "I have a windows application written in .NET, it should run on mono", then not, it's not a valid claim - but Mono has made efforts to make porting such applications simpler."

答:
Putting all technicalities aside, a very important part takes place when actually writing the code.

As with any cross-platform technology (be it Java, Python, Ruby...), if the code is not written with portability in mind, you should assume there's basically zero chance the code  will run properly (even if such a chance is in reality much, much higher), as the odd misbehavior could be quite critical. Read: don't take the random assembly and run it under Mono.

Yet for a new project (or one you can refactor easily), choosing .Net/Mono as a potentially portable runtime makes sense, but you save yourself a lot of hassles by testing your code on Mono very early on, even if the project has only a slight change of going multiplatform. If you use a continuous integration server, this can be as simple as setting up a Mono build node. Many issues can be solved while developping, just by making a habit out of it (like building path strings) and a huge chunk of your code can be portable and unit-tested on Mono just by using sane practices and a little bit of forethought. The remainder (i.e failing unit tests) is then platform-specific (like code using PInvoke) but should be encapsulated enough so as to be able to provide an alternative implementation per targeted platform. This way when the project eventually comes to being ported a good part of the work has been done at almost no cost and the remainder is to be developped Just In Time.

Of course, using a library not available (.Net) or compatible (third party) in Mono precludes any of this, but in my field this has yet to be seen. That is the strategy we actually use at work, and when applying it I have no fear of claiming that .Net+Mono is cross platform.


答:
The straight answer is YES, you may still have to. Also, for assertEquals you are essentially checking for two things - types and values, not if they exist. The reason is that the function will show error in an IDE (red line) if one of them is not in the scope. HMMMM.... You can still say that using text editor rather than smart IDEs will not tell you that - which is true. But why wouldn't you use it in the first place? Therefore, that test is automatically done even before you run the test. So, your first assumption about assertEqual test checking for three things is not necessarily correct - It is defenitely two, may be three. Also, when you say about scope, you need to be careful; global or local scope same? What I am trying to say is this:

```<code>package bla.bla.bla.SomeObject;

class FooTester{
//Global var "foo"
String fooStr = "foo";

@Test
testFoos_Are_They_In_Same_Scope() {
     SomeObject someObject = new someObject();  // Mock object
     String testFooStr = someObject.stringFoo();
     assertEquals(fooStr, testFooStr);
}
}
</code>```

Clearly, foo and testFooStr are not in the same scope. fooStr is global and testFooStr is local.

Another good argument for having three separate test is the following:

```<code>assertEquals("foo", someObj.stringFoo());
</code>```

To a person who has never done any programming, this would mean that you are testing for two strings to be equal or not. However, if you have a test where you can say:

```<code>/* Asserts if the condition is _NOT_ true
assert("THEY ARE NOT AT THE SAME MEMORY LOCATION, BUT MAY HAVE THE SAME VALUE", "foo" == someObj.stringFoo());
</code>```

You have to figure out very carefully what you are trying to test and write tests with meaningful names. If you can use one test for three cases, take care when writing them and use some sensible comments declaring test purpose (if necessary).

I have done this in the past and still do it. People criticised me for writing double tests, but never told me that I didn't write enough tests. It pays dividends in long-term.

Title: unit testing variable state explicit tests in dynamically typed languages

Body:
I have heard that a desirable quality of unit tests is that they test for each scenario independently. I realised whilst writing tests today that when you compare a variable with another value in a statement like:

```<code>assertEquals("foo", otherObject.stringFoo);
</code>```

You are really testing three things:

The variable you are testing exists and is within scope.

The variable you are testing is the expected type.

The variable you are testing's value is what you expect it to be.

Which to me raises the question of whether you should test for each of these implicitly so that a test fail would occur on the specific line that tests for that problem:

```<code>assertTrue(stringFoo);
assertTrue(stringFoo.typeOf() == "String");
assertEquals("foo", otherObject.stringFoo);
</code>```

For example if the variable was an integer instead of a string the test case failure would be on line 2 which would give you more feedback on what went wrong.

Should you test for this kind of thing explicitly or am i overthinking this?

Body:
The straight answer is YES, you may still have to. Also, for assertEquals you are essentially checking for two things - types and values, not if they exist. The reason is that the function will show error in an IDE (red line) if one of them is not in the scope. HMMMM.... You can still say that using text editor rather than smart IDEs will not tell you that - which is true. But why wouldn't you use it in the first place? Therefore, that test is automatically done even before you run the test. So, your first assumption about assertEqual test checking for three things is not necessarily correct - It is defenitely two, may be three. Also, when you say about scope, you need to be careful; global or local scope same? What I am trying to say is this:

package bla.bla.bla.SomeObject;

class FooTester{
//Global var "foo"
String fooStr = "foo";

@Test
testFoos_Are_They_In_Same_Scope() {
     SomeObject someObject = new someObject();  // Mock object
     String testFooStr = someObject.stringFoo();
     assertEquals(fooStr, testFooStr);
}
}

Clearly, foo and testFooStr are not in the same scope. fooStr is global and testFooStr is local.

Another good argument for having three separate test is the following:

assertEquals("foo", someObj.stringFoo());

To a person who has never done any programming, this would mean that you are testing for two strings to be equal or not. However, if you have a test where you can say:

/* Asserts if the condition is _NOT_ true
assert("THEY ARE NOT AT THE SAME MEMORY LOCATION, BUT MAY HAVE THE SAME VALUE", "foo" == someObj.stringFoo());

You have to figure out very carefully what you are trying to test and write tests with meaningful names. If you can use one test for three cases, take care when writing them and use some sensible comments declaring test purpose (if necessary).

I have done this in the past and still do it. People criticised me for writing double tests, but never told me that I didn't write enough tests. It pays dividends in long-term.


问:
If my team has low skill, should I lower the skill of my code?
For example, there is a common snippet in JS to get a default value:

```<code>function f(x) {
    x = x || 'default_value';
}
</code>```

This kind of snippet is not easily understood by all the members of my team, their JS level being low.

Should I not use this trick then? It makes the code less readable by peers, but more readable than the following according to any JS dev:

```<code>function f(x) {
    if (!x) {
        x = 'default_value';
    }
}
</code>```

Sure, if I use this trick and a colleague sees it, then they can learn something. But the case is often that they see this as "trying to be clever".

So, should I lower the level of my code if my teammates have a lower level than me?

答:
I'd discuss with my teammates what kind of coding standards we want to have as this is mostly about how should something that can be done in dozens of ways be done for our code base.  If there is a consensus that would be my initial attempt at an answer.

If there isn't, then I'd likely consider what kind of proposed standard makes sense and start putting that into practice once I've cleared it with management and some of the team.  The idea here is to make sure that management is OK with this idea and that I'm not just going off doing my own thing and then forcing everyone else to take it.

I'd look at this more like the question of what kind of standards and practices does your team have rather than just skill level as there are many ways to evaluate code.  How well can others maintain it is one of those criteria.


答: I would not call your example a trick, but just idiomatic. If you should use it depends IMHO not so much on the current level of your team, but if (at least some of) your team mates are willing to learn some new idioms. Of course, you should discuss this topic with them and not enforce this style on them. And you should not ask them to learn each day 5 new things or "tricks". But honestly, if you have only teammates are not willing to learn something new, even it is so simple and small than this idiom, you should consider to change to a different team.</p>

Title: If my team has low skill, should I lower the skill of my code?

Body:
For example, there is a common snippet in JS to get a default value:

```<code>function f(x) {
    x = x || 'default_value';
}
</code>```

This kind of snippet is not easily understood by all the members of my team, their JS level being low.

Should I not use this trick then? It makes the code less readable by peers, but more readable than the following according to any JS dev:

```<code>function f(x) {
    if (!x) {
        x = 'default_value';
    }
}
</code>```

Sure, if I use this trick and a colleague sees it, then they can learn something. But the case is often that they see this as "trying to be clever".

So, should I lower the level of my code if my teammates have a lower level than me?


答:
You should not lower your programming skill, but you might need to adjust how you write code. The goal, almost above all, is to make your code clear to the people who must read and maintain it.

Unfortunately it can be a bit of a judgement call as to whether any particular style is "clever" or just advanced usage. The code in the question is a good example of this - your solution isn't necessarily better than the other. Some will argue it is, some will disagree. Since both solutions have effectively equal runtime performance (read: the user will never know the difference), pick the style that the team as a whole is most comfortable with.

In some instances you need to teach them better ways to code, but at other times you need to compromise in the interest of clarity.


问:
Why do most programming languages only support returning a single value from a function?
Is there a reason why functions in most(?) programming languages are designed to support any number of input parameters but only one return value?

In most languages, it is possible to "work around" that limitation, e.g. by using out-parameters, returning pointers or by defining/returning structs/classes. But it seems strange that programming languages were not designed to support multiple return values in a more "natural" way.

Is there an explanation for this?

答:
Because functions are mathematical constructs that perform a calculation and return a result. Indeed, much that's "under the hood" of not a few programming languages focuses solely on one input and one output, with multiple inputs being just a thin wrapper around the input - and when a single value output doesn't work, using a single cohesive structure (or tuple, or Maybe) be the output (though that "single" return value is composed of many values).

This has not changed because programmers have found out parameters to be awkward constructs that are useful in only a limited set of scenarios. Like with many other things, the support isn't there because the need/demand isn't there.


答:
Ok, here goes my take on this big and complicated topic.

Pros for keeping your coding style:

Things like  x = x || 10 are idiomatic in JavaScript development and offer a form of consistency between your code and the code of external resources you use.

Higher level of code is often more expressive, you know what you get and it's easier to read across highly trained professionals.

You'll enjoy your job more. I personally value creating pretty code. I think it brings me a lot of satisfaction in my work.

Generally it creates more readable style. Sticking with the idioms of the language can be very valuable - they are often idioms for a reason.

Cons for keeping your coding style:

It'll be harder for the lower-level programmers to keep up. These are often the people maintaining your code and the ones who'll have to actually read the stuff you write.

Maintainers of code, often JavaScript code come from other languages. Your programmers might be competent in Java or C# but not understand how and when JavaScript differs exactly. These points are often idiomatic - an immediately invoked function expression (IIFE) is an example of such a construct.

My personal opinion

You should not lower the skill of your code. You should aspire to write code that is expressive, clear and concise. If you have any doubts about the level of your team  - educate them. People are more than willing to learn than you might think, and are willing to adapt new constructs when convinced they are better.

If they think you are 'just being clever,' try to argue your point. Be willing to admit that you're wrong sometimes, and no matter what, try to keep styles consistent throughout your work environment. Doing so will help to avoid hostility.

The most important thing is to stay consistent.

A team's code should be written as if one person coded it. You absolutely have to agree on coding guidelines. You should abide by those guidelines. If the coding guidelines specify that reading optional parameters should be done in the 'less clever' way, then that is the way.


答:
In mathematics, a "well-defined" function is one where there is only 1 output for a given input (as a side note, you can have only single input functions, and still semantically get multiple inputs using currying).

For multi-valued functions (eg. squared root of a positive integer, for example), it's sufficient to return a collection, or sequence of values.

For the types of functions you're talking about (ie. functions that return multiple values, of different types) I see it slightly differently than you seem to: I see the need/use of out params as a workaround for better design or a more useful data structure. For example, I'd prefer if *.TryParse(...) methods returned a Maybe<T> monad instead of using an out param. Think of this code in F#:

```<code>let s = "1"
match tryParse s with
| Some(i) -> // do whatever with i
| None -> // failed to parse
</code>```

Compiler/IDE/analysis support is very good for these constructs. This would solve much of the "need" for out params. To be completely honest, I can't think of any other methods off-hand where this wouldn't be the solution.

For other scenarios - the ones I can't remember - a simple Tuple suffices.

Title: Why do most programming languages only support returning a single value from a function?

Body:
Is there a reason why functions in most(?) programming languages are designed to support any number of input parameters but only one return value?

In most languages, it is possible to "work around" that limitation, e.g. by using out-parameters, returning pointers or by defining/returning structs/classes. But it seems strange that programming languages were not designed to support multiple return values in a more "natural" way.

Is there an explanation for this?

Body:
In mathematics, a "well-defined" function is one where there is only 1 output for a given input (as a side note, you can have only single input functions, and still semantically get multiple inputs using currying).

For multi-valued functions (eg. squared root of a positive integer, for example), it's sufficient to return a collection, or sequence of values.

For the types of functions you're talking about (ie. functions that return multiple values, of different types) I see it slightly differently than you seem to: I see the need/use of out params as a workaround for better design or a more useful data structure. For example, I'd prefer if *.TryParse(...) methods returned a Maybe<T> monad instead of using an out param. Think of this code in F#:

let s = "1"
match tryParse s with
| Some(i) -> // do whatever with i
| None -> // failed to parse

Compiler/IDE/analysis support is very good for these constructs. This would solve much of the "need" for out params. To be completely honest, I can't think of any other methods off-hand where this wouldn't be the solution.

For other scenarios - the ones I can't remember - a simple Tuple suffices.


问:
UML Diagrams of Multi-Threaded Applications
For single-threaded applications I like to use class diagrams to get an overview of the architecture of that application. This type of diagram, however, hasn’t been very helpful when trying to understand heavily multi-threaded/concurrent applications, for instance because different instances of a class "live" on different threads (meaning accessing an instance is save only from the one thread it lives on). Consequently, associations between classes don’t necessarily mean that I can call methods on those objects, but instead I have to make that call on the target object's thread.

Most literature I have dug up on the topic such as Designing Concurrent, Distributed, and Real-Time Applications with UML by Hassan Gomaa  had some nice ideas, such as drawing thread boundaries into object diagrams, but overall seemed a bit too academic and wordy to be really useful.

I don’t want to use these diagrams as a high-level view of the problem domain, but rather as a detailed description of my classes/objects, their interactions and the limitations due to thread-boundaries I mentioned above.

I would therefore like to know:

What types of diagrams have you found to be most helpful in understanding multi-threaded applications?

Are there any extensions to classic UML that take into account the peculiarities of multi-threaded applications, e.g. through annotations illustrating that

some objects might live in a certain thread while others have no thread-affinity;

some fields of an object may be read from any thread, but written to only from one;

some methods are synchronous and return a result while others are asynchronous that get requests queued up and return results for instance via a callback on a different thread.

答:
My answer is complementary to Dipan's in that it involves UML sequence diagrams. I found that a style that's not 100% pure UML is OK, too. Take a look at the diagrams used in Concurrency Patterns. Some are almost UML-like (but this one is definitely not standard):

If you're familiar with wait/notify in Java thread synchronization, you'll appreciate the following sequence diagram from the document I mentioned:


问:
Need help understanding Mocks and Stubs
I'm new to use mocking frameworks and I have a few questions on the things that I am not clear on. I'm using Rhinomocks to generate mock objects in my unit tests. I understand that mocks can be created to verify interactions between methods and they record the interactions etc and stubs allow you to setup data and entities required by the test but you do not verify expectations on stubs.

Looking at the recent unit tests I have created, I appear to be creating mocks literally for the purpose of stubbing and allowing for data to be setup. Is this a correct usage of mocks or is it incorrect if you're not actually calling verify on them?

For example:

```<code>user = MockRepository.GenerateMock<User>();
        user.Stub(x => x.Id = Guid.NewGuid());
        user.Stub(x => x.Name = "User1");
</code>```

In the above code I generate a new user mock object, but I use a mock so I can stub the properties of the user because in some cases if the properties do not have a setter and I need to set them it seems the only way is to stub the property values. Is this a correct usage of stubbing and mocking?

Also, I am not completely clear on what the difference between the following lines is:

```<code>user.Stub(x => x.Id).Return(new Guid());

user.Stub(x => x.Id = Guid.NewGuid());
</code>```

答:
Mocks and stubs are abstract concepts. Looking at the docs you can find a way to create a Stub:

MockRepository.GenerateStub<...>

But it seems that they also decided to make it convenient to stub a method of a Mock, like you're doing.

Greg Moeck made a great presentation about the use of mocks: http://www.youtube.com/watch?v=R9FOchgTtLM

Title: Need help understanding Mocks and Stubs


答:
It does complicate the syntax a little, but there's no good reason at the implementation
level not to allow it.  Contrary to some of the other responses, returning multiple values, where available, leads to clearer and more efficient code.  I can't count how often I have wished I could return an X and a Y, or a "success" boolean and a useful value.


答: In addition to what's already been said when you look at the paradigms used in assembly when a function returns it leaves a pointer to the returning object in a specific register. If they used variable/multiple registers the calling function would not know where to get the returned value(s) if that function was in a library. So that would make linking to libraries difficult and instead of setting an arbitrary number of returnable pointers they went with one. Higher level languages don't quite have the same excuse.</p>


问:
Can you recommend a good commit message template / guidelines to enforce in the company?
In Git it's possible to set and enforce a good commit template.

Can you recommend (preferably with argumentation) a good commit template / guidelines to enforce in the company?

答:
[ticketId][ABC][topicId][WIP] Message, where:

ticketId - id of an item in task repository

ABC - add (feature), fix (bugfix), str (structure), dep (dependency) rem (backward incompatibility/remove), rea (readability), ref (refactoring)

topicId - can be a job selector for jenkins and/or branch name and/or topic name for gerrit

WIP - work in progress/or not (i.e. Continuous Integration may requires this)

message - detail of the modification

Examples:

[#452567][add][menu_item] new item - guestbook

[#452363][fix][banner_top][WIP] 1024x300 can be used now

[#452363][fix][banner_top] 500x200 can be used now

[#452713][rem][page] left middle ad


问:
What is a Non-Functional Requirement?
In my breakdown of work I have to define work against 'Functional' and 'Non-Functional' design elements / work in my applications. I read the description from Wikipedia here: https://en.wikipedia.org/wiki/Non-functional_requirement but as typical the description did not speak exactly to me to clear up my understanding.

Can someone please explain in terms of an example when creating an application from scratch, what would be defined as a 'Non-Functional' requirement?

答:
Requirements like performance, response times, data integrity and security are non-functional. Actually any requirement that is not related to direct user interaction.

You could agree with your client that all pages have to be fully loaded within 2 seconds if you are building a website.

You could agree with your client that the application can give only 5 security flaws when tested with vulnerability scanner x.

You could even agree with your client that your code must pass a code review by an independent reviewer.

Title: What is a Non-Functional Requirement?


问:
How to familiarize myself with Python
I'm a Python beginner. I started programming with Python 1.5 months back.

I downloaded the Python docs and read some parts of the tutorial. I have been programming on codechef.com and solving problems of projecteuler. I am thinking of reading Introduction to algorithms and following this course on MIT opencourse ware as I haven't improved much in programming and I am wasting a lot of time thinking just what should I do when faced with any programming problem.

But I think that I still don't know the correct way to learn the language itself. Should I start with the library reference or continue with the Python tutorial? Is learning algorithms useful for languages such as C and not so much for Python as it has "batteries included"?

Are there some other resources for familiarization with the language and in general for learning to solve programming problems? Or do I need to just devote some more time?

答:
The best solution, IMO, is to pick a project and implement it in python. It doesn't matter what the project is, though it should be interesting to you. As you struggle to overcome obstacles, you'll learn the parts of python that you need to learn.

Eventually you'll complete a decent sized project. Next, start asking yourself "how can I do that, but with threads?", or "how can I do that, but with multiprocessing?" or "how can I add a GUI to it?" or "how can I save my results in a database".

Focus on a problem that you understand well, and learn as you go. Build a solid foundation, then build upon that foundation.

Title: How to familiarize myself with Python


答:
If you write good code but you think your present or future colleagues may have difficulty following it, you should add a brief comment to explain it.

That way, you might teach them something without insulting their individual intelligence or embarrassing anyone in a group discussion.


答:
ADO.NET can serialize to XML and has almost all of the functionality of an RDBMS.  (Well, the cheap ones, anyway.)

I know it's "Old" and looked down on, now, but ADO.NET works really well for exactly what you're describing.  It even does a pretty decent job of tracking non-committed changes.

It may be "Old," but it's certainly not "Busted."  It's got a fairly heavy memory footprint, though, so your call on that.  4000 records won't be an issue.

Title: C# Minimal SQL Database


答: I would +1 using Test-driven development.  This way you would only have to run your tests again (which is still refresh), but less click through to a particular function or a particular case because your test-case would run.  Another thing to look into would be automated testing with something like Selinium or Windmill.</p>

Title: Minimal Refresh(F5) Web App Development

Body:
Although questions similar to this one has already been asked and I can perhaps assemble the answer for myself by reading  already posted materials. Still I am going ahead with the question, cause I feel it has elements of new flavor and I would like to see the views of others on how to tackle this.

I have developed several Web Applications of various scale. In some of them, I was only Developer, in another I led small teams and was part of a big team in another.

Most of these were developed using PHP. One of them used Kohana Framework, the rest were all developed using Raw PHP. The main difficulty that I faced in regards to speedy development was, whenever a small change was  done to fix a bug or modify a feature, I had to refresh my web browser, go through several pages until I reached the page which included the fix.

I would like to know, what should be the development approach so that I can test out my code without having to, or at least minimize the number of refreshes required to test out changes in code. Although, the concepts maybe applicable for developments of any nature,  for this question, let us stick to PHP and it's framework.


答:
Some languages, like Python, support multiple return values natively, while some languages like C# support them via their base libraries.

But in general, even in languages that support them, multiple return values are not used often because they're sloppy:

Functions that return multiple values are hard to name clearly.

It's easy to mistake the order of the return values

```<code>(password, username) = GetUsernameAndPassword()
</code>```

(For this same reason, many people avoid having too many parameters to a function; some even take it as far as to say a function should never have two parameters of the same type!)

OOP languages already have a better alternative to multiple return-values:  classes.

They're more strongly-typed, they keep the return values grouped as one logical unit, and they keep the names of (properties of) the return values consistent across all uses.

The one place they are pretty convenient is in languages (like Python) where multiple return values from one function can be used as multiple input parameters to another.  But, the use-cases where this is a better design than using a class are pretty slim.

Body:
Some languages, like Python, support multiple return values natively, while some languages like C# support them via their base libraries.

But in general, even in languages that support them, multiple return values are not used often because they're sloppy:

Functions that return multiple values are hard to name clearly.

It's easy to mistake the order of the return values

(password, username) = GetUsernameAndPassword()

(For this same reason, many people avoid having too many parameters to a function; some even take it as far as to say a function should never have two parameters of the same type!)

OOP languages already have a better alternative to multiple return-values:  classes.

They're more strongly-typed, they keep the return values grouped as one logical unit, and they keep the names of (properties of) the return values consistent across all uses.

The one place they are pretty convenient is in languages (like Python) where multiple return values from one function can be used as multiple input parameters to another.  But, the use-cases where this is a better design than using a class are pretty slim.