问:
How to make complex objects immutable?

The example I'm about to give is for the PHP language, but I think this scenario applies to most languages.

Let's say I have an object called Response and I want it to be immutable. Every method should return a new instance rather than modifying the state of the current instance. Responses have headers, so I create a method called withHeader($name, $value) that makes a copy of my response object, sets the header, and returns the new instance. It's pretty simple to use:

```<code>$newResponse = $oldResponse->withHeader('Content-Type', 'application/json');
</code>```

Then I decide the headers actually have quite a few properties and I'd rather separate this out into a separate object called a HeaderBag. Now I want my Response to hold a HeaderBag but I still want it to be immutable.

I can't make the the bag a public property, like $response->headers because even if the $headers object is immutable, the property can still be reassigned. So maybe I add something like $response->getHeaders() which returns my HeaderBag object, but now how do I manipulate it?

If I move my withHeader method into this sub-object, then I wind up with something like $response->getHeaders()->withHeader(...). The withHeader method would presumably return a new HeaderBag since it too is immutable, but then what? I guess I'd end up with something like this:

```<code>$newResponse = $oldResponse->withHeaders($oldResponse->getHeaders()->withHeader($name, $value));
</code>```

Which seems a bit ridiculous; to add a single value we have to clone two objects and write this abomination of a line. Sure, we can write a helper method on the Response object to shorten it, but the whole idea was to move all the header-related methods into the HeaderBag class.

Questions:

Is there a better way to do this?

If there isn't, is it even worth the effort/cost to make objects immutable?

If we could design a new language with immutability in mind, what would this look like?

答:
An http response can naturally be thought of as immutable, but only from the moment that it has been fully constructed and issued.  Before that moment, various implementations of "response" classes in various environments are generally used as builders (see Builder Pattern) which get passed around in order for various routines to add to them piecemeal all the information that constitutes the final response.  So, during the lifetime of the response as a builder, it is by its very nature mutable.

Now, it is still possible to take a class which is mutable by nature and turn it into an immutable class, but what I would like to suggest to you is that although doing so might be a fabulous exercise on paper, (the entire series of Erik Lippert's articles on immutability was nothing short of fascinating,) it is not really something that you would want to be doing in practice with any non-trivial class, because you end up with abominations precisely like the one you discovered.  Plus, it is clearly not worth the effort, and it is stupendously wasteful in terms of computing resources.

So, my suggestion would be that if you really like the idea of an immutable response, (I like it too,) then rename your current response to ResponseBuilder, let it be mutable, and when it is complete, create an immutable response out of it and discard the builder.

Title: How to make complex objects immutable?


问:
Multiple sites with the same codebase in Python
I am trying to run a large amount of sites which share about 90% of their code. They are simply designed to query an API and return the results. They will have a common userbase / database but will be configured slightly different and will have different CSS (perhaps even different templating).

My initial idea was to run them as separate applications with a common library but I have read about the sites framework which would allow them to run from a single instance of Django which may help to reduce memory usage.

https://docs.djangoproject.com/en/dev/ref/contrib/sites/

Is the site framework the right approach to a problem like this, and does it have real benefits over running separate applications?

Initially I thought it was, but now I think otherwise. I have heard the following:

Your SITE_ID is set in settings.py, so in order to have multiple
  sites, you need multiple settings.py configurations, which means
  multiple distinct processes/instances. You can of course share the
  code base between them, but each site will need a dedicated worker /
  WSGIDaemon to serve the site.

This effectively removes  any benefit of running multiple sites under one hood, if each site needs a UWSGI instance running.

Alternative ideas of systems:

https://github.com/iivvoo/django_layers

https://github.com/shestera/django-multisite

I don't know what route to be taking with this.

答:
Django will help you in that manner. You will redirect multiple sites to your Django instance, and the Django instance will use the API that can help you with saving through economies of scale, with VM costs/ API subscription costs, etc.

In this context, I am assuming that you are not using limited free tiers, or you do not have complicated SLAs with your service providers (like the fair use of resources). Before redirecting all your sites into one Django instance (which will work on one server, and will use one API), please check your agreements that you do not have penalties or upper thresholds.

One other aspect you need to consider is the user profiles and separate workloads of your sites. If overall workload will be too much, you will eventually go for a load balancer which will increase your number of instances. On the other hand, since it will be the same implementation working behind, development of the Software will be easier.

For a precise answer, you need to investigate metrics, check your available resources and focus on the business case (the drive behind your optimization needs). Unfortunately, this is more art than science.

Umut.

ContentLicense: CC BY-SA 3.0


问:
Extended usage of an exception
I'm in the process of building a routing system for learning purposes and have encountered an issue which I think is a bit in the grey area of best practices. Can you guys help me decide if this is wrong, okay or could be done in a different way.

When resolving an incoming request and a route resource has been matched the HTTP request method is validated against the route's supported HTTP methods to ensure its capable of handling such requests. If this is not the case an exception of type UnsupportedMethodException is thrown.

The HTTP status code documentation states that if a request method is denied/unsupported an Allow header containing a list of supported methods should be returned in the response.

10.4.6 405 Method Not Allowed

The method specified in the Request-Line is not allowed for the
  resource identified by the Request-URI. The response MUST include an
  Allow header containing a list of valid methods for the requested
  resource.

So to accommodate this I thought of extending the usage of the otherwise generic exception to require a sequential array of supported methods in its constructor.

```<code>class UnsupportedMethodException extends \RuntimeException {

    /**
     * A sequential array of supported HTTP request methods.
     *
     * @var array $supported
     */
    private $supported = [];

    /**
     * @param string     $message           The typical exception message.
     * @param array      $supportedMethods  A sequential array of HTTP request methods the matched route supports.
     * @param \Exception $previous          Any previous exceptions
     */
    public function __construct($message, array $supportedMethods, \Exception $previous = null)
    {
        parent::__construct($message, null, $previous);
        $this->supported = $supportedMethods;
    }

    /**
     * @return array
     */
    public function getSupportedMethods()
    {
        return $this->supported;
    }

}
</code>```

With the usage of type hinting the catch block provides I now have a solid method for fetching the supported methods and generating a proper HTTP response.

So my question is, do you guys think this is a good practice? Something tells me the exception class shouldn't contain such logic, but I have no proof/reference to back this up.

答:
Storing information related to the exceptional circumstance in the exception is definitely a good thing, as it can allow a handler to fix & retry or fail gracefully. It's not logic but data, so you don't have to worry about the exception class being too complex. If the exception took a route and extracted the supported methods, that would be getting too coupled, but taking the methods as an argument is just dumb enough.

Other questions, "How to write a good exception message" and "Why do many exception messages not contain useful details?", are closely related but focused on the message, rather than other exception fields.

Title: Extended usage of an exception


答:
I will attempt to address the three questions you asked at the very bottom.

1) Is there a better way to do this?

The better way to do this is to build a generic library or language which is capable of efficiently managing the creation and updating of immutable objects. I will try to address this in the answer to the 3rd question.

2) If there isn't, is it even worth the effort/cost to make objects immutable?

This is a hard question, but I would say that unless PHP has a robust library for this (which it may or may not, I am not familiar with PHP) purpose the answer is probably no. First, it would be inefficient and error prone if you just clone your objects. Secondly, if you are working in a language like PHP where the entire language and community is built around and used to mutability, it can be confusing for other programmers when a library is immutable.

3) If we could design a new language with immutability in mind, what would this look like?

Fortunately you wouldn't have to design a new language to know what it would look like because it's already been done. You could look at existing ones like Haskell or Clojure. These languages were designed with immutability in mind. Almost everything in those languages is immutable: Lists, Vectors, Maps, Sets, Records etc and they are implemented in a way which makes updates much faster than copying the entire object.

Clojure for instances uses Hash array mapped trie http://en.wikipedia.org/wiki/Hash_array_mapped_trie to implement its Vectors, Maps, Sets and Records which gives O(log(n)) insert/update speed and the underlying implementation itself is never visible to the end user (in fact small Vectors or Maps may use a completely different representation).

When almost everything in your language is immutable some of the problems you were facing go away. For instance, if the Response holds a Bag there is not such a big problem exposing the Bag because the Bag is immutable too. Also, when you create a new Response where the status code changed, but the headers were the same, you don't need to copy the headers Bag, you can just create a pointer to it because that Bag and everything contained in it is immutable! Allowing the compiler, runtime and libraries to make assumptions about the immutability of other things in the language is part of what allows languages designed with immutable data structures to be more efficient and more usable than trying add immutability as an afterthought to a language which started off mutable.

This is actually how the popular Ring framework https://github.com/ring-clojure/ring works in Clojure. A response is just a Map:

{:status 200
  :headers {"Content-Type" "text/html"}
  :body "Hello World"}
```

<p>As you can see, the response is a Map, and the headers are just another Map. What it would look like to produce a new Map with Content-Type="text/xml" would be:</p>

<pre class="lang-clojure prettyprint-override"><code>(assoc-in response [:headers "Content-Type"] "text/xml")
</code>```

The assoc-in function is from the standard library which does the work from the "ridiculous" example of knowing how to get at the nested Map and rebuild the data structures it was a part of so that the programmer doesn't need to make the explicit calls to your withHeader and withHeaders functions. There are also numerous other techniques and functions which make common operations easier. For instance if we had more than one update we wanted to make to the response we might use the -> or thread-first macro.

(-> response
   (assoc-in [:headers "Content-Type"] "text/xml")
   (assoc-in [:headers "Content-Disposition"] "attachment; filename=\"data.xml\""))
