答:
This is a very good question, as I have seen a number of C++ developers write terrible C# code.

It is best not to think of C# as "C++ with nicer syntax".  They are different languages which require different approaches in your thinking.  C++ forces you to be constantly thinking about what the CPU and memory will be doing.  C# is not like that.  C# specifically is designed so that you are not thinking about the CPU and memory and instead are thinking about the business domain you are writing for.

One example of this that I have seen is that a lot of C++ developers will like to use for loops because they're faster than foreach.  This is usually a bad idea in C# because it restricts the possible types of the collection being iterated over (and therefore the re-usability and flexibility of the code).

I think that the best way to readjust from C++ to C# is to try and approach coding from a different perspective.  At first this will be hard, because over the years you will be completely used to using the "what are the CPU and memory doing" thread in your brain to filter the code you write.  But in C#, you should instead be thinking about the relationships between the objects in the business domain.  "What do I want to do" as opposed to "what is the computer doing".

If you want to do something to everything in a list of objects, instead of writing a for loop on the list, create a method which takes an IEnumerable<MyObject> and use a foreach loop.

Your specific examples:

Controlling the lifetime of resources that require deterministic cleanup (like files). This is easy having using in hand but how to use it properly when ownership of the resource is being transfered [... betwen threads]? In C++ I would simply use shared pointers and let it take care of 'garbage collection' just at the right time.

You should never do this in C# (particularly between threads).  If you need to do something to a file, do it in one place at one time.  It's ok (and indeed good practice) to write a wrapper class which manages the unmanaged resource which gets passed between your classes, but don't try and pass a File between threads and have separate classes write/read/close/open it.  Don't share ownership of unmanaged resources.  Use the Dispose pattern to deal with cleanup.

Constant struggling with overriding functions for specific generics (I love things like partial template specialization in C++). Should I just abandon any attempts to do any generic programming in C#? Maybe generics are limited on purpose and it is not C#-ish to use them except for a specific domain of problems?

Generics in C# are designed to be generic.  Specializations of generics should be handled by derived classes.  Why should a List<T> behave differently if it's a List<int> or a List<string>?  All of the operations on List<T> are generic so as to apply to any List<T>.  If you want to change the behaviour of the .Add method on a List<string>, then create a derived class MySpecializedStringCollection : List<string> or a composed class MySpecializedStringCollection : IList<string> which uses the generic internally but does things in the different way.  This helps you avoid violating the Liskov Substitution Principle and royally screwing others who use your class.

Macro-like functionality. While generally a bad idea, for some domain of problems there is no other workaround (e.g. conditional evaluation of a statement, like with logs that should only go to Debug releases). Not having them means that I need to put more if (condition) {...} boilerplate and it is still not equal in terms of triggering side effects.

As others have said, you can use preprocessor commands to do this.  Attributes are even better.  In general attributes are the best way to handle things which are not "core" functionality for a class.

In short, when writing C#, keep in mind that you should be thinking entirely about the business domain and not about the CPU and memory.  You can optimize later if necessary, but your code should reflect the relationships between the business principles you're trying to map.

Title: How to migrate my thinking from C++ to C#

Body:
I am an experienced C++ developer, I know the language in great details and have used some of its specific features intensively. Also, I know principles of OOD and design patterns. I am now learning C# but I cannot stop the feeling not being able to get rid of C++ mindset. I tied myself so hard to the strengths of C++ that I cannot live without some of the features. And I cannot find any good workarounds or replacements for them in C#.

What good practices, design patterns, idioms that are different in C# from C++ perspective can you suggest? How to get a perfect C++ design not looking dumb in C#?

Specifically, I cannot find a good C#-ish way to deal with (recent examples):

Controlling the lifetime of resources that require deterministic cleanup (like files). This is easy having using in hand but how to use it properly when ownership of the resource is being transfered [... betwen threads]? In C++ I would simply use shared pointers and let it take care of 'garbage collection' just at the right time.

Constant struggling with overriding functions for specific generics (I love things like partial template specialization in C++). Should I just abandon any attempts to do any generic programming in C#? Maybe generics are limited on purpose and it is not C#-ish to use them except for a specific domain of problems?

Macro-like functionality. While generally a bad idea, for some domain of problems there is no other workaround (e.g. conditional evaluation of a statement, like with logs that should only go to Debug releases). Not having them means that I need to put more if (condition) {...} boilerplate and it is still not equal in terms of triggering side effects.


问:
Use JSON objects or POJOs in back end service?
I'm building a back end service for mobile clients.

The requirement is that the mobile clients will pass me a token, I'll use that token to talk to other systems (behind the company firewall) in my company, and return to the user some information.

Here's a typical scenario:

A mobile client asks for some customer data and makes a call with the customers token. I use the token against the customer database system and get back the customer details. I then return the data (removing some fields that are not relevent )to the mobile client.

All data between systems (me, mobile client, customer database) use JSon.

The question is whether I should work with JSon objects throught my code or try and use POJOs?

Right now, I only need to remove some fields from the customer database before returning to the client.

The future may require more involved transformations but I can't be sure that will happen or the nature of the transformations.

Thanks

答:
Its a classic tradeoff  Performance + ease of use vs. scalability and flexability.

POJOs are highly perfomant and very easy to use in a Java program. BUT they are restricted to a single VM. You cannot pass a POJO to another VM or another server or another process not implemented in Java. To pass the POJO to a Java program in another VM you need to serialize the POJO and de-serialize it at the receiving process. The default Java serialize methods have historically been very dependent on the version of Java used.

JSON formatted messages can be passed between processes, between servers, and can be easily read by Java programs but also Javascript, php, python C, C++ etc. etc.

Other benefits of using a JSON (or XML :-) ) include ease of debugging ( you can just read the message ) and ease of testing (its trivial to create store and copy JSON messages for use in a testing framework).

ContentLicense: CC BY-SA 3.0


问:
Should Latin-1 be used over UTF-8 when it comes to database configuration?
We are using MySQL at the company I work for, and we build both client-facing and internal applications using Ruby on Rails.

When I started working here, I ran into a problem what I had never encountered before; the database on the production server is set to Latin-1, meaning that the MySQL gem throws an exception whenever there is user input where the user copies & pastes UTF-8 characters.

My boss calls these "bad characters" since most of them are non-printable characters, and says that we need to strip them out. I've found a few ways to do this, but eventually we've ended up in a circumstance where a UTF-8 character was needed. Plus it's a bit of a hassle, especially since it seems like the only solution I ever read about for this issue is to just set the database to UTF-8 (makes sense to me).

The only argument that I've heard for sticking with Latin-1 is that allowing non-printable UTF-8 characters can mess up text/full-text searches in MySQL. Is this really true?

Are there other reasons one should use Latin-1 over UTF-8? It's my understanding that it is superior and becoming more ubiquitous.

答:
To begin with the answer, it doesn't matter, how your server is configured. The character encoding in MySQL could be configured per-column (means, same table could hold characters in multiple encodings, easy). I.e. my server (and a number of legacy databases in it) is configured for cp1251 by default for old clients that unable to set correct collation upon connect (different hardware clients), but main databases in production are all using UTF-8.

Speaking of "wasted space" - you can't realistically call important data a waste, can you? Storage space increase, however, will be different depending on the language your data is in. From insignificant (less than 1%) increase if your site is primarily in English and up to 100%, if it is mailny using characters outside the ASCII range. And even more, if you move firther east. Later UTF-8 (so-called UTF8mb4) specifications allow up to 4 bytes per code point.

And to "who's right"… Truth is, this is a social question more than it is technical. There could be valid reasons for specific server setups, but you must know the implications. But if you ask me, there's no reason to not use UTF-8. It's the one kind to rule all texts in the world.


问:
RESTful Api: Send email with links to client URL
A client can call the following REST api URI to send an enquiry

```<code>POST /v1/businesses/{business_name}/enquiries
</code>```

The enquiry can then be viewed through the following call:

```<code>GET /v1/businesses/{business_name}/enquiries/{enquiry_id}
</code>```

When a new enquiry is posted, the business is informed via email. The email includes a link to the enquiry. The issue I have is that the API will add the following link to email:

```<code>http://api.com/v1/businesses/{business_name}/enquiries/{enquiry_id}
</code>```

When a user clicks the link in the email, they will be incorrectly taken to the API resource instead of the client page. So I need the email to contain the following link:

```<code>http://client.com/dashboard/{business_name}/enquiries/{enquiry_id}
</code>```

Noted: Above client URL is an example. Clients can implement their own routing however they want, a single page client app URL could also be used. The point is, the client URL must be exposed in the email, not the API URL.

I'm not quite sure how to get client URLs into the email.

One option would be to provide a client URL in the original POST request. Problem with this is that the client won't know the URL to use until after the POST, at which point the email has already been added to the queue.

Another option is to pull out the queueing of emails from the API and make the clients responsible for it. I don't really like this idea as client implementers will not be too happy that they purchased the API, only to then find out they then have to decide when to queue emails.

答:
For a simple solution that doesn't require you to change the links in the emails, you could have the relevant part of your API respond to requests from user agents in a way that makes sense to an end user.

Have your API respond to requests with an accept header containing text/html by redirecting them to a remote resource specified by the business. Allow the businesses to set up the redirect path (with some simple token replacement) through another part of the API.

If the business hasn't set up a redirect path, serve up an HTML page containing the content of the enquiry instead of redirecting the request.

Of course, this only needs to be done for the part of the API that's linked to in the emails.

This approach has the advantage of businesses being able to change the redirect path at any time, and if a customer clicks on a link in an old email, they will get sent to the new remote resource. This also allows you to do click tracking if you want to.

