问:
Is there any reason to use C++ instead of C, Perl, Python, etc.?
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?

答:
I see way too many C programmers that hate C++. It took me quite some time (years) to slowly understand what is good and what is bad about it. I think the best way to phrase it is this:

Less code, no run-time overhead, more safety.

The less code we write, the better. This quickly becomes clear in all engineers that strive for excellence. You fix a bug in one place, not many - you express an algorithm once, and re-use it in many places, etc. Greeks even have a saying, traced back to the ancient Spartans: "to say something in less words, means that you are wise about it". And the fact of the matter, is that when used correctly, C++ allows you to express yourself in far less code than C, without costing runtime speed, while being more safe (i.e. catching more errors at compile-time) than C is.

Here's a simplified example from my renderer: When interpolating pixel values across a triangle's scanline. I have to start from an X coordinate x1, and reach an X coordinate x2 (from the left to the right side of a triangle). And across each step, across each pixel I pass over, I have to interpolate values.

When I interpolate the ambient light that reaches the pixel:

```<code>  typedef struct tagPixelDataAmbient {
      int x;
      float ambientLight;
  } PixelDataAmbient;

  ...
  // inner loop
  currentPixel.ambientLight += dv;
</code>```

When I interpolate the color (called "Gouraud" shading, where the "red", "green" and "blue" fields are interpolated by a step value at each pixel):

```<code>  typedef struct tagPixelDataGouraud {
      int x;
      float red;
      float green;
      float blue;  // The RGB color interpolated per pixel
  } PixelDataGouraud;

  ...
  // inner loop
  currentPixel.red += dred;
  currentPixel.green += dgreen;
  currentPixel.blue += dblue;
</code>```

When I render in "Phong" shading, I no longer interpolate  an intensity (ambientLight) or a color (red/green/blue) - I interpolate a normal vector (nx, ny, nz) and at each step, I have to re-calculate the lighting equation, based on the interpolated normal vector:

```<code>  typedef struct tagPixelDataPhong {
      int x;
      float nX;
      float nY;
      float nZ; // The normal vector interpolated per pixel
  } PixelDataPhong;

  ...
  // inner loop
  currentPixel.nX += dx;
  currentPixel.nY += dy;
  currentPixel.nZ += dz;
</code>```

Now, the first instinct of C programmers would be "heck, write three functions that interpolate the values, and call them depending on the set mode".
First of all, this means that I have a type problem - what do I work with? Are my pixels PixelDataAmbient? PixelDataGouraud? PixelDataPhong? Oh, wait, the efficient C programmer says, use a union!

```<code>  typedef union tagSuperPixel {
      PixelDataAmbient a;
      PixelDataGouraud g;
      PixelDataPhong   p;
  } SuperPixel;
</code>```

..and then, you have a function...

```<code>  RasterizeTriangleScanline(
      enum mode, // { ambient, gouraud, phong }
      SuperPixel left,
      SuperPixel right)
  {
      int i,j;
      if (mode == ambient) {
          // handle pixels as ambient...
          int steps = right.a.x - left.a.x;
          float dv = (right.a.ambientLight - left.a.ambientLight)/steps;
          float currentIntensity = left.a.ambientLight;
          for (i=left.a.x; i<right.a.x; i++) {
              WorkOnPixelAmbient(i, dv);
              currentIntensity+=dv;
          }
      } else if (mode == gouraud) {
          // handle pixels as gouraud...
          int steps = right.g.x - left.g.x;
          float dred = (right.g.red - left.g.red)/steps;
          float dgreen = (right.g.green - left.a.green)/steps;
          float dblue = (right.g.blue - left.g.blue)/steps;
          float currentRed = left.g.red;
          float currentGreen = left.g.green;
          float currentBlue = left.g.blue;
          for (j=left.g.x; i<right.g.x; j++) {
              WorkOnPixelGouraud(j, currentRed, currentBlue, currentGreen);
              currentRed+=dred;
              currentGreen+=dgreen;
              currentBlue+=dblue;
          }
...
</code>```

Do you feel the chaos slipping in?

First of all, one typo is all that is needed to crash my code, since the compiler will never stop me in the "Gouraud" section of the function, to actually access the ".a." (ambient) values. A bug not caught by the C type system (that is, during compilation), means a bug that manifests at run-time, and will require debugging. Did you notice that I am accessing left.a.green in the calculation of "dgreen"? The compiler surely didn't tell you so.

Then, there is repetition everywhere - the for loop is there for as many times as there are rendering modes, we keep doing "right minus left divided by steps". Ugly, and error-prone. Did you notice I compare using "i" in the Gouraud loop, when I should have used "j"? The compiler is again, silent.

What about the if/else/ ladder for the modes? What if I add a new rendering mode, in three weeks? Will I remember to handle the new mode in all the "if mode==" in all my code?

Now compare the above ugliness, with this set of C++ structs and a template function:

```<code>  struct CommonPixelData {
      int x;
  };
  struct AmbientPixelData : CommonPixelData {
      float ambientLight;
  };
  struct GouraudPixelData : CommonPixelData {
      float red;
      float green;
      float blue;  // The RGB color interpolated per pixel
  };
  struct PhongPixelData : CommonPixelData {
      float nX;
      float nY;
      float nZ; // The normal vector interpolated per pixel
  };

  template <class PixelData>
  RasterizeTriangleScanline(
      PixelData left,
      PixelData right)
  {
      PixelData interpolated = left;
      PixelData step = right;
      step -= left;
      step /= int(right.x - left.x); // divide by pixel span
      for(int i=left.x; i<right.x; i++) {
          WorkOnPixel<PixelData>(interpolated);
          interpolated += step;
      }
  }
</code>```

Now look at this. We no longer make a union type-soup: we have specific types per each mode. They re-use their common stuff (the "x" field) by inheriting from a base class (CommonPixelData). And the template makes the compiler CREATE (that is, code-generate) the three different functions we would have written ourselves in C, but at the same time, being very strict about the types!

Our loop in the template cannot goof and access invalid fields - the compiler will bark if we do.

The template performs the common work (the loop, increasing by "step" in each time), and can do so in a manner that simply CAN'T cause runtime errors. The interpolation per type (AmbientPixelData, GouraudPixelData, PhongPixelData) is done with the operator+=() that we will add in the structs - which basically dictate how each type is interpolated.

And do you see what we did with WorkOnPixel<T>? We want to do different work per type? We simply call a template specialization:

```<code>void WorkOnPixel<AmbientPixelData>(AmbientPixelData& p)
{
    // use the p.ambientLight field
}

void WorkOnPixel<GouraudPixelData>(GouraudPixelData& p)
{
    // use the p.red/green/blue fields
}
</code>```

That is - the function to call, is decided based on the type. At compile-time!

To rephrase it again:

we minimize the code (via the template), re-using common parts,

we don't use ugly hacks, we keep a strict type system, so that the compiler can check us at all times.

and best of all: none of what we did has ANY runtime impact. This code will run JUST as fast as the equivalent C code - in fact, if the C code was using function pointers to call the various WorkOnPixel versions, the C++ code will be FASTER than C, because the compiler will inline the type-specific WorkOnPixel template specialization call!

Less code, no run-time overhead, more safety.

Does this mean that C++ is the be-all and end-all of languages? Of course not. You still have to measure trade-offs. Ignorant people will use C++ when they should have written a Bash/Perl/Python script. Trigger-happy C++ newbies will create deep nested classes with virtual multiple inheritance before you can stop them and send them packing. They will use complex Boost meta-programming before realizing that this is not necessary. They will STILL use char*, strcmp and macros, instead of std::string and templates.

But this says nothing more than... watch who you work with. There is no language to shield you from incompetent users (no, not even Java).

Keep studying and using C++ - just don't overdesign.

Body:
I see way too many C programmers that hate C++. It took me quite some time (years) to slowly understand what is good and what is bad about it. I think the best way to phrase it is this:

Less code, no run-time overhead, more safety.

The less code we write, the better. This quickly becomes clear in all engineers that strive for excellence. You fix a bug in one place, not many - you express an algorithm once, and re-use it in many places, etc. Greeks even have a saying, traced back to the ancient Spartans: "to say something in less words, means that you are wise about it". And the fact of the matter, is that when used correctly, C++ allows you to express yourself in far less code than C, without costing runtime speed, while being more safe (i.e. catching more errors at compile-time) than C is.

Here's a simplified example from my renderer: When interpolating pixel values across a triangle's scanline. I have to start from an X coordinate x1, and reach an X coordinate x2 (from the left to the right side of a triangle). And across each step, across each pixel I pass over, I have to interpolate values.

When I interpolate the ambient light that reaches the pixel:

  typedef struct tagPixelDataAmbient {
      int x;
      float ambientLight;
  } PixelDataAmbient;

  ...
  // inner loop
  currentPixel.ambientLight += dv;

When I interpolate the color (called "Gouraud" shading, where the "red", "green" and "blue" fields are interpolated by a step value at each pixel):

  typedef struct tagPixelDataGouraud {
      int x;
      float red;
      float green;
      float blue;  // The RGB color interpolated per pixel
  } PixelDataGouraud;

  ...
  // inner loop
  currentPixel.red += dred;
  currentPixel.green += dgreen;
  currentPixel.blue += dblue;

When I render in "Phong" shading, I no longer interpolate  an intensity (ambientLight) or a color (red/green/blue) - I interpolate a normal vector (nx, ny, nz) and at each step, I have to re-calculate the lighting equation, based on the interpolated normal vector:

  typedef struct tagPixelDataPhong {
      int x;
      float nX;
      float nY;
      float nZ; // The normal vector interpolated per pixel
  } PixelDataPhong;

  ...
  // inner loop
  currentPixel.nX += dx;
  currentPixel.nY += dy;
  currentPixel.nZ += dz;