```

There are also many methods in the standard libraries for these languages which could apply a function to a value in a nested structure, merge two immutable Maps together, compare Maps for equality, etc.

Title: How to make complex objects immutable?

Body:
The example I'm about to give is for the PHP language, but I think this scenario applies to most languages.

Let's say I have an object called Response and I want it to be immutable. Every method should return a new instance rather than modifying the state of the current instance. Responses have headers, so I create a method called withHeader($name, $value) that makes a copy of my response object, sets the header, and returns the new instance. It's pretty simple to use:

```<code>$newResponse = $oldResponse->withHeader('Content-Type', 'application/json');
</code>```

Then I decide the headers actually have quite a few properties and I'd rather separate this out into a separate object called a HeaderBag. Now I want my Response to hold a HeaderBag but I still want it to be immutable.

I can't make the the bag a public property, like $response->headers because even if the $headers object is immutable, the property can still be reassigned. So maybe I add something like $response->getHeaders() which returns my HeaderBag object, but now how do I manipulate it?

If I move my withHeader method into this sub-object, then I wind up with something like $response->getHeaders()->withHeader(...). The withHeader method would presumably return a new HeaderBag since it too is immutable, but then what? I guess I'd end up with something like this:

```<code>$newResponse = $oldResponse->withHeaders($oldResponse->getHeaders()->withHeader($name, $value));
</code>```

Which seems a bit ridiculous; to add a single value we have to clone two objects and write this abomination of a line. Sure, we can write a helper method on the Response object to shorten it, but the whole idea was to move all the header-related methods into the HeaderBag class.

Questions:

Is there a better way to do this?

If there isn't, is it even worth the effort/cost to make objects immutable?

If we could design a new language with immutability in mind, what would this look like?

Body:
I will attempt to address the three questions you asked at the very bottom.

1) Is there a better way to do this?

The better way to do this is to build a generic library or language which is capable of efficiently managing the creation and updating of immutable objects. I will try to address this in the answer to the 3rd question.

2) If there isn't, is it even worth the effort/cost to make objects immutable?

This is a hard question, but I would say that unless PHP has a robust library for this (which it may or may not, I am not familiar with PHP) purpose the answer is probably no. First, it would be inefficient and error prone if you just clone your objects. Secondly, if you are working in a language like PHP where the entire language and community is built around and used to mutability, it can be confusing for other programmers when a library is immutable.

3) If we could design a new language with immutability in mind, what would this look like?

Fortunately you wouldn't have to design a new language to know what it would look like because it's already been done. You could look at existing ones like Haskell or Clojure. These languages were designed with immutability in mind. Almost everything in those languages is immutable: Lists, Vectors, Maps, Sets, Records etc and they are implemented in a way which makes updates much faster than copying the entire object.

Clojure for instances uses Hash array mapped trie http://en.wikipedia.org/wiki/Hash_array_mapped_trie to implement its Vectors, Maps, Sets and Records which gives O(log(n)) insert/update speed and the underlying implementation itself is never visible to the end user (in fact small Vectors or Maps may use a completely different representation).

When almost everything in your language is immutable some of the problems you were facing go away. For instance, if the Response holds a Bag there is not such a big problem exposing the Bag because the Bag is immutable too. Also, when you create a new Response where the status code changed, but the headers were the same, you don't need to copy the headers Bag, you can just create a pointer to it because that Bag and everything contained in it is immutable! Allowing the compiler, runtime and libraries to make assumptions about the immutability of other things in the language is part of what allows languages designed with immutable data structures to be more efficient and more usable than trying add immutability as an afterthought to a language which started off mutable.

This is actually how the popular Ring framework https://github.com/ring-clojure/ring works in Clojure. A response is just a Map:

{:status 200
  :headers {"Content-Type" "text/html"}
  :body "Hello World"}

As you can see, the response is a Map, and the headers are just another Map. What it would look like to produce a new Map with Content-Type="text/xml" would be:

(assoc-in response [:headers "Content-Type"] "text/xml")

The assoc-in function is from the standard library which does the work from the "ridiculous" example of knowing how to get at the nested Map and rebuild the data structures it was a part of so that the programmer doesn't need to make the explicit calls to your withHeader and withHeaders functions. There are also numerous other techniques and functions which make common operations easier. For instance if we had more than one update we wanted to make to the response we might use the -> or thread-first macro.

(-> response
   (assoc-in [:headers "Content-Type"] "text/xml")
   (assoc-in [:headers "Content-Disposition"] "attachment; filename=\"data.xml\""))

There are also many methods in the standard libraries for these languages which could apply a function to a value in a nested structure, merge two immutable Maps together, compare Maps for equality, etc.


问:
How to not let anyone inspect elements of a webpage?
I was thinking to make some jQuery functions that will use ajax to control mysql. The whole idea is to make separate files of PHP (e.g query.php, addRow.php, update.php and delete.php) provide data to them via the GET variables like query.php?sql=SELECT * FROM table and then control them with jQuery AJAX functions that I'll make later. Expected code:

```<code>$(element).click(function (e) {
    mysql.query("DELETE row FROM table WHERE name = 'John Doe'");
});
</code>```

And then it'll send query through AJAX and the query will be performed.

So the problem is SECURITY . I mean anyone can just change javascript from browser's inspector or use console to control my databases. What can be done for this problem. Is there anyway to not let anyone change elements in the browser console. If not is there ANYWAY to overcome this security problem?

答:
As a 20+ years programmer i am surprised HTML/php programming is so weak in how a user can use inspect element to change a value e.g product id before submitting.

My solution is to use java script variables and only use HTML such as textboxes to inform the user of my intentions.

eg
declare variables in a global space i.e outside of a function.

Example below uses j query library.

It is a small example.

The demonstration is that changing the value of textbox c using inspect
element will not change the final result displayed in result textbox.

When saving the data to server save the javascript  values to the
server... not the html values.

```<code>             <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</code>```

```<code>      <script>
      var a = 0;
      var b = 0;
      var result= 0;
      </script>
</code>```

and i can use the values while informing the user in HTML textboxes

```<code>      <script>
       a = 5;
       $('#a').val(a);
       b = 3;
       $('#b').val(b);

       result=a+b;
       $('#result').val(result);

       alert(result);

       </script>
</code>```

Body:
As a 20+ years programmer i am surprised HTML/php programming is so weak in how a user can use inspect element to change a value e.g product id before submitting.

My solution is to use java script variables and only use HTML such as textboxes to inform the user of my intentions.

eg
declare variables in a global space i.e outside of a function.

Example below uses j query library.

It is a small example.

The demonstration is that changing the value of textbox c using inspect
element will not change the final result displayed in result textbox.

When saving the data to server save the javascript  values to the
server... not the html values.

             <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

      <script>
      var a = 0;
      var b = 0;
      var result= 0;
      </script>

and i can use the values while informing the user in HTML textboxes

      <script>
       a = 5;
       $('#a').val(a);
       b = 3;
       $('#b').val(b);

       result=a+b;
       $('#result').val(result);

       alert(result);

       </script>


答:
Disclaimer: I wrote this as I was coming up with it

I think ideally we would have read-only properties, like in C#. Then we could expose $response->headers without worrying it'll be re-assigned. Then what we need is a way for HeaderBag::withHeader to return a (new) Response object, but only when we've accessed it via the response object -- not if we're working with it on its own. i.e. this would return a new Response object,

$newResponse = $oldResponse->headers->withHeader('Content-Type', 'text/xml')
```

<p>but this would return a <code>HeaderBag</code> object:</p>

<pre class="lang-php prettyprint-override"><code>$newHeaders = $standaloneHeaders->withHeader('Content-Type', 'text/xml');
</code>```

This of course would be super confusing if the method returned different objects depending on how it was called, so we need fix up the syntax a bit to make it more clear...

What if we had a new "with" operator (ω) that behaves a bit like assignment (=) except it returns a new instance of the object on the left with the new property set. For example, instead of

```<code>obj.x = 5
</code>```

You would write

```<code>obj2 = obj ω x = 5
</code>```

Better yet, you could manipulate several properties at once while only making one copy of the object:

obj2 = obj ω x = 5, y = 6
```

<p>Then going back to our example above we could write:</p>

<pre class="lang-php prettyprint-override"><code>$newResponse = $oldResponse ω headers = $oldResponse->headers->withHeader('Content-Type', 'text/xml');
</code>```

But that's not much better. Maybe we can add another symbol to represent the object being manipulated? For example, if you wanted to increment a value, you could either write:

```<code>obj2 = obj ω x = obj.x + 1
</code>```

Or

```<code>obj2 = obj ω x = τ + 1
</code>```

Where τ refers to the property just after the ω. Now we can write:

$newResponse = $oldResponse ω headers = τ->withHeader('Content-Type', 'text/xml');
```

<p>Getting better, but I think we can still improve it. Let's pretend our <code>HeaderBag</code> implements an array interface, such that we can get a header via <code>$response->headers['Content-Type']</code>.</p>

<pre class="lang-php prettyprint-override"><code>$newResponse = $oldResponse ω headers = τ ω τ['Content-Type'] = 'text/xml';
</code>```

Now let's see what it looks like to set a whole bunch of properties all at once:

$newResponse = $oldResponse
    ω headers = τ ω τ['Content-Type'] = 'text/xml',
                    τ['Content-Disposition'] = 'attachment; filename="data.xml"',
      status = 200,
      body = '<root>text</root>'
```

<p>I think I might need some parentheses in there, or maybe I should remove the <code>,</code> operator and require more <code>ω</code>s, I'm not sure, but that's the general idea.</p>

<p>We might want to replace <code>ω</code> with something a bit easier to type, perhaps <code>w/</code>? For <code>τ</code> I was thinking "this" but that has a different meaning inside of classes.</p>