Here's an example of how it might work:

Your client "Business A" wants to show enquiries on their own dashboard, so they set up a redirect path by making a request: PUT /v1/businesses/business_a/enquirypath, containing {"path":"http://business_a.com/dashboard/enquiries/{id}"}.

Your client "Business B" doesn't have their own dashboard, so they don't set up a redirect path.

You send out emails on behalf of businesses A and B. The emails link to the same resources that your API uses.

An end user clicks the link in the email from Business B. Your server sees that HTML content is being requested (rather than JSON/XML). Business B has not indicated that requests should be redirected, so the API simply serves up the enquiry in user-friendly HTML form, like the user agent requested.

An end user clicks the link in the email from Business A. Your server sees that HTML content is being requested again. Business A has indicated that enquiry requests should be redirected to their own server, so your API redirects the request to the path they specified.


问:
iOS chat application design, sending/relaying the message over to the end user
I have a design question. Let us say you were tasked with building a chat application, specifically for iOS (iOS Chat Application). For simplicity let us say you can only chat with one person at a time (no group chat functionality).

How then can you achieve sending a message directly to an end user from phone A to phone B?

Obviously there is a web service layer with some API calls. One of the API calls available will be startChat(). After starting a chat, when you send a message, you make another async call, let us call it sendMessage() and pass in a string with your message. Once it goes to the web service layer, the message gets stored in a database.

Here is where I am currently stuck. After the message gets sent to the web service layer, how do we then achieve sending/relaying the message over to the end user? Should the web server send out a message to the end user and notify them, or should each client call a receiveMessage() method periodically, and if the server side has some info for them it can then respond with that info?

Finally, how can we handle the case in which the user you are trying to send a message to is offline? How can we make sure the end user gets the packet when he moves back to an area with signal?

答: Other users have suggested APNS but you should be aware that if you late r decide to port your application to Android and/or Windows Phone, this will be harder to achieve if you are tied to a platform-specific push API. There are several alternatives that are suitable for use on all 3 platforms listed in this stack overflow question: https://stackoverflow.com/questions/9801720/push-notifications-on-all-3-platforms-android-ios-windows-phone</p>


答:
I'm in agreement on simplest approach is generally the best and for me JSON manipulation win out hands down in this situation.

The important bit of the question is '(removing some fields that are not relevant ) to the mobile client'

So from what I understand there is more than one mobile client variant and for each different json fields are selected from the source customer data json.

Using the DTO approach, I would first have to marshall the source customer data JSON to a DTO, then if I had 4 mobile clients then I would need 4 DTO's and multiple method for setting the attributes on each Type of DTO.

Using the JSONObject approach, I would have something like:

```<code>JSONObject sourceCustomerData = JSONObject.fromObject(httpResponseInputStream)
</code>```

and would pass the sourceCustomerData to a method to return the JSON suitable to individual mobile client something like:

```<code>JSONObject customerDataClientX = getRequiredJson(requiredJsonFeildsForMobileClientA, sourceCustomerData)
</code>```

where requiredJsonFeildsForMobileClientA is list of required JSON fields. Therefore for each mobile client a different list of required JSON fields can be passed in.

DTO PROS
- Straight forward and verbose code POJO's.
- Suitable for more complex transformations.
- Easily testable.

DTO CONS
- DTO's are models held in code, they cannot changed without manipulating code.
- More code as DTO and there population code are directly related to the number of mobile client variants.

JSONObject  PROS

- Straight forward code.
- Easily testable, it's a function on external factors.
- Less code as one shoe fits all, not directly related to the number of mobile client variants

- There is no model held in code, the list of JSON fields for each mobile client can be held in configuration externally.

JSONObject CONS

- Not suitable for more complex transformations.
- JSONObject requires navigation JSON model, not so nice to ready or write.

In future, as more complex transformations are required we can add then in and even consider moving to a DTO’s based model if it makes the task easier.

Title: Use JSON objects or POJOs in back end service?

Body:
I'm building a back end service for mobile clients.

The requirement is that the mobile clients will pass me a token, I'll use that token to talk to other systems (behind the company firewall) in my company, and return to the user some information.

Here's a typical scenario:

A mobile client asks for some customer data and makes a call with the customers token. I use the token against the customer database system and get back the customer details. I then return the data (removing some fields that are not relevent )to the mobile client.

All data between systems (me, mobile client, customer database) use JSon.

The question is whether I should work with JSon objects throught my code or try and use POJOs?

Right now, I only need to remove some fields from the customer database before returning to the client.

The future may require more involved transformations but I can't be sure that will happen or the nature of the transformations.

Thanks

Body:
I'm in agreement on simplest approach is generally the best and for me JSON manipulation win out hands down in this situation.

The important bit of the question is '(removing some fields that are not relevant ) to the mobile client'

So from what I understand there is more than one mobile client variant and for each different json fields are selected from the source customer data json.

Using the DTO approach, I would first have to marshall the source customer data JSON to a DTO, then if I had 4 mobile clients then I would need 4 DTO's and multiple method for setting the attributes on each Type of DTO.

Using the JSONObject approach, I would have something like:

JSONObject sourceCustomerData = JSONObject.fromObject(httpResponseInputStream)

and would pass the sourceCustomerData to a method to return the JSON suitable to individual mobile client something like:

JSONObject customerDataClientX = getRequiredJson(requiredJsonFeildsForMobileClientA, sourceCustomerData)

where requiredJsonFeildsForMobileClientA is list of required JSON fields. Therefore for each mobile client a different list of required JSON fields can be passed in.

DTO PROS
- Straight forward and verbose code POJO's.
- Suitable for more complex transformations.
- Easily testable.

DTO CONS
- DTO's are models held in code, they cannot changed without manipulating code.
- More code as DTO and there population code are directly related to the number of mobile client variants.

JSONObject  PROS

- Straight forward code.
- Easily testable, it's a function on external factors.
- Less code as one shoe fits all, not directly related to the number of mobile client variants

- There is no model held in code, the list of JSON fields for each mobile client can be held in configuration externally.

JSONObject CONS

- Not suitable for more complex transformations.
- JSONObject requires navigation JSON model, not so nice to ready or write.

In future, as more complex transformations are required we can add then in and even consider moving to a DTO’s based model if it makes the task easier.


问:
Leaving intentional bugs in code for testers to find
We don't do this at our firm, but one of my friends says that his project manager asked every developer to add intentional bugs just before the product goes to QA. This is how it works:

Just before the product goes to QA, the development team adds some intentional bugs at random places in the code. They properly back up the original, working code to make sure that those bugs aren't shipped with the end product.

Testers are also informed about this. So they will test hard,
because they know there are bugs present and that not finding them might
be considered as a sign of incompetence.

If a bug (intentional or otherwise) has been found, they will be reported for the development team to fix. The development team then adds another intentional bug in a related section of the code just before the product goes to the second-level QA. The project manager says a tester should think like a developer and he/she should expect new bugs in sections where changes were made.

Well, this is how it goes. They say that this approach has following advantages.

Testers will be always on their toes and they will test like crazy.
That helps them to also find hidden (unintentional) bugs so developers
can fix them.

Testers feed on bugs. Not finding any bugs will affect their morale.
So giving them an easy one to find will help their morale.

If you ignore the scenario where one of these intentional bugs gets shipped with the final product, what are the other drawbacks we should consider before even thinking of adopting this approach?

Some clarifications:

They properly backup the original code in source control.

When a tester finds the intentional bug, the development team just ignores it. If tester finds out an unintentional (original) bug, the development team first checks whether it is caused by any of the intentional bugs. That is, the development team first tries to reproduce that on the original working code and tries to fix it if they can.

Just ignore the relationship issues between QA and development team. I specifically asked this question on Programmers, not on The Workplace. Consider that there is good rapport between QA and the development team, and they party together after working hours. The project manager is a nice, old gentleman who is always ready to support both teams (Godsend).

答:
Although it is a bad idea in general (the other answers perfectly explain why), there is a few special situation where intentionally injecting bugs into the production code in a controlled, temporary manner can make sense.

When you refactor the test code - and you should, test code deserves the same attention to detail as production code - you might want to know whether the test code is still finding the bugs it's supposed to find.

You can then intentionally break the production code in order to verify if the tests still work.

There are multiple levels on which this is possible:

A developer that has just refactored some unit test might break the production code to verify that the unit test still finds what it's supposed to find.

A tester that has just refactored some acceptance test might break the production code to verify that the acceptance test still verifies what it's supposed to verify.

If the interface is stable and robust enough (i.e. protocol based), the company might want to keep a suite of known faulty product versions and run tests against them in order to regression test the test.

Whether these things make sense depends. If I'm a developer and it takes me just a minute to inject a bug, test the unit test, remove the bug - then why not. But I should have my editor, my cycle and my version control system under such a good control that I would not accidentally commit / deliver / check-in / push the bug. Same goes for the tester and the acceptance test.

Whether it makes sense for an organization to keep suites of known faulty product versions and regression test the test depends. For an online shop I wouldn't. For automotive embedded, aerospace embedded, banking cards or pay TV cards I would.

How much effort this is strongly depends on how decoupled the tests are from the production code. The more decoupled the tests are from the production code, the less effort it is to do this, the more cohesive the tests are with the production code, the more effort.

The reason is simply this: When your tests and your production code are cohesive, changing the production code requires changing the tests often, and that would break the dependency between the tests and the faulty production samples. You would then have to also maintain the faulty production samples. In rare cases even that can be worth the effort, and mocking as well as smart usage of a version control system can significantly reduce the effort, but it requires far above skilled developers.