Now, the first instinct of C programmers would be "heck, write three functions that interpolate the values, and call them depending on the set mode".
First of all, this means that I have a type problem - what do I work with? Are my pixels PixelDataAmbient? PixelDataGouraud? PixelDataPhong? Oh, wait, the efficient C programmer says, use a union!

  typedef union tagSuperPixel {
      PixelDataAmbient a;
      PixelDataGouraud g;
      PixelDataPhong   p;
  } SuperPixel;

..and then, you have a function...

  RasterizeTriangleScanline(
      enum mode, // { ambient, gouraud, phong }
      SuperPixel left,
      SuperPixel right)
  {
      int i,j;
      if (mode == ambient) {
          // handle pixels as ambient...
          int steps = right.a.x - left.a.x;
          float dv = (right.a.ambientLight - left.a.ambientLight)/steps;
          float currentIntensity = left.a.ambientLight;
          for (i=left.a.x; i<right.a.x; i++) {
              WorkOnPixelAmbient(i, dv);
              currentIntensity+=dv;
          }
      } else if (mode == gouraud) {
          // handle pixels as gouraud...
          int steps = right.g.x - left.g.x;
          float dred = (right.g.red - left.g.red)/steps;
          float dgreen = (right.g.green - left.a.green)/steps;
          float dblue = (right.g.blue - left.g.blue)/steps;
          float currentRed = left.g.red;
          float currentGreen = left.g.green;
          float currentBlue = left.g.blue;
          for (j=left.g.x; i<right.g.x; j++) {
              WorkOnPixelGouraud(j, currentRed, currentBlue, currentGreen);
              currentRed+=dred;
              currentGreen+=dgreen;
              currentBlue+=dblue;
          }
...

Do you feel the chaos slipping in?

First of all, one typo is all that is needed to crash my code, since the compiler will never stop me in the "Gouraud" section of the function, to actually access the ".a." (ambient) values. A bug not caught by the C type system (that is, during compilation), means a bug that manifests at run-time, and will require debugging. Did you notice that I am accessing left.a.green in the calculation of "dgreen"? The compiler surely didn't tell you so.

Then, there is repetition everywhere - the for loop is there for as many times as there are rendering modes, we keep doing "right minus left divided by steps". Ugly, and error-prone. Did you notice I compare using "i" in the Gouraud loop, when I should have used "j"? The compiler is again, silent.

What about the if/else/ ladder for the modes? What if I add a new rendering mode, in three weeks? Will I remember to handle the new mode in all the "if mode==" in all my code?

Now compare the above ugliness, with this set of C++ structs and a template function:

  struct CommonPixelData {
      int x;
  };
  struct AmbientPixelData : CommonPixelData {
      float ambientLight;
  };
  struct GouraudPixelData : CommonPixelData {
      float red;
      float green;
      float blue;  // The RGB color interpolated per pixel
  };
  struct PhongPixelData : CommonPixelData {
      float nX;
      float nY;
      float nZ; // The normal vector interpolated per pixel
  };

  template <class PixelData>
  RasterizeTriangleScanline(
      PixelData left,
      PixelData right)
  {
      PixelData interpolated = left;
      PixelData step = right;
      step -= left;
      step /= int(right.x - left.x); // divide by pixel span
      for(int i=left.x; i<right.x; i++) {
          WorkOnPixel<PixelData>(interpolated);
          interpolated += step;
      }
  }

Now look at this. We no longer make a union type-soup: we have specific types per each mode. They re-use their common stuff (the "x" field) by inheriting from a base class (CommonPixelData). And the template makes the compiler CREATE (that is, code-generate) the three different functions we would have written ourselves in C, but at the same time, being very strict about the types!

Our loop in the template cannot goof and access invalid fields - the compiler will bark if we do.

The template performs the common work (the loop, increasing by "step" in each time), and can do so in a manner that simply CAN'T cause runtime errors. The interpolation per type (AmbientPixelData, GouraudPixelData, PhongPixelData) is done with the operator+=() that we will add in the structs - which basically dictate how each type is interpolated.

And do you see what we did with WorkOnPixel<T>? We want to do different work per type? We simply call a template specialization:

void WorkOnPixel<AmbientPixelData>(AmbientPixelData& p)
{
    // use the p.ambientLight field
}

void WorkOnPixel<GouraudPixelData>(GouraudPixelData& p)
{
    // use the p.red/green/blue fields
}

That is - the function to call, is decided based on the type. At compile-time!

To rephrase it again:

we minimize the code (via the template), re-using common parts,

we don't use ugly hacks, we keep a strict type system, so that the compiler can check us at all times.

and best of all: none of what we did has ANY runtime impact. This code will run JUST as fast as the equivalent C code - in fact, if the C code was using function pointers to call the various WorkOnPixel versions, the C++ code will be FASTER than C, because the compiler will inline the type-specific WorkOnPixel template specialization call!

Less code, no run-time overhead, more safety.

Does this mean that C++ is the be-all and end-all of languages? Of course not. You still have to measure trade-offs. Ignorant people will use C++ when they should have written a Bash/Perl/Python script. Trigger-happy C++ newbies will create deep nested classes with virtual multiple inheritance before you can stop them and send them packing. They will use complex Boost meta-programming before realizing that this is not necessary. They will STILL use char*, strcmp and macros, instead of std::string and templates.

But this says nothing more than... watch who you work with. There is no language to shield you from incompetent users (no, not even Java).

Keep studying and using C++ - just don't overdesign.


问:
Why are C string literals read-only?
What advantage(s) of string literals being read-only justify(-ies/-ied) the:

Yet another way to shoot yourself in the foot

```<code>char *foo = "bar";
foo[0] = 'd'; /* SEGFAULT */
</code>```

Inability to elegantly initialize a read-write array of words in one line:

```<code>char *foo[] = { "bar", "baz", "running out of traditional placeholder names" };
foo[1][2] = 'n'; /* SEGFAULT */
</code>```

Complicating the language itself.

```<code>char *foo = "bar";
char var[] = "baz";
some_func(foo); /* VERY DANGEROUS! */
some_func(var); /* LESS DANGEROUS! */
</code>```

Saving memory?
I've read somewhere (couldn't find the source now) that long time ago, when RAM was scarce, compilers tried to optimize memory usage by merging similar strings.

For example, "more" and "regex" would become "moregex". Is this still true today, in the era of digital blu-ray quality movies? I understand that embedded systems still operate in environment of restricted resources, but still, the amount of memory available has increased dramatically.

Compatibility issues?
I assume that a legacy program that would try to access read-only memory would either crash or continue with undiscovered bug. Thus no legacy program should try to access string literal and therefor allowing to write to string literal would not harm valid, non-hackish, portable legacy programs.

Are there any other reasons? Is my reasoning incorrect? Would it be reasonable to consider a change to read-write string literals in new C standards or at least add an option to compiler? Was this considered before or are my "problems" too minor and insignificant to bother anyone?

答:
Historically (perhaps by rewriting parts of it), it was the contrary. On the very first computers of the early 1970s (perhaps PDP-11) running a prototypical embryonic C (perhaps BCPL) there was no MMU and no memory protection (which existed on most older IBM/360 mainframes). So every byte of memory (including those handling literal strings or machine code) could be overwritten by an erroneous program (imagine a program changing some % to / in a printf(3) format string). Hence, literal strings and constants were writable.

As a teenager in 1975, I coded in the Palais de la Découverte museum in Paris on old 1960s era computers without memory protection: IBM/1620 had only a core memory -which you could initialize thru the keyboard, so you had to type several dozens of digits to read the initial program on punched tapes; CAB/500 had a magnetic drum memory; you could disable writing some tracks thru mechanical switches near the drum.

Later, computers got some form of memory management unit (MMU) with some memory protection. There was a device forbidding the CPU to overwrite some kind of memory. So some memory segments, notably the code segment (a.k.a. .text segment) became read-only (except by the operating system which loaded them from disk). It was natural for the compiler and the linker to put the literal strings in that code segment, and literal strings became read only. When your program tried to overwrite them, it was bad, an undefined behavior. And having a read-only code segment in virtual memory gives a significant advantage: several processes running the same program share the same RAM (physical memory pages) for that code segment (see MAP_SHARED flag for mmap(2) on Linux).

Today, cheap microcontrollers have some read-only memory (e.g. their Flash or ROM), and keep their code (and the literal strings and other constants) there. And real microprocessors (like the one in your tablet, laptop or desktop) have a sophisticated memory management unit and cache machinery used for virtual memory & paging. So the code segment of the executable program (e.g. in ELF) is memory mapped as a read-only, shareable, and executable segment (by mmap(2) or execve(2) on Linux; BTW you could give directives to ld to get a writable code segment if you really wanted to). Writing or abusing it is generally a segmentation fault.

So the C standard is baroque: legally (only for historical reasons), literal strings are not const char[] arrays, but only char[] arrays that are forbidden to be overwritten.

BTW, few current languages permit string literals to be overwritten (even Ocaml which historically -and badly- had writable literal strings has changed that behavior recently in 4.02, and now has read-only strings).

Current C compilers are able to optimize and have "ions" and "expressions" share their last 5 bytes (including the terminating null byte).

Try to compile your C code in file foo.c with gcc -O -fverbose-asm -S foo.c and look inside the generated assembler file foo.s by GCC

At last, the semantics of C is complex enough (read more about CompCert & Frama-C which are trying to capture it) and adding writable constant literal strings would make it even more arcane while making programs weaker and even less secure (and with less defined behavior), so it is very unlikely that future C standards would accept writable literal strings. Perhaps on the contrary they would make them const char[] arrays as they morally should be.

Notice also that for many reasons, mutable data is harder to handle by the computer (cache coherency), to code for, to understand by the developer, than constant data. So it preferable to have most of your data (and notably literal strings) stay immutable. Read more about functional programming paradigm.

In the old Fortran77 days on IBM/7094, a bug could even change a constant: if you CALL FOO(1) and if FOO happened to modify its argument passed by reference to 2, the implementation might have changed other occurrences of 1 into 2, and that was a really naughty bug, quite hard to find.

ContentLicense: CC BY-SA 3.0

Title: Why are C string literals read-only?


问:
Automatically reverting commits that fail the build
A colleague of mine told me that he is thinking in making our CI server to revert commits that failed the build, so the HEAD in master is always stable (as in passing the build at least).

Is this a best practice or it may be more problematic than just leaving master broken until the developer fixes it?

My thinking is that reverting the commit will make more complex the task of readding the commit and fix (developer will have to revert the revert and then commit the fix, which will also clutter the git log) and we should just leave the commit and then commit the fix. Although I see some advantages in having master stable, this revert of failing commits does not convince me.

edit: Doesn't matter if it is master or any other development branch, but the question stays the same: should the CI system revert a commit that failed the build?

another (lenghty) edit: Ok, we're using git in a strange way. We believe that the concept of branches goes against real CI, because committing to a branch isolates you from the other developers and their changes, and adds time when you have to reintegrate your branch and deal with possible conflicts. If everyone commits to master this conflicts are reduced to the minimum and every commit passes all tests.

Of course, this forces you to push only stable (or you break the build) and program more carefully to not break backwards compatibility or do feature-toggling when introducing new features.

There are tradeoffs when doing CI this or that way, but that is out of the scope of question (see related question for this). If you prefer, I may reword the question: a small team of developers work together in a feature branch. If one developer commits something that breaks the build for that branch, should the CI system revert the commit or not?

答:
I would suggest using a Gerrit + Jenkins environment to keep your master branch always in a good shape. People push their new code to Gerrit which triggers a Jenkins job to pull that patch, builds, tests, and so on. If other developers like your patch and Jenkins completes its job successfully, then Gerrit will merge that piece of code to your master branch.

Its a similar environment described by @brian-vandenberg

Besides keeping your branch in a good shape you also add a code review step which improves code quality and knowledge sharing about your software.

[1] Jenkins https://jenkins-ci.org/

[2] Gerrit https://www.gerritcodereview.com/


问:
Bower, NPM, Gulp in ASP.NET MVC, what problem am I solving?
I work at a small web development company, and we use no dependency management whatsoever at the frontend side. External libraries are simply downloaded and pasted into the lib folder of whatever website needs them, and our own libraries are happily copy-pasted. All websites are built on ASP.NET MVC.

Recently I was asked to see if frontend package managers like npm and bower were useful for us, mainly because those are terms that you encounter often nowadays when you're searching online for javascript libraries and such.

So I went and read a lot of articles on npm, bower, grunt, gulp, yeo and many more, and I started experimenting with them in a test web application. But after following a few tutorials, I felt that I was spending a lot of time on things that Visual Studio and ASP.NET MVC already did for me, like bundling scripts and minification. There was a lot of new syntax I had to learn, even though I still had no idea what the point of it all was. It felt like I was adding a whole bunch of configuration in what felt like a clunky way just to make updating frontend libraries is slightly easier. I struggled with Gulp/Grunt the most; I simply could not think of anything that I wanted to do with it, that I couldn't do already.

So the actual question is this: Why would I want to use things like bower and gulp in an ASP.NET MVC environment? What problems are they solving, besides making library updates slightly faster? We don't really feel the urge to update our libraries daily; many of our sites run on pretty old jquery versions, and run fine. An I missing something completely, or are we simply not the intended audience for these systems?

I am sorry if this has been asked before or is common knowledge, but I couldn't find it anywhere. For example, if you search online for 'bower + ASP.NET', you will get plenty of articles on how to use them, but hardly any that touch the why.

UPDATE: Let me clarify the question: What are common things that a developer would use the new host of supported managers in VS2015 (gulp, bower) for, that he can't do without them?

答:
I'll hazard an answer for this one.

You're a .NET developer, stepping into the land of frontend tooling in Javascript. Let's address some of the tooling.

First - in your question, you have blurred the distinction between package managers (npm, Bower) and task runners (Gulp, Grunt). Each is a tool in the toolset, responsible for different areas.

Visual Studio provides task runners for frontend workflows (such as minification and bundling), but outside of Nuget, it doesn't provide a package manager for any frontend modules. While Nuget works, in a sense, it wasn't really designed for frontend packages, specifically; further, as it's not part of the frontend ecosystem, the wealth of packages available in npm or even Bower aren't available through Nuget. (The ones that are may have been altered or tailored to a specific environment, which isn't always what you want.)

In terms of task runners, the web ecosystem has evolved and open-source plugins have been created for Gulp and Grunt that allow a lot of behavior - but these aren't available for Visual Studio. The ecosystem, language, and tooling simply don't match.

Frontend development is no longer a subset of backend development, like it used to be. Javascript in the browser has become its own system, not just an afterthought; the tooling has been updated to reflect this. It's come a long way over the years, and it's moving faster - much faster - than the equivalent tools in Visual Studio. The main reason you'll want to transition to these tools are as follows:

The .NET ecosystem is migrating to the existing toolchains, instead of trying to roll their own. New versions of .NET are changing their task runners to use Grunt, and they are also switching to JSON-based configuration.

.NET is aiming to become more portable. Using the tools provided by the frontend ecosystem (which is by nature platform-agnostic) makes sense in this regard.

These tools are usable outside of the confines of .NET (as JS in the browser, again, has become its own system).

You'll simply have more options in the long run (and, arguably, earlier).

That said - if using the provided tools in VS is easier, then by all means, use them to get your work done. Familiarize yourself with the new toolchains, though, because you're going to need them.


问:
Why use an opaque "handle" that requires casting in a public API rather than a typesafe struct pointer?
I'm evaluating a library whose public API currently looks like this:

libengine.h

```<code>/* Handle, used for all APIs */
typedef size_t enh;

/* Create new engine instance; result returned in handle */
int en_open(int mode, enh *handle);

/* Start an engine */
int en_start(enh handle);

/* Add a new hook to the engine; hook handle returned in h2 */
int en_add_hook(enh handle, int hooknum, enh *h2);
</code>```

Note that enh is a generic handle, used as a handle to several different datatypes (engines and hooks).

Internally, most of these APIs of course cast the "handle" to an internal structure which they've malloc'd:

engine.c

```<code>struct engine
{
    // ... implementation details ...
};

int en_open(int mode, *enh handle)
{
    struct engine *en;

    en = malloc(sizeof(*en));
    if (!en)
        return -1;

    // ...initialization...

    *handle = (enh)en;
    return 0;
}

int en_start(enh handle)
{
    struct engine *en = (struct engine*)handle;

    return en->start(en);
}
</code>```

Personally, I hate hiding things behind typedefs, especially when it compromises type safety. (Given an enh, how do I know to what it's actually referring?)

So I submitted a pull request, suggesting the following API change (after modifying the entire library to conform):

libengine.h

```<code>struct engine;           /* Forward declaration */
typedef size_t hook_h;    /* Still a handle, for other reasons */

/* Create new engine instance, result returned in en */
int en_open(int mode, struct engine **en);

/* Start an engine */
int en_start(struct engine *en);

/* Add a new hook to the engine; hook handle returned in hh */
int en_add_hook(struct engine *en, int hooknum, hook_h *hh);
</code>```

Of course, this makes the internal API implementations look a lot better, eliminating casts, and maintaining type safety to/from the consumer's perspective.

libengine.c

```<code>struct engine
{
    // ... implementation details ...
};

int en_open(int mode, struct engine **en)
{
    struct engine *_e;

    _e = malloc(sizeof(*_e));
    if (!_e)
        return -1;

    // ...initialization...

    *en = _e;
    return 0;
}

int en_start(struct engine *en)
{
    return en->start(en);
}
</code>```

I prefer this for the following reasons:

Added type safety

Improved clarity of types and their purpose

Removed casts and typedefs

It follows the recommended pattern for opaque types in C

However, the owner of the project balked at the pull request (paraphrased):

Personally I don't like the idea of exposing the struct engine. I still think the current way is cleaner & more friendly.

Initially I used another data type for hook handle, but then decided to switch to use enh, so all kind of handles share the same data type to keep it simple. If this is confusing, we can certainly use another data type.

Let's see what others think about this PR.

This library is currently in a private beta stage, so there isn't much consumer code to worry about (yet). Also, I've obfuscated the names a bit.

How is an opaque handle better than a named, opaque struct?

Note: I asked this question at Code Review, where it was closed.

答:
The "simple is better" mantra has become too much dogmatic. Simple is not always better if it complicates other things. Assembly is simple - each command is much simpler than higher-level languages commands - and yet Assembly programs are more complex than higher-level languages that do the same thing. In your case, the uniform handle type enh makes the types simpler at the cost of making the functions complex. Since usually project's types tend to grow in sub-linear rate compared to it's functions, as the project gets bigger you usually prefer more complex types if it can make the functions simpler - so in this regard your approach seems to be the correct one.

The project's author is concerned that your approach is "exposing the struct engine". I would have explained to them that it's not exposing the struct itself - only the fact that there is a struct named engine. The user of the library already needs to be aware of that type - they need to know, for example, that the first argument of en_add_hook is of that type, and the first argument is of a different type. So it actually makes the API more complex, because instead of having the function's "signature" document these types it needs to be documented somewhere else, and because the compiler can no longer verify the types for the programmer.

One thing that should be noted - your new API makes user code a bit more complex, since instead of writing:

```<code>enh en;
en_open(ENGINE_MODE_1, &en);
</code>```

They now need more complex syntax to declare their handle:

```<code>struct engine* en;
en_open(ENGINE_MODE_1, &en);
</code>```

The solution, however, is quite simple:

```<code>struct _engine;
typedef struct _engine* engine
</code>```

and now you can straightforwardly write:

```<code>engine en;
en_open(ENGINE_MODE_1, &en);
</code>```

Body:
The "simple is better" mantra has become too much dogmatic. Simple is not always better if it complicates other things. Assembly is simple - each command is much simpler than higher-level languages commands - and yet Assembly programs are more complex than higher-level languages that do the same thing. In your case, the uniform handle type enh makes the types simpler at the cost of making the functions complex. Since usually project's types tend to grow in sub-linear rate compared to it's functions, as the project gets bigger you usually prefer more complex types if it can make the functions simpler - so in this regard your approach seems to be the correct one.

The project's author is concerned that your approach is "exposing the struct engine". I would have explained to them that it's not exposing the struct itself - only the fact that there is a struct named engine. The user of the library already needs to be aware of that type - they need to know, for example, that the first argument of en_add_hook is of that type, and the first argument is of a different type. So it actually makes the API more complex, because instead of having the function's "signature" document these types it needs to be documented somewhere else, and because the compiler can no longer verify the types for the programmer.

One thing that should be noted - your new API makes user code a bit more complex, since instead of writing:

enh en;
en_open(ENGINE_MODE_1, &en);

They now need more complex syntax to declare their handle:

struct engine* en;
en_open(ENGINE_MODE_1, &en);

The solution, however, is quite simple:

struct _engine;
typedef struct _engine* engine

and now you can straightforwardly write:

engine en;
en_open(ENGINE_MODE_1, &en);


答:
I suspect the real reason is inertia, that's what they've always done and it works so why change it?

The main reason I can see is that the opaque handle lets the designer put anything at all behind it, not just a struct. If the API returns and accepts multiple opaque types they all look the same to the caller and there's never any compilation problems or recompiles needed if the fine print changes. If en_NewFlidgetTwiddler(handle **newTwiddler) changes to return a pointer to the Twiddler instead of a handle, the API doesn't change and any new code will silently be using a pointer where before it was using a handle. As well, there's no danger of the OS or anything else quietly "fixing" the pointer if it gets passes across boundaries.

The disadvantage of that, of course, is that the caller can feed anything at all into it. You have a 64 bit thing? Shove it into the 64 bit slot in the API call and see what happens.

```<code>en_TwiddleFlidget(engine, twiddler, flidget)
en_TwiddleFlidget(engine, flidget, twiddler)
</code>```

Both compile but I bet only one of them does what you want.

Title: Why use an opaque "handle" that requires casting in a public API rather than a typesafe struct pointer?

Body:
I'm evaluating a library whose public API currently looks like this:

libengine.h

```<code>/* Handle, used for all APIs */
typedef size_t enh;

/* Create new engine instance; result returned in handle */
int en_open(int mode, enh *handle);

/* Start an engine */
int en_start(enh handle);

/* Add a new hook to the engine; hook handle returned in h2 */
int en_add_hook(enh handle, int hooknum, enh *h2);
</code>```

Note that enh is a generic handle, used as a handle to several different datatypes (engines and hooks).

Internally, most of these APIs of course cast the "handle" to an internal structure which they've malloc'd:

engine.c

```<code>struct engine
{
    // ... implementation details ...
};

int en_open(int mode, *enh handle)
{
    struct engine *en;

    en = malloc(sizeof(*en));
    if (!en)
        return -1;

    // ...initialization...

    *handle = (enh)en;
    return 0;
}

int en_start(enh handle)
{
    struct engine *en = (struct engine*)handle;

    return en->start(en);
}
</code>```

Personally, I hate hiding things behind typedefs, especially when it compromises type safety. (Given an enh, how do I know to what it's actually referring?)

So I submitted a pull request, suggesting the following API change (after modifying the entire library to conform):

libengine.h

```<code>struct engine;           /* Forward declaration */
typedef size_t hook_h;    /* Still a handle, for other reasons */

/* Create new engine instance, result returned in en */
int en_open(int mode, struct engine **en);

/* Start an engine */
int en_start(struct engine *en);

/* Add a new hook to the engine; hook handle returned in hh */
int en_add_hook(struct engine *en, int hooknum, hook_h *hh);
</code>```

Of course, this makes the internal API implementations look a lot better, eliminating casts, and maintaining type safety to/from the consumer's perspective.

libengine.c

```<code>struct engine
{
    // ... implementation details ...
};

int en_open(int mode, struct engine **en)
{
    struct engine *_e;

    _e = malloc(sizeof(*_e));
    if (!_e)
        return -1;

    // ...initialization...

    *en = _e;
    return 0;
}

int en_start(struct engine *en)
{
    return en->start(en);
}
</code>```

I prefer this for the following reasons:

Added type safety

Improved clarity of types and their purpose

Removed casts and typedefs

It follows the recommended pattern for opaque types in C

However, the owner of the project balked at the pull request (paraphrased):

Personally I don't like the idea of exposing the struct engine. I still think the current way is cleaner & more friendly.

Initially I used another data type for hook handle, but then decided to switch to use enh, so all kind of handles share the same data type to keep it simple. If this is confusing, we can certainly use another data type.

Let's see what others think about this PR.

This library is currently in a private beta stage, so there isn't much consumer code to worry about (yet). Also, I've obfuscated the names a bit.

How is an opaque handle better than a named, opaque struct?

Note: I asked this question at Code Review, where it was closed.

Body:
I suspect the real reason is inertia, that's what they've always done and it works so why change it?

The main reason I can see is that the opaque handle lets the designer put anything at all behind it, not just a struct. If the API returns and accepts multiple opaque types they all look the same to the caller and there's never any compilation problems or recompiles needed if the fine print changes. If en_NewFlidgetTwiddler(handle **newTwiddler) changes to return a pointer to the Twiddler instead of a handle, the API doesn't change and any new code will silently be using a pointer where before it was using a handle. As well, there's no danger of the OS or anything else quietly "fixing" the pointer if it gets passes across boundaries.

The disadvantage of that, of course, is that the caller can feed anything at all into it. You have a 64 bit thing? Shove it into the 64 bit slot in the API call and see what happens.

en_TwiddleFlidget(engine, twiddler, flidget)
en_TwiddleFlidget(engine, flidget, twiddler)

Both compile but I bet only one of them does what you want.


答:
I believe that the attitude stems from a long-time philosophy to defend a C library API from abuse by beginners.

In particular,

Library authors know it's a pointer to the struct, and the struct's details is visible to library code.

All experienced programmers who use the library also knows it's a pointer to some opaque structs;

They had enough hard painful experience to know not to mess with the bytes stored in those structs.

Inexperienced programmers know neither.

They will try to memcpy the opaque data or increment the bytes or words inside the struct. Go hacking.

The long-time traditional countermeasure is to:

Masquerade the fact that an opaque handle is actually a pointer to an opaque struct that exists in the same process-memory-space.

To do so by claiming it is an integer value having same number of bits as a void*

To be extra-circumspect, masquerade the pointer's bits as well, e.g.
struct engine* peng = (struct engine*)((size_t)enh ^ enh_magic_number);

This is just to say it has long traditions; I had no personal opinion on whether it's right or wrong.


问:
When to load related database data in web request?
I'm trying to determine when a web application should query a database for related data that may or may not be used in the current request.

As an example, consider a database that tracks assets for a company.  There is an Assets table, an Owners table, and a Users table.  Assets may be assigned to an OwnerID, and Asset records will track the UserIDs that created, updated, and deleted the Asset.

When doing web requests for the data, I see two main options:

Read all of the data in one request, with a join to Owners and multiple joins to Users (user created/updated/deleted).  While this makes for a heavier query, it would reduce repeated calls to the database.  It also simplifies the use of OOP within the application, as every entity will be fully populated and can be accessed easily, e.g.: Asset.Owner.Email, Asset.LastUpdatedBy.Name, etc.

Only read the data from the Owners table up front, and create separate database requests when the application requires any Owner or User information other than the ID.  In about half of the HTTP requests, no extra info will be required, and in the other half of the HTTP requests, the application will need to query the name, email, etc. of the Owner and each of the users who created, updated, or deleted the asset.  I like the idea of the lean initial request, but I worry about performance when doing an additional handful of requests to get the related data.  It also complicates the OOP design in the application somewhat; instead of being able to simply retrieve Asset.Owner.Email, I'll have to first check if the Asset.Owner object has been populated, call Asset.LoadOwnerByID(Asset.OwnerID), then finally access the value.  (Ignore the fact that Asset shouldn't have a LoadOwnerByID method - that's just an example.)

Now that I've written it out, I'm leaning towards Option 1 as being the most efficient and simple way to do things.  But it gets a little less obvious when you add more recursive relations to the data, e.g.: Each user has a ReportsToUserID value pointing to another User, and each Owner has an AccountManagedByUserID field pointing to a User.

In these examples, what is your preferred way to do things, and what have you found to be the most efficient, both in terms of performance and programming complexity?

PS - I'm intentionally leaving out specifics on web framework and database type because I have had this question come up in all environments, from ASP.Net/MSSQL to Java/SQLite to PHP/MySQL, and I believe the principles will generally apply to all of those environments.

答:
In your DAO layer, you should have a way to mark a relationship as required or optional (terms may vary based on whatever framework you use).

Required relationships mean that if A links to B and I query A, the web service must return B as well. Use this for data where the two objects are always used together.

Optional relationships mean that if A links to B and I query A, the web service will not also return B. If the consumer of the service wants B, it will send another query.

This should strike a good balance. Consumers that need little data get little data in a single query. Consumers that need more data still have to perform fewer queries due to some queries returning multiple records.

This really helps because once you have recursive relationships, object graphs can grow to obscenely large sizes even if you detect recursion and use the existing value (e.g. A -> B -> A just queries A and B and sets their links to each other rather that requerying A). I have seen services return 50+ objects for a single request, and most of them were not needed.

Bonus points if you put dead reference detection in. A links to B, but the service did not return B. That is, A has the foreign key ID of B, but no B object returned. When you get B from A, something at the framework level detects if it is absent and pulls B from the web service behind the scenes, making client code completely unaware of the two types of relationships.


问:
Should I include `assembly` as programming language in the CV?
In the answer for one question someone wrote that assembly is not a language, it's a process. I tend to agree, since the assembly "language" is dependent on the architecture it will run on, which may differ quite a bit from one CPU to another.

So if you've written assembly for one architecture, does that mean you can include it in the CV under merely assembly along with the other programming languages? Or do you explicitly say that you've written assembly for that particular architecture?

EDIT: Changed 'dabbled' to 'written'. English isn't my native language and I misunderstood the term, thinking it meant that you've used it a lot instead of just a bit.

答:
I wouldn't put "assembler" for the
  same reason I wouldn't put "compiler".

Although I must admit I'm not sure I would want to include anything in which I have just "dabbled".

Anyway, my CV does include "6502 assembly language". Interestingly, I don't expect to write for the 6502 again any time soon (I am primarily C# programmer these days) but I include it because it communicates interesting things about me and my experience:

It indicates that I know how these computer things actually work at a fairly low level. This means I understand what is going on when I write high-level code, and this knowledge is still useful for solving problems and debugging code.

It suggests that I know about techniques for memory management, optimisation, but-twiddling etc. that are often lost on programmers who have not dealt with things at this level.

It shows that I've been around a while, with a wealth of experience as a developer.

It suggests that I can still get the job done even when my modern tools let me down (as they do sometimes).

It often elicits interest at interview.

This last point is key. I have had interesting and beneficial conversations at interview based on my mention of the 6502, typically where the interviewer has also programmed in assembly language (of any kind, but particularly 6502). This certainly hasn't done me any harm, and might well have helped me secure my present position.

ContentLicense: CC BY-SA 2.5


问:
Would combining enums with static strings in java be sloppy?
Currently my team has a number of constants defined as static final strings.  I want to be able to iterate over these strings as if they were an enum in one location, but everywhere else they are used just as constant strings.  The other developers do not want them as Enums because they don't want to have to add a .value to the enum every time they want to use the constants, feeling it's too verbose and thus cumbersome.

It seems like the easiest way to maintain the way others have done things while still getting the convenience of iterating (without getting into reflection) is to do both.  Have an enum, but in addition define a static final field which is set equal to the enum's value for each enum, so that others can choose to use the static string most of the time, but have the enum to fall back on when they want a true "Enum".

However, somehow this feels wrong to me, even though it meets the two desired needs.  Is there a better way of making these strings iterable?

答:
The other developers do not want them as Enums because they don't want to have to add a .value to the enum every time they want to use the constants, feeling it's too verbose and thus cumbersome.

This is easy.  The other developers' objections aren't simply differences of opinion; they're factually wrong.  You can statically import the enum constants to avoid constantly typing the enum class name.  I would argue that this reduces clarity, but that's a matter of opinion.  For example, if you have an enum called MetasyntacticVariable, you could write:

```<code>import static MetasyntacticVariable.*;

class Derp {
   void someMethod(MetasyntacticVariable var) {
      if(var == FOO) { ... }
   }
}
</code>```

Change the enum to a non-instantiable class containing string constants, and the code size is about the same, but you give up type safety:

```<code>import static MetasyntacticVariables.*;

class Derp {
   void someMethod(String var) {
      if(FOO.equals(var)) { ... }
   }
}
</code>```

I hope you're not using the constant interface antipattern to avoid importing constants.

Body:
The other developers do not want them as Enums because they don't want to have to add a .value to the enum every time they want to use the constants, feeling it's too verbose and thus cumbersome.

This is easy.  The other developers' objections aren't simply differences of opinion; they're factually wrong.  You can statically import the enum constants to avoid constantly typing the enum class name.  I would argue that this reduces clarity, but that's a matter of opinion.  For example, if you have an enum called MetasyntacticVariable, you could write:

import static MetasyntacticVariable.*;

class Derp {
   void someMethod(MetasyntacticVariable var) {
      if(var == FOO) { ... }
   }
}

Change the enum to a non-instantiable class containing string constants, and the code size is about the same, but you give up type safety:

import static MetasyntacticVariables.*;

class Derp {
   void someMethod(String var) {
      if(FOO.equals(var)) { ... }
   }
}

I hope you're not using the constant interface antipattern to avoid importing constants.


问:
Rest design - Multiple calls vs returning all data in one call
I am trying to build a rest API for an android app. Suppose I have a users table with (id, name, email) and a songs table with (id, song_name, album) and a rich join association between them as streams having (user_id, song_id, listen_count). I want to fetch details about all the streams and show it in the app as a list. The list would be showing the song name, album name, user name and listen count. I see three plausible options -

GET to /streams and fetch a list of all the song_ids and user_ids. Then make GET to /user/:id and /song/:id for each user and song id to get the user and song information.

GET to /streams and fetch a list of all the user_ids and song_ids. Then one GET to /user?ids=<comma_separated_ids> to fetch information about all the users and a GET to song?ids=<comma_separated_ids> to fetch information about all the songs.

GET to /streams and fetch everything in one call. Something like -

```<code>[

  {

    "user_id" : 10,
    "song_id" : 14,
    "listen_count" : 5,
    "user" : {
      "id"     : 10,
      "name"   : "bla",
      "email"  : "bla",
    },
    "song" : {
      "id"     : 14,
      "name"   : "blu",
      "album"  : "blu"
   }
  },
...
]
</code>```

I'm tempted to go with option 3 because it gives me everything in one call, but I don't think it's very rest-full and I fear that it won't be scalable. Option 2 is good but it takes 3 calls which would mean considerable time loading the list. And option 1 follows rest but will take numerous calls for showing the list and doing so many calls from a mobile device isn't feasible.

What would be the recommended way to go about this?

答:
You definitely want a single GET operation that returns metadata about each song and user in addition to their opaque ids.

As you pointed out, it's much simpler. That is a good thing.

Making one of the most common operations for your client apps a single server request instead of O(n) requests is much more scalable. In the long run, the network will be your biggest bottleneck, so you don't want to send any more requests than you have to.

The ids by themselves are kinda useless except for making additional REST calls.

As long as your metadata has a relatively small and bounded size (e.g. no pages of descriptive text or actual audio files, just names, types, counts and so on) returning it in addition to the ids is unlikely to be a performance issue.


问:
The Programmers Bill of Responsibilities
So, we've all heard of The Programmers Bill of Rights and XP has a similar concept.

It's a common complaint these days that we hear a lot about people's rights but not so much about their responsibilities, so what should be on the programmers bill of responsibilities.  That is things that they should do, which they may find unpalatable, but that which separate programmers acting professionally and responsibly, from those who do not.

I'm primarily interested in the unpalatable ones and the ones which tend not to happen.  That is the ones that programmers tend to shirk and avoid, rather than the ones which 90% of programmers actually want to do (such as always refactor and use source control).

So, what should be on the Programmers Bill of Responsibilities?

答: A programmer should not do or implement anything which is unethical or illegal, such as write viruses or hack others' systems (unless it is to discover security holes and then inform the victim about it and what he or she can do to avoid this from being exploited by any malicious hackers).


答:
When creating a REST interface, there is no requirement, or even expectation, that the responses on the REST interface correspond directly to tables or joins in the database.

Your /streams interface can just as easily be represented as

```<code>[
  {
    "listen_count" : 5,
    "user" : {
      "href"     : "/users/10",
      "name"   : "bla",
    },
    "song" : {
      "href"     : "/songs/14",
      "name"   : "blu",
      "album"  : "blu"
    }
  },
  ...
]
</code>```

Where the JSON objects contain the main details of users and songs that are (nearly) always relevant for consumers of a stream resource, and a link to the relevant user/song resources if further details are needed.

This is essentially a variation of your third option, with a fallback to option 1 if more details are needed.

Title: Rest design - Multiple calls vs returning all data in one call

Body:
I am trying to build a rest API for an android app. Suppose I have a users table with (id, name, email) and a songs table with (id, song_name, album) and a rich join association between them as streams having (user_id, song_id, listen_count). I want to fetch details about all the streams and show it in the app as a list. The list would be showing the song name, album name, user name and listen count. I see three plausible options -

GET to /streams and fetch a list of all the song_ids and user_ids. Then make GET to /user/:id and /song/:id for each user and song id to get the user and song information.

GET to /streams and fetch a list of all the user_ids and song_ids. Then one GET to /user?ids=<comma_separated_ids> to fetch information about all the users and a GET to song?ids=<comma_separated_ids> to fetch information about all the songs.

GET to /streams and fetch everything in one call. Something like -

```<code>[

  {

    "user_id" : 10,
    "song_id" : 14,
    "listen_count" : 5,
    "user" : {
      "id"     : 10,
      "name"   : "bla",
      "email"  : "bla",
    },
    "song" : {
      "id"     : 14,
      "name"   : "blu",
      "album"  : "blu"
   }
  },
...
]
</code>```

I'm tempted to go with option 3 because it gives me everything in one call, but I don't think it's very rest-full and I fear that it won't be scalable. Option 2 is good but it takes 3 calls which would mean considerable time loading the list. And option 1 follows rest but will take numerous calls for showing the list and doing so many calls from a mobile device isn't feasible.

What would be the recommended way to go about this?

Body:
When creating a REST interface, there is no requirement, or even expectation, that the responses on the REST interface correspond directly to tables or joins in the database.

Your /streams interface can just as easily be represented as

[
  {
    "listen_count" : 5,
    "user" : {
      "href"     : "/users/10",
      "name"   : "bla",
    },
    "song" : {
      "href"     : "/songs/14",
      "name"   : "blu",
      "album"  : "blu"
    }
  },
  ...
]

Where the JSON objects contain the main details of users and songs that are (nearly) always relevant for consumers of a stream resource, and a link to the relevant user/song resources if further details are needed.

This is essentially a variation of your third option, with a fallback to option 1 if more details are needed.


答:
I'm trying to determine when a web application should query a database for related data that may or may not be used in the current request.

For such general questions it's hard to give a general answer.

You have to consider two points: convenience and performance.

Many things, which seem at first sight convenient are at hindsight performancekillers. Whether it's one or the other - or maybe neither, depends on the amount of data in the DB, which is releated to the lifecycle of an application.

If you start out with an application, you oftentimes have near to no data. So to minimize the roundtrips to the DB you catch as much data as you could with one request. You want to present rich data fast.

With small datasets the resultset is small, the queries - though complex - are fast enough, Joins seem cheap.

That changes with time. Tables will contain lots and lots of data. Big queries will become costly and you have to break up your concepts. Sometimes even it would be best to avoid database joins and do it in main memory.

From my perspective the question - as asked - is of a rather philosophical nature.

But nevertheless there are some rules of thumb one could give:

1) Always retrieve as less data as possibly needed. This is some kind of YAGNI (you ain't gonna need it). Even if it sounds nice to have the data at hand: if you (the user) do not need it, it's pointless to query for it

2) Measure your queries. Despite the previous point: if your application is fast enough, why worry? There are several measurepoints:

UX - sometimes only psychological: Does you user think or perceives the app as fast

How fast is the network between the user and the datacenter?

Is your database delivering data really fast? Are queries best effort?

As long as your users feel snappyness, the connection is pleasant and your queries are fast there is no problem in querying as much data as you could.

Depending on this rudimentary metrics you could evaluate your two solutions:

If you have small datasets, a fast DB, a good to medium connection, you could query as much data as you can get, which would result in a super fast app. On the other hand. If that is the case, there would be no noticeable difference to the second option, to query data when needed.

But beware of changes:

if the datasets grow big and the connection stays good, option 2 becomes more attractive.

but suddenly your user is on mobile - which is today oftentimes a horrible experience - one big costly query could be more attractive, although all it's disadvantages: the user could perhaps not rely on a stable connection - and you are able to deliver a nice UX with all data received.

tl;dr

When to load related database data in web request?

It depends.

Body:
I'm trying to determine when a web application should query a database for related data that may or may not be used in the current request.

As an example, consider a database that tracks assets for a company.  There is an Assets table, an Owners table, and a Users table.  Assets may be assigned to an OwnerID, and Asset records will track the UserIDs that created, updated, and deleted the Asset.

When doing web requests for the data, I see two main options:

Read all of the data in one request, with a join to Owners and multiple joins to Users (user created/updated/deleted).  While this makes for a heavier query, it would reduce repeated calls to the database.  It also simplifies the use of OOP within the application, as every entity will be fully populated and can be accessed easily, e.g.: Asset.Owner.Email, Asset.LastUpdatedBy.Name, etc.

Only read the data from the Owners table up front, and create separate database requests when the application requires any Owner or User information other than the ID.  In about half of the HTTP requests, no extra info will be required, and in the other half of the HTTP requests, the application will need to query the name, email, etc. of the Owner and each of the users who created, updated, or deleted the asset.  I like the idea of the lean initial request, but I worry about performance when doing an additional handful of requests to get the related data.  It also complicates the OOP design in the application somewhat; instead of being able to simply retrieve Asset.Owner.Email, I'll have to first check if the Asset.Owner object has been populated, call Asset.LoadOwnerByID(Asset.OwnerID), then finally access the value.  (Ignore the fact that Asset shouldn't have a LoadOwnerByID method - that's just an example.)

Now that I've written it out, I'm leaning towards Option 1 as being the most efficient and simple way to do things.  But it gets a little less obvious when you add more recursive relations to the data, e.g.: Each user has a ReportsToUserID value pointing to another User, and each Owner has an AccountManagedByUserID field pointing to a User.

In these examples, what is your preferred way to do things, and what have you found to be the most efficient, both in terms of performance and programming complexity?

PS - I'm intentionally leaving out specifics on web framework and database type because I have had this question come up in all environments, from ASP.Net/MSSQL to Java/SQLite to PHP/MySQL, and I believe the principles will generally apply to all of those environments.


答:
There seems to be a confusion on both sides here:

using a handle approach does not requiring using a single handle type for all handles

exposing the struct name does not expose its details (only its existence)

There are advantages to using handles rather than bare pointers, in a language like C, because handing over the pointer allows direct manipulation of the pointee (including calls to free) whereas handing over a handle requires that the client go through the API to perform any action.

However, the approach of having a single type of handle, defined via a typedef is not type safe, and may cause lots of griefs.

My personal suggestion would thus be to move toward type safe handles, which I think would satisfy the both of you. This is accomplished rather simply:

```<code>typedef struct {
    size_t id;
} enh;

typedef struct {
    size_t id;
} oth;
</code>```

Now, one cannot accidentally pass 2 as a handle nor can one accidentally pass a handle to a broomstick where a handle to the engine is expected.

So I submitted a pull request, suggesting the following API change (after modifying the entire library to conform)

That is your mistake: before engaging in significant work on an open source library, contact the author(s)/maintainer(s) to discuss the change upfront. It will allow the both of you to agree on what to do (or not do), and avoid unnecessary work and the frustration that results from it.

Body:
There seems to be a confusion on both sides here:

using a handle approach does not requiring using a single handle type for all handles

exposing the struct name does not expose its details (only its existence)

There are advantages to using handles rather than bare pointers, in a language like C, because handing over the pointer allows direct manipulation of the pointee (including calls to free) whereas handing over a handle requires that the client go through the API to perform any action.

However, the approach of having a single type of handle, defined via a typedef is not type safe, and may cause lots of griefs.

My personal suggestion would thus be to move toward type safe handles, which I think would satisfy the both of you. This is accomplished rather simply:

typedef struct {
    size_t id;
} enh;

typedef struct {
    size_t id;
} oth;

Now, one cannot accidentally pass 2 as a handle nor can one accidentally pass a handle to a broomstick where a handle to the engine is expected.

So I submitted a pull request, suggesting the following API change (after modifying the entire library to conform)

That is your mistake: before engaging in significant work on an open source library, contact the author(s)/maintainer(s) to discuss the change upfront. It will allow the both of you to agree on what to do (or not do), and avoid unnecessary work and the frustration that results from it.


答:
In your resume, you should typically have a section for programming languages, another one for assembly languages (of course if you know assembly language that is) etc. Here's an example:

Technical Credentials:

Programming Languages: Algol, COBOL, Pascal, Lisp

Assembly Languages: x86, x86-64

Just make sure you can defend what you have written in your CV. If you have done specific projects using an assembly language, list it out clearly under a Project Details section. I'd also recommend that you mention some of the more important instructions that you've used.

Title: Should I include `assembly` as programming language in the CV?

Body:
In the answer for one question someone wrote that assembly is not a language, it's a process. I tend to agree, since the assembly "language" is dependent on the architecture it will run on, which may differ quite a bit from one CPU to another.

So if you've written assembly for one architecture, does that mean you can include it in the CV under merely assembly along with the other programming languages? Or do you explicitly say that you've written assembly for that particular architecture?

EDIT: Changed 'dabbled' to 'written'. English isn't my native language and I misunderstood the term, thinking it meant that you've used it a lot instead of just a bit.


问:
Repository pattern with service layer - too much separation?
I have an MVC site which uses the repository pattern. I don't feel like I'm using the MVC style enough, so I'm getting ready to re-architect some of it. But I'm also wanting to do it so if the front-end ever changes, it will be easier to swap out.

Here's what I have currently

Models - some of my models contain my entities/classes directly. (Login model contains Customer class, which is a direct correlation to the Customer table/repository class)
Views - some of my views contain repo queries - ie

```<code>_customerRepo.Query().FirstOrDefault(c => c.Login == User.Identity.Name);
</code>```

Controllers - Not as big of a deal here, controllers calling some repo queries, and some of them also use some services to call the repos - ie

```<code>_customerService.GetAllCustomers()
</code>```

which calls

```<code>_customerRepo.Query().All();
</code>```

Here are my thoughts:

1) Models should contain ONLY the data needed to be presented on the view. Even if all properties of the Customer table/object are presented on the view, they should be re-written to their own model/class so the view knows nothing about the database architecture or backend objects

2) Views should only be accessing model objects

3) (And this is where I'm struggling on which path to take)

a) Controllers (or somewhere on the MVC side, should be code that converts the object data returned from the repo/services and converts them to the models. I'm assuming I could just place this code in a model constructor. But I've noticed that DI expects a default empty constructor in case there are validation errors

b) Controllers call repo interfaces on well-named methods to retrieve data (ie _customerRepo.GetAllCustomers()

c) Controllers ONLY access a service layer. The service layer then is the only thing that interacts with the repo layer.