<p>This needs a bit more thought, but I welcome your feedback. WuHoUnited gave some examples of manipulating nested objects in Clojure, but I'm not sure if it's as flexible as my solution which lets you call any method at any point in the chain.</p>

<hr>

<p>With this semi-ideal solution in mind, we can try converting it back into syntactically valid PHP:</p>

<pre class="lang-php prettyprint-override"><code>$newResponse = $oldResponse->withProp(['headers' => function($headers) {
    return $headers->withKey(['Content-Type' => 'application/json']);
]);
</code>```

Something like that. Implementation would look like:

<?php
trait WithTrait {

    public function withProp($data) {
        $new = clone $this;

        foreach($data as $prop=>$cb) {
            $new->{$prop} = $cb($this->{$prop});
        }

        return $new;
    }

    public function withKey($data) {
        $new = clone $this;

        foreach($data as $key=>$cb) {
            $new[$key] = $cb($this[$key]);
        }

        return $new;
    }
}
```

I think this could work, but I don't think I want to go down this road when Mike's solution is so much simpler.

Title: How to make complex objects immutable?

Body:
Disclaimer: I wrote this as I was coming up with it

I think ideally we would have read-only properties, like in C#. Then we could expose $response->headers without worrying it'll be re-assigned. Then what we need is a way for HeaderBag::withHeader to return a (new) Response object, but only when we've accessed it via the response object -- not if we're working with it on its own. i.e. this would return a new Response object,

$newResponse = $oldResponse->headers->withHeader('Content-Type', 'text/xml')

but this would return a HeaderBag object:

$newHeaders = $standaloneHeaders->withHeader('Content-Type', 'text/xml');

This of course would be super confusing if the method returned different objects depending on how it was called, so we need fix up the syntax a bit to make it more clear...

What if we had a new "with" operator (ω) that behaves a bit like assignment (=) except it returns a new instance of the object on the left with the new property set. For example, instead of

obj.x = 5

You would write

obj2 = obj ω x = 5

Better yet, you could manipulate several properties at once while only making one copy of the object:

obj2 = obj ω x = 5, y = 6

Then going back to our example above we could write:

$newResponse = $oldResponse ω headers = $oldResponse->headers->withHeader('Content-Type', 'text/xml');

But that's not much better. Maybe we can add another symbol to represent the object being manipulated? For example, if you wanted to increment a value, you could either write:

obj2 = obj ω x = obj.x + 1

Or

obj2 = obj ω x = τ + 1

Where τ refers to the property just after the ω. Now we can write:

$newResponse = $oldResponse ω headers = τ->withHeader('Content-Type', 'text/xml');

Getting better, but I think we can still improve it. Let's pretend our HeaderBag implements an array interface, such that we can get a header via $response->headers['Content-Type'].

$newResponse = $oldResponse ω headers = τ ω τ['Content-Type'] = 'text/xml';

Now let's see what it looks like to set a whole bunch of properties all at once:

$newResponse = $oldResponse
    ω headers = τ ω τ['Content-Type'] = 'text/xml',
                    τ['Content-Disposition'] = 'attachment; filename="data.xml"',
      status = 200,
      body = '<root>text</root>'

I think I might need some parentheses in there, or maybe I should remove the , operator and require more ωs, I'm not sure, but that's the general idea.

We might want to replace ω with something a bit easier to type, perhaps w/? For τ I was thinking "this" but that has a different meaning inside of classes.

This needs a bit more thought, but I welcome your feedback. WuHoUnited gave some examples of manipulating nested objects in Clojure, but I'm not sure if it's as flexible as my solution which lets you call any method at any point in the chain.

With this semi-ideal solution in mind, we can try converting it back into syntactically valid PHP:

$newResponse = $oldResponse->withProp(['headers' => function($headers) {
    return $headers->withKey(['Content-Type' => 'application/json']);
]);

Something like that. Implementation would look like:

<?php
trait WithTrait {

    public function withProp($data) {
        $new = clone $this;

        foreach($data as $prop=>$cb) {
            $new->{$prop} = $cb($this->{$prop});
        }

        return $new;
    }

    public function withKey($data) {
        $new = clone $this;

        foreach($data as $key=>$cb) {
            $new[$key] = $cb($this[$key]);
        }

        return $new;
    }
}

I think this could work, but I don't think I want to go down this road when Mike's solution is so much simpler.


问:
How to test android apps that depend on telecom provider connection?
I am planning to write an app that needs phone number and contact list. Is there any way that I can test my app without buying a telecom provider connection for my android phone. Without a sim the phone doesn't have a phone number and I am wondering if mock phone number is only way to get pass this.</p>

答: ADT emulator might help you a lot, with GSM carrier simulation. It also support two phone simulation for calls, etc. which is enough for many test cases. </p>


问:
Do I have to be a hardcore programmmer to succeed?
I know someone who is a very good programmer with a good software development job and income. However, he spends practically all his time on his computer. Whether it is work or his own projects he is always programming or learning about new programming techniques etc.

I am wondering, do I have to be like that to be a good programmer? I enjoy programming a lot and I enjoy learning about new stuff, but I simply don't spend as much time doing that stuff as he does. Does this just mean my "experience rate" will be slower, or do I simply have to be on top of all new information that comes out and be constantly improving and practicing my skills, or I won't be good enough as a programmer?

答:
Depends upon your metric.

I've been a professional programmer for 25 years. The people I most like to work with know what technologies to apply when. You can be a very effective coder without being on the bleeding edge if you have the maturing and common sense to know when a solution is appropriate.

I have come across many coders who blindly apply the latest technologies without taking into account:

how they are going to scale when the program gets 10x (or 100x) bigger

how they are going to scale when you have millions of rows in a database

how appropriate they will be when other team members with less experience
have to use them

how quickly they can be deployed

IMHO, maturity only comes with experience (often, not even then). Hours tinkering at home gives you experience tinkering. It does not necessarily make you a more effective coder at work.


答:
It depends on what you mean by "succeed".

If you mean succeed in the classical sense, as in to make as much money as possible with absolutely no regard to personal health, relationships, etc. then it will be much harder if you are not programming all the time. People who get jobs at Google, VMware, etc. are either geniuses or work 60-80 hour weeks to make the money that they do (generally, this is not a broad paintbrush here).

However, I do not view success that way. To me, working all the time and forgetting about health, relationships, etc. is quite easy to do. I've met plenty of people who make way more money at my age who also don't have any real friends or hobbies. They are part of a "get rich or die trying" diatribe which seems to me doesn't leave much for happiness. I've seen more unhappy rich people than happy ones. To me, that is not success. What is very difficult to do is to have a balance where you can leave work and pursue healthy, creative endeavors and foster a balanced life where work is only a part of it (albeit a significant part).

You get to define what success means to you. Me, personally, I work to live, not live to work. I like programming and learning, but I also love my hobbies, exercising, and dating. I have recently gotten into photography as a hobby, and I love it. I also believe that a good programmer is a creative programmer, and I believe that my new hobby will help me at work as well, to think outside the box.

Keep in mind that the way to truly make lots of money and "succeed" is to get into management and lead lots of people. If you don't take the time to develop the social skills necessary for this, a programmer will be a programmer forever. Programmers have a glass ceiling once they hit 40 or so, but for management, the sky is the limit.

Title: Do I have to be a hardcore programmmer to succeed?

Body:
I know someone who is a very good programmer with a good software development job and income. However, he spends practically all his time on his computer. Whether it is work or his own projects he is always programming or learning about new programming techniques etc.

I am wondering, do I have to be like that to be a good programmer? I enjoy programming a lot and I enjoy learning about new stuff, but I simply don't spend as much time doing that stuff as he does. Does this just mean my "experience rate" will be slower, or do I simply have to be on top of all new information that comes out and be constantly improving and practicing my skills, or I won't be good enough as a programmer?


问:
Design ideas - validation based on conditions outside of the domain
I am facing a very interesting problem here, and I'd like to see some design ideas from domain driven design perspective.

To make it easier to express what I need I have following hypothetical situation. I have a bounded-context named Customer, which is used to handle create new customer, update customer, searching customer and so on. I have a customer class look like

```<code>public class Customer
{
    public int Id { get; set ; }
    public int SocialInsuranceNumber { get; set ; }

    public bool IsValid()
    {
        // my logic to validate social insurance number
    }
}
</code>```

So I have a straightforward logic in my entity to validate the data. The Canadian Social Insurance Number validation rule indicates all values begins with 0 should not be used, but Canadian government might use it for some reason. So there are possible 2 validation rules here now.

The business has the requirement of one single application - for majority of the situations when user enters a social insurance number we have to make sure the value cannot start with 0 and the value must be a valid SIN, but in some unique situation we must allow a valid SIN starting with 0.

My domain service code looks like

```<code>public class CustomerService
{
    public void AddCustomer(Customer customer)
    {
        if (customer.IsValid())
        {
            // save to database
        }
    }
}
</code>```

If I add a boolean parameter to Customer class's IsValid() function to make to look like IsValid(bool allowLeadingZero), I could make the code work. But I think it looks ugly.

From design perspective how would you suggest a more elegant way to deal with such requirement?

答:
If I were you I would make SocialInsuranceNumber a Value Object with validation in its constructor. However, since the logic for validation is complex you might prefer to delegate the validation logic into a Domain Factory instead.

The factory will have a validation strategy injected into it depending on the type of the social security number you are validating.

So SocialInsuranceNumber's constructor will validate for NULL, empty, min length, illegal characters, ...etc, but SocialInsuranceNumberFactory will validate whether the pattern used in valid in case it was Canadian or not using a CanadianSocialInsuranceNumberValidator or DefaultSocialInsuranceNumberValidator.


答:
Being a great software engineer is not always about the more technologies you know, the better you are. It is essential to know basics that apply across technologies, e.g. patterns, testing, automation, requirements gathering, etc... It is important to know HOW to figure out what you need to use and you also need to know when to step back and ask for help. (You do not need to know everything)

A great software engineer most companies want to keep are solid in their understanding of practices and can scale out their talents to not just produce great software in isolation but also to influence others in the right way. Great engineers need to know how to communicate the right way (with peers or high management) and how to tap into others talents and how to improve others around you. These things are a lot harder to learn and require a completely different mindset than learning a new language or technology but these are things that you learn on the job by changing your behaviors and not something you have to go home and study from books after work.


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: That because you are a programmer, you know how to fix the copier.</p>

ContentLicense: CC BY-SA 2.5


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

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

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

答:
Often this happens because you haven't defined the problem properly and accurately. Perhaps you're trying to solve a preconceived solution instead of the actual problem itself.

The problem is only what you observe, not what you imagine.

"My bloody car won't start" is a problem. "The battery is flat." is a preconceived solution to the car-starting problem. Even testing the battery doesn't prove it is the only cause of the problem. Unless you have actually recharged or replaced the battery and successfully started the car then you have no proof that the battery is the cause of the problem problem.

Simplify and keep simplifying. Break it down into small parts. If you can't solve those parts, smash them. You'll feel better. Then break it down into different small parts. Each one of those parts must be observable phenomenon.


答:
In your comment to Lawrence, you elaborated "Money is not my goal here. I want to be a successful programmer so that I can do well at my job and provide for a family some day, but not so much that I become dead to the world and my computer is my life."

Then yes, you can certainly achieve that as a programmer without unbalancing your life. I would say it is easier to achieve what you want that way, in any case. There are certainly many unbalanced programmers and unbalanced programming work environments, but you don't need (or, probably, want) to compete with those programmers or suffer with those workplaces.

What you do need, is to develop your general understanding of computer engineering, enough skills to do some useful things fairly well, and then to find a relatively sane and stable workplace. If you like working with computers and find programming makes sense to you and is relatively easy to figure out, then probably you're pretty well-suited to becoming a good programmer.


答:
Edited to be more answer-like:

No, you don't need to spend all your time on a computer to be a good developer. It's all very well and good to be on top of every new technology that comes out, but in my experience that doesn't always lead to the knowledge of how best to apply those technologies to real business processes. Sometimes, your time is better spent understanding how to get the greatest gains from the mature technologies you already use, rather than trying to integrate new technologies that no-one else has experience with.

Another thing to keep in mind is that as a programmer, you do not write code for the sake of writing code. Depending on your definition of 'successful', it may be more worthwhile spending time understanding the business processes behind the software you write, and that understanding generally isn't gained on a computer.

No-one is saying that spending all your time on a computer won't make you a better programmer, but spending some time in the real world, understanding how software is used, can make you a better software engineer.

Also, if (when?) you become a lead developer due to your knowledge of how stuff works, you generally are given more flexibility with pushing the technological boundaries, and implementing technologies you may not as a general programmer.


问:
How do you respond to a request for 'emergency contact information' for when you are on vacation?
I want to go on vacation and not think about work at all but they want me to provide them a contact number in the event of an emergency (server goes down, web service malfunctions, etc). I am afraid that it will be abused (they will contact me before trying everything for example) but I also think that if I am on vacation I should not be bothered even if there is an outage. Does anyone have experience with situations like this? What's the tactful approach? Any creative solutions?</p>

答:
'Emergency contact information'

Type 1 response: in each case, the contacts you are giving are well-trained to handle a particular type of emergency situation. An emergency response team should consist of various professionals.

Give the building hazmat emergency contact information.

Or, give your lawyer's contact information, in case you need to obtain a bail.

Train a deputy officer. You should pay at least 40% of your own salary to that officer.

Type 2 response: delegate emergency power to your boss.

A robust server should be able to solve every problem by restarting. To make it easier, someone should wire the restart to a panic button.

If it is too difficult to restart the server, try turn off and cycle the entire building's power.

Another panic button will automatically sign up a cloud service with your credit card info, and then migrate the server to the cloud. Bill your boss later.

Type 3 response: for mission-critical operations.

Insist on using Twitter for text-only communication.

Set up a secret code system, for example: hard disk down = 041

Meanwhile, bring a laptop with VPN and 3G worldwide roaming so that you can fix the problem remotely.

Hire a local driver who is also trained as a security guard.


问:
Big O Question about an algorithm with (n^2 + n) / 2 growth rate
I'm asking this question because I am confused about one aspect regarding big O notation.

I am using the book, Data Structures and Abstractions with Java by Frank Carrano. In the chapter on the "Efficiency of Algorithms" he shows the following algorithm:

```<code>int sum = 0, i = 1, j = 1
for (i = 1 to n) {
    for (j = 1 to i)
        sum = sum + 1
}
</code>```

He initially describes this algorithm as having a growth rate of (n2 + n)/2. Which looking at it seems intuitive.

However, it is then stated that (n2 + n)/2 behaves like n2 when n is large. In the same paragraph he states (n2 + n)/2 also behaves much like n2/2. He uses this to classify the above algorithm as O(n2).

I get that (n2 + n)/2  is similar to n2/2 because percentage wise, n makes little difference. What I do not get is why (n2 + n)/2 and n2 are similar, when n is large.

For example, if n = 1,000,000:

```<code>(n^2 + n) / 2 =  500000500000 (5.000005e+11)
(n^2) / 2     =  500000000000 (5e+11)
(n^2)         = 1000000000000 (1e+12)
</code>```

That last one is not similar at all. In fact, quite obviously, it's twice as much as the middle one. So how can Frank Carrano say they are similar? Also, how is the algorithm classified as O(n2). Looking at that inner loop I would say it was n2 + n/2

答:
When talking about complexity, you're only interested in the time factor changes based on the number of elements (n).

As such you can remove any constant factor (like the 2 here).

This leaves you with O(n^2 + n).

Now, for a reasonable large n the product, i.e. n * n, will be significantly bigger than just n, which is the reason you're allowed to skip that part as well, which leaves you indeed with a final complexity of O(n^2).

It is true, for small numbers there'll be a significant difference, but this becomes more marginally the bigger your n becomes.


答:
When calculating the Big-O complexity of an algorithm, the thing being shown is the factor that gives the largest contribution to the increase in execution time if the number of elements that you run the algorithm over increases.

If you have an algorithm with a complexity of (n^2 + n)/2 and you double the number of elements, then the constant 2 does not affect the increase in the execution time, the term n causes a doubling in the execution time and the term n^2 causes a four-fold increase in execution time.

As the n^2 term has the largest contribution, the Big-O complexity is O(n^2).

Title: Big O Question about an algorithm with (n^2 + n) / 2 growth rate

Body:
I'm asking this question because I am confused about one aspect regarding big O notation.

I am using the book, Data Structures and Abstractions with Java by Frank Carrano. In the chapter on the "Efficiency of Algorithms" he shows the following algorithm:

```<code>int sum = 0, i = 1, j = 1
for (i = 1 to n) {
    for (j = 1 to i)
        sum = sum + 1
}
</code>```

He initially describes this algorithm as having a growth rate of (n2 + n)/2. Which looking at it seems intuitive.

However, it is then stated that (n2 + n)/2 behaves like n2 when n is large. In the same paragraph he states (n2 + n)/2 also behaves much like n2/2. He uses this to classify the above algorithm as O(n2).

I get that (n2 + n)/2  is similar to n2/2 because percentage wise, n makes little difference. What I do not get is why (n2 + n)/2 and n2 are similar, when n is large.

For example, if n = 1,000,000:

```<code>(n^2 + n) / 2 =  500000500000 (5.000005e+11)
(n^2) / 2     =  500000000000 (5e+11)
(n^2)         = 1000000000000 (1e+12)
</code>```

That last one is not similar at all. In fact, quite obviously, it's twice as much as the middle one. So how can Frank Carrano say they are similar? Also, how is the algorithm classified as O(n2). Looking at that inner loop I would say it was n2 + n/2


答:
It just looks like you need to work out the big O notation a bit more.  How convenient this notation is, it is very misleading because of the use of an equal sign, which is not used here to denote the equality of functions.

As you know, this notation expresses an asymptotic comparisons of functions, and writing f = O(g) means that f(n) grows at most as fast as g(n) as n goes to infinity.  A simple way to translate this is to say that the function f/g is bounded.  But of course, we have to take care of the places where g is zero and we end up with the more robust definition that you can read almost everywhere.

This notations turns out to be very convenient for computing – this is why it is so widespread – but it should be handled with care as the equal sign we see there does not denote an equality of functions.  This is pretty much like saying that 2 = 5 mod 3 does not imply that 2 = 5 and if you are keen on algebra, you can actually understand the big O notation as an equality modulo something.

Now, to go back to your specific question, it is totally useless to compute a few numeric values and compare them: however large one million is, it does not account for asymptotic behaviour.  It would more useful to plot ratio of the functions f(n) = n(n-1)/2 and g(n) = n² – but in this special case we can readily see that f(n)/g(n) is smaller than 1/2 if n > 0 which implies that f = O(g).

To improve your understanding of the notation, you should

Work with a clean definition, not a fuzzy impression based on things being similar – as you just experienced it, such a fuzzy impression does not work well.

Take some time to work out examples in details. If you work out as little as five examples within a week, it will be enough to improve your confidence. This is an effort which is definitely worth.

Algebraic side note If A is the algebra of all functions Ν→Ν and C the subalgebra of bounded functions, given a function f the set of functions belonging to O(f) is a C-submodule of A, and computation rules on the big O notation just describe how A operates on these submodules. Thus, the equality we see is an equality of C-submodules of A, this is just another sort of modulus.


问:
What do I need for a database server for Mobile-Apps?
I'm struggling getting my head around writing a server for a mobile app. The app is quite simple and would manly rely on geographic data and some other basic stuff liker users etc. nothing special about that.

What I just can't find an answer to is what I should use when it comes to a Web-API for server/client communication and what relational database system I should use.

I'd just need somebody to draw me a picture about how a server looks like and what options there are (just a few) for the main parts of it. I am not an unexperienced programmer - just one who has never written a server for a mobile App.

答:
There are a lot of tutorial type articles on the web around node.js which was the new hotness for writing applications for the other new hotness of mobile development. In the ones I read they all seemed to want to use a NoSQL DB such as mongodb.

But the concept is the same - you write a server in whatever language you like, that exposes a networked interface to the clients that connect over the internet - so it makes sense to write your server as a web server that exposes a REST interface. The server then stores data in a database, whether its a relational one like MySQL or something new like MongoDB doesn't really matter.

So its very simple: client -> webserver -> DB.


答:
what I should use when it comes to a Web-API for server/client communication

Use a REST-style API over HTTP(S) (e.g. /customer/<key>, /product/<key)

Use application/json as the content format

Use a user/apikey or better OAuth2 authorization scheme

Don't fall for the WS*/XML variant with all their proclaimed advantages like security contexts or well structured documents. YAGNI

I found this guide useful.

what relational database system I should use

Depends on your specific use case, and your web framework. Typical options:

a. NoSQL like MongoDB, CouchDB - provide JSON APIs out of the box. If you don't need any server logic other than data persistence & query, maybe a good choice

b. SQL like MySQL, PostgreSQL - the internet workhorses. Only makes sense in combination with a webframework. My preference: Python-based Flask (somewhat hard to grow with) or Django (somewhat harder to get started, easy to grow with) - depending on your language of choice there are many more to choose from.

c. Commercial BaaS (backend as a service), e.g. Parse or many others

I'd just need somebody to draw me a picture about how a server looks like

I have ample and positive experience with the following stack:

App: Phonegap/Cordova as the cross-platform framework, requirejs and backbonejs to modularize apps

Server: Django with django-tastypie as the REST API, based on MySQL and in parts  MongoDB for file and document storage.

Asynchronous processing is handled by Celery over RabbitMQ.

In this case the server implements the data model as Python classes, which are mapped by Django's ORM to the DB backend (pluggable backends, so the actual DB is of litte concern). The models and/or additional modules contain the business logic, which is agnostic to whether it is used by a remote client or in server-side view code.

The REST API sits on top of these models, and is provided by several tastypie-based resources that in most cases map 1:1 to the models, in other cases they provide some intermediate processing logic such as when there are multiple models involved to satisfy a query.

Title: What do I need for a database server for Mobile-Apps?

Body:
I'm struggling getting my head around writing a server for a mobile app. The app is quite simple and would manly rely on geographic data and some other basic stuff liker users etc. nothing special about that.

What I just can't find an answer to is what I should use when it comes to a Web-API for server/client communication and what relational database system I should use.

I'd just need somebody to draw me a picture about how a server looks like and what options there are (just a few) for the main parts of it. I am not an unexperienced programmer - just one who has never written a server for a mobile App.


问:
Are companies in certain locations (big city vs small town, etc) more likely to offer telecommute contract programming work?
I'm interested in taking on more contract projects for programming and, although it'd be nice to find clients just in my area, I want to expand my search a bit to other areas where a company may allow me to telecommute. I'm wondering if anyone who has experience with this has noticed that whether a company would be more likely to be open to this based on if they are in a bigger city vs a smaller town.

I would think that companies in smaller areas may have trouble finding programmers for some things and therefore would be more willing to outsource but maybe I am wrong. Any info is appreciated, I'm just trying to get an idea as to how to concentrate my efforts with networking with people form different areas, etc.

答:
I've done offsite programming contracts for 3M, Adobe, Apple, Kinko's, Microsoft, Motorola, and lots of folks you've probably never heard of, including an Oscar-winning special-effects firm, and a couple of artists who got a grant from the French government.

In my experience, willingness to use telecommuting contractors has nothing to do with a company's size or location, and everything to do with corporate culture and the personalities of the decision-makers. Some companies and managers are so risk-averse they'd rather not have work done at all than let somebody do it offsite.

Most of my telecommute contracts have come from companies in or near a big city; that's probably because that's where most people who need programming are. But you never know - I've also done contracts for folks in small towns in Illinois and Oregon.


问:
Why was the AT&T assembly syntax designed this way?
The AT&T assembly syntax, often called the GAS syntax, keeps surprising me. For example, its parameter order:

```<code>mov $100,%eax /* Destination after source */
</code>```

This just seems so counter-intuitive! Nearly all programming languages (and the good old mathematical notation) go the other way around: destination before source, like this:

```<code>int a = 100;   /* Destination before source (C-style) */
a := 100       // Destination before source (Pascal-style)
mov eax,100    ;  Destination before source (Intel assembly syntax)
</code>```

There are other points, for example, sigils... The %-s before every register and the $ before every constant literal (except for those used as the fourth operand in the very strange-looking effective addressing syntax) mightily clutter up the code, when it would have been trivial to avoid them. What is, or was, their advantage?

答:
I do not know what the deal is with sigils, other than perhaps to scare the uninitiated and to annoy those wise enough to know that they could have very easily been missing.  Hopefully, another answerer will have more insight on this.  (As ratchet freak mentioned in the comments, it was probably done this way in order to simplify the parser, which perhaps made sense back in those days when computing resources were meager.)

Now, as far as operand order is concerned, there are arguments that can be made for it and against it, although the arguments against it win.

It can be argued that GAS syntax is slightly more consistent than, say, Intel syntax, because when thinking of "moving" stuff, something gets moved from one place to another. When reading the code out loud, it makes sense to say "move this value to that register", but it does not make sense to say "move this register from that value".

By contrast, other assembly languages (Zilog, etc.) call these instructions "ld", which stands for "load", where it makes sense to have destination before source, because something is being loaded with a value. This has the additional benefit of following the standard operand order of mathematics, but it can be argued that this is not necessary, because assembly language programming is not mathematics, and there is no need to pretend that it is. (Similar things should look similar, and different things should look different.)

Of course, the argument for GAS syntax is lost if you consider that "move" is the wrong choice of verb in the first place, because the source operand does not lose its contents as a result of the "mov" operation: the bits do not really get moved, they are copied.

And then things get complicated even more by the fact that the Intel x86 instruction set includes instructions such as "lea" (load effective address) which go with the "load" verb instead of the "move" verb, in which case the GAS operand order is just plain wrong from whichever way you look at it.

Bottom line: it is just a matter of convention, so whoever builds the CPU gets to pick their preferred convention, and then whoever writes an assembler which is not required to be compatible with preexisting assemblers may, if they so please, come up with their own convention.  The first GAS assembler was probably written for some architecture in which the convention was source-operand-first, and then in subsequent ports of the assembler to other architectures the authors decided that having to change the instruction set and the register set was enough of a burden already, so they probably thought that it would be cool to at least stick with the same operand order.


答:
Using an exception to be part of program-flow is an anti-pattern, they should not be used for things that you expect to happen - hence the name!

I'd say that practicality trumps such rules however, but here I'd question why you are throwing such an exception and simply not returning the 405 result code - if the method succeeded you wouldn't throw an exception to return a 200 code, so I don't see throwing this exception is best practice here.

But, if you are throwing this, then I would call a function in the returning handler that fetches the allowed methods, not pass the data back via the exception.

Title: Extended usage of an exception

Body:
I'm in the process of building a routing system for learning purposes and have encountered an issue which I think is a bit in the grey area of best practices. Can you guys help me decide if this is wrong, okay or could be done in a different way.

When resolving an incoming request and a route resource has been matched the HTTP request method is validated against the route's supported HTTP methods to ensure its capable of handling such requests. If this is not the case an exception of type UnsupportedMethodException is thrown.

The HTTP status code documentation states that if a request method is denied/unsupported an Allow header containing a list of supported methods should be returned in the response.

10.4.6 405 Method Not Allowed

The method specified in the Request-Line is not allowed for the
  resource identified by the Request-URI. The response MUST include an
  Allow header containing a list of valid methods for the requested
  resource.

So to accommodate this I thought of extending the usage of the otherwise generic exception to require a sequential array of supported methods in its constructor.

```<code>class UnsupportedMethodException extends \RuntimeException {

    /**
     * A sequential array of supported HTTP request methods.
     *
     * @var array $supported
     */
    private $supported = [];

    /**
     * @param string     $message           The typical exception message.
     * @param array      $supportedMethods  A sequential array of HTTP request methods the matched route supports.
     * @param \Exception $previous          Any previous exceptions
     */
    public function __construct($message, array $supportedMethods, \Exception $previous = null)
    {
        parent::__construct($message, null, $previous);
        $this->supported = $supportedMethods;
    }

    /**
     * @return array
     */
    public function getSupportedMethods()
    {
        return $this->supported;
    }

}
</code>```

With the usage of type hinting the catch block provides I now have a solid method for fetching the supported methods and generating a proper HTTP response.

So my question is, do you guys think this is a good practice? Something tells me the exception class shouldn't contain such logic, but I have no proof/reference to back this up.


问:
Run a c++ program under lots of different data maps
I want to run a c++ program to process a lot of data from different xml files and output results. I run the program once per file and potentially have around 50 different files.

The trouble is each xml file has different naming convention for the nodes, for example:

A.xml

```<code><entry>
    <id><![CDATA[9]]></id>
    <description><![CDATA[Dolce 27 Speed]]></description>
 </entry>
</code>```

B.xml

```<code><item>
    <uuiid><![CDATA[9]]></uuid>
    <content><![CDATA[Dolce 27 Speed]]></content>
 </item>
</code>```

What is the appropriate way to define these mappings, so when I run the program the software knows what data is in what tags, so I can store the id, description etc together no matter what the input tags are.

Ideas I have so far are:

A) Start the program with flags (in the real program there will be 10 mappings so could get messy), I.e ./main --id uuid --description content

B) Put them in a map and refer to that at start up (any suggestions on how to do the map would be great), I.e ./main --map example1

