问:
Storing and retrieving simple data within a framework
I'm determined to get a decent answer to this, because while I have my own approach (constants) I'm not convinced I'm doing it as efficiently as I could be.

So I'm editing the entire question, to add actual code for a more clear description, and am adding a bounty (as much as I can).

(Sorry Ixrec, your answer might not stand any more).

Basic overview of my (simple) framework

htaccess sends all requests to Front Controller (index.php)

Front Controller loads Bootstrap.php

Bootstrap loads all other framework things - e.g. Error reporting
setup; Auto loading; PHP Version check; Router;

Problem

I'm stuck at deciding on the best way to store "simple data" that's used throughout the framework. Some used 3-4 times, some only once (at the moment).

Simple data is things like: PHP Version Running; Minimum PHP Version framework requires to operate; Allowed characters in the URI; Framework data (name, support contact details);

While arrays and constants are simple and affective, they instantly pollute the global space, and constants do so indefinitely (end of stack).

Classes seems good approach in terms of data is only called where needed, and so global space is not just immediately polluted with all data.

However, a class to just store some small data seems over kill (i.e. "5.4.0").

So I am conflicted with what option to choose, as all have pros and cons.

I can choose, but wanted some feedback from more seasoned devs.

Requirements

1)

Data to be re-usable.

Not all, but most data will likely be used in multiple classes/files/templates (or at least want it open for future possibilities).

2)

Avoid over polluting global data as much as possible (i.e. just including a file with 50 data items in an array or 50 constants).

While the data needs to be re-usable, and so global (i.e. constants) is the easiest option, I am trying to avoid just shoving it all into global instantly.

I also feel it's best to keep all this data as one type, ie ALL in an array, or ALL in constants, and all in one place - making it easy to manage.

But if that is not the best approach do say - remember while it is different data for different components, so arguably some could be in classes, some array, some constants etc, they have a common ground in that they are ALL simple data. So whatever option is best it will be likely be best for all this data.

Examples/Options

I have a "PHP Version Check", which is a class loaded early on in Bootstrap which checks if the running (server) PHP version is adequate for what the framework requires to operate.

So using the data required for that component as an example of the data problem I face:

NOTE: There are currently about 50 data items. The examples below only have one data item, which makes it appear as if the issues don't matter, especially polluting global space (the total data items will likely also grow in the future).

OPTION 1 - ARRAY

```<code>$ConfigArray['phpVersionRunning'] = PHP_VERSION;
$ConfigArray['phpVersionRequired'] = '5.4.0';
</code>```

PROS

Data will be in a single array, a simple approach.

CONS

Data is immediately pushed into global.

Data can be altered.

Array name and array index name being long enough to be descriptive means long code in other files where this data is needed.

e.g. if ( $ConfigArray['phpVersionRequired'] !==  $ConfigArray['phpVersionRunning'] )

OPTION 2 - CONSTANTS

```<code>define ('PHP_VERSION_RUNNING', PHP_VERSION);
define ('PHP_VERSION_REQUIRED', '5.4.0');
</code>```

PROS

This is the most simple and clean looking approach, where used in other files constants are clear in their purpose etc.

e.g. if ( PHP_VERSION_RUNNING !==  PHP_VERSION_REQUIRED )

Instantly accessible wherever needed, including in classes.

Data cannot be altered.

CONS

They are all pushed into global instantly.

They remain in global right through Front End, controllers, templates, view, etc, and won't be needed by them.

OPTION 3 - CLASS

```<code>class PhpVersionData
  {

    private $VersionRunning;
    private $VersionRequired;

    protected function __construct()
      {
        $this->VersionRunning = PHP_VERSION;
        $this->VersionRequired = '5.4.0';
      }

    protected function getVersionRunning()
      {
        return $this->VersionRunning;
      }

    protected function getVersionRequired()
      {
        return $this->VersionRequired;
      }

  }
</code>```

PROS

Data is only created at the first point where it's needed.

CONS

Firstly, this just looks way OTT for just basic data.

Constructor and Methods can be protected, so class would need extending so not instantly polluting global space, but then am treading into singleton territory and also tight coupling (?).

If public methods/constructor instead, then am back to potential global pollution issue.

OPTION 4 - Separate data loading:

Another approach is to use constants, or array or variables, but stored in separate files. So each file could be included separately and only when needed.

This avoids everything being immediately in global space, and with array/constant I could unset them once they are no longer needed.

On paper, this sounds like a great idea, but in practice it seems very fiddly, and maintaining it would be harder as data is stored and called all over the place.

Summary

They all have pros and cons which conflict each other. While one option seems ideal, such as constants, it has a major con which pollutes global space indefinitely.

In honesty, I'm swayed to a config array, as although it is pushed into global from the start, I can clean it up at points in the stack where it's no longer needed.

But there are pros and cons to all approaches, and would like to know what is the most robust approach juggling global space pollution, maintainability, ease of use/readability, etc.

答:
I don't particularly care for any of your proposed approaches simply because it's tying your classes directly to your configuration.  Which means that once you do decide on an approach then you are pretty much stuck with it.

Instead, you should consider adopting more of a dependency injection approach.

```<code>class Bootstrap
{
    public function __construct($phpVersionRequired)
    {
        if (version_compare(PHP_VERSION, $phpVersionRequired) < 0) {
</code>```

The point being is that your actual code neither knows nor cares where $phpVersionRequired comes from.  Your question talks about global data and global accessibility but you don't really want that.

Of course whomever creates the Bootstrap object needs to know where $phpVersionRequired comes from.  There raises the question of what do you mean by "simple framework".    Like @Ixrec has suggested, you best bet might be to look at some existing solutions.  If your simple framework includes a dependency injection container then most of the injection stuff can be abstracted away.