Am I trying to extract the model, controller, service, repo layers too much? Is the serivces layer too much overhead since it can all be done by the repos?

What's the recommended approach to converting the objects/business entities to the models?

答:
Yes, the service layer is an overhead if you don't have any business logic there. Layered architecture looks like an overhead when a layer (in your case service) is not doing much. But a layered architecture provides your loose coupling which is generally good for adapting requirements in future.

If you can guarantee that you will never need to do anything in service layer except data copy from repo to model then you can remove the service layer in your design. However if your application is basic then you don't have to worry about adding another layer for performance or other reason.

Personally I will keep the service layer and (depends on the technology) will implement a generic DAO/Repository layer.


问:
How to *detect* if open source software is used in a commercial product?
The established procedure regarding releasing code out in the open is to accompany it with a license. Out of the many flavors that exist (BSD, MIT, GPL, LGPL, Boost ...) there are some that prohibit using the code in proprietary software, unless you pay an agreed fee ofcourse.

I have two questions on this :

How is such a violation detectable ? The question stems from the fact that comercial products almost never show their code so you can't know what they use.

I am NOT asking about the legal ramifications - that's off-topic - I'm asking about the technical approach to detect such usage.
- Are there any known cases where such a violation has been reported and persecuted?  If so, how was it detected?