C) None of the above

答:
I would think that the best thing to do would be to employ a tool like Xalan or Xtrans or any other XSLT processor to implement an intermediate XML transformation step, so that your software needs to know only one naming convention.

The ability to perform such transformations is one of the major reasons why XML was invented in the first place.


答:
The simple answer is thats the order the binary instructions on most processors are laid out.

Back when men were men and sheep were scared assembly programers spent a lot of time looking at raw binary code (and sometimes trying to infer what instruction was hanging from the on/off lights in the control panel). It was just easier if the assembly code followed the instruction,target,source order of the machine code.

Title: Why was the AT&T assembly syntax designed this way?

Body:
The AT&T assembly syntax, often called the GAS syntax, keeps surprising me. For example, its parameter order:

```<code>mov $100,%eax /* Destination after source */
</code>```

This just seems so counter-intuitive! Nearly all programming languages (and the good old mathematical notation) go the other way around: destination before source, like this:

```<code>int a = 100;   /* Destination before source (C-style) */
a := 100       // Destination before source (Pascal-style)
mov eax,100    ;  Destination before source (Intel assembly syntax)
</code>```

There are other points, for example, sigils... The %-s before every register and the $ before every constant literal (except for those used as the fourth operand in the very strange-looking effective addressing syntax) mightily clutter up the code, when it would have been trivial to avoid them. What is, or was, their advantage?