The Silex micro-framework (http://silex.sensiolabs.org/) might be a good starting point.  The Symfony 2 framework (http://symfony.com/doc/current/reference/index.html) represents the other end of the spectrum.

What is relevant is that both use the same Symfony\Config component (http://symfony.com/doc/current/components/config/introduction.html).

So maybe spend some time researching existing solutions and perhaps rethink this global approach to locating dependencies.  Inject your dependencies instead of trying to pull them out of some global resource.

===========================================================

Update 06 Mar 2015

So the question appears to be about where to actually store the config options and how to access them.  My answer is to use a dependency injection container.  In PHP, Pimple is a simple and widely used container: http://pimple.sensiolabs.org/

```<code>use Pimple\Container;

$container = new Container();

// Here is a config parameter
$container['php_version_required'] = '5.5.5';

// Here is a service definition which injects the above parameter
$container['bootstrap'] = function ($c) {
    return new Bootstrap($c['php_version_required']);
};

// Here we get our bootstrap object with it's dependency injected
$bootstrap = $container['bootstrap'];
$bootstrap->run();
</code>```

Of course you will probably want to read the values of your config options from some sort of parameter file but the values themselves would be saved in your container.  The more advanced Symfony 2 container (http://symfony.com/doc/current/components/dependency_injection/introduction.html) has additional support for reading config files as well as caching for improved performance.

Body:
I don't particularly care for any of your proposed approaches simply because it's tying your classes directly to your configuration.  Which means that once you do decide on an approach then you are pretty much stuck with it.

Instead, you should consider adopting more of a dependency injection approach.

class Bootstrap
{
    public function __construct($phpVersionRequired)
    {
        if (version_compare(PHP_VERSION, $phpVersionRequired) < 0) {

The point being is that your actual code neither knows nor cares where $phpVersionRequired comes from.  Your question talks about global data and global accessibility but you don't really want that.

Of course whomever creates the Bootstrap object needs to know where $phpVersionRequired comes from.  There raises the question of what do you mean by "simple framework".    Like @Ixrec has suggested, you best bet might be to look at some existing solutions.  If your simple framework includes a dependency injection container then most of the injection stuff can be abstracted away.

The Silex micro-framework (http://silex.sensiolabs.org/) might be a good starting point.  The Symfony 2 framework (http://symfony.com/doc/current/reference/index.html) represents the other end of the spectrum.

What is relevant is that both use the same Symfony\Config component (http://symfony.com/doc/current/components/config/introduction.html).

So maybe spend some time researching existing solutions and perhaps rethink this global approach to locating dependencies.  Inject your dependencies instead of trying to pull them out of some global resource.

===========================================================

Update 06 Mar 2015

So the question appears to be about where to actually store the config options and how to access them.  My answer is to use a dependency injection container.  In PHP, Pimple is a simple and widely used container: http://pimple.sensiolabs.org/

use Pimple\Container;

$container = new Container();

// Here is a config parameter
$container['php_version_required'] = '5.5.5';

// Here is a service definition which injects the above parameter
$container['bootstrap'] = function ($c) {
    return new Bootstrap($c['php_version_required']);
};

// Here we get our bootstrap object with it's dependency injected
$bootstrap = $container['bootstrap'];
$bootstrap->run();

Of course you will probably want to read the values of your config options from some sort of parameter file but the values themselves would be saved in your container.  The more advanced Symfony 2 container (http://symfony.com/doc/current/components/dependency_injection/introduction.html) has additional support for reading config files as well as caching for improved performance.


问:
Why aren't "fat binaries" more widely used for cross-platform applications?
As far as I know, so-called "fat binaries"--executable files that contain machine code for multiple systems--are only really used on Apple PCs, and even there it seems like they only used them because they needed to transition from PowerPC to x86.

These days a lot of software is cross-platform, and it seems like making a single fat binary would be in many ways simpler than keeping track of a dozen or so different downloads for each combination of operating system and architecture, not to mention somehow conveying to the customer which one they want.

I can come up with plenty of guesses as to why this approach never caught on, for instance:

A lack of cross-compilation tools making multi-OS binaries infeasible

You need to test the code on each OS anyway, so you already have to have systems that can compile natively for each OS

Apparently 32-bit programs "just work" on 64-bit machines already

Dynamic linking works differently on each OS, so a "fat library" might not work even if a "fat application" would

But since I always work with a library or framework that hides all these OS-specific and architecture-specific details from me, I don't know how true any of that really is, or if there are even more issues I don't know about. So, what are the actual reasons why fat binaries aren't generally used to create multi-architecture and/or multi-OS software? (outside of Apple)

答:
Internet age distribution logistics disincentivizes fat binaries in two ways:

The point of sale does not involve physical goods and therefore favor fewer SKU's as is the case when products compete for retail shelf space and customers have limited opportunities to make a purchase.

The costs of bandwidth favors delivering just the minimum necessary bits for a particular software package. Shipping a fat binary down the wire degrades both customer experience and seller infrastructure efficiency.

Fat binaries made more sense when software was shrink wrapped physical media.

ContentLicense: CC BY-SA 3.0


问:
dynamic programming with memoization
I’ve a problem with a programming exercise. I hope you can help me. In this exercise I need to find out what the maximum profit is of taking pictures from several items in a park. For taking pictures I only have 50 minutes.  Each item which you photograph has its own price. You can only photograph each item once.
The exercise looks like this directed weighted graph:

The profit of taking pictures of items is shown right.

For this problem I’m going to use dynamic programming memoization, but I don’t know how to start. I’ve seen code from the knacksack problem, but I’m still stuck.

If you have any tips I would be really thankful!

This is the only code I have. The array for the names:

```<code>N[0] = ‘a’;
N[1] = ‘b’
N[2] = ‘c’
</code>```

I got this array for the weights:

```<code>W[0][0] = 100
W[0][1] = 17
W[0][2] = 40
W[1][0] = 60
W[1][1] = 100
W[1][2] = 103
W[2][0] = 23
W[2][1] = 29
W[2][2] = 100
</code>```

To get from the start to a, b or c it also cost time. I got the following array for that:

```<code>SW[0] = 12
SW[1] = 19
SW[2] = 10
</code>```

答:
As this is an excersize, I'll just give you a hint.

Look at the traveling salesperson dynamic programming algorithm. Its solving a similiar problem, and you should be able to adjust it to fit this problem.

Title: dynamic programming with memoization


问:
Should I implement the consumer/producer pattern in my java video app, and if yes, how?
I built a small video frame analysis app with desktop Java 8. On each frame, I extract data (5 doubles now, but could expand to a 1920x1080x3 OpenCV Mat in the future). I would like to store this data into a database (Java DB, for example) to perform some time-series analysis, and periodically return the results to the user.

I am worried about hard-drive access times if I write to the database and run the app on a single thread, and the best solution that occured to me would be to implement the producer/consumer pattern with multithreading. The examples I found all implement 3 threads:

the main thread

the producer thread

the consumer thread

Is there an advantage in doing that compared to a 2 thread implementation?

main and producer thread

consumer thread

And is that the right way to handle real-time data with a database?

PS: the above question was asked here, but I was told it would be better to ask on SE.programmers instead.

答:
The difference between those choices are in the affinity of task assignments to threads.

As I explain in an earlier question, it is entirely your choice to implement this affinity or not. There are ways to implement multithreading without the affinity of tasks to threads.

Producer-Consumer pattern is suitable if:

The dataflow pipeline is linear - no forks and joins in the flow of data

The producer has one output

The consumer has one input

All stages in between have exactly one input and one output

The data is sequential

If each piece of data is tagged with a serially increasing number, then all stages will see data arriving with the same serially increasing values.

Each stage in between will have to generate exactly one output item for each received item.

It is possible to relax this limitation, as I explained in the comments elsewhere. In general, FIFO queues do not have this limitation.

If maximizing CPU utilization is not the goal(*).

In general, while Producer-Consumer pattern can utilize more than one core, it does not utilize more cores than the number of stages it has.

If a bottleneck exists (that is, there is a stage that takes the longest time to process compared to other stages), the throughput of this stage will determine the throughput of the whole system.

To maximize throughput(*), one generally will try:

Break the pipeline into fine-grained stages.

This is the idea exploited in the design of CPU instruction pipelines.

Careful consideration is needed because each additional stage increases overhead.

Allow some intermediate stages to run in parallel.

The CPU analogy would be the duplication of execution units in superscalar architecture.

In software, this means some carefully-chosen stages will be executed by multiple threads.

These threads will feed from a single FIFO queue, process each data separately, and then send their output into a single thread-safe reordering queue(*).

Focus on optimization of the bottleneck stages. Examples:

Algorithm optimization.

Micro-optimization, such as SIMD programming.

Offloading to specialized processing devices, such as GPU or FPGA.

(*) Maximizing throughput - number of video frames processed per second - is the ultimate goal. Not maximizing CPU utilization.

Some optimizations such as algorithm improvements will decrease CPU utilization of that stage, meanwhile increasing overall efficiency so that overall, the same result can be computed with a lower number of total CPU instructions being executed.

(*) The reordering queue is necessary because when two pieces of data, tagged [0] and [1] respectively are processed, sometimes the output for [1] will finish ahead of time. To preserve the ordering property of the pipeline, the output for [1] has to be held back until the output for [0] is ready.

If these changes are not sufficient to maximize throughput to the desired level, one could also move away from the single-pipeline producer-consumer pattern, and move to a dataflow or data-graph framework.

In a more general dataflow or data-graph framework:

The dataflow graph is not necessary linear. Any directed acyclic graph (DAG) of processing stages can be used.

Tasks have no affinity to threads.

All stages become memoryless (stateless) by default (not allowed to carry state forward), unless explicitly modeled with a data-dependency path.

All stages can execute concurrently in any numbers (multiplicities) by default, unless explicitly constrained with a control-dependency path.

Disclaimer: some of the terminology used here may be loose or incorrect. Corrections are welcome.


问:
Methods accounting for all input to method
This is more of a conceptual question. Let's say that you had the following enum

```<code>public enum FooEnum {
    ALPHA,
    BETA,
    GAMMA,
    DELTA;
}
</code>```

And let's say you have the following method:

```<code>public void doSomething(FooEnum value) {
    if (value == FooEnum.ALPHA) {
        // print something to the console
    }
    // other values ignored
}
</code>```

Now, this example seems a little bit odd to me, as we're completely disregarding every other value of FooEnum. Think of it not restricted to just enums, but let's say something like

```<code>public class Person {

    public void doSomething(String s) {
        if (s.equals("asdf") {
            System.out.println("something");
        }
        // disregard all other values
    }
}
</code>```

To me it seems like we should be at least doing something about other values we don't care about. I've often done input validation before hand to get something like

```<code>public void doSomething(String s) {
    if (s == null) {
        throw new IllegalArgumentException();
    }
    // do stuff
}
</code>```

but what happens in this example

```<code>public void doSomething(FooEnum value) {
    if (value == null) {
        throw new IllegalArgumentException();
    }
    if (value == FooEnum.ALPHA) {
        // do something ALPHA specific
    }
    // ignore other logically grouped values in FooEnum
}
</code>```

What is the (or are some) suggested ways to avoid/refactor this? The primary way I could think of is to either log that it was intentionally ignored. What other patterns could be used.

答:
I think you're looking for 2 things, but I answered this question a while ago

This is a very clear example of the Command Pattern

Basically it goes like this:

Look up the thing to do

Do it

If you use a defaulting map (there are implementations around) then, in the event the command was not found, you can do the default which can use the Null Object Pattern

As for the part about validation: Precondition checking is such a simple but effective way to eliminate bugs that it has it's own Java spec JSR 303. That spec allows you to do something like:

```<code>public void doSomething(@NotNull String name, @Range(min = 0, max = 125) int age) {

}
</code>```

and the infrastructure built into the running environment of your code will throw exceptions for you if these preconditions fail.

Oh, by the way: Ada was able to do this sort of thing decades ago.

Body:
I think you're looking for 2 things, but I answered this question a while ago

This is a very clear example of the Command Pattern

Basically it goes like this:

Look up the thing to do

Do it

If you use a defaulting map (there are implementations around) then, in the event the command was not found, you can do the default which can use the Null Object Pattern

As for the part about validation: Precondition checking is such a simple but effective way to eliminate bugs that it has it's own Java spec JSR 303. That spec allows you to do something like:

public void doSomething(@NotNull String name, @Range(min = 0, max = 125) int age) {

}

and the infrastructure built into the running environment of your code will throw exceptions for you if these preconditions fail.

Oh, by the way: Ada was able to do this sort of thing decades ago.


问:
Should I use properties for the properties of properties?
Sometimes I use some indirect properties to set or get some other sub-properties,

I give an example

```<code>class Page
{
    public string MainText
    { set { MainParagraph.Text = value; } get { return MainParagraph.Text; }}
    public TextBlock MainParagraph {set; get;}
    public TextBlock FootNotes {set; get;}
}

class TextBlock
{
    public String Text {set; get;}
    public bool   RightToLeft {set; get;}
}
</code>```

Without the MainText property of the Page I have to use myPage.MainParagraph.Text = something and now I use myPage.MainText = something, however one may still use the first alternative. (Should I prevent it?)

Please note Text is not a real property of Page and in this way it may represent some sub-properties but not all of them. Is there any trade off?

For example for the RightToLeft property I prefer myPage.FootNote.RightToLeft = true because it's an specific attribute of each TextBlock but MainText could still be known as the main text of each page.

Is it better to make FootNotes public, but MainParagraph private? Then do I need to define a property in the Page for every property of the MainParagraph?

答:
I believe that you should either expose object TextBlock from Page or have delegate methods in Page to provide access to the methods of TextBlock but not both. I guess it depends how many properties and methods of TextBlock you want to expose, so if they are many, that just provide TextBlock and do not have all those simple delegations.

You can also check two opposite refactorings from the Fowler's catalog: Hide Delegate and Remove Middle Man


问:
Manage content for multiple websites and mobile apps
I need to manage content (pages, key/value list, assets and more) in one webbased system for multiple websites and mobile apps.

My idea is to create a web api, secured with tokens for apps and sites and some kind of OAuth authentication, also with JSON web tokens. I want to create it with ASP.net Web Api, Entity Framework and Identify.

My idea is to split up the cms into a single page application, probably in AngularJS, and the Web API. So first create the domain model, how do we need to structure all the content/data and store this. After that create the api. And when that is finished, I need to create a SPA-cms webapplication for the end users.

Every website or app can use the api to read and write data over https and with a secret token, and every other party is free to choose whatever technique or programming language they want to use.

What do you all think about this idea? Can it be a architechture/technique to use for a long time? And do you think this architecture can be used for high traffic websites?

Thanks!

Edit: I just want to talk about ideas... if this is the best for this time, to use an API, or just create a MVC-CRUD application with forms and stuff

答:
Yes, this better for long run. Isolating core app and providing access through api is good practice currently that way no matter what type of client it is , it can make use of the same environment that web app is using, also there is no need to rewrite api for any specific client </p>

<p>Make sure u have proper access control for resource accessing in API </p>

Body:
Yes, this better for long run. Isolating core app and providing access through api is good practice currently that way no matter what type of client it is , it can make use of the same environment that web app is using, also there is no need to rewrite api for any specific client

Make sure u have proper access control for resource accessing in API


问:
What is the best way to expose services to mobile devices?
We are working on providing services to mobile devices(Android, iOS and Windows). These services mostly return data and nothing OS or any programming language specific. We are currently planning on providing the service as a REST API since the clients can leverage the HTTP API provided by the OS but a co worker of mine is suggesting an rpc interface to get the data required. I am not sure if that is a good idea because it would need a lot more code than making simple calls to RESTful service. How can I convince him that using RPC is not a good idea? </p>

答:
Yes, Rest API is very powerful for your scenario

Expose all of your services through API endpoints. Always consider doing following when building Apis

Authentication - have an  strong authentication system in your API, like token based authentication ( Json web token)

Authorization - every single API need to be access controlled, have the user privileges in your database and cross verify it every time

Also one thing I suggest is never ask user specific information and process on it after authentication , always take all the logged in user specific information from database using provided authentication token


问:
How to handle inmutable data on Databases
I'm working on a quotation software. It basically creates quotations for customers based on certains ProductModel that contains n Plan that contains n PriceRange

Edit:

Here's a ER diagram of the current DB

When you create a quotation, you select 1 or many PriceRanges for it. The thing is those PriceRanges attribute's values can be modified by an user. If they change an attribute's value, previous quotation should maintain the value it was created with (Along with the Plan and ProductModel attribute's values it was created with).

We tried creating a table called QuotationDataParam that contain each attribute for the other 3 tables (ProductModelName, Description, PlanName, RangeLow, RangeHigh, Bounty and Fine). But that way you can't group a PriceRange by Plans,  nor can group Plans by ProductModel.

答:
I assume the issue is that you would like to have some constraints and foreign keys to make the database automagically enforce statements like "every quoted price is within the price range for that customer/product/etc", but can't because the price ranges can change.

I would associate a timestamp with every price range and quotation. When the price range changes, you don't delete the old range, but simply add a new range with a more recent timestamp. That way, to validate a quotation, you simply check for the newest price range whose timestamp is before the quotation's timestamp. Alternatively, you can give every version of every price range a unique id number via some other mechanism, but I think the timestamp is more meaningful in your case.

Of course, this can be a bit complicated, especially when it comes to those grouping queries you suggested, but most businesses can probably benefit from having a formal audit trail of who changed which product's prices when, so there are plenty of reasons to go this route.


问:
Testing generic errors
I've got a program that validates it's input, and then errors.

So far for each kind of error I created a new derived class. But this was getting pretty unwieldy (the input is complex so there are many possible errors) so instead I made the base more flexible and removed all the derived classes.

The core resulting issue is that now when I test with certain invalid inputs, I'm not sure how to identify the "correct" error anymore. If the program produces an error on invalid input but it's the wrong one, how am I going to identify the correct error without effectively hardcoding internal error implementation details?

Edit: I also intended to specify that the reason I went with a new derived class per error type is that I need dynamically extensible error types. Something like an enumeration would never be suitable.

答:
I believe the standard approach is to use an error code (of enum type) and an error message (of string type). The "code" makes it easy to programmatically identify a specific type of error (if(e.code === DIVIDE_BY_ZERO)), and the "message" makes it easy to show something meaningful to the user (std::cout << e.message).

A new derived exception class should probably be reserved for those categories of exceptions that you know you want to handle differently from the others. In other words, if you know of a place where you have code you want to put in a catch(const SomeNewExceptionType& e) block, then it's worth creating SomeNewExceptionType. This usually happens when the error handler needs significantly more information than just the type of error. For instance, a syntax exception may want to carry around a chunk of the abstract syntax tree it was working on when something went wrong.

It's also possible that you're simply categorizing your errors wrong (eg, creating MissingSemicolonException and TooManyArgumentsException and so on instead of a single SyntaxException). We may need more information to help if that's the case.

Title: Testing generic errors


问:
A separate endpoint specifically for sync in a REST api
I am working on a multi client/single server app. Communication between the two happens via RESTful API. There are several resources that need to stay in sync across all clients, including images captured from camera, likes and comments on these images, user profiles and user followers/followings. My current approach involves GETing all resources changed on server since last sync, like GET /images?since=<last-sync-timestamp>, GET /users/:id/followers?since=<last-sync-timestamp> etc. and POSTing all client changes since last sync to the same endpoints, like POST /images, POST /user/:id/followers

The main drawback to this approach is way too many network calls - For each resource I need to sync, I need to perform at least 2 network calls.

So I am thinking about introducing a new endpoint like /sync which provides all syncable resources that have changed since last sync timestamp. Both client and server will need to parse the JSON and put the respective data in appropriate tables, but now, no matter how many resources I have to sync, I will only need to perform two network calls, but change the structure of the JSON as reosurces get added/removed.

Any thoughts on why the second approach is superior/inferior to the first one?

答:
Here is how we do it , am not sure if it's good or bad but is works so good.

I too have an dedicated endpoint for sync

```<code>/sync/{syncKey}
</code>```

As soon as the user authenticated , if the user client (mobile apps) want to have sync they can call add to sync API , ther I store one entry per device per user , and return the entry key as sync key

Then whenever any changes happened on any resource for that user I will add the entity key (only primary key)  to all the devices sync entry for that user ( it supports all CRUD  operations)

Then the client call the get sync API using the sync key to fetch the sync entry, if any key is present for any resources then client will make separate API call for each resource using the resource key and make appropriate changes in there end and finally send an clear sync API calls to remove the synced keys from db

When the user logs out client will send delete request to remove the sync entry completely

Body:
Here is how we do it , am not sure if it's good or bad but is works so good.

I too have an dedicated endpoint for sync

/sync/{syncKey}

As soon as the user authenticated , if the user client (mobile apps) want to have sync they can call add to sync API , ther I store one entry per device per user , and return the entry key as sync key

Then whenever any changes happened on any resource for that user I will add the entity key (only primary key)  to all the devices sync entry for that user ( it supports all CRUD  operations)

Then the client call the get sync API using the sync key to fetch the sync entry, if any key is present for any resources then client will make separate API call for each resource using the resource key and make appropriate changes in there end and finally send an clear sync API calls to remove the synced keys from db

When the user logs out client will send delete request to remove the sync entry completely


答:
Aside the type, you can usually specify a textual description. For instance, in a method SetPercentage(value) a error OutOfRangeError thrown when the value is inferior to zero, but also superior to one hundred.

Same type—two different errors.

The text of the error can then specify what went wrong specifically. For instance:

if (value < 0) {
    raise OutOfRangeError("The value should not be inferior to 0.");
}

if (value > 100) {
    raise OutOfRangeError("The value should not be superior to 100.");
}
```

<h2>Description used purely for debugging</h2>

<p>This is what is commonly used in languages such as Java or C# which use <em>exceptions</em> rather then <em>errors</em>. In those exceptions, <strong>the description is intended to be read by a developer maintaining (and debugging) the application; it is not expected to be shown to the end user or to be used programmatically.</strong> It is not that useful to be able to determine programmatically which one of the two exceptions occurred (doing a <code>switch</code> over the textual description is obviously a terrible idea).</p>

<p>Look at the larger picture. Imagine that the code above is in our business layer. Then, in presentation layer, we have:</p>

<pre class="lang-cs prettyprint-override"><code>try:
    int percentage = conversions.parseInt(field.value);
    if (percentage < 0) {
        field.highlightInRed();
        // The percentage should be superior to zero.
        form.showError("Le pourcentage doit être supérieur à zéro.");
    }
    else if (percentage > 100) {
        field.highlightInRed();
        // The percentage should be inferior to one hundred.
        form.showError("Le pourcentage doit être inférieur à cent.");
    }

    // Call to the business layer happens here.
    rebate.changeValue(precentage);

catch ConversionError:
    field.highlightInRed();
    // The percentage should be an integer number.
    form.showError("Le pourcentage doit être un nombre entier.");
</code>```

Here, we don't wait until the business layer throws an exception: an exception should remain exceptional, while users typing "13" when requested to enter a digit or users writing "250" when requested to enter a number between 0 and 100 are not that exceptional.

Interaction designers may even decide that input validation may happen on every key stroke. You type 3 and 8, the field background remains white. You type an additional 0—the field background turns red and a hint appears, showing that 380 is not a valid value for this field. You wouldn't ask the business layer to generate exceptions at every key stroke, would you?

It's only if I fail, as a developer, to provide correct checks at presentation layer, than OutOfRangeError in business layer will be raised. This would probably result in a crash and a bug report containing the stack trace: a person debugging that will then find and solve the error in the presentation layer.

If you notice some sort of logic duplication between the business layer and the presentation layer in the example above, refactoring may help:

In business layer, value was an integer. What if I create a type Percentage inherited from a newly created class IntInRange:

abstract class IntInRange
{
    private int value;
    public abstract readonly IntInRange Min;
    public abstract readonly IntInRange Max;
    public void SetValue(int value)
    {
        // Raise OutOfRangeErrors here.
        this.value = value;
    }
    ...
}

class Percentage : IntInRange
{
    public readonly Percentage Min = 0;
    public readonly Percentage Max = 100;
}
```</li>
<li><p>In presentation layer, I can then use data binding to tell that a given field is associated with the variable <code>rebate.percentage</code> of type <code>Percentage</code>. If the data binding framework is smart, I can bridge its error handling with the rules described in <code>IntInRange</code> type, and the framework will handle all the errors itself. If it's really smart, it will generate humanly-readable text of the errors, such as "The percentage should be superior to 0.", the word "percentage" corresponding to the name of the variable.</p></li>
</ol>

<p>Notice that here, the text of the exception is still neither used programmatically, nor shown to the end user. The data binding framework figures the information from the class itself, and the <code>OutOfRangeError</code> should never be hit (or it would indicate a bug in the framework or in the code using this framework).</p>

<h2>Code used for APIs</h2>

<p>Another usage which is proper to errors, and not exceptions, consists of embedding a <em>code</em> in the error. This code is then used not only during the debugging, but also by third-party developers accessing an API.</p>

<p>For instance, an abstract API can return <code>Error 500371</code>, which appears to indicate that the percentage value is inferior to zero, or <code>Error 500373</code>, which means that the percentage value is superior to one hundred.</p>

<p>While many APIs use cryptic error codes (often numbers), this is not always the case. Especially REST services use more and more text identifiers of an error:</p>

<pre class="lang-js prettyprint-override"><code>{
    "error": {
        "id": "percentage-superior-to-100",
        "uri": "http://example.com/errors/percentage-superior-to-100",
        "description": "The specified value of the percentage is out of range. The value should be superior or equal to 0 and inferior or equal to 100."
    }
}
</code>```

Here, while description can change (and can be localized), the id is guaranteed to remain the same forever (until the API is obsoleted) and can be used programmatically.

Title: Testing generic errors

Body:
I've got a program that validates it's input, and then errors.

So far for each kind of error I created a new derived class. But this was getting pretty unwieldy (the input is complex so there are many possible errors) so instead I made the base more flexible and removed all the derived classes.

The core resulting issue is that now when I test with certain invalid inputs, I'm not sure how to identify the "correct" error anymore. If the program produces an error on invalid input but it's the wrong one, how am I going to identify the correct error without effectively hardcoding internal error implementation details?

Edit: I also intended to specify that the reason I went with a new derived class per error type is that I need dynamically extensible error types. Something like an enumeration would never be suitable.

Body:
Aside the type, you can usually specify a textual description. For instance, in a method SetPercentage(value) a error OutOfRangeError thrown when the value is inferior to zero, but also superior to one hundred.

Same type—two different errors.

The text of the error can then specify what went wrong specifically. For instance:

if (value < 0) {
    raise OutOfRangeError("The value should not be inferior to 0.");
}

if (value > 100) {
    raise OutOfRangeError("The value should not be superior to 100.");
}

Description used purely for debugging

This is what is commonly used in languages such as Java or C# which use exceptions rather then errors. In those exceptions, the description is intended to be read by a developer maintaining (and debugging) the application; it is not expected to be shown to the end user or to be used programmatically. It is not that useful to be able to determine programmatically which one of the two exceptions occurred (doing a switch over the textual description is obviously a terrible idea).

Look at the larger picture. Imagine that the code above is in our business layer. Then, in presentation layer, we have:

try:
    int percentage = conversions.parseInt(field.value);
    if (percentage < 0) {
        field.highlightInRed();
        // The percentage should be superior to zero.
        form.showError("Le pourcentage doit être supérieur à zéro.");
    }
    else if (percentage > 100) {
        field.highlightInRed();
        // The percentage should be inferior to one hundred.
        form.showError("Le pourcentage doit être inférieur à cent.");
    }

    // Call to the business layer happens here.
    rebate.changeValue(precentage);

catch ConversionError:
    field.highlightInRed();
    // The percentage should be an integer number.
    form.showError("Le pourcentage doit être un nombre entier.");

Here, we don't wait until the business layer throws an exception: an exception should remain exceptional, while users typing "13" when requested to enter a digit or users writing "250" when requested to enter a number between 0 and 100 are not that exceptional.

Interaction designers may even decide that input validation may happen on every key stroke. You type 3 and 8, the field background remains white. You type an additional 0—the field background turns red and a hint appears, showing that 380 is not a valid value for this field. You wouldn't ask the business layer to generate exceptions at every key stroke, would you?

It's only if I fail, as a developer, to provide correct checks at presentation layer, than OutOfRangeError in business layer will be raised. This would probably result in a crash and a bug report containing the stack trace: a person debugging that will then find and solve the error in the presentation layer.

If you notice some sort of logic duplication between the business layer and the presentation layer in the example above, refactoring may help:

In business layer, value was an integer. What if I create a type Percentage inherited from a newly created class IntInRange:

abstract class IntInRange
{
    private int value;
    public abstract readonly IntInRange Min;
    public abstract readonly IntInRange Max;
    public void SetValue(int value)
    {
        // Raise OutOfRangeErrors here.
        this.value = value;
    }
    ...
}

class Percentage : IntInRange
{
    public readonly Percentage Min = 0;
    public readonly Percentage Max = 100;
}

In presentation layer, I can then use data binding to tell that a given field is associated with the variable rebate.percentage of type Percentage. If the data binding framework is smart, I can bridge its error handling with the rules described in IntInRange type, and the framework will handle all the errors itself. If it's really smart, it will generate humanly-readable text of the errors, such as "The percentage should be superior to 0.", the word "percentage" corresponding to the name of the variable.

Notice that here, the text of the exception is still neither used programmatically, nor shown to the end user. The data binding framework figures the information from the class itself, and the OutOfRangeError should never be hit (or it would indicate a bug in the framework or in the code using this framework).

Code used for APIs

Another usage which is proper to errors, and not exceptions, consists of embedding a code in the error. This code is then used not only during the debugging, but also by third-party developers accessing an API.

For instance, an abstract API can return Error 500371, which appears to indicate that the percentage value is inferior to zero, or Error 500373, which means that the percentage value is superior to one hundred.

While many APIs use cryptic error codes (often numbers), this is not always the case. Especially REST services use more and more text identifiers of an error:

{
    "error": {
        "id": "percentage-superior-to-100",
        "uri": "http://example.com/errors/percentage-superior-to-100",
        "description": "The specified value of the percentage is out of range. The value should be superior or equal to 0 and inferior or equal to 100."
    }
}

Here, while description can change (and can be localized), the id is guaranteed to remain the same forever (until the API is obsoleted) and can be used programmatically.


问:
Is static universally "evil" for unit testing and if so why does Resharper recommend it?
I have found that there are only 3 ways to unit test (mock/stub) dependencies that are static in C#.NET:

Moles

TypeMock

JustMock

Given that two of these are not free and one has not hit release 1.0, mocking static stuff is not too easy.

Does that make static methods and such "evil" (in the unit testing sense)?  And if so, why does resharper want me to make anything that can be static, static? (Assuming resharper is not also "evil".)

Clarification:
I am talking about the scenario when you want to unit test a method and that method calls a static method in a different unit/class.  By most definitions of unit testing, if you just let the method under test call the static method in the other unit/class then you are not unit testing, you are integration testing.  (Useful, but not a unit test.)

答:
The simple truth rarely acknowledged is that if a class contains a compiler-visible dependency on another class, it cannot be tested in isolation from that class. You can fake up something that looks like a test, and will appear on a report as if it was a test.

But it will not have the key defining properties of a test; failing when things are wrong, passing when they are right.

This applies to any static calls, constructor calls, and any reference to methods or fields not inherited from a base class or interface. If the class name appears in the code, it is a compiler-visible dependency, and you can't validly test without it. Any smaller chunk simply is not a valid testable unit. Any attempt to treat it as if it were will have results no more meaningful than writing a little utility to emit the XML used by your test framework to say 'test passed'.

Given that, there are three options:

define unit testing to be testing of the unit composed of a class and it's hard-coded dependencies. This works, providing you avoid circular dependencies.

never create compile-time dependencies between classes you are responsible for testing. This works, providing you don't mind the resulting code style.

don't unit test, integration test instead. Which works, providing it doesn't conflict with something else you need to use the term integration testing for.


答:
A fat binary approach makes most sense if:

Both architectures coexist on the same system

Everything else is more or less the same for all architectures

That's why they are not used for cross-platform code (both criteria don't apply), or to support different Linux distributions with one binary (1. doesn't apply, 2. applies to a certain degree).

On Linux, both criteria would still apply if you want to support both 32 and 64 bit on a single Linux distribution. But why bother, if you already have to support multiple distributions?

On Windows, the transition from 16 bit to 32 bit happened initially with the introduction of Windows NT, which was major deviation from the 16 bit Windows world in many regards (virtual memory, multi-user access control, API changes...). With all these changes, it was  better to keep the 32 and 16 bit worlds separate. NT had already the concept of "subsystems" support different OS "personae" (Win32, POSIX), so making Win16 a third subsystem was a straightforward choice.

The Win32 to Win64 transition didn't involve similar major changes, but Microsoft used a similar approach anyway, probably because it was proven and tried.

Title: Why aren't "fat binaries" more widely used for cross-platform applications?

Body:
As far as I know, so-called "fat binaries"--executable files that contain machine code for multiple systems--are only really used on Apple PCs, and even there it seems like they only used them because they needed to transition from PowerPC to x86.

These days a lot of software is cross-platform, and it seems like making a single fat binary would be in many ways simpler than keeping track of a dozen or so different downloads for each combination of operating system and architecture, not to mention somehow conveying to the customer which one they want.

I can come up with plenty of guesses as to why this approach never caught on, for instance:

A lack of cross-compilation tools making multi-OS binaries infeasible

You need to test the code on each OS anyway, so you already have to have systems that can compile natively for each OS

Apparently 32-bit programs "just work" on 64-bit machines already

Dynamic linking works differently on each OS, so a "fat library" might not work even if a "fat application" would

But since I always work with a library or framework that hides all these OS-specific and architecture-specific details from me, I don't know how true any of that really is, or if there are even more issues I don't know about. So, what are the actual reasons why fat binaries aren't generally used to create multi-architecture and/or multi-OS software? (outside of Apple)


答:
In C#, the way this is done is by adding metadata to your object's members in the form of property attributes, each of which is a class.  There aren't that many of them; they embody categories of errors, and some of them take parameters.  For example, to validate a class property as a number between 0 and 50, you might decorate the property with an attribute that looks something like this:

```<code>[Range(0, 50)]
</code>```

And then use Reflection to inspect that metadata to determine how to validate each property.

It is my understanding that C++ isn't as adept at this type of introspection.  In the old days of ASP.NET MVC, we didn't have these attributes, so we would simply write a validation method that would return a collection of ValidationError objects.  This collection could then be handed back to the View for display to the user.  In a ViewModel object, this makes perfect sense, because the only purposes of the ViewModel object is to display data to, and retrieve data from, the user via the UI.

Title: Testing generic errors

Body:
In C#, the way this is done is by adding metadata to your object's members in the form of property attributes, each of which is a class.  There aren't that many of them; they embody categories of errors, and some of them take parameters.  For example, to validate a class property as a number between 0 and 50, you might decorate the property with an attribute that looks something like this:

[Range(0, 50)]

And then use Reflection to inspect that metadata to determine how to validate each property.

It is my understanding that C++ isn't as adept at this type of introspection.  In the old days of ASP.NET MVC, we didn't have these attributes, so we would simply write a validation method that would return a collection of ValidationError objects.  This collection could then be handed back to the View for display to the user.  In a ViewModel object, this makes perfect sense, because the only purposes of the ViewModel object is to display data to, and retrieve data from, the user via the UI.


答:
Keep price range data in the PriceRange table, but store this information in the quotation also, using extra quotation detail tables if necessary.

This is no different than any other ordinary invoice.  The prices for each line item are always copied to the invoice line items, so that they reflect the price of the items at the time the invoice was created.

Title: How to handle inmutable data on Databases

Body:
I'm working on a quotation software. It basically creates quotations for customers based on certains ProductModel that contains n Plan that contains n PriceRange

Edit:

Here's a ER diagram of the current DB

When you create a quotation, you select 1 or many PriceRanges for it. The thing is those PriceRanges attribute's values can be modified by an user. If they change an attribute's value, previous quotation should maintain the value it was created with (Along with the Plan and ProductModel attribute's values it was created with).

We tried creating a table called QuotationDataParam that contain each attribute for the other 3 tables (ProductModelName, Description, PlanName, RangeLow, RangeHigh, Bounty and Fine). But that way you can't group a PriceRange by Plans,  nor can group Plans by ProductModel.


问:
Bad sign if nobody can comprehend one's code?
If a coder writes code that nobody other than he can understand, and code reviews always end with the reviewer scratching his head or holding their head in their hands, is this a clear sign that the coder is simply not cut-out for professional programming?  Would this be enough to warrant a career change?  How important is comprehensible code in this industry?

Consider these C examples, compare:

```<code>if (b)
  return 42;
else
  return 7;
</code>```

versus:

```<code>return (b * 42) | (~(b - 1) * 7);
</code>```

Is there ever an excuse to employ the latter example? if so, when and why?

EDIT: Leaving the original latter snippet for consideration, adding a correction:

```<code>return (b * 42) | ((b - 1) & 7);
</code>```

I think the other interesting observation is that it requires that b is 1 for true and 0 for false, any other values would render strange results.

答:
If I were presented code like this in a code review, I'd have two questions to pose:

Why did we elect to write it this way?  Since bit manipulation like this is used to circumvent some sort of performance bottleneck, one would presume that we have a bottleneck that is rectified if we employ this approach instead.  An immediate follow-up question would be, "How did we prove that this was a critical bottleneck?"

Do we have any sort of acceptance framework (unit tests, etc) that prove that the optimized approach is equivalent to the non-optimized approach?  If we don't, that's when alarm bells go off, but they're not as loud as one might consider.

Ultimately, the code you write should be maintainable.  Code that is fast but difficult to broach when a bug occurs in it is not good code.  If they could satisfy both of my concerns above, then I'd probably let it go with a request to add both the justification and its equivalent, non-bit form.

In general, a code review should identify and make clear these shortcomings; if there was no justifiable reason to write the code that way, or the code is simply not correct (as a few others have pointed out here), there's no reason to have written it that way in the first place, and it must be corrected.  If this is a continuing trend; that is, a developer continues to write code that is efficient but horribly obfuscated, at that point, their lead or senior management should step in and reiterate the importance of clear code.


问:
Expectations on input / output of array dimensions and approaches to implement support for variable dimensions input arrays

Preamble

As we are vectorising our colour API, we are changing the accepted input types for most of our functions. We would be keen on keeping backward compatibility with the existing code.

Let's define the following input variables:

numeric

```<code>R
</code>```

shape: ()

A pixel R value of an RGB triplet for example.

1d

```<code>[R, G, B]
</code>```

shape: (3)

A pixel RGB values triplet for example.

2d

```<code>[[R, G, B],
 [R, G, B],
 [R, G, B],
 [R, G, B],
 [R, G, B],
 [R, G, B]]
</code>```

shape: (6, 3)

A line of RGB values triplet for example.

3d

```<code>[[[R, G, B],
  [R, G, B],
  [R, G, B]],

 [[R, G, B],
  [R, G, B],
  [R, G, B]]]
</code>```

shape: (2, 3, 3)

An image of RGB values triplet for example.

Expectations

A function that was previously accepting a numeric as input may now accept a numeric or a 1d array. A function previously accepting a 1d array as input may now accept a 1d, 2d or 3d array.

Most of our codebase vectorisation is now prototyped. Specifically, in order to support 1d, 2d or 3d arrays with functions originally taking a 1d array as input, we convert the input array to a 2d one. The inner algorithms now work with the 2d arrays thus their implementation is straightforward and predictable.

For a given function, as we modify the input array dimensions for its algorithm purpose, the resulting output array dimensions are altered (if we don't do anything about it).

We would like to know the following:

Is trying to maintain the array dimensions a commonly expected behaviour?

A path that seems logical is to maintain the dimensions of the input array: for example we suppose that somebody inputing an image (with a 3d shape) to our RGB_to_XYZ function would probably expect to get an image with a 3d shape, somebody inputing a 1d RGB pixel to that same function would probably expect to get a 1d XYZ pixel in return and not a 2d array.

An alternative path would be to enforce the expected input / output array dimensions for each function (which would break backward compatibility).

Implementations

The alternative path doesn't present any difficulties in its implementation.

The logical path is however trickier: as we have prototyped the code in that regard, we have a lot of redundant boiler plate code at the start and end of each function in order to retrieve the dimensions of the input array, change its dimensions and reshape the output array. This is not very elegant and confusing for somebody reading the code while contributing to a harder maintainability.

Is there an elegant way to implement the "logical" path behaviour?

We are thinking about a wrapper function (decorator as we are using Python) that could be responsible of handling all the dimensions / reshaping wizardry, the functions themselves could then have fixed expectations on the input / output like in the alternative path.

答:
Is trying to maintain the array dimensions a commonly expected behaviour?

To me this sounds a little like "Would people expect my API to do all these type conversions under the hood?" to which the answer is "Probably yes, but they shouldn't care either way, since they shouldn't have to worry about your implementation". Maybe you have a hyper-optimized way of frobnicating colors that only have an R-component, and that "old" overload should be calling it.

If you're trying to ask "Would people expect us to maintain backwards compatibility by supporting all the old types?" then the answer depends entirely on your user base, and we don't know anything about them. For instance, historically Microsoft Windows can't even fix bugs safely, much less change argument types. On the other hand, Python 3 "broke" one of its most basic I/O primitives, and that seems to have worked out okay. Maybe your users would even appreciate having a "clean break" from the old API. It all depends.

Is there an elegant way to implement the "logical" path behaviour?

My solution in C++ would probably look something like this:

```<code>class ColorFrobnicator {
  public:
    int frobnicate(const int R) {
        std::vector<int> colors = { R, 0, 0 };
        return actuallyFrobnicate(colors);
    }
    int frobnicate(const std::vector<int>& colors) {
        return actuallyFrobnicate(colors);
    }

  private:
    int actuallyFrobnicate(const std::vector<int>& colors) {
        /* the code that actually matters goes here */
        return finalValueAfterExtensiveFrobnication;
    }
}
</code>```

I think this is about as "elegant" as backwards compatibility can ever get: Put all the conversions and wrappers up in the interface, and move all the "real code" down into the implementation. That way none of your real code ever has to go if(oldAPI) { convertToArray(R); }, and you can easily make changes to the old or new interfaces without touching the real code.

I don't have all that much experience in Python, but I'm sure there's an equally palatable way of handling this in that language.

Body:
Is trying to maintain the array dimensions a commonly expected behaviour?

To me this sounds a little like "Would people expect my API to do all these type conversions under the hood?" to which the answer is "Probably yes, but they shouldn't care either way, since they shouldn't have to worry about your implementation". Maybe you have a hyper-optimized way of frobnicating colors that only have an R-component, and that "old" overload should be calling it.

If you're trying to ask "Would people expect us to maintain backwards compatibility by supporting all the old types?" then the answer depends entirely on your user base, and we don't know anything about them. For instance, historically Microsoft Windows can't even fix bugs safely, much less change argument types. On the other hand, Python 3 "broke" one of its most basic I/O primitives, and that seems to have worked out okay. Maybe your users would even appreciate having a "clean break" from the old API. It all depends.

Is there an elegant way to implement the "logical" path behaviour?

My solution in C++ would probably look something like this:

class ColorFrobnicator {
  public:
    int frobnicate(const int R) {
        std::vector<int> colors = { R, 0, 0 };
        return actuallyFrobnicate(colors);
    }
    int frobnicate(const std::vector<int>& colors) {
        return actuallyFrobnicate(colors);
    }

  private:
    int actuallyFrobnicate(const std::vector<int>& colors) {
        /* the code that actually matters goes here */
        return finalValueAfterExtensiveFrobnication;
    }
}

I think this is about as "elegant" as backwards compatibility can ever get: Put all the conversions and wrappers up in the interface, and move all the "real code" down into the implementation. That way none of your real code ever has to go if(oldAPI) { convertToArray(R); }, and you can easily make changes to the old or new interfaces without touching the real code.

I don't have all that much experience in Python, but I'm sure there's an equally palatable way of handling this in that language.


问:
eBook editions of programming books
(I'll get my justification for why this is on topic in early: programming books tend to have fairly specific formatting needs - code samples, tables, images and graphs - which are not common to all book types and are not necessarily well handled by eBook readers.  Similarly they're used in different ways - you often dip in and out rather than read cover to cover.)

I've just noticed that Don't Make Me Think by Steve Krug is available as an eBook edition for the Kindle (and presumably also for other readers) which set me thinking.

There are certain advantages to eBook readers for tech books - primarily that you can carry a massive library of what would be heavy physical books around very easily.  The downside is that certain eBook readers allegedly aren't particularly well equipped to cope with tables, code samples and so on and a book like Don't Make Me Think presumably makes extensive use of these sorts of things.

So, the question, what are your experiences of reading and using programming books on an eBook reader and would you recommend it? I'm specifically interested in the latest generation Kindle but happy to hear about all devices - might be useful to state which one you use in the answer.

答:
I actually have Don't Make Me Think for Kindle after finding it was significantly cheaper than the print version of the book. It's a pretty faithful rendering of the book, but with the default format settings, some pages break in the wrong places: Krug will be talking about a figure on one page but the figure itself will be 3 or 4 pages back. I still find it perfectly readable if you were reading it cover-to-cover.

Which leads to my main issue with books like that in ebook format: I have a few other books in PDF, ePub, and Kindle format, and what I've found is that they stop being references and are really only useful for reading once.

The problem is that it's very hard to "flip" through an ebook: I'm used to being able to keep my finger on one page while I quickly skim a different part of the book. With ebooks, you only get to see one page (maybe two) at a time. So it very much becomes a sequential experience: read page 1 first, then page 2, etc.

So I still prefer physical books for things I know I'm going to need to reference constantly. I really wouldn't recommend it until they figure out better ways to "flip" through a book: text-based search, which is the current workaround, isn't a good substitute.

ContentLicense: CC BY-SA 2.5

Title: eBook editions of programming books


答:
I could also use a template to generate derived classes via tagging rather than actually generating a new class each time. Something like

```<code>class BaseException {
    ...
};
template<typename T> struct DerivedException : BaseException {
    using BaseException::BaseException;
};
struct CyclicReference {};
</code>```

Then I could employ

```<code>throw DerivedException<CyclicReference>(...);
</code>```

This would mean that I could still name/specify each kind of exception, but it would not be infinitely laborious to specify each derived class individually, as it's just a separate "tag" type for each one, which I feel is much more maintainable, and users can still specify their own "tag" types or even just use the base directly. Then during testing, I can simply check the tag. And as a double bonus, I could specialize or create a new derived if I really needed more than the base.

Triple bonus: I've just discovered that re-using the tags almost certainly means duplicated code.

Title: Testing generic errors

Body:
I could also use a template to generate derived classes via tagging rather than actually generating a new class each time. Something like

class BaseException {
    ...
};
template<typename T> struct DerivedException : BaseException {
    using BaseException::BaseException;
};
struct CyclicReference {};

Then I could employ

throw DerivedException<CyclicReference>(...);

This would mean that I could still name/specify each kind of exception, but it would not be infinitely laborious to specify each derived class individually, as it's just a separate "tag" type for each one, which I feel is much more maintainable, and users can still specify their own "tag" types or even just use the base directly. Then during testing, I can simply check the tag. And as a double bonus, I could specialize or create a new derived if I really needed more than the base.

Triple bonus: I've just discovered that re-using the tags almost certainly means duplicated code.


问:
How to name a function that makes sure an element exists and returns it?
```<code>function getOrInsertEmptyElemById(id){
    var elem = $(id) || document.body.insert('<div id="'+id+'"></div>');
    return elem;
}
</code>```

I find myself using functions like the above quite often. But I struggle on naming them.

How is a make sure it exists and return function usually named?

答:
It's a guard or a guard function. The idea is that checks to make sure that some condition is true and then either continues or aborts the branching condition. It can also be regarded as a kind of filter function.

This should not to be confused with guards as they are used in Haskell and other functional style programming languages, which operate more like switches.

You might consider naming it as "NullGuard" or "NullFilter". "NullCatcher" might also be good as this pattern is also somewhat similar to the often more familiar "try, catch, finally" pattern of exception handling.


答:
Besides the excellent points made by Sparky (items 1 and 3) and Donscarletti, this post brings me to another one I answered a long time ago: How do I document my code?.

Lots of people are or call themselves programmers, some are good, not many are excellent. Just like in many other walks of life. You can decide to judge those who appear less good than you are or less good than what you would expect them to be (not very helpful, waste of time), you can try to help them (great) or coerce them to do better (you may have no choice), or ignore them and simply do your best (you may have no choice, this is sometimes the best route). Whatever your choice of action is generally depends on many factors well beyond simple technical ability.

Title: Bad sign if nobody can comprehend one's code?

Body:
If a coder writes code that nobody other than he can understand, and code reviews always end with the reviewer scratching his head or holding their head in their hands, is this a clear sign that the coder is simply not cut-out for professional programming?  Would this be enough to warrant a career change?  How important is comprehensible code in this industry?

Consider these C examples, compare:

```<code>if (b)
  return 42;
else
  return 7;
</code>```

versus:

```<code>return (b * 42) | (~(b - 1) * 7);
</code>```

Is there ever an excuse to employ the latter example? if so, when and why?

EDIT: Leaving the original latter snippet for consideration, adding a correction:

```<code>return (b * 42) | ((b - 1) & 7);
</code>```

I think the other interesting observation is that it requires that b is 1 for true and 0 for false, any other values would render strange results.


问:
3 tier architecture in .NET web applications
Nowadays most systems are designed as web apps. In the .NET world the famous three tier architecture is usually translated like this.

Front End (Web Application)

Middle Tier (custom DLLs using an ORM to access and process data)

Back End (SQL Server, Oracle, MySQL)

To me, the middle tier is not actually the middle tier because regardless of how isolated the mid tier is, it executes in the context of a web server (as it resides in the DLLs) and essentially a part of the web application.

My Questions:

Is it correct to say that a 3 tier arch is a simple 2 tier arch?

Is it correct to design the apps, that requiring heavy data processing, with no physically separate middle tier?

What options are available for the middle tier other than hosting it in WCF or Windows Service?

答:
We know that nowadays the systems are designed as web applications. Every imaginable system is either converted or planned to be converted to a web app.

Huh?

While web apps are certainly quite popular and useful, they are by no means the be-all-end-all. Here are some cases where web apps are a poor choice and a "desktop" app would be a much better fit:

Intensive client side computation. Imagine a team of 50 astrophysicists all working together plotting an extremely intricate spacefaring mission. Now imagine that their equation system solving tool (e.g. WolframAlpha) is a web app. Do you really want a queue of jobs that each take minutes or hours to compute sitting around on the webserver? And consider that most of these jobs are going to be interim results, not the final answer, so many calculations need to be performed in a serial fashion. A web app would destroy productivity; calculate on the client and only push end results.

Complicated or cascading validation rules. As a user, if I have to make 20 or 30 calls out to the webserver for validation checks when entering data, I'm going to get impatient with the app very quickly, even if each call only takes tens of milliseconds. Additionally, if the business objects are in C#, it's really aggravating to have to reproduce (and test) all the validation logic in JavaScript. A fat client prevents that code duplication and reduces user wait time.

Very high levels of security. Say a classified government facility wants to pre-encrypt all data before any transmission or storage occurs. Tightly securing data through a web application is difficult. A web app has a greater attack surface than a desktop app. And then the webserver has to decrypt the data, perform its operations, then encrypt again before storage. Or the client could do everything and push the finished encrypted data to the DB.

Minimizing maintenance and resource usage. A web app means you need a web server. But say the requirement is for a simple CRUD app that's only used in a single physical office, and the app rarely if ever changes. The users don't care if they're looking at a browser or a locally installed executable. Why complicate things by adding unnecessary components? Removing the web server from the equation makes the system simpler (meaning less chance of breakage), and reduces server and bandwidth usage.

In (very simplified) terms of three tiered architecture, the difference between a "web" and "desktop" app is where you put the middle tier: client side or server side. All of the examples above support three tiers, despite having only two physical machines (a client and a DB), because there's a difference between logical and physical tiers. If it helps, you can initially think of them as focusing on two different domains: design and deployment. Understanding these differences is an important part of system architecture and design.

Say I have a web app and find that users in Europe heavily consume a particular critical service, but the US users almost never use it. My web app servers are located in the US and can't be moved. If my middle logical tier is tied to my web app's servers, I can't break out the service and move it to a different physical location to improve EU performance. But if things are logically separated properly, I can change the physical middle tier without affecting the system's logical architecture at all.

To me, the middle tier is not actually the middle tier because regardless of how isolated the design is and how stateless the DLLs are, they execute in the context of a web server only and essentially a part of the web application.

You're conflating physical and logical tiers. If your middle tier is part of the context of the web server, then you don't really have a middle tier; you have a complex web app and a DB. If it simply resides there, then you have three logical but two physical tiers.

Is it correct to design the apps this way when there is no technical middle layer, even the applications that require heavy processing?

The only possible answer to this is "it depends", specifically on the requirements and use cases. You have a simple CRUD app? Then a middle tier probably isn't necessary (either physically or logically). Even my "heavy processing" example above functions fine on two physical tiers. But here's a real world example I worked on which would have been impossible without a middle tier: a very big client had many users in many different countries who needed many different reports. Different reports accessed different DBs and had different processing and run time requirements. So we used a middle tier which created and managed a job queue and generated the reports. Key points about why a middle tier was important:

It provided an abstract interface to the UI tier, easily able to be consumed by web or desktop apps (we had both).

It made it easy to make priority and scheduling decisions about which data to fetch from the DB and when. We had some very contentious tables, and blindly submitting many large requests for report data would kill performance.

It did work which was impossible to accomplish on the other two logical tiers. The DBs couldn't generate the reports and the clients couldn't manage the queue.

It saved doing work on the other two physical tiers. We had a lot of data which needed to be globally accessible, so pushing all of it to the client and generating the report there was not feasible. We also had very busy DBs; the DBAs would have murdered us if we'd cut out a chunk of the servers' resources for executing middleware on a VM or demanded a bunch of complicated, resource intensive jobs to run a custom queue.

Current is the only option for middle tier for a web app is a windows Service and nothing else?

Not at all. Your middle tier can be designed and deployed as almost whatever you want it to be, as long as it sits between and is distinct from the client and storage tiers. Web services, console apps, Linux servers... the list goes on.


答:
To me, the middle tier is not actually the middle tier because
  regardless of how isolated the design is and how stateless the DLLs
  are, they execute in the context of a web server only and essentially
  a part of the web application.

No, the middle tier could be in another server(s) altogether when it comes to large applications. For example you might be hosting the web frontend in one server and communicating with another server where domain model logic is hosted. Also depending on the demand of your system it could be multiple servers.

Is my observation and understanding correct that 3 tier arch is not
  really a 3 tier but a simple 2 tier arch?

Refer to the previous comment.

Is it correct to design the apps this way when there is no technical
  middle layer, even the applications that require heavy processing?

When heavy processing is required, it would not be optimal to use the web server to do the processing, as it would affect user experience and they may notice the web site is 'slow'. You could always delegate heavy/time consuming processing to some another server and display result to the user appropriately (push instead of waiting screen)

Current is the only option for middle tier for a web app is a windows
  Service and nothing else?

It could be application server with exposed web service

Scalable roles (similar to microsoft azure provides) subscribed to a queue

Title: 3 tier architecture in .NET web applications

Body:
Nowadays most systems are designed as web apps. In the .NET world the famous three tier architecture is usually translated like this.

Front End (Web Application)

Middle Tier (custom DLLs using an ORM to access and process data)

Back End (SQL Server, Oracle, MySQL)

To me, the middle tier is not actually the middle tier because regardless of how isolated the mid tier is, it executes in the context of a web server (as it resides in the DLLs) and essentially a part of the web application.

My Questions:

Is it correct to say that a 3 tier arch is a simple 2 tier arch?

Is it correct to design the apps, that requiring heavy data processing, with no physically separate middle tier?

What options are available for the middle tier other than hosting it in WCF or Windows Service?


问:
Is functional language without runtime written in C possible?
Every functional language that compiles to native code relies on quite big runtime written in C programming language (well at least ones that I know of, for example Haskell, OCaml, Gambit/Chicken Scheme, SBCL, Mercury). Basically C is used to implement all the low level stuff like garbage collection, lazyness, OS abstraction layer and etc.

I'm interested if it is even possible to implement functional programming language all in itself, without doing anything in other programming language like C? If it is possible how for example garbage collection would need to be implemented?

I know that there are some projects that somehow compile OCaml, Haskell and Erlang to run on bare bones Xen hypervisor. Does the Xen provide low level features like garbage collection or there is still some C layer involved in these projects?

Is there still any functional programming language that doesn't rely on C runtime?

答:
In principle? Yes. C is a programming language like all others. What C can do, other languages can be made to do. </p>

<p>In practice? Rarely. C is near-ubiquitous as a systems programming language (there are exceptions, but they will be provided in the outraged comments, so I don't bother listing them), and it is almost always a better idea to use what is already available than to write your own low-level OS wrapper. (There is also a bit of synergy in that many OS kernels are themselves written in C, so calling conventions etc. are a bit easier to handle when you use C). There is value in having a universal standard, even if it is such an old, warty standard as C is, therefore people rarely bother avoiding it on purpose. </p>

Body:
In principle? Yes. C is a programming language like all others. What C can do, other languages can be made to do.

In practice? Rarely. C is near-ubiquitous as a systems programming language (there are exceptions, but they will be provided in the outraged comments, so I don't bother listing them), and it is almost always a better idea to use what is already available than to write your own low-level OS wrapper. (There is also a bit of synergy in that many OS kernels are themselves written in C, so calling conventions etc. are a bit easier to handle when you use C). There is value in having a universal standard, even if it is such an old, warty standard as C is, therefore people rarely bother avoiding it on purpose.


答:
Is there still any functional programming language that doesn't rely
  on C runtime?

The answer to this exact question is yes: C is not the only low-level language  which is suitable as a compilation target (although definitely the most popular one). For example, the Embedded ML described in Functional Programming for Embedded Flight Software Development by A. J. Harris has a Forth runtime (as well as a C one).

The answer to your other question, namely "is it possible to implement a functional language all in itself", i.e. without a huge runtime written in an external language, is also yes as far as I'm concerned. Uniqueness Types, as presented in e.g. the Clean language, enable possibility to model destructive updates while maintaining a referential transparency. The Mercury language, which is mentioned in your question, has a Compile Time Garbage Collection feature, which eliminates the need for a conventional GC. Lazyness, I believe, has to be handled explicitly, i.e. you can't have true call-by-need semantics without the runtime support, but you still can implement lazy data structures which would cover most of the need for lazyness.

I believe the reason we don't see any mainstream functional languages  implemented this way is that although possible, it's rather impractical to do so, due to both efficiency and language complexity reasons.

Title: Is functional language without runtime written in C possible?

Body:
Every functional language that compiles to native code relies on quite big runtime written in C programming language (well at least ones that I know of, for example Haskell, OCaml, Gambit/Chicken Scheme, SBCL, Mercury). Basically C is used to implement all the low level stuff like garbage collection, lazyness, OS abstraction layer and etc.

I'm interested if it is even possible to implement functional programming language all in itself, without doing anything in other programming language like C? If it is possible how for example garbage collection would need to be implemented?

I know that there are some projects that somehow compile OCaml, Haskell and Erlang to run on bare bones Xen hypervisor. Does the Xen provide low level features like garbage collection or there is still some C layer involved in these projects?

Is there still any functional programming language that doesn't rely on C runtime?


问:
Functional Programming style: How to write functions - explicit currying, implicit currying or lamdas?
So I have been using F# for a while and studying a bit of Haskell on the side and I have realized I could rewrite the exact same function one of three different ways.

Either with implicit currying, explicit currying, or with lambda expressions.

```<code>//lambdas
let add'  =  fun x -> fun y -> x + y

//explicit currying
let add' x  =
   let subFunction y =
      x + y
   subFunction

//implicit currying
let add' x y = x + y
</code>```

All of these have the signature int -> int -> int. All of them do the same thing.

Which one should I use in which case?

答:
In the situations similar to the one you've described you should always use the third option, or, better yet, just let add' = (+) (but beware of Monomorhism Restriction). I see no sense in the other two definitions you have provided.

However, it's common to use nested functions in a way similar to your second example if the nested function takes auxiliary arguments, such as an accumulator in tail-recursive functions.


问:
Returning multiple values from a c function using pointers; style of parameter list
What is good programming style for writing C-language functions and function calls to functions which return pointers?

For example, if I have a function my_function which return two integers through pointer arguments. How should I call this function, such that it is easy for a person who is not familiar with my code, to see that it returns two values?

And how should I write the function definition?

For example, I could always put the return values last in the parameter list, and
when I call the function, I could add some extra space to separate input arguments from return values.

Also, for the function definition, I could add an empty line with a comment between the input parameters and the return values. For example:

void my_function(
   int a,
   int b,
/* return values */
   int *c,
   int *d)
{
   /* do something */
}

int main()
{
   int a = 1;
   int b = 2;
   int c;
   int d;

   my_function(a,b,   &c, &d);
}
```

答:
You could note the flow of  information in the function definition:

```<code>void my_function(
   /*  in */ int  a,
   /*  in */ int  b,
   /* out */ int* c,
   /* out */ int* d)
{
   /* do something */
}
</code>```

This way, it's easy to see what happens. If you export this function, you will also include the comments in the prototype so that everybody could see the direction of information flow.

Furthermore, adhere to one style in your functions. For example, if you write the return values always on the end of the parameter list and someone sees you calling

```<code>whatever(p1, p2, p3, &p4);
</code>```

one will know that there's a high probability that p4 is the return value of your function.

Body:
You could note the flow of  information in the function definition:

void my_function(
   /*  in */ int  a,
   /*  in */ int  b,
   /* out */ int* c,
   /* out */ int* d)
{
   /* do something */
}

This way, it's easy to see what happens. If you export this function, you will also include the comments in the prototype so that everybody could see the direction of information flow.

Furthermore, adhere to one style in your functions. For example, if you write the return values always on the end of the parameter list and someone sees you calling

whatever(p1, p2, p3, &p4);

one will know that there's a high probability that p4 is the return value of your function.


问:
Is it bad practice to make methods public solely for the sake of unit testing?
I have a class with a public method. It has other methods that 'assist' with the purpose of the public method. The public method must be tested. However, I also want to unit test the private methods.

It would be impossible for my unit tests to call private methods and test them in isolation, so they must be public.

The problem here is that I'm left with code that, I feel, has been written with a lack of respect for OOP convention, purely for the sake of being able to unit test it.

Am I right in amending the access of methods purely for 'testability'? Or should I be rethinking and refactoring the structure as a whole to separate out the functionality of the private methods (despite the fact they don't do a lot at all and may, at times, resemble small helper methods)?

答:
If you have methods 'assisting', chances are your single, big method is actually doing too much. Splitting into smaller methods and then moving these methods into separate classes with public interfaces keeps the class with the big method responsible for one thing and one thing only (see Single Responsibility Principle). This move into separte classes automatically makes for a testable structure as your methods must be made public.

An example

Take a BankAccount-class that does budget calculations by looking at a list of Expenditures it contains. An Expenditure has a category (sports, food, car,...), an amount and a date. You might have a method on BankAccount called "CalculateExpenditureFor" taking a begin and enddate and a category. That method would filter the Expenditures to only have Expenditures that match the date and category and then proceed to sum up the amounts. Take note of the amount of 'ands' I need to express that requirement! This is clear indication that your method does too much.

This method will actually do two things: filter the expenditures and sum up the amounts. Now imagine your BankAccount contains an ExpenditureLedger-class, which contains the Expenditures (a 'ledger' is a book or file containing a list of financial transactions, hence the name). You could then have a FilterExpenditures-method on the ExpenditureLedger which takes care of the filtering on date and category. The resulting list of Expenditures can then be used by the BankAccount to tally up the amounts.

In this scenario, you have a public method on the ExpenditureLedger that can be tested (you feed the ledger Expenditures and check the result). You can also check the BankAccount-method by feeding it a (preferably mocked) ExpenditureLedger so you can test the code that sums up the amounts returned by the ExpenditureLedger.


问:
Micro-services architecture and reporting services?
as I understand it micro-services are autonomous and have complete control over their own data and therefor each micro-service has a dedicated database.

I was wondering what would be the approach to implement reporting in a micro-services architecture, if reports depend on data that exists in multiple databases where each database is governed by its own micro-service.

答:
I'm not exactly sure why a micro-service should have 'complete control over their own data'. What I understood is, that a micro-service should be stateless.
That means it should not depend its 'action' on some state (possible from a database), but only from the 'input' data (eg: message) - therefore it's action should be repeatable when the 'same' input triggers the action at any given time.

A service which depends on 'changing-over-time' reporing data may not have those properties, but it totally depends on your use-cases. If you 'just' trigger the generation of a report, the output may (and must) change over time.

Perhaps a micro-service architecture may not be the best fit for a reporting applicaction...


答:
Yes it is very bad practice - you're letting your tools make design decisions for you.

I think the main problem here is that you're trying to treat each individual method as a unit. This is generally the cause of all unit test woes. Except for some cases where your method is very complex and requires a lot of testing, you should be treating your classes as units. Martin Fowler even treats related classes as a unit too (sometimes).

As a result, you should be instantiating a class, then calling method(s) on its public interface as it would be used. This gives you your examples for your documentation, and ensures it works as the whole thing is intended. You should be trying here to test the private methods by calling the public ones - and if a private method is never called, then why do you still have it in code?

Title: Is it bad practice to make methods public solely for the sake of unit testing?

Body:
I have a class with a public method. It has other methods that 'assist' with the purpose of the public method. The public method must be tested. However, I also want to unit test the private methods.

It would be impossible for my unit tests to call private methods and test them in isolation, so they must be public.

The problem here is that I'm left with code that, I feel, has been written with a lack of respect for OOP convention, purely for the sake of being able to unit test it.

Am I right in amending the access of methods purely for 'testability'? Or should I be rethinking and refactoring the structure as a whole to separate out the functionality of the private methods (despite the fact they don't do a lot at all and may, at times, resemble small helper methods)?


答:
You should not have to change your unit tests if you have only changed internal implementation details and not the API.  The fact that your old tests still work after a change is the proof that your changes have not broken things.  You can look at the commit log, see that absolutely nothing in the test code has changed and feel reassured (as long as your tests were good in the first place).

Now, you are proposing a design which forces changes to your tests when you alter implementation.  You destroy that confidence.  There will always be a risk that changes have been made to the genuine public API tests in the course of testing implementation changes.

Either your object hierarchy is wrong and those methods should be public on some other object, or they are implementation details to your object and you are wasting time testing them (and risking making your whole design more fragile).  Test the contract.

An important question is "Why do you want to test them?"  If these methods are in the right place and not relevant to external code then you need to stop being a control freak, shake off your OCD and trust the system.  If not testing them really is a problem, your current object hierarchy (or your API design) is wrong.


答:
I'd use a tool to document the code. E.g. with doxygen you can write:

```<code>/**
 *  \brief Performs something and stores result in \a c and \a d
 *
 *  \param[in]  a ...
 *  \param[in]  b ...
 *  \param[out] c ...
 *  \param[out] d ...
 *
 *  Detailed description here.
 */
void my_function(int a, int b, int *c, int *d)
{
   /* do something */
}
</code>```

The special comment block has a simple structure (it's a C comment block with some additional markings). So it's easy to read and, at the same time, allows to extract documentation.

Ordering function parameters so that all input-only parameters are before any output parameters is quite common in C but it isn't the only option (e.g. memcpy).

Anyway the most important aspect is a uniform code style.

As a general rule I try to avoid OUT parameters whenever possible.

Also consider that:

in the C standard there are precedents for returning structures that contain all the results (the div / ldiv / C99 lldiv functions from <stdlib.h>);

mixing return value and return parameters is usually the least clean option (but having a function that return a status and return data via OUT parameters is sensible in C).

Somewhat related:

What is best practice on ordering parameters in a function?

Google C++ Style Guide. Why input-then-output parameter ordering?

Title: Returning multiple values from a c function using pointers; style of parameter list

Body:
What is good programming style for writing C-language functions and function calls to functions which return pointers?

For example, if I have a function my_function which return two integers through pointer arguments. How should I call this function, such that it is easy for a person who is not familiar with my code, to see that it returns two values?

And how should I write the function definition?

For example, I could always put the return values last in the parameter list, and
when I call the function, I could add some extra space to separate input arguments from return values.

Also, for the function definition, I could add an empty line with a comment between the input parameters and the return values. For example:

void my_function(
   int a,
   int b,
/* return values */
   int *c,
   int *d)
{
   /* do something */
}

int main()
{
   int a = 1;
   int b = 2;
   int c;
   int d;

   my_function(a,b,   &c, &d);
}
```

Body:
I'd use a tool to document the code. E.g. with doxygen you can write:

/**
 *  \brief Performs something and stores result in \a c and \a d
 *
 *  \param[in]  a ...
 *  \param[in]  b ...
 *  \param[out] c ...
 *  \param[out] d ...
 *
 *  Detailed description here.
 */
void my_function(int a, int b, int *c, int *d)
{
   /* do something */
}

The special comment block has a simple structure (it's a C comment block with some additional markings). So it's easy to read and, at the same time, allows to extract documentation.

Ordering function parameters so that all input-only parameters are before any output parameters is quite common in C but it isn't the only option (e.g. memcpy).

Anyway the most important aspect is a uniform code style.

As a general rule I try to avoid OUT parameters whenever possible.

Also consider that:

in the C standard there are precedents for returning structures that contain all the results (the div / ldiv / C99 lldiv functions from <stdlib.h>);

mixing return value and return parameters is usually the least clean option (but having a function that return a status and return data via OUT parameters is sensible in C).

Somewhat related:

What is best practice on ordering parameters in a function?

Google C++ Style Guide. Why input-then-output parameter ordering?