答:
Disclaimer: this is my layman understanding. I am not involved or educated in anything like this. Consider my answer to be somewhat untrustworthy. I have no legal knowledge or training.

This is fairly basic software forensics, which has plenty of overlap with software reverse engineering as far as the technical skill set is concerned.

It is not sufficient for one to identify the evidence. One has to testify in court that during the search for evidence, one does not break any law (including contracts, copyrights, etc., or anything forbidden by law). Otherwise the evidence might not be used in a lawsuit.

As a result, such work must be carried out with heavy supervision of legal experts, etc. But the work in that environment would be pretty much like standard software reverse engineering. (See disclaimer above. This is just my imagination and from my reading of popular articles describing the same.)

As for practical techniques, notice that a lot of software contains constants, string literals (hardcoded strings), etc., which allow for quick indiscriminate scanning for potential targets. Typically, this "scanning" has to be done by yet another third-party - not by the same business entity that will be performing the detailed analysis - in order to comply with the law. The accuracy from this potential target search might be low, as it has been frequently publicly reported that false-positives do occur, and occasionally causes legitimate software to be temporarily taken offline. (Reports on the latter can be searched online; the former viewpoint about "low accuracy" is personal opinion and is not substantiated.)

After the initial targets have been found and the work is transferred to a proper software forensics team, the team would just reverse-engineer the binaries to recreate the structure, sequence, organization of the compiled software. In the superficial sense the compiled code do not directly resemble the source code, but software forensics can identify plenty of evidence that can lead a court judge to conclude that it is highly unlikely that the binary is not produced other than by compiling from the source code that is allegedly being infringed.