答:
Constant factor

The point of big O notation is that you can choose an arbitrarily large constant factor so that O(function(n)) is always larger than C*function(n).  If algorithm A is a billion times slower than algorithm B, then they have same O complexity, as long as that difference doesn't grow when n grows arbitrarily large.

Let's assume a constant factor of 1000000 to illustrate the concept - it's a million times larger than neccessary, but that illustrates the point that they're considered irrelevant.

(n^2 + n) / 2 "fits inside" O(n^2) because for any n, no matter how large, (n^2+n)/2 < 1000000*n^2.

(n^2 + n) / 2 "doesn't fit" a smaller set, e.g. O(n) because for some values (n^2+n)/2 > 1000000*n.

The constant factors can be arbitrarily large - an algorithm with running time of n years has O(n) complexity which is "better" than an algorithm with a running time of n*log(n) microseconds.


问:
How to handle Django get-single-instance-in-view pattern?
A lot of my Django views start a little bit like this:

```<code>try:
    # here request.POST could also be request.GET or a captured URL parameter
    MyModel.objects.get(user = request.user, some_attr = int(request.POST['some_val']))
except KeyError:
    # error_view is a view that returns a pretty, formatted 500 response
    return error_view(request, message = 'Incomplete data was submitted (some_val was missing). No action was taken.', next = request.get_full_path())
except ValueError:
    return error_view(request, message = 'The data (some_val = %s) was not formatted correctly. No action was taken.' % request.POST['some_val'], next = request.get_full_path())
except MyModel.DoesNotExist:
    return error_view(request, message = 'The data you were looking for (some_val = %s) could not be found. It is possible you used an outdated form, or the data was just recently removed. No action was taken.' % request.POST['some_val'], next = request.get_full_path())
</code>```