The concept of intentionally injecting faults in production code is called sabotage, the injected fault is called saboteur.


问:
What is the difference between Optionals and Nullable type
Swift has Optionals. C# has Nullable types.

As far as I can tell both serve same purpose, besides value of some type they store information whether variable has value or is undefined (uninitialized).

Question is are Optionals just Nullable types with different name or are there other conceptual differences?

In another words, talking about concept itself, or in context of languages that do not have Optionals or Nullables, does it matter whict term is used?

When implementing that functionality in language does it matter whether I name type Optionals<T> or Nullable<T>

答:
In .NET, there are two categories of type: references and values (int, double, structs, enums etc). Amongst their differences is the fact that a reference can be null, whereas a value cannot. Thus if you have a value type and want to convey "optional" or "unknown" semantics, you can adorn it with Nullable<>. Note that Nullable<> is constrained by type to accept only value types (it has a where T : struct clause). Nullable<> also has special affordances from the compiler whereby a null value is protected from NullReferenceExceptions:

```<code>string x = null;
x.ToString(); // throws a NullReferenceException

int? y = null;
y.ToString(); // returns ""
</code>```

In functional languages (such as Scala, F#, Haskell, Swift etc) it is common for null to not exist. This is because on the whole people regard the existence of null as a bad idea, and language designers have decided to address this problem by disallowing it.

This means that again we need some way to represent a non-value in these languages. Enter the Option type (nomenclature varies, it's called Maybe in Haskell). This does a similar job to Nullable in that it wraps a type to add the case where the value is "None" or "Unknown" etc.

The real difference is in the extra functions given to you by languages that implement Option. As an example, take Option.map (in pseudocode):

```<code>function Option<T2> Option.map(opt: Option<T1>, mapFunc: T1 -> T2) {
    if (opt is None) return None
    else return Option<T2>(mapFunc(opt.Value))
}
</code>```

Chaining functions like Option.map is a powerful way to avoid the typical null check boilerplate you see everywhere in C#:

```<code>if (service == null)
    return null;
var x = service.GetValue();
if (x == null || x.Property == null)
    return null;
return x.Property.Value;
</code>```

The Nullable equivalent in C# would be:

```<code>public static Nullable<T2> Map<T1, T2>(this Nullable<T1> nullable, Func<T1, T2> f)
    where T1 : struct
    where T2 : struct
{
    if (!nullable.HasValue) return (T2?)null;
    else return (T2?) f(nullable.Value);
}
</code>```

However this has limited utility in C# because it will only work for value types.

The new version of C# offers the "null propagation" operator (?.) which is similar to the Option.map function except it is only applicable for methods and property accessors. The above sample would be rewritten

```<code>return service?.GetValue()?.Property?.Value;
</code>```

Body:
In .NET, there are two categories of type: references and values (int, double, structs, enums etc). Amongst their differences is the fact that a reference can be null, whereas a value cannot. Thus if you have a value type and want to convey "optional" or "unknown" semantics, you can adorn it with Nullable<>. Note that Nullable<> is constrained by type to accept only value types (it has a where T : struct clause). Nullable<> also has special affordances from the compiler whereby a null value is protected from NullReferenceExceptions:

string x = null;
x.ToString(); // throws a NullReferenceException

int? y = null;
y.ToString(); // returns ""

In functional languages (such as Scala, F#, Haskell, Swift etc) it is common for null to not exist. This is because on the whole people regard the existence of null as a bad idea, and language designers have decided to address this problem by disallowing it.

This means that again we need some way to represent a non-value in these languages. Enter the Option type (nomenclature varies, it's called Maybe in Haskell). This does a similar job to Nullable in that it wraps a type to add the case where the value is "None" or "Unknown" etc.

The real difference is in the extra functions given to you by languages that implement Option. As an example, take Option.map (in pseudocode):

function Option<T2> Option.map(opt: Option<T1>, mapFunc: T1 -> T2) {
    if (opt is None) return None
    else return Option<T2>(mapFunc(opt.Value))
}

Chaining functions like Option.map is a powerful way to avoid the typical null check boilerplate you see everywhere in C#:

if (service == null)
    return null;
var x = service.GetValue();
if (x == null || x.Property == null)
    return null;
return x.Property.Value;

The Nullable equivalent in C# would be:

public static Nullable<T2> Map<T1, T2>(this Nullable<T1> nullable, Func<T1, T2> f)
    where T1 : struct
    where T2 : struct
{
    if (!nullable.HasValue) return (T2?)null;
    else return (T2?) f(nullable.Value);
}

However this has limited utility in C# because it will only work for value types.

The new version of C# offers the "null propagation" operator (?.) which is similar to the Option.map function except it is only applicable for methods and property accessors. The above sample would be rewritten

return service?.GetValue()?.Property?.Value;


问:
Checking "instanceof" rather than value using a switch statement
Is there some syntax (other than a series of if statements) that allows for the use of a switch statement in Java to check if an object is an instanceof a class?  I.e., something like this:

```<code>switch (object) {
     case instanceof SecondObject:
        break;
     case instanceof ThirdObject:
        break;
}
</code>```

Sidenote:  I recognize that as a design pattern, checking against instanceof and making decisions based on it is not as preferable as using inheritance.  To give some context why this would be useful to me, here's my situation:

I'm working on a project that involves a kryonet client/server.  For communication over KryoNet, you pass objects that it serializes using kryo.  Anything added to the object increases the size of these packets,1 so to minimize the network traffic, you keep these objects as light weight as possible.  When you receive a packet, you need to know what to do with it, so I'm making this determination based on what type of packet object the passed object is an instanceof.  This approach is the same undertaken in the examples included with Kryonet's distribution.  I'd love to clean up the hideous class that translates these packets into action, and figure a switch statement would at least make it look moderately more organized.

1As I wrote the statement above, I had doubts about whether what I was saying was accurate. The answer below seems to disagree:

Methods don't add anything to the runtime size of an object. The
  method code is not transmitted, and nothing about the methods requires
  any representation in an object's state. This is not a sound reason
  for instanceof testing, etc.

I guess the real issue is I don't know what happens under the hood for Kryo to serialize an object and I was nervous to do anything that increased the bandwidth.  Your answers have inspired me to do it with inheritance and add the appropriate methods to the objects.  So thank you!

答:
I fully realize that I am 2 years late to the party :-) but probably few clarifications will help other devs.

What the other answers missed to address was the mentioning of the "Kryonet" which adds additional twist to the problem: usually when kryonet is used it  means that

a) the client is an android app and

b) the client is some game

If both conditions are met IMHO using the instanceof if-else sequence is the way to go.

The usual way of structuring client/server app in our case android game + "pure" java server is to use (at least) 3 projects:

"common" - which contains code common for the server and the client, most importantly all the message classes (which usually implement some tag/marker interface as GameMessage).

server - contains the server and includes the common project. Usually all messages are simply registered in Kryonet, i.e. no pooling is used (because on server GC is not considered a problem)

android client - contains the android app (game) and includes the common project. Because in java games creating objects during the game may trigger the GC it is considered the biggest mortal sin (which leads straight to the hell of missed frames) it is considered good practice1 to use object pooling for the game messages (this requires little customization on the Kryonet/kryo in order to use object pools). All messages are (must be) registered in kryonet in the same order as on the server in order things to work.

First, lets look at the alternatives and see why they are not fit for the structure/implementation described above:

1. They say 'Use polymorphism and method overriding'

Take a look here for an example of the proposed solution (accepted answer by jmg). It looks very elegant but there there are at least 2 big problems:

You can't just use parameterless overrided method like do() because in real implementation you will some need external data to act upon. For example when receiving PlayerAbandonedGame message on the server you will need at least the particular game object as parameter in order to call removePlayer(Player pl) method. NewGameState message will require reference to the particular GameState variable that will be updated and so on. One very ugly solution is overrided method to have single parameter like TheWholeThing which contains all the objects that may be needed. It is needless to say that this not only violates the principle of encapsulation but also "spreads" the game logic across multiple message classes.

Remember that we have the common project and all the messages are defined there. Even if server-to-client messages are completely distinct set to client-to-server messages it will be simply stupid to put server or client logic in the common project.

Game message objects are just data containers. It is up to the server or the client to handle that data in a particular way (or even ignore it as often happens with out of order UDP messages).

2. They say 'Use reflection'

Our context is 'a) the client is an android app'. The reaction of every android developer hearing Use reflection should be to stand up, clear his/hers throat and with his/hers best british accent to say: 'Are you completely mAd?!' :-)

Reflection is very slow on older Android versions, it is slow even now (5.0). Also IMO using reflection is the ugliest possible solution not just for this particular problem. It should be avoided up in the stack, i.e. in app dev.

Way to go

Back to the original question: if one really insist on using switch the solution is to have base class like:

```<code>public abstract class GameMessage {
    byte mCode; // not private because of kryo

    public GameMessage(byte code) {
        super();
        mCode = code;
    }

    public byte getCode() {
        return mCode;
    }
}
</code>```

concrete message will look like:

```<code>public class PlayerAbandonedGame extends GameMessage {
    // some fields

    public PlayerAbandonedGame() {
        super((byte) 42);
    }
}
</code>```

and then message handler will look like:

```<code>public synchronized void onMessageReceived(GameMessage msg) {
    switch(msg.getCode()) {
        case 42:
            // do something
            break;
        default:
            mLogger.error("Unknown message code {}", msg.getCode());
            // may be even throw an exception?
            break;
    }

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

Of course it is advisable to use enum values instead of hardcoded numbers...

Potential drawback is (as mentioned in other answers) if you create new message class and forget to add it to some of the switch statements. The compiler cannot catch this problem and you will hit it only runtime (in the default case).

Real (small) drawback is that code field is send each time and adds to the traffic. In reality this adds about 1-10% to the size of the messages (if you use byte for the code field).

How I do it

I personally use if-else sequence with instanceof test like:

```<code>public synchronized void onMessageReceived(GameMessage msg) {
    if (msg instanceof MyLetterAttemptResult) {
        handleMyLetterAttemptResult((MyLetterAttemptResult) msg);
        mPools.release(msg);
    } else if (msg instanceof InAutoMatchQueue) {
        handleInAutoMatchQueue((InAutoMatchQueue) msg);
    } else if (msg instanceof AutoMatchRetry) {
        handleAutomatchRetry();
    // more else-ifs
    } else {
        mLogger.error("Unknown message {}", msg.getClass().getSimpleName());
        // throw exception may be?
    }
}
</code>```

Isn't that "code smell"? You bet it is, but after trying all other alternatives it seems to me that it is best. To reduce the smelliness it is better to try to keep code in the ifs short like above. Just call handle* method and release message back to the pool (if it is pooled).

Isn't that slow? It is a bit slower than the switch(msg.getCode()) but not that much. Here is some benchmarking (answer by Dan Mihai Ile). Advantage is that you don't have the code field send each time over the network. Keep the most frequently used messages at the top so they are found first.

Isn't that error prone? There is a risk if you create new message class and forget to add corresponding else if. The thing is that you have just two separate message handling methods - one on the server and one on the client. Both are the single most important code pieces repectively on the server and the client. You will simply have to not mess it up. Just add the new message class immediately to the unit test that tests onMessageReceived().

This is not OOP! I have a better solution! I will be very happy to discuss it and use it :-). btw, I wonder if @Cameron (the author of this question) found better solution. After all this question is 2 years old...

1 For me avoiding the GC is more like "utter crap" than "best practice". As Eonil commented in 1: I regard avoiding GC on GC based language is a kind of insane trial.

Body:
I fully realize that I am 2 years late to the party :-) but probably few clarifications will help other devs.

What the other answers missed to address was the mentioning of the "Kryonet" which adds additional twist to the problem: usually when kryonet is used it  means that

a) the client is an android app and

b) the client is some game

If both conditions are met IMHO using the instanceof if-else sequence is the way to go.

The usual way of structuring client/server app in our case android game + "pure" java server is to use (at least) 3 projects:

"common" - which contains code common for the server and the client, most importantly all the message classes (which usually implement some tag/marker interface as GameMessage).

server - contains the server and includes the common project. Usually all messages are simply registered in Kryonet, i.e. no pooling is used (because on server GC is not considered a problem)

android client - contains the android app (game) and includes the common project. Because in java games creating objects during the game may trigger the GC it is considered the biggest mortal sin (which leads straight to the hell of missed frames) it is considered good practice1 to use object pooling for the game messages (this requires little customization on the Kryonet/kryo in order to use object pools). All messages are (must be) registered in kryonet in the same order as on the server in order things to work.

First, lets look at the alternatives and see why they are not fit for the structure/implementation described above:

1. They say 'Use polymorphism and method overriding'

Take a look here for an example of the proposed solution (accepted answer by jmg). It looks very elegant but there there are at least 2 big problems:

You can't just use parameterless overrided method like do() because in real implementation you will some need external data to act upon. For example when receiving PlayerAbandonedGame message on the server you will need at least the particular game object as parameter in order to call removePlayer(Player pl) method. NewGameState message will require reference to the particular GameState variable that will be updated and so on. One very ugly solution is overrided method to have single parameter like TheWholeThing which contains all the objects that may be needed. It is needless to say that this not only violates the principle of encapsulation but also "spreads" the game logic across multiple message classes.

Remember that we have the common project and all the messages are defined there. Even if server-to-client messages are completely distinct set to client-to-server messages it will be simply stupid to put server or client logic in the common project.

Game message objects are just data containers. It is up to the server or the client to handle that data in a particular way (or even ignore it as often happens with out of order UDP messages).

2. They say 'Use reflection'

Our context is 'a) the client is an android app'. The reaction of every android developer hearing Use reflection should be to stand up, clear his/hers throat and with his/hers best british accent to say: 'Are you completely mAd?!' :-)

Reflection is very slow on older Android versions, it is slow even now (5.0). Also IMO using reflection is the ugliest possible solution not just for this particular problem. It should be avoided up in the stack, i.e. in app dev.

Way to go

Back to the original question: if one really insist on using switch the solution is to have base class like:

public abstract class GameMessage {
    byte mCode; // not private because of kryo

    public GameMessage(byte code) {
        super();
        mCode = code;
    }

    public byte getCode() {
        return mCode;
    }
}

concrete message will look like:

public class PlayerAbandonedGame extends GameMessage {
    // some fields

    public PlayerAbandonedGame() {
        super((byte) 42);
    }
}

and then message handler will look like:

public synchronized void onMessageReceived(GameMessage msg) {
    switch(msg.getCode()) {
        case 42:
            // do something
            break;
        default:
            mLogger.error("Unknown message code {}", msg.getCode());
            // may be even throw an exception?
            break;
    }

    // ...
}

Of course it is advisable to use enum values instead of hardcoded numbers...

Potential drawback is (as mentioned in other answers) if you create new message class and forget to add it to some of the switch statements. The compiler cannot catch this problem and you will hit it only runtime (in the default case).

Real (small) drawback is that code field is send each time and adds to the traffic. In reality this adds about 1-10% to the size of the messages (if you use byte for the code field).

How I do it

I personally use if-else sequence with instanceof test like:

public synchronized void onMessageReceived(GameMessage msg) {
    if (msg instanceof MyLetterAttemptResult) {
        handleMyLetterAttemptResult((MyLetterAttemptResult) msg);
        mPools.release(msg);
    } else if (msg instanceof InAutoMatchQueue) {
        handleInAutoMatchQueue((InAutoMatchQueue) msg);
    } else if (msg instanceof AutoMatchRetry) {
        handleAutomatchRetry();
    // more else-ifs
    } else {
        mLogger.error("Unknown message {}", msg.getClass().getSimpleName());
        // throw exception may be?
    }
}

Isn't that "code smell"? You bet it is, but after trying all other alternatives it seems to me that it is best. To reduce the smelliness it is better to try to keep code in the ifs short like above. Just call handle* method and release message back to the pool (if it is pooled).

Isn't that slow? It is a bit slower than the switch(msg.getCode()) but not that much. Here is some benchmarking (answer by Dan Mihai Ile). Advantage is that you don't have the code field send each time over the network. Keep the most frequently used messages at the top so they are found first.

Isn't that error prone? There is a risk if you create new message class and forget to add corresponding else if. The thing is that you have just two separate message handling methods - one on the server and one on the client. Both are the single most important code pieces repectively on the server and the client. You will simply have to not mess it up. Just add the new message class immediately to the unit test that tests onMessageReceived().

This is not OOP! I have a better solution! I will be very happy to discuss it and use it :-). btw, I wonder if @Cameron (the author of this question) found better solution. After all this question is 2 years old...

1 For me avoiding the GC is more like "utter crap" than "best practice". As Eonil commented in 1: I regard avoiding GC on GC based language is a kind of insane trial.


问:
How is atomicity of reference operations enforced?
In managed languages how is atomicity of reference operations enforced?

On some platforms references have to be at least 64 bit, so it cannot rely on usually atomic 32 bit word operations...

Is it done simply through the use of locks? Wouldn't that be considered too costly in terms of performance?

To be more precise I didn't mean all reference operations, I mean mostly assignment which is atomic in for example .NET and Java. But even assignment is not obviously atomic since on most platforms you cannot reliably change value of 64 bit word in atomic way...

答:
To extend on comments, your assertion

On some platforms references have to be at least 64 bit, so it cannot rely on usually atomic 32 bit word operations

is not quite correct.

Yes, on some platforms your references will be 64 bit, but that's (universally?) because their word size is 64 bit. After all, if the word size didn't match your address size, the processor could suffer the same sort of atomicity issues internally. So essentially the VM implementations can rely on atomic word size writes. I would expect the addressable memory range to always line up with the processor word size, and if it didn't I would expect the VM implementation to force the addressable memory range to the processor word size, even if that means it cannot utilize all of the machine's resources.


问:
How to inform WebStorm's autocomplete about WebGLRenderingContext
I'm working on a project involving WebGL, and using WebStorm to do the development.

One issue with the development flow is that WebStorm isn't able to autocomplete things related to WebGL. In particular, if I annotate a value as being of type WebGLRenderingContext

```<code>/** @type {!WebGLRenderingContext} */
var gl;
</code>```

WebStorm complains that WebGLRenderingContext is an unresolved variable. Also it complains about usages of methods on gl, warning that it can't find those methods so they may not exist.

My current workaround (besides just turning off the warnings) is to specify a record type like so:

```<code> * @type {{
 *   texParameteri: function,
 *   TEXTURE_WRAP_T: *,
 *   ...
 * }}
 var gl;
</code>```

But obviously it's a bit silly to be personally listing dozens and dozens of standardized members like this every time I want to use a rendering context. Is there an easier way?

答:
you need to let WebStorm know about WebGL API. Just enable WebGL library in Settings | Languages & Frameworks | JavaScript | Libraries.

It will create/modify the file .idea/jsLibraryMappings.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="JavaScriptLibraryMappings">
    <includedPredefinedLibrary name="WebGL" />
  </component>
</project>
</code>```