问:
Is it a good idea to have separate UI components make their own webservice calls?
I have few UI components in an angularjs web-application. Each display data based upon same input. One shows stats which are calculated on the basis of a time period. Other shows a chart of daily progress of all of those stats in the given time period.

I have designed both the components in such a way that they make their own API call. However now I know that data that component A receives can be used to configure component B instead of it making another API call.

There is some calculation that I have to on daily data to get aggregated information. This can be done on the frontend too.

Example:
If data is for a year, component A shows a graph of 10 stats based on a list of 365 entries and component B receives 10 stats based on aggregate of the same 365 entries. Component B also has to show changes in each stat in terms of percentage between last 365 days and the ones that were selected.

Shall I have it as two API calls or just one ?

答:
It depends. When A and B obtain their data each on its own, this has the advantage that both are independent from each other, and A may be used without B, and B without A. The disadvantage is that you might need to pull the same data over the network twice, and that the data displayed by A and B might not be always consistent because the content changed between the two data requests.

If the data must be consistent, and/or you want to reduce network traffic, it will probably be a good idea to introduce a component C which works as a "data layer", makes the API call for both A and B, and provides the same data (or different views on the same data) for both. That will still allow to use A & B independently from each other (of course, not independent from C). Moreover, this provides you immediately with a place where you can put any code shared between A and B.