I find myself repeating code very similar to this a lot (but with different POST/GET/url, filter arguments, data type, next url or messages), sometimes several for one view.

What is the best way to approach this?

Just keep repeating these 8 lines, the code is different enough to not violate DRY

Make a decorator which passes the instance to the view, or returns the error view. Changes the function signature (is that ok?) and not that easy to generalize.

Write a function to do this. In that case, should it...

... return either a response or an instance, return it if it's a response.

... return a (instance, response) tuple, oneo f which is None, retuning response if it's not None.

... raise a special type of exception (say VisibleException), and create a middleware to display it using error_view.

... something else?

All the methods work but which one do you recommend and why?

I came up with 3.3 just now and it actually makes sense to me - these situations are abnormal exit routes after all - but I don't think I've seen it used before (admittedly I don't know what to search for), so perhaps it has a problem. (The programmer using the app has to add a Middleware, that's one).

EDIT: I was just reminded that get_object_or_404 throws an exception that is kind of displayed to the user, so perhaps 3.3 is a logical extension.

答:
As you pointed out, often the specifics of what constitutes invalid request parameters is different enough for each view, and so including this type of code in each view is (I think) fine and not a DRY violation.  It also self-documents the view by having code at the beginning that clarifies what the view expects to receive, either in the URL, GET, or POST, and that's worth something.