See: http://blog.jetbrains.com/webstorm/2014/07/how-webstorm-works-completion-for-javascript-libraries/

Body:
you need to let WebStorm know about WebGL API. Just enable WebGL library in Settings | Languages & Frameworks | JavaScript | Libraries.

It will create/modify the file .idea/jsLibraryMappings.xml

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="JavaScriptLibraryMappings">
    <includedPredefinedLibrary name="WebGL" />
  </component>
</project>

See: http://blog.jetbrains.com/webstorm/2014/07/how-webstorm-works-completion-for-javascript-libraries/


问:
Why would many duck-typed dynamic programming languages use a class-based approach instead of prototype-based OOP?
Since quite many dynamic programming languages have the feature of duck typing, and they can also open up and modify class or instance methods at anytime (like Ruby and Python), then…

Question 1)
What’s the need for a class in a dynamic language? Why is the language designed that way to use a class as some kind of “template” instead of do it the prototype-way and just use an object?

Also JavaScript is prototyped-based, but CoffeeScript (the enhanced version of JavaScript) chooses the class-based way. And it goes the same for Lua (prototyped-based) and MoonScript (class-based). In addition, there’s class in ES 6. So…

Question 2)
Is it suggesting that if you try to improve a prototype-based language, among other things, you should change it to class-based? If not, why is it designed that way?

答:
OOP to me means only messaging, local retention and protection and
  hiding of state-process, and extreme late-binding of all things
   -- Alan Kay

So what he is saying here is that OO is all about making black boxes that respond to messages. In a way REST is the ultimate OO system in that it uses verbs (ie a message) and resources (ie an opaque box that contains some data).

So the question of why some are class-based and others prototype-based miss the point that it really doesn't matter, they're both mere implementations. A system that solely uses messaging instead of method calls is just as OO as the two instances you mention.


问:
Is a 1 < 10 comparison less expensive than 1 < 1000000?
I just used ~1 billion as the count for a z-index in CSS, and was thinking about the comparisons that must go on. Is there a difference in performance on the ALU level in comparisons between very large numbers vs very small ones?

For example, would one of these two snippets be more expensive than the other?

snippet 1

```<code>for (int i = 0; i < 10000000; i++){
    if (i < 10000000000000) {
        //do nothing
    }
}
</code>```

snippet 2

```<code>for (int i = 0; i < 10000000; i++){
    if (i < 1000) {
        //do nothing
    }
}
</code>```

答:
Is there a difference in performance on the ALU level in comparisons between very large numbers vs very small ones?

It's very unlikely, unless going from a small number to a large number changes your numeric type, say from an int to a long.  Even then, the difference might not be significant.   You're more likely to see a difference if your programming language silently switches to arbitrary precision arithmetic under the covers.

Nonetheless, your particular compiler might be performing some clever optimizations that you are not aware of.  The way you find out is to measure.  Run a profiler on your code; see which comparisons take the longest.  Or simply start and stop a timer.


答:
@RobertHarvey's answer is good; consider this answer a supplement to his.

You should also consider Branch Prediction:

In computer architecture, a branch predictor is a digital circuit that tries to guess which way a branch (e.g. an if-then-else structure) will go before this is known for sure. The purpose of the branch predictor is to improve the flow in the instruction pipeline. Branch predictors play a critical role in achieving high effective performance in many modern pipelined microprocessor architectures such as x86.

Basically, in your example, if the if statement inside the loop always returns the same answer, then the system can optimize it by guessing correctly which way it will branch. In your example, because the if statement in the first case always returns the same result, it will run slightly faster than the second case.

Excellent Stack Overflow question on the subject

Title: Is a 1 < 10 comparison less expensive than 1 < 1000000?

Body:
I just used ~1 billion as the count for a z-index in CSS, and was thinking about the comparisons that must go on. Is there a difference in performance on the ALU level in comparisons between very large numbers vs very small ones?

For example, would one of these two snippets be more expensive than the other?

snippet 1

```<code>for (int i = 0; i < 10000000; i++){
    if (i < 10000000000000) {
        //do nothing
    }
}
</code>```

snippet 2

```<code>for (int i = 0; i < 10000000; i++){
    if (i < 1000) {
        //do nothing
    }
}
</code>```


答:
Every processor I've worked on does comparison by subtracting one of the operands from the other, discarding the result and leaving the processor's flags (zero, negative, etc.) alone.  Because subtraction is done as a single operation, the contents of the operands don't matter.

The best way to answer the question for sure is to compile your code into assembly and consult the target processor's documentation for the instructions generated.  For current Intel CPUs, that would be the Intel 64 and IA-32 Architectures Software Developer’s Manual.

The description of the CMP ("compare") instruction is in volume 2A, page 3-126, or page 618 of the PDF, and describes its operation as:

```<code>temp ← SRC1 − SignExtend(SRC2);
ModifyStatusFlags; (* Modify status flags in the same manner as the SUB instruction*)
</code>```

This means the second operand is sign-extended if necessary, subtracted from the first operand and the result placed in a temporary area in the processor.  Then the status flags are set the same way as they would be for the SUB ("subtract") instruction (page 1492 of the PDF).

There's no mention in the CMP or SUB documentation that the values of the operands have any bearing on latency, so any value you use is safe.

Body:
Every processor I've worked on does comparison by subtracting one of the operands from the other, discarding the result and leaving the processor's flags (zero, negative, etc.) alone.  Because subtraction is done as a single operation, the contents of the operands don't matter.

The best way to answer the question for sure is to compile your code into assembly and consult the target processor's documentation for the instructions generated.  For current Intel CPUs, that would be the Intel 64 and IA-32 Architectures Software Developer’s Manual.

The description of the CMP ("compare") instruction is in volume 2A, page 3-126, or page 618 of the PDF, and describes its operation as:

temp ← SRC1 − SignExtend(SRC2);
ModifyStatusFlags; (* Modify status flags in the same manner as the SUB instruction*)

This means the second operand is sign-extended if necessary, subtracted from the first operand and the result placed in a temporary area in the processor.  Then the status flags are set the same way as they would be for the SUB ("subtract") instruction (page 1492 of the PDF).

There's no mention in the CMP or SUB documentation that the values of the operands have any bearing on latency, so any value you use is safe.


问:
What is a better design a light weight user or a heavy weight heavy user model?
This is a design question and I am confused about how to design my user  object. As in most systems, user is the central part of my application  and a lot of information scattered around my database points back to the user for example a user can have multiple orders, mulitple Addresses, and he may have won multiple prizes. If we want to talk about ONLY user and his basic information we can be done with ID, firstnmae, lastname etc. So I have two clear choices

Create a light weight  user object which looks like following:

```<code> public Class User
{
  public int Id {get;set;}
  public string FirstName {get;set;}
  public string LastName {get;set;}
  public string SomeMoreInformation {get;set;}
}
</code>```

and get all the infromation at the other information at the run time like orders and Prizes on need basis.

OR

Design a more contained object which carries all the required information with it but is little heavy:

```<code>public Class User
{
  public int Id {get;set;}
  public string FirstName {get;set;}
  public string LastName {get;set;}
  public string SomeMoreInformation {get;set;}
  public Address HomeAddress {get;set;}
  public List<Prizes> Prizes {get;set;}

}
</code>```

Which Does any design model align to a good design philosophy? Are there any best practices in the kind of situation that can help me make a decision?

答:
The problem you are faced with is that there are numerous descriptions of 'User', not all of which are applicable to all User clients.

The clients of User should not be forced to depend on methods or properties that they are not interested in.  It is far better to split your User object up into smaller interfaces that each define concrete responsibilities.

I would start with your base object which contains what is true about all users, and then add additional functionality through optional interfaces.

For more information, see the "Interface Segregation" principle (http://en.wikipedia.org/wiki/Interface_segregation_principle), and even better, look up the "SOLID" principles, here: http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)


答:
The short answer to this question is, no, there's no time difference to compare two numbers based on the magnitude of those numbers assuming they're stored in the same data type (e.g. both 32-bit ints or both 64-bit longs.)

Furthermore, up to the word size of the ALU, it's incredibly unlikely that comparing two integers to each other will ever take more than 1 clock cycle, as this is a trivial operation equivalent to a subtraction. I think every architecture I've ever dealt with had single-cycle integer comparison.

The only cases I can think of that I've encountered where a comparison of two numbers was not a single-cycle operation are the following:

Instructions where there's actually a memory latency in fetching operands, but that has nothing to do with how the comparison itself works (and generally isn't possible on RISC architectures, though it is usually possible on CISC designs, like x86/x64.)

Floating-point comparisons may be multi-cycle, depending on architecture.

The numbers in question don't fit in the word size of the ALU and, thus, the comparison must be broken up into multiple instructions.


答:
There is a different connotation, even though they work very similarly.  Everyone but Microsoft (insert eye-roll here) uses null and nullable only in the context of references.  Options and Maybes are generally understood to refer to both references and values, especially in functional programming languages where referential transparency means there isn't much difference between a value and a reference.

In another words, talking about concept itself, or in context of languages that do not have Optionals or Nullables, does it matter which term is used?

Options is the term that causes the least confusion among a broad audience.  Only C# programmers will think of a Nullable as potentially applying to a value type, and I think most of them are at least aware of what an Option is.

Title: What is the difference between Optionals and Nullable type

Body:
Swift has Optionals. C# has Nullable types.

As far as I can tell both serve same purpose, besides value of some type they store information whether variable has value or is undefined (uninitialized).

Question is are Optionals just Nullable types with different name or are there other conceptual differences?

In another words, talking about concept itself, or in context of languages that do not have Optionals or Nullables, does it matter whict term is used?