答:
It depends on your concrete repositories, but generally speaking, I would add a service layer on top of the repositories.

Depending on your repository implementation, they might be specific to your persistence store. It makes testing easier as well and leads to a hexagonal architecture, instead of a classic layered architecture (which I consider a benefit), see https://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html.

Title: Repository pattern with service layer - too much separation?

Body:
I have an MVC site which uses the repository pattern. I don't feel like I'm using the MVC style enough, so I'm getting ready to re-architect some of it. But I'm also wanting to do it so if the front-end ever changes, it will be easier to swap out.

Here's what I have currently

Models - some of my models contain my entities/classes directly. (Login model contains Customer class, which is a direct correlation to the Customer table/repository class)
Views - some of my views contain repo queries - ie

```<code>_customerRepo.Query().FirstOrDefault(c => c.Login == User.Identity.Name);
</code>```

Controllers - Not as big of a deal here, controllers calling some repo queries, and some of them also use some services to call the repos - ie

```<code>_customerService.GetAllCustomers()
</code>```

which calls

```<code>_customerRepo.Query().All();
</code>```

Here are my thoughts:

1) Models should contain ONLY the data needed to be presented on the view. Even if all properties of the Customer table/object are presented on the view, they should be re-written to their own model/class so the view knows nothing about the database architecture or backend objects