However, since there are some situations where very specific patterns might benefit from refactoring, I would defer to the Django code itself for a good guideline on when a decorator (your option #2) or a function (option #3) might be the better option:

Django uses view decorators for patterns like login validation, permissions validation, etc.  Note that these are situations where the decorator doesn't need to pass results from its processing into the view itself.

Django provides functions (rather than decorators) to handle situations like get_object_or_404, get_list_or_404, etc. Note that in these situations, the view does need access to the results of the processing (namely, the instance).  Those functions are implemented similarly to your option #3.3 (although I think #3.1 would equally work).

To sum up, option #1 is usually fine and very useful for self-documenting code, but for very specific patterns, determine whether the view needs access to the results. If so, option #3 is probably better (otherwise, option #2).  If going with option #3, then 3.3 is the path Django takes, though 3.1 seems equally workable.

Side note:

You mentioned that you are currently returning a 500 response in these situations.  A 500 response indicates that the server experienced an error, which is not the case here, and so it's an incorrect response code to deliver.

Instead do one of the following:

If your view got a captured URL parameter that is incorrect, then either a 404 should be returned (since that URL doesn't exist), or the view should return a 301 or 302 redirect to a good URL.

If the view received GET or POST parameters that are incorrect, then a 400 Bad Request response should be returned.

ContentLicense: CC BY-SA 4.0


答:
If your exception did in fact contain any logic, I would take issue with it, but it does not, so I think it is fine.  What it contains is the range (the set, actually) of accepted values, which is not a bad idea.  (It might be unnecessary, because the range of accepted values is fixed and known in advance, but not bad at all.)

I think that it should also contain the name of the method that was not allowed, and possibly the URI that failed, since the "Method Not Allowed" response pertains to specific URIs. This information might not be useful for constructing the http response, but it should be useful for logging.

Title: Extended usage of an exception


问:
What problem does automated user interface testing solve?
We are currently investigating automated user interface testing (we currently do automated unit and integration testing).

We've looked at Selenium and Telerik and have settled on the latter as the tool of choice due to its much more flexible recorder - and we don't really want testers writing too much code.

However, I am trying to understand the overall benefit. What are peoples' views and what sort of things work well and what doesn't?

Our system is under constant development and we regularly release new versions of our (web based) platform.

So far the main benefit we can see is for regression testing, especially across multiple client deployments of our platform.

Really looking for other people's views.  We "think" it is the right thing to do but in an already busy schedule are looking for some additional insight.

答:
Automated User Interface Testing solves the ability to:

rapidly repeat testing of a large number of components

remember to test a large number of functions each time

compare runs and run times of test suites as the application grows

set up runs with hundreds of different inputs and variable conditions

enable people who did not write the test to run it and see any visual issues

allow end-users to see the application being used in a quick and easy way

distribute test UI runs to a network, remote server or service

start volume testing using parallel machines.

However, as others have noted:

Telerik...

the tool of choice due to its much more flexible recorder

is a red-flag for many of us.

Scripts recorded this way tend to not be a long-term solution because:

database/object ID tend to change from case to case

manually recorded scripts often rely on page layout tags that frequently change

common actions will need to be written over and over again instead of allowing re-use (see SitePrism & PageObject approach)

sometimes you need to use tools such as xpath to grab additional information based on current page information.  A simple recorded script won't do this.

developers and testers who write code will not be encouraged to use CSS classes, ID's and HTML5 data-attributes, which are practices that will lead to more robust, maintainable tests.

Telerik does have some advantages that should be considered though:

aimed at mobile clients

built-out tools to manage growth

handles Android, iOS and Windows Phone

An approach that can help bridge the gaps is to record the initial script using the tools page recorder but then change the script to use ID's, classes and data- attributes so that it will last over time.  This is an approach that I have actually used with the firefox selenium plugin.


答:
I think you misunderstand what the big O notation means.

When you see O(N^2) it basically means: when the problem gets 10 times as large, the time to solve it will be : 10^2 = 100 times as large.

Let's punch 1000 and 10000 in your equation:
1000:
(1000^2 + 1000)/2 = 500500
10000:
(10000^2 + 10000)/2 = 50005000

50005000/500500 = 99,91

So while the N got 10 times as big, the solutions got 100 times as big. Hence it behaves: O(N^2)


答:
The definition is that

```<code>f(n) = O(g(n))
</code>```

if there exists some constant C > 0 such that, for all n greater than some n_0, we have

```<code>|f(n)| <= C * |g(n)|
</code>```

This is clearly true for f(n) = n^2 and g(n) = 1/2 n^2, where the constant C should be 2. It's also easy to see that it's true for f(n) = n^2 and g(n) = 1/2 (n^2 + n).

Body:
The definition is that

f(n) = O(g(n))

if there exists some constant C > 0 such that, for all n greater than some n_0, we have

|f(n)| <= C * |g(n)|

This is clearly true for f(n) = n^2 and g(n) = 1/2 n^2, where the constant C should be 2. It's also easy to see that it's true for f(n) = n^2 and g(n) = 1/2 (n^2 + n).


问:
Clarification on Acquire/Release Semantics in multithreaded programming
In an attempt to fundamentally understand any concept, I try to understand the meaning of the words within the context it is being used.  Currently, I am trying to fundamentally understand the whole acquire/release semantics since I briefly touched upon this in school.

According to this article on MSDN, an operation has Acquire Semantics if other processors will see the effect of its change before the changes of any other operation.

On the otherhand, an operation has Release Semantics if other processors will see the effect of any preceding operation before seeing the effect caused by this operation.

I get it but the question is: what do the terms acquire and release relate to any of this?  If I were to explain this concept to say my daughter in grade 8, how do I translate these terms to their actual meanings?

答:
From Raymond Chen's blog:

The easy way to remember the difference between Acquire and Release is that Acquire is typically used when you are acquiring a resource (for example, taking a lock), whereas Release is typically used when you are releasing the resource.


答:
The reference is to some resource that fundamentally cannot be held by two agents simultaneously.

The classical example is a lock, mutex, semaphore or similar construct, and the canonical use case is making a money transfer. If you acquire an unsharable resource before subtracting and adding the amount from the two accounts, and don't release it until afterwards, and all operations on the accounts require that resource, then it's guaranteed that the amount of money in your system stays constant (as it should as per the principles of accounting). This is a good thing.

Since most solutions of the consistency problem come down to variations of such am unshareable resource, "Acquire and Release semantics" apparently are a shorthand of talking about them, without mentioning locs at all (I didn't know this before, but it sounds quite reasonable).

Title: Clarification on Acquire/Release Semantics in multithreaded programming

Body:
In an attempt to fundamentally understand any concept, I try to understand the meaning of the words within the context it is being used.  Currently, I am trying to fundamentally understand the whole acquire/release semantics since I briefly touched upon this in school.

According to this article on MSDN, an operation has Acquire Semantics if other processors will see the effect of its change before the changes of any other operation.

On the otherhand, an operation has Release Semantics if other processors will see the effect of any preceding operation before seeing the effect caused by this operation.

I get it but the question is: what do the terms acquire and release relate to any of this?  If I were to explain this concept to say my daughter in grade 8, how do I translate these terms to their actual meanings?


答:
Big-O is all about "how complicated" an algorithm is.  If you have two algorithms, and one takes n^2*k seconds to run, and the other takes n^2*j seconds to run, then you can argue about which one is better, and you might be able to make some interesting optimizations to try to affect k or j, but both of these algorithms are dead slow compare to an algorithm that takes n*m to run.  It doesn't matter how small you make the constants k or j, for a big enough input the n*m algorithm will always win, even if m is quite large.

So we call the first two algorithms O(n^2), and we call the second O(n).  It nicely divides the world up into classes of algorithms.  This is what big-O is all about.  It's like dividing vehicles up into cars and trucks and busses etc...  There's a lot of variation between cars, and you can spend all day arguing about whether a Prius is better than a Chevy Volt, but at the end of the day if you need to put 12 people into one, then this is a rather senseless argument.  :)


答:
They are trying to establish a correspondence between the terminology related to interlocked operations and the terminology related to acquiring/releasing a guarded resource, which is not an unreasonable thing to do, since the former are usually performed in order to accomplish the latter.

When performing an interlocked operation for the purpose of acquiring a resource, it does not really matter what happens before the acquisition, all that matters is that whatever operations are carried out on the resource once it has been acquired do in fact appear (from the point of view of other threads) to happen after the acquisition takes place, otherwise the resource might appear to be modified before it is locked.

When performing an interlocked operation for the purpose of releasing a resource, it does not really matter what happens after the release, all that matters is that the last operations carried out on the resource prior to its release do in fact appear (from the point of view of other threads) to happen before the release takes place, otherwise the resource might appear to be modified after it has been unlocked.


问:
How to maintain atomicity with a service like pattern
Imagine a route in an MVC web project which handles editing a user of your product. You can do things like change their name, their email, their group, their roles and so forth.
This data is put in a form and sent to the server.

Now imagine that we have a UserManager service to handle these actions. How do I make sure my route is atomic when the process could fail after an arbitrary number of actions?

```<code>userManager.SetEmail(userID, newEmail) // passes, no duplicate emails, email ok.
userManager.SetPassword(userID, newPassword) // passes, password validates.
userManager.SetGroup(userID, newGroupID) // FAIL!!! group id is invalid or something.
</code>```

The functions above would alter the email and password before failing on the group setting.

How can this be avoided?

答:
You need to use a memento.

At each step you look at the previous state and store it in a temporary object. If at any time there is a failure that requires rolling back, you simply look at each memento and restore the original state. This should normally be done as a LIFO stack to ensure changes are undone in reverse order.

Note the term "roll back" here: at a high level, this is exactly how ACID transactions work in modern relational databases. It is the same idea in a database as in your example.


答:
If the "userManager" exposes separate methods for setting the email, the password, etc. then it is explicitly exposing a model in which partial failure is possible and to be expected.

Sure, you can roll your own rollback mechanism as Snowman suggested, but I think it would be easier (more pragmatic perhaps?) to just add the ability to your "userManager" to accept an entire group of properties to be modified at once, (atomically,) so that it is the userManager's responsibility to make sure that all operations will succeed before applying them, or to make use of whatever transactioning mechanism might be made available to it by the underlying rdbms, the existence of which it is trying to abstract.

Title: How to maintain atomicity with a service like pattern

Body:
Imagine a route in an MVC web project which handles editing a user of your product. You can do things like change their name, their email, their group, their roles and so forth.
This data is put in a form and sent to the server.

Now imagine that we have a UserManager service to handle these actions. How do I make sure my route is atomic when the process could fail after an arbitrary number of actions?

```<code>userManager.SetEmail(userID, newEmail) // passes, no duplicate emails, email ok.
userManager.SetPassword(userID, newPassword) // passes, password validates.
userManager.SetGroup(userID, newGroupID) // FAIL!!! group id is invalid or something.
</code>```

The functions above would alter the email and password before failing on the group setting.

How can this be avoided?


问:
Why does an interface extend an interface instead of implementing it?
In Java suppose that I have interface A:

```<code>public interface A {
    // foo
}
</code>```

I also have interface B:

```<code>public interface B extends A {
    // foo + bar
}
</code>```

Why does interface B extend interface A and not implement interface A?

Wouldn't it make more sense if B implemented A?

Why did the language designers choose to use the word extend here?  Are there any subtleties that I am missing?

答:
An interface is a contract. It does not implement anything (properly-used default methods are a small exception).

What would it mean for one interface to "implement" another, anyway? It would need to have method bodies for some or all methods on the superinterface, making it a class.


答:
if n was a 1,000,000 then

```<code>(n^2 + n) / 2  =  500000500000  (5.00001E+11)
(n^2) / 2      =  500000000000  (5E+11)
(n^2)          = 1000000000000  (1E+12)
</code>```

1000000000000.00 what?

While the complexity gives us a way to predict a real-world cost (seconds or bytes depending on whether we are talking about time complexity or space complexity), it doesn't give us a number of seconds, or any other particular unit.

It gives us a degree of proportion.

If an algorithm has to do something n² times, then it will take n²×c for some value of c that is how long each iteration takes.

If an algorith has to do something n²÷2 times, then it will take n²×c for some value of c that is twice as long as each iteration takes.

Either way, the time taken is still proportional to n².

Now, these constant factors are not something we can just ignore; indeed you can have the case where an algorithm with O(n²) complexity does better than one with O(n) complexity, because if we are working on a small number of items then impact of the consant factors is greater and can overwhelm other concerns. (Indeed, even O(n!) is the same as O(1) for sufficiently low values of n).

But they are not what complexity tells us about.

In practice, there are a few different ways we can improve the performance of an algorithm:

Improve the efficiency of each iteration: O(n²) still runs in n²×c seconds, but c is smaller.

Reduce the number of cases seen: O(n²) still runs in n²×c seconds, but n is smaller.

Replace the algorithm with one that has the same results, but lower complexity: E.g. if we could repalce something O(n²) to something O(n log n) and hence changed from n²×c₀ seconds  to (n log n)×c₁ seconds.

Or to look at it another way, we've got f(n)×c seconds being taken and you can improve performance by reducing c, reducing n or reducing what f returns for a given n.

The first we can do by some micro-opts inside a loop, or using better hardware. It will always give an improvement.

The second we can do by perhaps identifying a case where we can short-circuit out of the algorithm before everything is examined, or filter out some data that won't be signficant. It won't give an improvement if the cost of doing this outweighs the gain, but it will generally be a bigger improvement than the first case, especially with a large n.

The third we can do by using a different algorithm entirely. A classic example would be replacing a bubble sort with a quicksort. With low numbers of elements we may have made things worse (if c₁ is greater than c₀), but it generally allows for the biggest gains, especially with very large n.

In practical use, complexity measures allow us to reason about the differences between algorithms precisely because they ignore the matter of how reducing n or c will help, to concentrate on examinging f()

Body:
if n was a 1,000,000 then

(n^2 + n) / 2  =  500000500000  (5.00001E+11)
(n^2) / 2      =  500000000000  (5E+11)
(n^2)          = 1000000000000  (1E+12)

1000000000000.00 what?

While the complexity gives us a way to predict a real-world cost (seconds or bytes depending on whether we are talking about time complexity or space complexity), it doesn't give us a number of seconds, or any other particular unit.

It gives us a degree of proportion.

If an algorithm has to do something n² times, then it will take n²×c for some value of c that is how long each iteration takes.

If an algorith has to do something n²÷2 times, then it will take n²×c for some value of c that is twice as long as each iteration takes.

Either way, the time taken is still proportional to n².

Now, these constant factors are not something we can just ignore; indeed you can have the case where an algorithm with O(n²) complexity does better than one with O(n) complexity, because if we are working on a small number of items then impact of the consant factors is greater and can overwhelm other concerns. (Indeed, even O(n!) is the same as O(1) for sufficiently low values of n).

But they are not what complexity tells us about.

In practice, there are a few different ways we can improve the performance of an algorithm:

Improve the efficiency of each iteration: O(n²) still runs in n²×c seconds, but c is smaller.

Reduce the number of cases seen: O(n²) still runs in n²×c seconds, but n is smaller.

Replace the algorithm with one that has the same results, but lower complexity: E.g. if we could repalce something O(n²) to something O(n log n) and hence changed from n²×c₀ seconds  to (n log n)×c₁ seconds.

Or to look at it another way, we've got f(n)×c seconds being taken and you can improve performance by reducing c, reducing n or reducing what f returns for a given n.

The first we can do by some micro-opts inside a loop, or using better hardware. It will always give an improvement.

The second we can do by perhaps identifying a case where we can short-circuit out of the algorithm before everything is examined, or filter out some data that won't be signficant. It won't give an improvement if the cost of doing this outweighs the gain, but it will generally be a bigger improvement than the first case, especially with a large n.

The third we can do by using a different algorithm entirely. A classic example would be replacing a bubble sort with a quicksort. With low numbers of elements we may have made things worse (if c₁ is greater than c₀), but it generally allows for the biggest gains, especially with very large n.

In practical use, complexity measures allow us to reason about the differences between algorithms precisely because they ignore the matter of how reducing n or c will help, to concentrate on examinging f()


答:
Interface implementation implies a finality that cannot be created by another interface - by their nature, an interface is meant to be incomplete.

The only reason you would extend an interface with another interface is if you need to change the defaults in the first one significantly, while still preserving the structure of the original.

As an example, if you have a basic vegetable-counting interface, you could implement it to count a specific type of vegetable.  But if you want to change the interface so that it can distinguish between different types of beans, you'd have to extend it first, then implement it for each type of bean.  Those final classes would then implement both Bean Counter and Vegetable Counter.

Title: Why does an interface extend an interface instead of implementing it?

Body:
In Java suppose that I have interface A:

```<code>public interface A {
    // foo
}
</code>```

I also have interface B:

```<code>public interface B extends A {
    // foo + bar
}
</code>```

Why does interface B extend interface A and not implement interface A?

Wouldn't it make more sense if B implemented A?

Why did the language designers choose to use the word extend here?  Are there any subtleties that I am missing?


答:
Think of extending as broadening the range of behavioural description and implementation as the concrete behaviour.

Say you have an interface quacking. This would be applicable to frogs as well as ducks. You could extend this general interface to swimming and flying which would then only be applicaple to the duck. The mechanism how a duck or frog swims is the implementation.

As @Snowman already mentioned: default methods are an exception to this concept.


问:
Understanding VB.NET variable scope
What's the difference between this code snippet:

```<code>Sub Test()
  Dim i as Integer = 0
  Dim q as String = ""
  While i<10
    q=String.Format("Some text {0}", i)
    Console.WriteLn(q)
    i=i+1
  End While
End Dub
</code>```

and this one:

```<code>Sub Test()
  Dim i as Integer = 0
  While i<10
    Dim q as String = String.Format("Some text {0}", i)
    Console.WriteLn(q)
    i=i+1
  End While
End Dub
</code>```

in terms of memory allocation and performance ...

答:
They are the same in terms of performance.  In VB.NET, a variable that is declared inside a loop keeps its value for the next itaration.

I would prefer the frist example as it is easier to read and probably has the intended behavior.

Here's the output of the two:

```<code>> Some text 0
> Some text 1
> Some text 2
> Some text 3
> Some text 4
> Some text 5
> Some text 6
> Some text 7
> Some text 8
> Some text 9
>
> Some text 0
> Some text 1
> Some text 2
> Some text 3
> Some text 4
> Some text 5
> Some text 6
> Some text 7
> Some text 8
> Some text 9
>
</code>```

Title: Understanding VB.NET variable scope

Body:
They are the same in terms of performance.  In VB.NET, a variable that is declared inside a loop keeps its value for the next itaration.

I would prefer the frist example as it is easier to read and probably has the intended behavior.

Here's the output of the two:

> Some text 0
> Some text 1
> Some text 2
> Some text 3
> Some text 4
> Some text 5
> Some text 6
> Some text 7
> Some text 8
> Some text 9
>
> Some text 0
> Some text 1
> Some text 2
> Some text 3
> Some text 4
> Some text 5
> Some text 6
> Some text 7
> Some text 8
> Some text 9
>


问:
When does it make sense to compile my own language to C code first?
When designing an own programming language, when does it make sense to write a converter that takes the source code and converts it to C or C++ code so that I can use an existing compiler like gcc to end up with machine code? Are there projects that use this approach?</p>

答:
Writing a compiler to produce machine code may not be much more difficult than writing one which produces C (in some cases it may be easier), but a compiler which produces machine code will only be able to produce runnable programs on the particular platform for which it was written; a compiler that produces C code, by contrast, may be able to produce program for any platform which uses a dialect of C which the generated code is designed to support.  Note that in many cases it may be possible to write C code which is completely portable and which will behave as desired without using any behaviors not guaranteed by the C standard, but code which relies upon platform-guaranteed behaviors may be able to run much faster on platforms which make those guarantees than code which does not.

For example, suppose a language supports a feature to yield a UInt32 from four consecutive bytes of an arbitrarily-aligned UInt8[], interpreted in big-endian fashion.  On some compilers, one could write the code as:

```<code>uint32_t dat = *(__packed uint32_t*)p;
return (dat >> 24) | (dat >> 8) | ((uint32_t)dat << 8) | ((uint32_t)dat << 24));
</code>```

and have the compiler generate a word-load operation followed by a reverse-bytes-in-word instruction.  Some compilers, however, would not support the __packed modifier and in its absence would generate code that wouldn't work.

Alternatively, one could write the code as:

```<code>return dat[3] | ((uint16_t)dat[2] << 8) | ((uint32_t)dat[1] << 16) | ((uint32_t)dat[0] << 24);
</code>```

such a code should work on any platform, even those where CHAR_BITS isn't 8 (assuming that each octet of source data ended up in a distinct array element), but such code may likely not run nearly as fast as the would the non-portable version on platforms supporting the former.

Note that portability often requires that code be extremely liberal with typecasts and similar constructs.  For example, code which wants to multiply two 32-bit unsigned integers and yield the lower 32 bits of the result must for portability be written as:

```<code>uint32_t result = 1u*x*y;
</code>```

Without that 1u, a compiler on a system where INT_BITS ranged from 33 to 64 could legitimately do anything it wanted if the product of x and y was larger than 2,147,483,647, and some compilers are prone to take advantage of such opportunities.

Body:
Writing a compiler to produce machine code may not be much more difficult than writing one which produces C (in some cases it may be easier), but a compiler which produces machine code will only be able to produce runnable programs on the particular platform for which it was written; a compiler that produces C code, by contrast, may be able to produce program for any platform which uses a dialect of C which the generated code is designed to support.  Note that in many cases it may be possible to write C code which is completely portable and which will behave as desired without using any behaviors not guaranteed by the C standard, but code which relies upon platform-guaranteed behaviors may be able to run much faster on platforms which make those guarantees than code which does not.

For example, suppose a language supports a feature to yield a UInt32 from four consecutive bytes of an arbitrarily-aligned UInt8[], interpreted in big-endian fashion.  On some compilers, one could write the code as:

uint32_t dat = *(__packed uint32_t*)p;
return (dat >> 24) | (dat >> 8) | ((uint32_t)dat << 8) | ((uint32_t)dat << 24));

and have the compiler generate a word-load operation followed by a reverse-bytes-in-word instruction.  Some compilers, however, would not support the __packed modifier and in its absence would generate code that wouldn't work.

Alternatively, one could write the code as:

return dat[3] | ((uint16_t)dat[2] << 8) | ((uint32_t)dat[1] << 16) | ((uint32_t)dat[0] << 24);

such a code should work on any platform, even those where CHAR_BITS isn't 8 (assuming that each octet of source data ended up in a distinct array element), but such code may likely not run nearly as fast as the would the non-portable version on platforms supporting the former.

Note that portability often requires that code be extremely liberal with typecasts and similar constructs.  For example, code which wants to multiply two 32-bit unsigned integers and yield the lower 32 bits of the result must for portability be written as:

uint32_t result = 1u*x*y;

Without that 1u, a compiler on a system where INT_BITS ranged from 33 to 64 could legitimately do anything it wanted if the product of x and y was larger than 2,147,483,647, and some compilers are prone to take advantage of such opportunities.