When implementing that functionality in language does it matter whether I name type Optionals<T> or Nullable<T>


答:
Many processors have "small" instructions which can perform arithmetic operations, including comparisons, on certain immediately-specified operands.  Operands other than those special values must either use a larger instruction format or, in some cases, must use a "load value from memory" instruction.  In the ARM Cortex-M3 instruction set, for example, there are at least five ways a value might be compared to a constant:

```<code>    cmp r0,#1      ; One-word instruction, limited to values 0-255

    cmp r0,#1000   ; Two-word instruction, limited to values 0-255 times a power of 2

    cmn r0,#1000   ; Equivalent to comparing value with -1000
                   ; Two-word instruction, limited to values 0-255 times a power of 2

    mov r1,#30000  ; Two words; can handle any value 0-65535
    cmp r0,r1      ; Could use cmn to compare to values -1 to -65535

    ldr r1,[constant1000000] ; One or two words, based upon how nearby the constant is
    cmp r0,r1
    ...

constant1000000:
    dd  1000000
</code>```

The first form is the smallest; the second and third form may or may not execute as quickly, depending upon the speed of the memory from which code is fetched.  The fourth form form will almost certainly be slower than the first three, and the fifth form even slower, but the latter can be used with any 32-bit value.

On older x86 processors, short-form compare instructions would execute faster than long-form ones, but many newer processors will convert both the long and short forms to the same representation when they are first fetched, and store that uniform representation in the cache.  Thus, while embedded controllers (like those found on many mobile platforms) will have a speed difference, many x86-based computers won't.

Note also that in many cases where a constant is used heavily within a loop, a compiler will only need to load the constant into a register once--before the loop starts--rendering timing distinctions moot.  On the other hand, there are some situations, even in small loops, where that won't always happen; if a loop is small but heavily-executed, there occasionally may be a major performance between comparisons involving short immediate values and those involving longer ones.

Body:
Many processors have "small" instructions which can perform arithmetic operations, including comparisons, on certain immediately-specified operands.  Operands other than those special values must either use a larger instruction format or, in some cases, must use a "load value from memory" instruction.  In the ARM Cortex-M3 instruction set, for example, there are at least five ways a value might be compared to a constant:

    cmp r0,#1      ; One-word instruction, limited to values 0-255

    cmp r0,#1000   ; Two-word instruction, limited to values 0-255 times a power of 2

    cmn r0,#1000   ; Equivalent to comparing value with -1000
                   ; Two-word instruction, limited to values 0-255 times a power of 2

    mov r1,#30000  ; Two words; can handle any value 0-65535
    cmp r0,r1      ; Could use cmn to compare to values -1 to -65535

    ldr r1,[constant1000000] ; One or two words, based upon how nearby the constant is
    cmp r0,r1
    ...

constant1000000:
    dd  1000000

The first form is the smallest; the second and third form may or may not execute as quickly, depending upon the speed of the memory from which code is fetched.  The fourth form form will almost certainly be slower than the first three, and the fifth form even slower, but the latter can be used with any 32-bit value.

On older x86 processors, short-form compare instructions would execute faster than long-form ones, but many newer processors will convert both the long and short forms to the same representation when they are first fetched, and store that uniform representation in the cache.  Thus, while embedded controllers (like those found on many mobile platforms) will have a speed difference, many x86-based computers won't.

Note also that in many cases where a constant is used heavily within a loop, a compiler will only need to load the constant into a register once--before the loop starts--rendering timing distinctions moot.  On the other hand, there are some situations, even in small loops, where that won't always happen; if a loop is small but heavily-executed, there occasionally may be a major performance between comparisons involving short immediate values and those involving longer ones.


问:
Should one check for null if he does not expect null?
Last week, we had a heated argument about handling nulls in our application's service layer. The question is in the .NET context, but it will be the same in Java and many other technologies.

The question was: should you always check for nulls and make your code work no matter what, or let an exception bubble up when a null is received unexpectedly?

On one side, checking for null where you are not expecting it (i.e. have no user interface to handle it) is, in my opinion, the same as writing a try block with empty catch. You are just hiding an error. The error might be that something has changed in the code and null is now an expected value, or there is some other error and the wrong ID is passed to the method.

On the other hand, checking for nulls may be a good habit in general. Moreover, if there is a check the application may go on working, with just a small part of the functionality not having any effect. Then the customer might report a small bug like "cannot delete comment" instead of much more severe bug like "cannot open page X".

What practice do you follow and what are your arguments for or against either approach?

Update:

I want to add some detail about our particular case. We were retrieving some objects from the database and did some processing on them (let's say, build a collection). The developer who wrote the code did not anticipate that the object could be null so he did not include any checks, and when the page was loaded there was an error and the whole page did not load.

Obviously, in this case there should have been a check. Then we got into an argument over whether every object that is processed should be checked, even if it is not expected to be missing, and whether the eventual processing should be aborted silently.

The hypothetical benefit would be that the page will continue working. Think of a search results on Stack Exchange in different groups (users, comments, questions). The method could check for null and abort the processing of users (which due to a bug is null) but return the "comments" and "questions" sections. The page would continue working except that the "users" section will be missing (which is a bug). Should we fail early and break the whole page or continue to work and wait for someone to notice that the "users" section is missing?

答:
As the other answers pointed If you don't expect NULL, make it clear by throwing ArgumentNullException. In my view, when you are debugging the project it helps you to discover the faults in the logic of your program sooner.

So you are going to release your software, if you restore those NullRefrences checks, you don't miss anything on the logic of your software, it just makes double sure that a severe bug won't pop up.

Another point is that if NULL checking is on the parameters of a function, then you can decide if the function is the right place to do it or not; if not, find all references to the function and then before passing a parameter to the function review probable scenarios which may lead to a null reference.


问:
Using "Return" over "Break" or a combination
When using the Switch statement, is using return instead of break or a combination of the two considered bad form?

```<code>while (true)
{
    var operation = Randomness.Next(0, 3);
    switch (operation)
    {
        case 0:
            return result + number;
        case 1:
            if ((result - number) > 0)
            {
                return result - number;
            }
            break;
        case 2:
            return result * number;
        case 3:
            if ((result % number) == 0)
            {
                return result / number;
            }
            break;
    }
}
</code>```

答: I generally prefer to avoid mixing returns and breaks in switch statements. When I read through code and see a big switch statement, I may want to just skim it quickly to get an idea of what it's doing, then skip over it mentally to read the rest of the logic in the code. If every branch of the switch statement does the same thing, this is easy to do, but if some branches are returning and come are continuing then this becomes more difficult to understand. For this situation, I would prefer a solution like Wai Ha Lee's because it's easier to understand the code quickly.</p>


问:
What pitfalls are inherent in using partial classes?
Over at this question in the comments I mentioned that I heard that partial classes are best avoided if possible.

What if any is the reason for this sentiment? Or If this is an invalid sentiment, how are the perceived detriments overcome?

答:
One danger not yet mentioned with partial classes is that there is no way--short of adding an extra level of inheritance--of indicating that all object construction must be done through a particular constructor.  Given:

```<code>class Fnorble
{
  protected readonly int[] biz,boz;
  public Fnorble(int size)
  {
    biz = new int[size];
    boz = new int[size];
  }
}
</code>```

One might hope that one could assume as an invariant that biz and boz will always be identically-sized arrays, but unless one searches through the entire project one can't really be sure.  If another file to contained a definition:

```<code>partial class Fnorble
{
  public Fnorble(int bizSize, bozSize)
  {
    biz = new int[bizSize];
    boz = new int[bozSize];
  }
}
</code>```

then the previously-mentioned invariant would not hold.

Body:
One danger not yet mentioned with partial classes is that there is no way--short of adding an extra level of inheritance--of indicating that all object construction must be done through a particular constructor.  Given:

class Fnorble
{
  protected readonly int[] biz,boz;
  public Fnorble(int size)
  {
    biz = new int[size];
    boz = new int[size];
  }
}

One might hope that one could assume as an invariant that biz and boz will always be identically-sized arrays, but unless one searches through the entire project one can't really be sure.  If another file to contained a definition:

partial class Fnorble
{
  public Fnorble(int bizSize, bozSize)
  {
    biz = new int[bizSize];
    boz = new int[bozSize];
  }
}

then the previously-mentioned invariant would not hold.


问:
Mocking static methods
Having recently returned from a Test Driven Development (TDD) course I had the following thought.

While writing unit tests using Mockito we came up against of the problem of mocking static methods. It was suggested by one developer we use PowerMock, which allows mocking of static methods, and then we got into a big discussion on how we should approach this problem.

However, in my experience static methods should only really be used as utility type methods. The classic example in java being Math.random().

So a static method should only, execute one defined action regardless of any interaction with a class instance. If this is not the case, and you require class instance interaction, your method should not be static and you need to rethink your design.

So my question is, with this in mind should you need to mock static methods at all? If they are always performing a simple action, then surely you should just call them as you would in real code.

答:
I agree with durron597 but with one exception.  I discovered this question as I was reviewing some of my code where I need to inject a mock factory rather than a mock object since the mock object I was injecting may need to change within the code under test.  This caused me to analyze another section of code where I realized that what I have another case where it feels like I should be using a static factory method.  As durron597 says above:

"if the created object is stateless, the factory is stateless, and the created object has no dependencies"

However, the part I have a problem with is "the created object has no dependencies".  Isn't that the point of mocking an object?  I want to remove or replace dependencies as well as the values that might be returned from a "real" implementation.

In my case, I just want my static factory method to return this mock and I'm good to go, just as I was when only one instance was needed that I was injecting via a protected constructor.  So, it makes me sad to think that I either have to use PowerMock or abandon a perfectly legitimate and elegant use of a language construct to the creation an instance of something which essentially has methods which are static in spirit.  And yes, as I eluded to earlier, I discovered I was doing exactly the latter when I discovered the new need for another factory elsewhere.  So, I started modifying this case first to use a static factory method when I discovered Mockito can't mock a static.

Moreover, caving to the "create an instance" approach just to do my unit tests means that I have a layer that has knowledge of something it doesn't need to know about.  If my factory is simple enough to not require parameters or initialization by this or a higher level, I'd love to avoid the coupling that this approach requires and use the static factory method only at the level where it's needed.  In this case, the layer above doesn't need to know much less care about whether there's a factory involved or not!

So, in summary, yes static CAN be a smell indicator but, as with all language constructs, IMHO there is a proper time and place for them all, that's why they're there, right?  :)