2) Views should only be accessing model objects

3) (And this is where I'm struggling on which path to take)

a) Controllers (or somewhere on the MVC side, should be code that converts the object data returned from the repo/services and converts them to the models. I'm assuming I could just place this code in a model constructor. But I've noticed that DI expects a default empty constructor in case there are validation errors

b) Controllers call repo interfaces on well-named methods to retrieve data (ie _customerRepo.GetAllCustomers()

c) Controllers ONLY access a service layer. The service layer then is the only thing that interacts with the repo layer.

Am I trying to extract the model, controller, service, repo layers too much? Is the serivces layer too much overhead since it can all be done by the repos?

What's the recommended approach to converting the objects/business entities to the models?


问:
JWT based webservice authentication
I'm currently writing a web service that will be consumed by an android app.

To access user specific content, one must authenticate against the service.

Since I'm not (primarily) using a webbrowser to make calls to my API, a solely session based authentication is not an option.

I don't want to pass the users credentials on every call either, so I decided to use a JWT[1] based authentication.

Edit: A few more details

The webservice is running on node.js.

The following modules play a key part in context to the question : express is used for the endpoints, passport for authentication, jwt-simple  to generate tokens. Not directly relevant for the question but involved in the process is bcrypt-nodejs for encryption and sequelize to query the database, for which postgresql is used.

So far, the process looks the following - using example endpoints

A first call is made to /api/auth/login/, passing along the username and the password of the authenticating user.

The api returns the users information stored in the database, along with a token. e.g.
{success: true, user: {id: 42, token: aaa.bbb.ccc}}

Any subsequent request passes said token as a query parameter to authenticate the same user.

The question that rises now is: How do I correlate the token to a user and verify its validity.

The options I see are the following.

Since the token carries a payload, it's actually enough to put the users id into it and assume that if the token properly decodes it's valid and the API call will be made with privileges of the user whose id is contained in the payload.

Since the token is encoded using a secret only known to the server, it shouldn't be possible to fake a token, unless someone gets its hands on the secret.

other claims as exp or iat can be included as well.

Upon generation of the token, it will be added to a tokens table which contains the token and its corresponding user id (id | user_id | token).
When a request is made, the database will be queried for existence of the token and only if an entry exists, its user_id will be used.

Long story short, my question breaks down into these:

Is it necessary/sound to add the token to a database or can I just use the payload to identify the user?

Does it make any sense to change the servers secret - used to encode the token - about every week, hence invalidating any token generated previously?

Using this approach an additional query against the database has to be made on every single request.

[1] - http://jwt.io/

答: Your token should contain the users id and a hash. If the hash matches the JWT, you're fine (as long as nobody knows the private key your are using to create that hash).</p>

Title: JWT based webservice authentication


问:
How to handle multiple models that relate to a single model
First of, sorry for the vague title.

In our website framework, we have modal classes to represent our database tables, that hold a rows data. I'm currently working on a stat style page, and I'm wondering how other programmers handle linking lots of models together.

For example, on the page, I'm listing all Customers, with there respective Addresses (multiple per Customer. Home, billing, work etc...), and every Order which links to the Customer and Address.

The only options I can think of, are:

Ditch the models, bring back a raw array from a join query, that has all the data needed.

Bring back all the different models, and sort them into an array, e.g $customers[0]['customer'], $customers[0]['addresses'] etc...

Create some sort of strange hybrid model that either holds all the data, or holds models.

None of these to me seems particularly ideal, but I don't know of any other ways to do this.

I'm currently using number 2, but I'm curious if there is a different way I could approach this.

Are there any other ways people manage this kind of scenario?

答:
So by the sounds of it you have an anemic domain model

http://www.martinfowler.com/bliki/AnemicDomainModel.html

This is a problem because you have objects that aren't actually doing anything other than holding data, but you have all the overhead of classes and objects without any behaviour.

If you can't figure out what your objects are doing other than just storing data, then they aren't objects. Objects are units of behaviour, not data. Objects that don't do anything other than hold data for something else are a design smell. It means your behaviour is some where else, but those objects/units of behaviour don't have access to the data they need to carry out their behaviour.

So I would go with option 1 since you seem to just need data structures. I would also look at the over all design again and see where your behaviour has gone missing to.


答:
You are simply lacking something called ORM - either via a Framework or (only in some use cases recommended) handcrafted.
Via ORM you define the Entity Relationships via code (e.g. 1 Order <-> n OrderPositions). And if you are using a framework the magic begins: you are able to resolve in one coded query all/most relationships which are needed - Little sidenote: sometimes this is not wanted and would later on in the product lifecycle cause problems.

After you retrieved your data from the database, the important part of the ORM kicks in: assembling the objects from the data retrieved and not only that; it creates the whole object graph (i.e. every related object is put in place - so to say).

After that your webframework (typically) serializes the data to JSON

Your frontend gets something like this:

```<code>{
  "posNr": "1",
  "description": "My Life with a nashorn",
  "price": "1990",
  "ordernumber": "1234",
  "customer": {
    "firstName": "Alice",
    "customernumber": "123456789",
    "address": {
      "street": "bakerstreet 221b",
      "city": "london"
    },
    "links": [{
      "rel": "customer",
      "href": "http://localhost:8080/customers/1"
    }]
  },
  "links": [{
    "rel": "self",
    "href": "http://localhost:8080/orders/1234/1"
  }]
}
</code>```

That said: If you need a collection of customers with their respective orders etc. you simply request a Collection from your application which would result an Array of the above structure.

In principle, this resembles your option 2. But you are doing it unnecessarily manually.

Title: How to handle multiple models that relate to a single model

Body:
First of, sorry for the vague title.

In our website framework, we have modal classes to represent our database tables, that hold a rows data. I'm currently working on a stat style page, and I'm wondering how other programmers handle linking lots of models together.

For example, on the page, I'm listing all Customers, with there respective Addresses (multiple per Customer. Home, billing, work etc...), and every Order which links to the Customer and Address.

The only options I can think of, are:

Ditch the models, bring back a raw array from a join query, that has all the data needed.

Bring back all the different models, and sort them into an array, e.g $customers[0]['customer'], $customers[0]['addresses'] etc...

Create some sort of strange hybrid model that either holds all the data, or holds models.

None of these to me seems particularly ideal, but I don't know of any other ways to do this.

I'm currently using number 2, but I'm curious if there is a different way I could approach this.

Are there any other ways people manage this kind of scenario?

Body:
You are simply lacking something called ORM - either via a Framework or (only in some use cases recommended) handcrafted.
Via ORM you define the Entity Relationships via code (e.g. 1 Order <-> n OrderPositions). And if you are using a framework the magic begins: you are able to resolve in one coded query all/most relationships which are needed - Little sidenote: sometimes this is not wanted and would later on in the product lifecycle cause problems.

After you retrieved your data from the database, the important part of the ORM kicks in: assembling the objects from the data retrieved and not only that; it creates the whole object graph (i.e. every related object is put in place - so to say).

After that your webframework (typically) serializes the data to JSON

Your frontend gets something like this:

{
  "posNr": "1",
  "description": "My Life with a nashorn",
  "price": "1990",
  "ordernumber": "1234",
  "customer": {
    "firstName": "Alice",
    "customernumber": "123456789",
    "address": {
      "street": "bakerstreet 221b",
      "city": "london"
    },
    "links": [{
      "rel": "customer",
      "href": "http://localhost:8080/customers/1"
    }]
  },
  "links": [{
    "rel": "self",
    "href": "http://localhost:8080/orders/1234/1"
  }]
}

That said: If you need a collection of customers with their respective orders etc. you simply request a Collection from your application which would result an Array of the above structure.

In principle, this resembles your option 2. But you are doing it unnecessarily manually.


问:
Best practice to authenticate third party to a website?
I've a website built with ASP.NET, and uses Cookie based Forms Authentication to protect it self from unauthorized access.

It also has a REST based API which uses API key based Authentication. (Key is distributed separately).

We've a case where one of our customers want to embed certain pages from our site inside their own site (using an IFRAME). That customer will also have many other customers who authenticate with customer's site.

What are the best ways to authenticate these third party customers temporarily into our site? Are there any accepted patterns for this kind of scenarios?

答:
It's not clear if your customer's website is using authentication. If you want a Single Sign On (SSO) solution, you'll need to find a common identity provider for both websites or look into identity federation.

You probably want to look at supporting some kind of token based authentication scheme. You'll need a Security Token Service (STS) like for example ADFS or Ping Identity which can issue tokens trusted by your site and also federate with your customers identity provider.

These issued tokens can also be used to authenticate with your web API.


问:
Pass data into a constructor or instead create virtual methods?
In an object oriented module describing a database, should I pass DB description data structures to the constructor in the constructors of derived classes, or should I instead create ("virtual" that is dynamic) methods which create the data structures and call them in the constructor?

These data structures are long (around 100 elements arrays).

A Python example follows:

```<code>class Base:
  def __init__(data_desciption):
    self.data_desciption = data_desciption
</code>```

vs

```<code>class Base:
  def __init__():
    self.data_desciption = self.data_desciption_init()
</code>```

or in C++:

```<code> class Base {
   DataDescription data;
 public:
   Base(DataDescription &data_description) {
     data = data_description;
   }
 };
</code>```

vs

```<code> class Base {
   DataDescription data;
 protected:
   virtual DataDescription &get_data_description() = 0;
 public:
   Base() {
     data = get_data_description();
   }
 };
</code>```

(probably not optimized for speed, but this is now irrelevant).
(oh, I've forgotten that C++ constructors can't call pure virtual functions. Not used C++ for a long time. But this does not change the essence of my question).

In fact I am now programming in Perl.

答:
Passing in the data structure will prevent a potential bug that can occur when a the constructor of a base class calls an abstract method defined by the child class.

This potential bug occurs when the child class has a member variable that is initialized in the constructor. Then, the implementation of the abstract method assumes that member variable has been initialized. In many languages, the base class constructor is always executed at the start of the child class constructor. This means the base class calls the abstract method before the child class has a chance to initialize it's member variable.

In Python, this can be avoided by initializing the member variables before calling the base class constructor. But you still have to be aware of this potential issue in order to work around it. I don't know enough Perl to comment on if this work around could also be used.


答:
You should have very specific, semantic requests.

For instance:

You want to pull information about a specific owner

```<code>example.com/owner/123
</code>```

You want to pull information about a specific owner's assets

```<code>example.com/owner/123/assets
</code>```

Now you want to pull all assets that belong to owner 123

```<code>example.com/ownerAndAssets/123
</code>```

Or you want to pull a specific user:

```<code>example.com/user/345
</code>```

You want to pull all user actions:

```<code>example.com/user/345/actions
</code>```

You want to pull the most recent 10 user actions for a given user:

```<code>example.com/user/345/actions/limit/10
</code>```

You want to pull a user and their 10 most recent actions:

```<code>example.com/userAndActions/345/limit/10
</code>```

If you architect the database queries well in repositories, it should be simple to contain all the necessary functionality in simple classes.

Title: When to load related database data in web request?

Body:
You should have very specific, semantic requests.

For instance:

You want to pull information about a specific owner

example.com/owner/123

You want to pull information about a specific owner's assets

example.com/owner/123/assets

Now you want to pull all assets that belong to owner 123

example.com/ownerAndAssets/123

Or you want to pull a specific user:

example.com/user/345

You want to pull all user actions:

example.com/user/345/actions

You want to pull the most recent 10 user actions for a given user:

example.com/user/345/actions/limit/10

You want to pull a user and their 10 most recent actions:

example.com/userAndActions/345/limit/10

If you architect the database queries well in repositories, it should be simple to contain all the necessary functionality in simple classes.


问:
When is an object passed to a function?
Trying to clearly state the semantics of a function call.

In calling a function, are the arguments passed to the function the ones the calling code initially gives or the ones the function receives?

With code like below, the calling code in bar() calls foo() twice.  This first time with int 2, then ...

1) Function foo() is called with a double 3.1, x has the converted value of int 3,

or

2) The value double 3.1 is converted to int 3 and function foo() is called,

or

3) Something else.

IOWs, is the conversion of double 3.1 to int 3 part of the call of a function (the conversion would not happen without the function call) or is it a preceding activity (consider to be part of the calling code) before the function call?

```<code>void foo(int x);

void bar() {
  foo(2);
  foo(3.1);
}
</code>```

This query is primarily C, yet language agnostic thoughts appreciated.  A quick answer is not needed.

[Edit]

Note: This is not an question of how platforms create the binary/executable to implement the program code - just about the code/language.

[Edit 2]
@ Erik Eidt useful comment provided better words to use (at least for C) for this question.

Perhaps a more succinct question would be, from the language perspective: "Are functions called with "actual arguments" or "formal parameters"?

C11 3.3 actual arguments and 3.16 1 formal parameter.

答:
I expect in every implementation of C, the conversion happens first. The psuedo-assembly for bar:

```<code>store 2 in argument-register-0
call foo
store 3.1 in temporary-register-0
convert-to-int temporary-register-0 into temporary-register-1
store temporary-register-1 in argument-register-0
call foo
</code>```

Your optimizer is probably smart enough to eliminate temporary-register0 and/or temporary-register-1, and different assembly versions may need to do extra trickery to deal with floating point - but the core steps are generally the same.

Title: When is an object passed to a function?

Body:
I expect in every implementation of C, the conversion happens first. The psuedo-assembly for bar:

store 2 in argument-register-0
call foo
store 3.1 in temporary-register-0
convert-to-int temporary-register-0 into temporary-register-1
store temporary-register-1 in argument-register-0
call foo

Your optimizer is probably smart enough to eliminate temporary-register0 and/or temporary-register-1, and different assembly versions may need to do extra trickery to deal with floating point - but the core steps are generally the same.


问:
Is there any practical trick to remember the difference between big-endian and little-endian?
I don't work every day with big-endian and little-endian problems and thus I find very difficult to remember which one is what.

Recently I got an interview asking the difference between the two; since I didn't remember I decided to "guess" (50% chance, after all) but I failed.

So, is there any wide known pratical trick to remember what is the difference between big endian and little endian?

答: The best way to remember this is that civilized peoples seek out variety and hence eat their eggs differently than they order their numbers. Whereas we write decimal digits starting at the big digits first (big endian), we eat soft boiled eggs from the little end (little endian).</p>