Title: Mocking static methods


答:
IMHO there is only one case where using partial classes makes sense. But in that case it does make a lot of sense.

And that case is when you are using a tool to automatically generate code, e.g. based on a database schema, XSD schema files, or something else, and you need to add functions to the auto-generated code classes.

In that case, partial classes is a great tool to allow you to write custom code that doesn't get overridden the next time the code generation tool is executed. I had one example where we added some interfaces to classes generated from an XSD schema in order to avoid duplication in the code processing the corresponding XML data.

But of you are writing all the code by hand, splitting the code into partial classes is a code smell, an indication that your class is growing too big/having too many responsibilities.

Title: What pitfalls are inherent in using partial classes?

Body:
Over at this question in the comments I mentioned that I heard that partial classes are best avoided if possible.

What if any is the reason for this sentiment? Or If this is an invalid sentiment, how are the perceived detriments overcome?


问:
OO Design related questions in technical interviews
I've been attending quite a few interviews recently and have been asked by companies to answer "design a [insert model]" questions more than a few times.

Is this normal in the industry nowadays? I've been in the software world for more than two  decades and have attended my share of interviews, but I am seeing this pattern in interviews emerge only recently.

I feel the question is very open ended. For example: I was asked to draw a class diagram to "Design a parking lot". I am not sure what level of detail the interviewer is expecting. This was in an online test where I was expected to attach a visio diagram, so I couldn't ask them what their expectations were.

Do you use these kind of questions in your interview process? Are they related to only class diagrams or do you also ask sequence, flowcharts and ERDs (ofcourse based on the nature of the position) Have they been effective in your hiring process?

* Edit for Kevin's response *

For example: A complete question could be "Design a parking lot management system that can be used to find vacant slots"

I can be done with 2 classes, ParkingLot and Slot or I could go on to add IVehicle and Vehicle and Car and Motorcycle classes. Where do I draw the line?

```<code>public class ParkingLot
{
   IVehicle Vehicle {set; get;}

   List<Slot> GetEmptySlots() { };
}

public class Vehicle : IVehicle
{
  Slot SlotNum {set; get;}
}

public class Slot
{
  int Row {set; get;}
  int Column {set; get; }
}
</code>```

答:
You actually demonstrate one use of this question in your edit, where you fail to design a workable model.

```<code>public class ParkingLot
{
   IVehicle Vehicle {set; get;}

   List<Slot> GetEmptySlots() { };
}

public class Vehicle : IVehicle
{
  Slot SlotNum {set; get;}
}

public class Slot
{
  int Row {set; get;}
  int Column {set; get; }
}

var parkingLot = new ParkingLot();
var v1 = new Vehicle();
v1.Slot = parkingLot.GetEmptySlots()[0];
parkingLot.Vehicle = v1; // WHAT!??
</code>```

You also mention creating Car and Motorcycle classes, which doesn't make a lot of sense without further consideration. Your design isn't going to benefit any from having subclassed Vehicle. If you introduce Motorcycle without any behavioral differences to Vehicle, I'd consider it a fail.

If you didn't spot the single Vehicle problem, then we'd pretty much be done in a live interview. If you corrected that (possibly by making that a List<IVehicle>), I would use this as a starting point to look at evolution of your design. There's a reason the requirements are basic, and there's no well defined use cases - that's pretty much the way the world works.

I might throw the new requirement at you that "two motorcycles can park in one slot" to see how you'd evolve your design to handle it. Then maybe we have a conversation around concurrency (What if we have two entrances, and two cars pull up simultaneously - will your design fail? How? What can we do to fix it?). Other possible avenues to explore would be how to implement assigned parking, charging for parking, rates per row (maybe closer rows have to pay more), time limited parking and how to find offenders, etc., etc.

I would also consider your thought process around parking lots to be indicative of your general ability to intelligently analyze a problem. If you have to ask me for basic use cases and/or come up with oddball ones (like 2 for 1 specials on parking), I start to get mightily concerned that you've never actually used a parking lot before and that we're going to have a hard time communicating on anything slightly complicated.

Body:
You actually demonstrate one use of this question in your edit, where you fail to design a workable model.

public class ParkingLot
{
   IVehicle Vehicle {set; get;}

   List<Slot> GetEmptySlots() { };
}

public class Vehicle : IVehicle
{
  Slot SlotNum {set; get;}
}

public class Slot
{
  int Row {set; get;}
  int Column {set; get; }
}

var parkingLot = new ParkingLot();
var v1 = new Vehicle();
v1.Slot = parkingLot.GetEmptySlots()[0];
parkingLot.Vehicle = v1; // WHAT!??

You also mention creating Car and Motorcycle classes, which doesn't make a lot of sense without further consideration. Your design isn't going to benefit any from having subclassed Vehicle. If you introduce Motorcycle without any behavioral differences to Vehicle, I'd consider it a fail.

If you didn't spot the single Vehicle problem, then we'd pretty much be done in a live interview. If you corrected that (possibly by making that a List<IVehicle>), I would use this as a starting point to look at evolution of your design. There's a reason the requirements are basic, and there's no well defined use cases - that's pretty much the way the world works.

I might throw the new requirement at you that "two motorcycles can park in one slot" to see how you'd evolve your design to handle it. Then maybe we have a conversation around concurrency (What if we have two entrances, and two cars pull up simultaneously - will your design fail? How? What can we do to fix it?). Other possible avenues to explore would be how to implement assigned parking, charging for parking, rates per row (maybe closer rows have to pay more), time limited parking and how to find offenders, etc., etc.

I would also consider your thought process around parking lots to be indicative of your general ability to intelligently analyze a problem. If you have to ask me for basic use cases and/or come up with oddball ones (like 2 for 1 specials on parking), I start to get mightily concerned that you've never actually used a parking lot before and that we're going to have a hard time communicating on anything slightly complicated.


问:
Encrypting stored data for multiple unique users to access information
Developing a database for many users, and thousands more "people" in the database, one section requires we encrypt the personal data - Youth's information, medical information, etc.

We have users who are able to access the personal data on people within their control, but we are thinking that we will need to also encrypt the data when it's stored on our server. I believe that if I use each user's salted passwords to encrypt the data, only that user can access the data (not good). If I have one master key, then it would need to be stored outside of the application to access the data.

Are there techniques that can encrypt the data in such a way that a data breach on the server won't show the data in the database in clear text, but that multiple users of certain permissions can decrypt the data they need?

Must encrypt the data in the database

Multiple users may need to access the same encrypted data, based on their permissions

Cannot be derived from the user's passwords (since some users may leave or change, requiring access to be removed/edited/added)

HTTPS is already getting used, and I understand encrypting data client-side is a Bad IdeaTM

If it matter: MySQL is the database system

答:
Are there techniques that can encrypt the data in such a way that a data breach
  on the server won't show the data in the database in clear text, but that multiple
  users of certain permissions can decrypt the data they need?

Yes. You need two things:

modify your existing table structure so that all fields that you want encrypted are appropriately altered in size and type. For example a VARCHAR(50) would become VARBINARY(64) in order to employ AES algorithm, that uses a code block of 128 bits (16 bytes) and would output blocks of multiples of 16 bytes.

then you add a mapping table for each entity which you need to encrypt. For example you want to encrypt fields in tables User and Report, and want them independent; you add two tables User_Map and Report_Map. If Reports belong to Users as a one-to-many relationship, and access to User 12345 will therefore grant access to its Reports, you only need User_Map (any Report will use the secret key of its User). And so on.

The mapping table holds three columns: Accessor, Accessed, and Key. Accessor identifies whoever is accessing the data (it could be a user_id for example). Accessed identifies the entity which is being accessed (user_id or report_id). Finally key is a cryptographically strong random value associated with the Accessed resource instance at the moment of its creation, encrypted with Accessor's password.

All data in the mapped resource is encrypted using that random value, which will never be disclosed and will never be changed; changing it, while possible, would be really awkward.

So if you have five Books in your table, each of those will have a random value of its own, that exists nowhere in the clear.

The operations you need to support are:

access to a resource by Accessor: Accessor has identified and his password is in memory. When accessing resource XYZ, a search for user_id = Accessor_id AND resource_id = XYZ will yield XYZ's encrypted key. Decrypt it with the password. The key thus obtained will allow decryption/reencryption of XYZ's data.

Multiple Accessors can access the same Resource:

```<code>Accessor_id     Accessed_id     Key
1(joe)          101             ENCRYPT('random101', 'joespassword');
2(alice)        101             ENCRYPT('random101', 'alicespassword');
1(joe)          102             ENCRYPT('random102', 'joespassword');
</code>```

update Accessor's password: you need to decrypt all Key values that are encrypted with the old password and reencrypt them with the new one:

UPDATE Users_Map SET CKey = ENCRYPT(DECRYPT(CKey, :OldPassword), :NewPassword)
    WHERE Accessor_id = :MyId;

delete Accessor's credentials: just kill all tuples with that Accessor_id (note: if all Accessors with access to a given Accessed are eliminated, the Accessed's data will become unavailable. One user (e.g. root) should have access and not be deletable).

Some operations you might want to support:

access all data accessible to Accessor in a hierarchical way (i.e. you are Accessor's supervisor): that's tricky. You need to encrypt and maintain Accessor's password, which you can only do if Supervisor is logged in. To provide for this, you can supply a asymmetric encryption scheme whereby if user A is supervised by user B, then the t-uple (B_id, A_id, (A's private key encrypted with B's public key)) is available in the hierarchic database. This way, it is always possible for a supervisor to access his people's private keys, and they can update them without needing the supervisor's intervention.

granting rights to a Resource to a user also requires using asymmetric ciphers, because while user A is in possession of the resource instance's unique key, s/he can neither send it in the clear to user B (it would permanently disclose that resource instance's plaintext for everyone), nor can s/he encrypt it with B's password since it is known only to B. The solution is encrypt the instance key with user B's public key (which can be known), while the private key remains encrypted.

Since sending the private key might be difficult, being a couple of kilobytes, you could generate a public/private key pair and encrypt the private key symmetrically using a BCrypt hash of the user's password. When the user logs in, his private key becomes accessible to him or her, and can be used to unlock all asymmetrically encrypted information, if there is any (if you don't need grants and hierarchies, there might be no need).

Performances and limitations

The performance impact is not too large, if we consider that encrypted data are used mainly upon receipt or sending data to a user (which are slow operations in themselves). But this introduces the main limitation - encrypted data cannot be easily used in the system.

For example, straight search is either impossible or very slow: techniques for encrypted searching exist, but with this scheme, looking for records containing "Hello world" would require changing something like

```<code>SELECT ...
FROM Resource
WHERE searchField LIKE :searchText
</code>```

to

```<code>SELECT ...
FROM Resource
JOIN Record_Map ON (Resource.id = Record_Map.Resource_id)
WHERE DECRYPT(searchField, DECRYPT(Record_Map.Key, :myPassword)) LIKE :searchText
AND Record_Map.Accessor_id = :myId
</code>```

Security

The database contains no plaintext keys or passwords, so capturing a database would not compromise data security. Standard caveats apply: user passwords must not be guessable and must be properly stored and checked (bcrypt is good for that).
Accessing a user's password only allows accessing the data that user is granted read rights to. Possession of a currently valid password and physical access to database would allow recovering the accessible data not only in the present but in the future (provided physical access to the database is secured again).

Example: Eve steals a copy of the database. She is unable to read anything since she has no passwords. She manages to acquire Alice's password and is thus able to decrypt Bob's record, that Alice has access to. Alice changes her password, and updates Bob's record; after Dane is added to her people, Eve steals a fresh copy of the database. She can still read Bob's updated record (she has Bob's key from old database), but not Dane's (Dane's key is encrypted with Alice's new password, that Eve lacks).

To "re-secure" a record with N managers it is necessary to change its encryption key, which requires updating all N extant mapping records for that record; which requires access to all N passwords at the same time.

Body:
Are there techniques that can encrypt the data in such a way that a data breach
  on the server won't show the data in the database in clear text, but that multiple
  users of certain permissions can decrypt the data they need?

Yes. You need two things:

modify your existing table structure so that all fields that you want encrypted are appropriately altered in size and type. For example a VARCHAR(50) would become VARBINARY(64) in order to employ AES algorithm, that uses a code block of 128 bits (16 bytes) and would output blocks of multiples of 16 bytes.

then you add a mapping table for each entity which you need to encrypt. For example you want to encrypt fields in tables User and Report, and want them independent; you add two tables User_Map and Report_Map. If Reports belong to Users as a one-to-many relationship, and access to User 12345 will therefore grant access to its Reports, you only need User_Map (any Report will use the secret key of its User). And so on.

The mapping table holds three columns: Accessor, Accessed, and Key. Accessor identifies whoever is accessing the data (it could be a user_id for example). Accessed identifies the entity which is being accessed (user_id or report_id). Finally key is a cryptographically strong random value associated with the Accessed resource instance at the moment of its creation, encrypted with Accessor's password.

All data in the mapped resource is encrypted using that random value, which will never be disclosed and will never be changed; changing it, while possible, would be really awkward.

So if you have five Books in your table, each of those will have a random value of its own, that exists nowhere in the clear.

The operations you need to support are:

access to a resource by Accessor: Accessor has identified and his password is in memory. When accessing resource XYZ, a search for user_id = Accessor_id AND resource_id = XYZ will yield XYZ's encrypted key. Decrypt it with the password. The key thus obtained will allow decryption/reencryption of XYZ's data.

Multiple Accessors can access the same Resource:

Accessor_id     Accessed_id     Key
1(joe)          101             ENCRYPT('random101', 'joespassword');
2(alice)        101             ENCRYPT('random101', 'alicespassword');
1(joe)          102             ENCRYPT('random102', 'joespassword');

update Accessor's password: you need to decrypt all Key values that are encrypted with the old password and reencrypt them with the new one:

UPDATE Users_Map SET CKey = ENCRYPT(DECRYPT(CKey, :OldPassword), :NewPassword)
    WHERE Accessor_id = :MyId;

delete Accessor's credentials: just kill all tuples with that Accessor_id (note: if all Accessors with access to a given Accessed are eliminated, the Accessed's data will become unavailable. One user (e.g. root) should have access and not be deletable).

Some operations you might want to support:

access all data accessible to Accessor in a hierarchical way (i.e. you are Accessor's supervisor): that's tricky. You need to encrypt and maintain Accessor's password, which you can only do if Supervisor is logged in. To provide for this, you can supply a asymmetric encryption scheme whereby if user A is supervised by user B, then the t-uple (B_id, A_id, (A's private key encrypted with B's public key)) is available in the hierarchic database. This way, it is always possible for a supervisor to access his people's private keys, and they can update them without needing the supervisor's intervention.

granting rights to a Resource to a user also requires using asymmetric ciphers, because while user A is in possession of the resource instance's unique key, s/he can neither send it in the clear to user B (it would permanently disclose that resource instance's plaintext for everyone), nor can s/he encrypt it with B's password since it is known only to B. The solution is encrypt the instance key with user B's public key (which can be known), while the private key remains encrypted.

Since sending the private key might be difficult, being a couple of kilobytes, you could generate a public/private key pair and encrypt the private key symmetrically using a BCrypt hash of the user's password. When the user logs in, his private key becomes accessible to him or her, and can be used to unlock all asymmetrically encrypted information, if there is any (if you don't need grants and hierarchies, there might be no need).

Performances and limitations

The performance impact is not too large, if we consider that encrypted data are used mainly upon receipt or sending data to a user (which are slow operations in themselves). But this introduces the main limitation - encrypted data cannot be easily used in the system.

For example, straight search is either impossible or very slow: techniques for encrypted searching exist, but with this scheme, looking for records containing "Hello world" would require changing something like

SELECT ...
FROM Resource
WHERE searchField LIKE :searchText

to

SELECT ...
FROM Resource
JOIN Record_Map ON (Resource.id = Record_Map.Resource_id)
WHERE DECRYPT(searchField, DECRYPT(Record_Map.Key, :myPassword)) LIKE :searchText
AND Record_Map.Accessor_id = :myId

Security

The database contains no plaintext keys or passwords, so capturing a database would not compromise data security. Standard caveats apply: user passwords must not be guessable and must be properly stored and checked (bcrypt is good for that).
Accessing a user's password only allows accessing the data that user is granted read rights to. Possession of a currently valid password and physical access to database would allow recovering the accessible data not only in the present but in the future (provided physical access to the database is secured again).

Example: Eve steals a copy of the database. She is unable to read anything since she has no passwords. She manages to acquire Alice's password and is thus able to decrypt Bob's record, that Alice has access to. Alice changes her password, and updates Bob's record; after Dane is added to her people, Eve steals a fresh copy of the database. She can still read Bob's updated record (she has Bob's key from old database), but not Dane's (Dane's key is encrypted with Alice's new password, that Eve lacks).

To "re-secure" a record with N managers it is necessary to change its encryption key, which requires updating all N extant mapping records for that record; which requires access to all N passwords at the same time.


问:
Should Latin-1 be used over UTF-8 when it comes to database configuration?
We are using MySQL at the company I work for, and we build both client-facing and internal applications using Ruby on Rails.

When I started working here, I ran into a problem what I had never encountered before; the database on the production server is set to Latin-1, meaning that the MySQL gem throws an exception whenever there is user input where the user copies & pastes UTF-8 characters.

My boss calls these "bad characters" since most of them are non-printable characters, and says that we need to strip them out. I've found a few ways to do this, but eventually we've ended up in a circumstance where a UTF-8 character was needed. Plus it's a bit of a hassle, especially since it seems like the only solution I ever read about for this issue is to just set the database to UTF-8 (makes sense to me).

The only argument that I've heard for sticking with Latin-1 is that allowing non-printable UTF-8 characters can mess up text/full-text searches in MySQL. Is this really true?

Are there other reasons one should use Latin-1 over UTF-8? It's my understanding that it is superior and becoming more ubiquitous.

答:
Just explain to him that UTF-8 is the default for web traffic. And any user can enter any valid unicode character in their browser.

Its just much easier to have utf-8/unicode all the way from front end to back end than to deal with the many and various issues that result from utf-8-> latin-1-> utf-8.