答:
In general, you don't want any implementation details exposed in the API.  msw and VoiceofUnreason's answers are both communicating that, so it's important to pick up on.

Keep in mind the principle of least astonishment, especially since you're worried about idempotence. Take a look at some of the comments in the article you posted (https://stormpath.com/blog/put-or-post/); there is a lot of disagreement there about how the article presents idempotence. The big idea that I would take away from the article is that "Identical put requests should cause identical results". I.e. If you PUT an update to a company's name, the company's name changes and nothing else changes for that company as a result of that PUT. The same request 5 minutes later should have the same effect.

An interesting question to think about (check out gtrevg's comment in the article): any PUT request, including a full update, will modify dateUpdated even if a client doesn't specify it. Wouldn't that make any PUT request violate idempotency?

So back to the API. General things to think about:

Implemenation details exposed in the API should be avoided

If the implementation changes, your API should still be intuitive and easy-to-use

Documentation is important

Try not to warp the API to get performance improvements

Title: How to design a complex REST API considering DB performance?

Body:
I've been following some tutorials on how to design REST APIs, but I still have some big questions marks. All these tutorials show resources with relatively simple hierarchies, and I would like to know how the principles used in those apply to a more complex one. Furthermore, they stay at a very high/architectural level. They barely show any relevant code, let alone the persistence layer. I'm specially concerned about database load/performance, as Gavin King said:

you will save yourself effort if you pay attention to the database at
  all stages of development

Let's say my application will provide training for Companies. Companies have Departments and Offices. Departments have Employees. Employees have Skills and Courses, and certain Level of certain skills are required to be able to sign for some courses. The hierarchy is as as follows, but with :

-Companies
  -Departments
    -Employees
      -PersonalInformation
        -Address
      -Skills (quasi-static data)
        -Levels (quasi-static data)
      -Courses
        -Address
  -Offices
    -Address
```

<p>Paths would be something as:</p>

<pre class="lang-none prettyprint-override"><code>companies/1/departments/1/employees/1/courses/1
companies/1/offices/1/employees/1/courses/1
</code>```

Fetching a resource

So ok, when returning a company, I obviously don't return the whole hierarchy companies/1/departments/1/employees/1/courses/1 + companies/1/offices/../. I might return a list of links to the departments or the expanded departments, and have to take the same decission at this level: do I return a list of links to the department's employees or the expanded employees? That will depend on the number of departments, employees, etc.

Question 1: Is my thinking correct, is "where to cut the hierarchy" a typical engineering decission I need to make?

Now let's say that when asked GET companies/id, I decide to return a list of links to the department collection, and the expanded office information. My companies don't have many offices, so joining with the tables Offices and Addresses shouldn't be a big deal. Example of response:

GET /companies/1

200 OK
{
  "_links":{
    "self" : {
      "href":"http://trainingprovider.com:8080/companies/1"
      },
      "offices": [
            { "href": "http://trainingprovider.com:8080/companies/1/offices/1"},
            { "href": "http://trainingprovider.com:8080/companies/1/offices/2"},
            { "href": "http://trainingprovider.com:8080/companies/1/offices/3"}
      ],
      "departments": [
            { "href": "http://trainingprovider.com:8080/companies/1/departments/1"},
            { "href": "http://trainingprovider.com:8080/companies/1/departments/2"},
            { "href": "http://trainingprovider.com:8080/companies/1/departments/3"}
      ]
  }
  "name":"Acme",
  "industry":"Manufacturing",
  "description":"Some text here",
  "offices": {
    "_meta":{
      "href":"http://trainingprovider.com:8080/companies/1/offices"
      // expanded offices information here
    }
  }
}
```

<p>At the code level, this implies that (using Hibernate, I'm not sure how it is with other providers, but I guess that's pretty much the same) I won't put a collection of <code>Department</code> as a field in my <code>Company</code> class, because:</p>

<ul>
<li>As said, I'm not loading it with <code>Company</code>, so I don't want to load it eagerly</li>
<li>And if I don't load it eagerly, I might as well remove it, because the persistence context will close after I load a Company and there is no point in trying to load it afterwards (<code>LazyInitializationException</code>).</li>
</ul>

<p>Then, I'll put a <code>Integer companyId</code> in the <code>Department</code> class, so that I can add a department to a company.</p>

<p>Also, I need to get the ids of all the departments. Another hit to the DB but not a heavy one, so should be ok. The code could look like:</p>

```@Service
@Path("/companies")
public class CompanyResource {

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CompanyParser companyParser;

    @Path("/{id}")
    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response findById(@PathParam("id") Integer id) {
        Optional<Company> company = companyService.findById(id);
        if (!company.isPresent()) {
            throw new CompanyNotFoundException();
        }
        CompanyResponse companyResponse = companyParser.parse(company.get());
        // Creates a DTO with a similar structure to Company, and recursivelly builds
        // sub-resource DTOs such as OfficeDTO
        Set<Integer> departmentIds = companyService.getDepartmentIds(id);
        // "SELECT id FROM departments WHERE companyId = id"
        // add list of links to the response
        return Response.ok(companyResponse).build();
    }
}
```

```@Entity
@Table(name = "companies")
public class Company {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private String industry;

    @OneToMany(fetch = EAGER, cascade = {ALL}, orphanRemoval = true)
    @JoinColumn(name = "companyId_fk", referencedColumnName = "id", nullable = false)
    private Set<Office> offices = new HashSet<>();

    // getters and setters
}
```

```@Entity
@Table(name = "departments")
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private Integer companyId;

    @OneToMany(fetch = EAGER, cascade = {ALL}, orphanRemoval = true)
    @JoinColumn(name = "departmentId", referencedColumnName = "id", nullable = false)
    private Set<Employee> employees = new HashSet<>();

    // getters and setters
}
```

Updating a resource

For the update operation, I can expose an endpoint with PUT or POST. Since I want my PUT to be idempotent, I can't allow partial updates. But then, if I want to modify the company's description field, I need to send the whole resource representation. That seems too bloated. The same when updating an employee's PersonalInformation. I don't think it makes sense having to send all the Skills + Courses together with that.

Question 2: Is PUT just used for fine-grained resources?

I've seen in the logs that, when merging an entity, Hibernate executes a bunch of SELECT queries. I guess that's just to check if anything has changed and update whatever information needed. The upper the entity in the hierarchy, the heavier and more complex the queries. But some sources advise to use coarse grained resources. So again, I'll need to check how many tables are too much, and find a compromise between resource granularity and DB query complexity.

Question 3: Is this just another "know where to cut" engineering decission or am I missing something?

Question 4: Is this, or if not, what is the right "thinking process" when designing a REST service and searching for a compromise between resource granularity, query complexity and network chattiness?


问:
How do I design my application to use REST for itself?
I'm not sure how to ask this.  I know this is simplistic, but I understand (I think):

REST is an architecture, not required, simply a way to build

REST is a style and a community standard for transfer of data

REST uses verbs and nouns, mostly the latter, GET, POST, PUT,
DELETE...

As I read I only see the architecture from the consumers point of view and the creator of the API for the consumer.

What I cannot find is how to do this for just my application.  What if I'm not sharing anything with anyone at the moment.  I want to build my application to follow this architecture for the future.

What do I do now?  If I want to use this type of construct:

Examples:

PUT http://www.example.com/customers/12345

PUT http://www.example.com/customers/12345/orders/98765

PUT http://www.example.com/buckets/secret_stuff

I my application, when I create a new person, I use an HTML <form action="something.php" method=POST>  Now how do I do this with PUT?  Where does this go?

If I use http://www.example.com/customers/12345 how do I know within my application that I want to PUT or GET or whatever?

I'm using MVC, where's my action?  I realize the consumer might use my architecture/service with nouns, but this is for only me.  How do I know what to do, if I can't use PUT in a form tag?

Right now I use my PHP page to grab the query string based upon a RewriteRule:

```<code>require_once("database\\adapters\\PDO\\Database.bootstrap.php");
class App {
    protected $_controller = 'Welcome';
    protected $_method = 'index';
    protected $_params = [];
    protected $_model = 'Welcome';

    public function __construct(){
    $url = $this->parseURL();
    //This works because I put the rewrite rules in IIS;
    //Our RewriteRule in IIS (or Apache) is ^(.+)$  This is any character saved to a variable.
    //The new location is index.php?url=$1 [QSA, L].  This will look a little different after you import it into IIS.

    if (file_exists('app\\controllers\\' . $url[0] . '.controller.php')){
        $this->_controller = $url[0];
        $this->_model = $url[0];
        unset($url[0]);  //Unset removes that element from the array;
        //var_dump($url);
    }

    //Get the controller and model.  All done by convention over configuration;
    require_once 'app\\controllers\\' . $this->_controller . '.controller.php';
    require_once 'app\\models\\Parent.model.php';

    //get a new Database object from the bootstrap;
    $_DB = new DatabaseBootstrap();

    $this->_controller = $this->_controller . "Controller";

    $this->_model = new ParentModel($_DB->getAdapter());
    $this->_controller = new $this->_controller($this->_model);

    //This checks to see if our method from the url exists;
    //Your querystring will look like this - http://server/virtualdirectory/controller/action/variables1/variable2.....

    if(isset($url[1])){
        if(method_exists($this->_controller,$url[1])){
            $this->_method = $url[1];
            unset($url[1]);
        }
    }

    $this->_params = $url ? array_values($url) : [];

    //This calls your controller and your method and sends over your array of parameters
    call_user_func_array([$this->_controller, $this->_method],$this->_params)
}

public function parseURL(){
    if(isset($_GET['url'])){
        return $url = explode('/',filter_var(rtrim($_GET['url'],'/'),FILTER_SANITIZE_URL));
        }
    }
</code>```

EDIT:  Based upon my reading of the answers, it appears I cannot use REST natively as in using HTTP verbs.  I either have to use the name of the types in AJAX or I have to have a hidden field that contains my REST method like so (example from cakePHP):

```<code><form id="RecipeEditForm" method="post" action="/recipes/edit/5">
<input type="hidden" name="_method" value="PUT" />
</code>```

And it seems this is done for the "greater good."  That is, so that others can consume my API services using libraries such as curl or using AJAX where one can create any request method they wish (?).  Since we are using a REST architecture, the consumer using the API would simply put PUT, DELETE, etc.  Some future architecture might not use those verbs, so we make up new keywords.  It's just that PUT, etc. are in the w3 specs for HTTP, which are not very well supported.?

答:
I my application, when I create a new person, I use an HTML  Now how do I do this with PUT? Where does this go?

You don't.  If you are using html as your representation of application state, then the links you provide in your hypertext use GET or POST.  Yes, you can try to fake PUT/DELETE via post, but the client isn't going to recognize those actions as idempotent, nor will the various caches, reverse proxies, etc between your server and the application.  Don't fight the tides; you'll get far fewer surprises down the road.

If you take HTML out of the picture, the story changes.  For instance, if you are going to use JSON as the representation of state, your resources can support the PUT and DELETE methods directly.

There's no reason that your server can't do both.  Provide html representations of the application state with GET/POST links, and provide json representations with application state that includes PUT/DELETE links as well.  The basic plot is that when a client arrives at your service, you give them the representation that matches the content-type the client supports, and from that point, the client simply follows the links that your server provides.

The resources are not necessarily 1-1.  For instance, if you want an idempotent "create", using a PUT is perfect... but not in HTML, where put isn't supported.  You'll probably end up doing a POST, and to a different resource.  So at the representation level, you've got more work to do than just transforming the json to html.

If I use http://www.example.com/customers/12345 how do I know within my application that I want to PUT or GET or whatever?

Link relations and media types.  That is, the link in your application state includes meta data that describes the kind of link it is, and the documentation of your api tells the application programmer what meanings are associated with that link.

For example, review the Paged Feeds specification.  The application state provides the url and the link relation.  Your api specification explains the semantics of the relation.

```<code><link
    rel="http://www.example.com/docs/links/relations/create"
    href="http://www.example.com/customers/12345"
    ...
/>
</code>```

Using the identifier of the documentation as the spelling of the link relation makes it really easy for developers to find the docs, but it's not required to do that; you'll have noticed that the Paged Feeds specification uses spellings "next", "previous", and so on.

ContentLicense: CC BY-SA 3.0

Body:
I my application, when I create a new person, I use an HTML  Now how do I do this with PUT? Where does this go?

You don't.  If you are using html as your representation of application state, then the links you provide in your hypertext use GET or POST.  Yes, you can try to fake PUT/DELETE via post, but the client isn't going to recognize those actions as idempotent, nor will the various caches, reverse proxies, etc between your server and the application.  Don't fight the tides; you'll get far fewer surprises down the road.

If you take HTML out of the picture, the story changes.  For instance, if you are going to use JSON as the representation of state, your resources can support the PUT and DELETE methods directly.

There's no reason that your server can't do both.  Provide html representations of the application state with GET/POST links, and provide json representations with application state that includes PUT/DELETE links as well.  The basic plot is that when a client arrives at your service, you give them the representation that matches the content-type the client supports, and from that point, the client simply follows the links that your server provides.

The resources are not necessarily 1-1.  For instance, if you want an idempotent "create", using a PUT is perfect... but not in HTML, where put isn't supported.  You'll probably end up doing a POST, and to a different resource.  So at the representation level, you've got more work to do than just transforming the json to html.

If I use http://www.example.com/customers/12345 how do I know within my application that I want to PUT or GET or whatever?

Link relations and media types.  That is, the link in your application state includes meta data that describes the kind of link it is, and the documentation of your api tells the application programmer what meanings are associated with that link.

For example, review the Paged Feeds specification.  The application state provides the url and the link relation.  Your api specification explains the semantics of the relation.

<link
    rel="http://www.example.com/docs/links/relations/create"
    href="http://www.example.com/customers/12345"
    ...
/>

Using the identifier of the documentation as the spelling of the link relation makes it really easy for developers to find the docs, but it's not required to do that; you'll have noticed that the Paged Feeds specification uses spellings "next", "previous", and so on.


问:
When is it appropriate to make a separate function when there will only ever be a single call to said function?
We are designing coding standards, and are having disagreements as to if it is ever appropriate to break code out into separate functions within a class, when those functions will only ever be called once.

For instance:

```<code>f1()
{
   f2();
   f4();
}

f2()
{
    f3()
    // Logic here
}

f3()
{
   // Logic here
}

f4()
{
   // Logic here
}
</code>```

versus:

```<code>f1()
{
   // Logic here
   // Logic here
   // Logic here
}
</code>```

Some argue that it is simpler to read when you break up a large function using separate single-use sub functions. However, when reading code for the first time, I find it tedious to follow the logic chains and optimize the system as a whole. Are there any rules typically applied to this sort of function layout?

Please note that unlike other questions, I am asking for the best set of conditions to differentiate allowable and non-allowable uses of single call functions, not just if they are allowed.

答:
I think function naming is very important here.

A heavily dissected function can be very self-documenting. If each logical process within a function is split out into its own function, with minimal internal logic, then the behavior of each statement can be reasoned out by the names of the functions and the parameters they take.

Of course, there is a downside: the function names. Like comments, such highly specific functions can often get out of sync with what the function is actually doing. But, at the same time, by giving it a proper function name you make it harder to justify scope creep. It becomes more difficult to make a sub-function do something more than it clearly ought to.

So I would suggest this. If you believe a section of code could be split out, even though nobody else calls it, ask yourself this question: "What name would you give it?"

If answering that question takes you more than 5 seconds, or if the function name you pick is decidedly opaque, there's a good chance that it isn't a separate logical unit within the function. Or at the very least, that you're not sure enough about what that logical unit is really doing to properly split it out.

But there is an additional problem that heavily dissected functions can encounter: bug fixing.

Tracking down logical errors within a 200+line function is hard. But tracking them through 10+ individual functions, while trying to remember the relationships between them? That can be even harder.

However again, semantic self-documentation through names can play a key role. If each function has a logical name, then all you need to do to validate one of the leaf functions (besides unit testing) is to see if it actually does what it says it does. Leaf functions tend to be short and focused. So if every individual leaf function does what says it should, then the only possible problem is that someone passed them the wrong stuff.

So in that case, it can be a boon to bug fixing.

I think it really does come down to the question of whether you can assign a meaningful name to a logical unit. If so, then it can probably be a function.


答:
DRY - Don't repeat yourself - is just one of several principles that have to be balanced.

Some other that come to mind here are naming. If the logic is convoluted not obvious to the casual reader, extraction into  method/function whose name better encapsulated what and why it is doing it it can improve program readability.

Also aiming for less than 5-10 lines of code method/function may come into play, depending on how many lines the //logic becomes.

Also, a function with parameters can act as an api and can name the parameters appropriately to then make the code logic clearer.

Also you may find that over time collections of such functions do reveal dome useful grouping, e.g. admin and then they can be easily gathered under it.

Title: When is it appropriate to make a separate function when there will only ever be a single call to said function?

Body:
We are designing coding standards, and are having disagreements as to if it is ever appropriate to break code out into separate functions within a class, when those functions will only ever be called once.

For instance:

```<code>f1()
{
   f2();
   f4();
}

f2()
{
    f3()
    // Logic here
}

f3()
{
   // Logic here
}

f4()
{
   // Logic here
}
</code>```

versus:

```<code>f1()
{
   // Logic here
   // Logic here
   // Logic here
}
</code>```

Some argue that it is simpler to read when you break up a large function using separate single-use sub functions. However, when reading code for the first time, I find it tedious to follow the logic chains and optimize the system as a whole. Are there any rules typically applied to this sort of function layout?

Please note that unlike other questions, I am asking for the best set of conditions to differentiate allowable and non-allowable uses of single call functions, not just if they are allowed.


问:
Resuming a project where you left off
Sometimes when I resume work on a project after a long break, I forget where in the many files and lines I stopped working.  I can usually find it after a minute, but I'm wondering if any popular IDEs have a built-in way to indicate where you stopped working.

I currently use XCode/C++, but I'm curious if other IDEs have this feature.

Obviously I could make an additional file, and I'll do that if there isn't a more elegant way.

答:
Just check the last commit you made to the versioning system,be it a local repository or a remote centralized one. You can list the files changed in that last commit and get a diff report. That should pretty well tell you where you left off.

If you don't use a source code versioning system, then you should.

Title: Resuming a project where you left off


问:
Exposing blocking API in golang?
I have a golang library that abstracts a network service (think IRC-alike). The network server produces events which users of my library should consume. I'm using blocking network calls internally. I want to design my API to minimise friction users of my library, so i'm trying to decide between

having the user supply func callbacks to mylib.doStuff(), which would enter my library's blocking network loop; it would be up to the caller to background this into a goroutine if they wished (and then perform their own synchronisation as necessary); or

having the user call mylib.startDoingStuff(), which would spawn a background goroutine to handle the blocking network calls, returning multiple channels of events for the caller to select over. It has the advantage of isolating the goroutine and the blocking from the calling code.

What's more idiomatic? What would you expect to see in a network library?

答:
I found a resource on the topic:

https://inconshreveable.com/07-08-2014/principles-of-designing-go-apis-with-channels/

https://www.reddit.com/r/golang/comments/2acr79/principles_of_designing_go_apis_with_channels/

In the end, i'm convinced a channel-based API is probably the way forward (at least for a v1 package), following the example of stdlib crypto/ssh.

However, the above link did strongly caution against implementing a channel-based API, mentioning a range of pitfalls (adequately describing buffer limits, edge case behavior, exhaustion behavior and so on)

Title: Exposing blocking API in golang?


问:
Project Cleanup and Version Control Best Practices
Question Background:

I have a rather large project that I started before I learned about a beautiful thing called version control. Now, I have a ton of files labeled with the convention "ProjectName_Date."

Question:

I'm thinking of deleting the old files and starting a new repository with the latest version. However, is that a good practice? Would it be better to try to maintain that history by figuring out what changes were made between files and then store everything in a repository? Or is it better to start from scratch and not risk setting up a questionable repository?

What I've done:

I know the question is subjective, but I've read different articles (like the one here) about best practices and can't find anything helpful regarding this type of issue. It seems like everything assumes that you're starting from scratch.

Any advice in the form of experience or an article is appreciated.
Thanks!

答:
I'd say, do not bother with the old snapshots.

Commit current state into the repo and start using it as soon as possible.

Just backup the old snapshots and in a couple of month you will not even remember they've existed.

From experience, when we migrated from CVS to GIT, the old CVS source control was left there for reference, but after a few month nobody needed to ever look at it.

Better invest your time into learning your source control system.


答:
Pretty much depends on what your // Logic Here is.

If it's a one-liner, then probably you don't need a functional decomposition.

If, on the other hand, it's lines and lines of code, then it is much better to put it into a separate function and name it appropriately (f1,f2,f3 does not pass muster here).

This is all have to do with human brains on average are not very efficient with processing large amounts of data at a glance.  In a sense, it does not matter what data: multi-line function, busy intersection, 1000-piece puzzle.

Be a friend of your code maintainer's brain, cut down on pieces in the entry point.  Who knows, that code maintainer may even be you a few month later.


问:
Is there any downside to commit messages containing the ticket number
I was wondering if it would be good practice for commit messages to contain the ticket number they were apart of. It would be like

```<code>    2568 Fix heating issue

    Summary of the issue with a bunch of detailed comments
</code>```

It would be a bit of a pain to get the ticket or isse # in each commit and I am wondering if people think it would be worth it in the long run. Also if my branch has the ticket number is this redundant? The main issue is that I use source tree and that in the log / history view it can get a little complicated to see what commit corresponds with what ticket. I just would like a better way to see how everything works.

答: Including reference numbers (tickets, features, requirements, etc.) in commit messages is a great idea.  But it should never be a substitute for a good message.  At my current employer, we're now on our second source control system, our third ticketing system, and our second requirements management system.  Needless to say, the old systems' data were never migrated into their replacements, and even if they were, the numbering systems overlap.


答:
The "right" answer, according to the prevalent coding dogmas, is to split large functions into small, easy to read, testable and tested functions with self documenting names.

That said, defining "large" in terms of "lines of code" can seem arbitrary, dogmatic, and tedious, which can cause unnecessary disagreements, scruples, and tension. But, fear not! For, if we recognize that the primary purposes behind the lines-of-code limit are readability and testability, we can easily find the appropriate line-limit for any given function! (And start building the foundation for an internally relevant soft-limit.)

Agree as a team to allow the megalithic functions, and to extract lines into smaller, well-named functions at the first sign that the function is either difficult to read as a whole, or when subsets are uncertain in correctness.

... And if everyone is honest during the initial implementation, and if none of them are touting an IQ over 200, the limits of understandability and testability can often be identified before anyone else sees their code.


问:
REST API paging via headers
Let's say I have REST API which provides me list of something and I want to implement paging support - possibility to tell "give me records 20-29 (page 3)". Currently, I don't care about implementation server-side, but about how client tell API he want specific page.

You can pass it in URI (/some-list?page=3) or send it via POST data (you can't use it with GET), but what about headers? Is it good practice (or against something)?

Can I use range or some custom X- header to define, which page (or offset and length) I want to receive?

//EDIT: I also don't care about SEO, search engines etc. My use case is API used internaly in my code.

答:
For pagination, you should be considering the techniques described in RFC 5005.  Roughly, each page of results is a separate resource, which itself contains hyperlinks to the previous/next page of results.  Then, as usual, the application can just follow the links to navigate from one application state to the next.

The actual spelling of the uri doesn't matter too much.  You could treat the ranges as part of the query parameters, or as separate resources under a pages collection, or...

```<code>/some-list?page=3
/some-list/3
/some-list/pages/3
/some-list/records/20?order=ascending&limit=10
</code>```

You'll want to give some thought to whether page 3 "now" has the same representation as page 3 at some other time.  If not, you may want to have these resources redirect to another identifier that has a better caching lifetime.

Some apis will identify paging resources by putting the pagination data in the path; which isn't a great fit if you believe that the path should represent the position of a resource in a hierarchy.  Query parameters are a much better fit.

As what you are doing is a safe query (no changes to server state), GET, rather than POST, is certainly the correct method to be considering.

Even if you need to allow the client to specify the query parameters (as opposed to defining the pagination links within the hypermedia), you should still be treating this as a simple GET.  The heuristic to justify this choice is the behavior of a web browser, which packs parameters into the query string when a form with the get action is submitted.  It works, it's stateless, the browser is still following a link contained within the application state.

If you aren't describing the application state with an html representation, then UriTemplates are a reasonable approach to representing the link.  You could document the contraints on the parameters are part of the definition of the link relation.

Title: REST API paging via headers

Body:
For pagination, you should be considering the techniques described in RFC 5005.  Roughly, each page of results is a separate resource, which itself contains hyperlinks to the previous/next page of results.  Then, as usual, the application can just follow the links to navigate from one application state to the next.

The actual spelling of the uri doesn't matter too much.  You could treat the ranges as part of the query parameters, or as separate resources under a pages collection, or...

/some-list?page=3
/some-list/3
/some-list/pages/3
/some-list/records/20?order=ascending&limit=10

You'll want to give some thought to whether page 3 "now" has the same representation as page 3 at some other time.  If not, you may want to have these resources redirect to another identifier that has a better caching lifetime.

Some apis will identify paging resources by putting the pagination data in the path; which isn't a great fit if you believe that the path should represent the position of a resource in a hierarchy.  Query parameters are a much better fit.

As what you are doing is a safe query (no changes to server state), GET, rather than POST, is certainly the correct method to be considering.

Even if you need to allow the client to specify the query parameters (as opposed to defining the pagination links within the hypermedia), you should still be treating this as a simple GET.  The heuristic to justify this choice is the behavior of a web browser, which packs parameters into the query string when a form with the get action is submitted.  It works, it's stateless, the browser is still following a link contained within the application state.

If you aren't describing the application state with an html representation, then UriTemplates are a reasonable approach to representing the link.  You could document the contraints on the parameters are part of the definition of the link relation.


问:
REST API vs directly DB calls in Desktop Application
I am currently planing an application that will be used in a company. It is required to build a Desktop Application. At the moment they are not sure if the application should be available on mobile or browser in the near future.

I have two possibilities:

Access the database directly from the Desktop Application

Create a REST API and connect to this

Can I use a REST API if the application stays just a Desktop Application within the company? I know that it's possible, but is it "the right" way? (Best practices)

There are some (possible) advantages and disadvantages for creating directly a REST API:

Disadvantages:

Takes longer to develop

More complex

The server does more work

̶Se̶̶c̶̶u̶̶r̶̶i̶̶t̶̶y̶̶ ̶̶i̶̶s̶̶s̶̶u̶̶e̶̶s̶̶?̶

Slower? (The server and the Desktop Application are on the same Network)

Advantages:

Migrating to other platforms is easier

The Business Logic is also needed when calling directly the database. It won't take much longer to develop

Same goes for complexity

Security (as mentioned by tkausl in the comments)

Maintainability (as mentioned by WindRaven in the comments)

答:
When it comes to a large applications with huge database containing milions of records, you soon realize, plain selects, updates, inserts and deletes simply are not enough.

So you start thinking in a different way. You create procedures and triggers to take care of more complicated stuff directly in the database and this is not very good. Databases offer great performance when performing CRUD operations. Long procedures? Not so much.

The problem with procedures

Now imagine, that you switch to a database which does not support the concept of procedures? What are you going to do? You are forced to move the procedures to your code base instead, where you can be pretty sure that once you program it in let's say Java, it will always stay there, no matter which database engine you choose.

Not to mention, your procedures are usually part of your business logic and it is not a good idea to have your business logic splatered across your codebase and database.

Ideally, you should always have a mediator between the database and the client implementing its own business rules. Providing direct access to database is not a good idea, because when you do so, the one with access has direct access to the tables and can do pretty much anything with the data there is.

Disadvantages

Takes longer to develop: Of course, you are creating a new system, that is going to be more time consuming than simply giving the client a database connection string and let him write the queries.

More complex: Complexity  of a system > complexity of a database query.

The server does more work: Not necessarily. With good design, caching,... you can move the load from the database server to the one of the mediator.

Slower: In terms of development? Yes. In terms of speed when retrieving data? No. You can optimize your mediator using caches (such as - popular as of January 2016 - Redis, Elasticsearch) and actually make it deliver data faster than a plain database query.

Advantages

Migrating to other platforms is easier: Migrating to a new database engine? Definitely. Migrating the whole mediator to a new language? Not really.

The Business Logic is also needed when calling directly the database. It won't take much longer to develop: As explained previously, the procedures problem.

Security: With proper authorization having mediator is definitely much more secure than giving a user direct access to the database, because you restrict him to the end points which run only the queries you want to.

Maintainability: One of the best benefits of having a mediator. If there is a bug in an API your clients call, you fix it, push the fix to your VCS repository, build your mediator from the currect version of VCS containing the fix and all your clients are suddenly using the fix, without them needing to download an update. This is simply impossible to do, if the queries are stored directly in the client applications. In that case, clients are forced to update their application.


答:
If you only have to update/patch/support a single version, then just starting the repository with your last version is a perfectly good idea. Keep a backup of the old versions, just in case, but I'd expect it to be unlikely you'll need it.

However, if you have to support multiple versions of your project, I would recommend making a commit per each of the versions you have to support (don't bother with committing intermediate versions, just make sure to keep a backup of them just in case), and tag them accordingly. For obsolete versions that you no longer have to provide support for, just treat them as if they were non-official versions and don't commit them.

Title: Project Cleanup and Version Control Best Practices

Body:
Question Background:

I have a rather large project that I started before I learned about a beautiful thing called version control. Now, I have a ton of files labeled with the convention "ProjectName_Date."

Question:

I'm thinking of deleting the old files and starting a new repository with the latest version. However, is that a good practice? Would it be better to try to maintain that history by figuring out what changes were made between files and then store everything in a repository? Or is it better to start from scratch and not risk setting up a questionable repository?

What I've done:

I know the question is subjective, but I've read different articles (like the one here) about best practices and can't find anything helpful regarding this type of issue. It seems like everything assumes that you're starting from scratch.

Any advice in the form of experience or an article is appreciated.
Thanks!


答:
What you have there is version control. I think we can all agree that it is a pretty crappy form of version control, but you at least do have different versions, even if you don't have commit messages.

Why throw away that history?

From what I can gather from your description, it's a three-line script and a matter of minutes to import that history into a VCS. Better to have it than to not have it. It probably took you more time to write this question than it will take to write the script and perform the import.

Something like:

```<code>#!/bin/sh

for projectversion in /tmp/project/ProjectName_*; do
  versiondate=`basename $projectversion | sed -e 's/ProjectName_//'`
  rm -rf *
  mv $projectversion/* .
  git add .
  GIT_AUTHOR_NAME=multiple GIT_AUTHOR_EMAIL=multiple GIT_AUTHOR_DATE=$versiondate git commit -m "Automatically import version $versiondate."
done
</code>```

[NOTE: I didn't check this, and it definitely isn't properly quoted, so use at your own risk. It's just a sketch. Oh, and it also turned out to be seven lines, not three :-D ]

If you have some sort of ChangeLog or NEWS file, you could also use that as the commit message.

Body:
What you have there is version control. I think we can all agree that it is a pretty crappy form of version control, but you at least do have different versions, even if you don't have commit messages.

Why throw away that history?

From what I can gather from your description, it's a three-line script and a matter of minutes to import that history into a VCS. Better to have it than to not have it. It probably took you more time to write this question than it will take to write the script and perform the import.

Something like:

#!/bin/sh

for projectversion in /tmp/project/ProjectName_*; do
  versiondate=`basename $projectversion | sed -e 's/ProjectName_//'`
  rm -rf *
  mv $projectversion/* .
  git add .
  GIT_AUTHOR_NAME=multiple GIT_AUTHOR_EMAIL=multiple GIT_AUTHOR_DATE=$versiondate git commit -m "Automatically import version $versiondate."
done

[NOTE: I didn't check this, and it definitely isn't properly quoted, so use at your own risk. It's just a sketch. Oh, and it also turned out to be seven lines, not three :-D ]

If you have some sort of ChangeLog or NEWS file, you could also use that as the commit message.


答:
Here's my opinion on the matter: You have the right idea of wanting to use a webservice, but you may be planning on using the wrong tech.

When you say REST, I'm assuming you're talking about Asp.Net WebApi. That's the wrong tech for intranet applications. REST & WebApi are awesome, don't get me wrong, but for any kind of internal application, WCF web services are the way to go in my humble opinion. They allow the client to reference the service endpoint just like a class library, which means you're not dealing in XML or JSON in your desktop client. You're working with classes & objects.

Anyway, yes. You've got the right idea. If they're not sure if they'll need a web based client, then you have to architect your system to easily add it if they decide they want it later. It's much easier to add different types of clients when you have a service oriented architecture.

Title: REST API vs directly DB calls in Desktop Application

Body:
I am currently planing an application that will be used in a company. It is required to build a Desktop Application. At the moment they are not sure if the application should be available on mobile or browser in the near future.

I have two possibilities:

Access the database directly from the Desktop Application

Create a REST API and connect to this

Can I use a REST API if the application stays just a Desktop Application within the company? I know that it's possible, but is it "the right" way? (Best practices)

There are some (possible) advantages and disadvantages for creating directly a REST API:

Disadvantages:

Takes longer to develop

More complex

The server does more work

̶Se̶̶c̶̶u̶̶r̶̶i̶̶t̶̶y̶̶ ̶̶i̶̶s̶̶s̶̶u̶̶e̶̶s̶̶?̶

Slower? (The server and the Desktop Application are on the same Network)

Advantages:

Migrating to other platforms is easier

The Business Logic is also needed when calling directly the database. It won't take much longer to develop

Same goes for complexity

Security (as mentioned by tkausl in the comments)

Maintainability (as mentioned by WindRaven in the comments)


答:
Any time you feel the need to write a comment to describe what a block of text is doing, you have found an opportunity to extract a method.

Rather than

```<code>//find eligible contestants
var eligible = contestants.Where(c=>c.Age >= 18)
eligible = eligible.Where(c=>c.Country == US)
</code>```

try

```<code>var eligible = FindEligible(contestants)
</code>```

Body:
Any time you feel the need to write a comment to describe what a block of text is doing, you have found an opportunity to extract a method.

Rather than

//find eligible contestants
var eligible = contestants.Where(c=>c.Age >= 18)
eligible = eligible.Where(c=>c.Country == US)

try

var eligible = FindEligible(contestants)


问:
TDD with a half baked Java EE application
I am a second year Computer Science student currently on a placement and I am currently developing a Java EE application that collects meta data from several sources and then visualises the data. This is the first major programming project I have done. (Nothing like university with 200 lines of code for an assignment)

I am about half of the way through the development of this application and have learnt an incredible amount. One of those things is TDD. From learning this I have gained an understanding of how important testing is and how it can help speed up development.

The reason for the back story is to cover for my ignorance. My university hasn't taught it to me and it is non-existent at my work place. I am incredibly keen in making sure I follow best practice in everything I do and I would like to include it in my application as I feel it would bring many benefits.

The problems I have though, are:

My application (like many I am sure) will contact several external sources. Take my message consumer for example. It will contact up to 3 remote restful interfaces and a database. The URLS of these apis are dynamic and are only accessible once the application has loaded the properties file (which has to be modified by the application user).

I feel it would be difficult to retro-fit the tests on a system that hasn't been built in a TDD manner.

I practically don't have time to retro-fit/ learn how to do advanced TDD with java EE applications.

As it isn't practice at all in my work place I wouldn't be able to ask questions or be corrected on if what I was doing is best.

Should I just accept defeat on this project as I am too far in and going forward I should just enforce TDD on everything I can? (where it is practical of course).

I'm just concerned that any future potential employers might look at my work from this placement and think less of me because lack of good practice. (Not worried what the current company thinks as it isn't a thing and they are very happy with my project.)

答:
There are a lot of articles, books, blogposts, conference talks... that deal with this issue. Michael Feathers' Working Effectively With Legacy Code is by many considered to be one of, if not THE best books on the subject. There is a twelve-page PDF available for free online that formed the basis of the book and should serve as a good starting point. Don't be fooled by the term 'legacy code': yesterday I've seen code written just last week that wasn't properly structured and hard to test and I consider that 'legacy' as well.

Remember that TDD, as any aspect of development, is also a learning experience. I've been doing TDD for years now and my style has grown and evolved as I've written and maintained test code, read books, heard talks on the subject, etc... In that regard you probably shouldn't be concerned with future employers. As long as you can prove that you evolve and learn (which you do in adopting TDD-practices) they probably won't hold it against you.


问:
At what point in a projects life-cycle do you begin writing tests?
I'm not in the field, so I don't have any professional experience from projects following the TDD design. I am trying to adopt this pattern, but I'm confused as to when I start actually writing the tests. In my example, a personal blogging app. I'm starting from complete scratch using ASP.NET 5, MVC 6. I've built the main functionality such as displaying the homepage, allowing login using Identity, allowing the posting of a blog post, and retrieval of those blog posts through an MVC controller as well as an API.

This is all done using the Repository pattern, and MVVM.

At what point in that process should I really begin testing?

Do I test that the repository does what it should do? That smells weird to me, since repositories are injectable.

Do I test that the ViewModel has certain properties?

Or is it acceptable to simply start with testing whether a valid ViewModel allows creation of a new BlogPost, and an invalid does not?

答:
TDD revolves mostly around unit testing, this answer is going to cover that.

Why do you make applications? Do you make them to see see that C# works well, or do you make them to solve a problem presented by your client (be aware, sometimes the client may as well be you)?

Unless you are a .NET developer working for the Microsoft company and are actually responsible for maintaining the C# language, it is almost always the second case. You are trying to solve a problem, a problem, which has some rules.

The rules presented to you are your business logic, your domain. Once you start working on your domain, that is the latest when you should start writing tests.

Latest? Yes. Speaking from a position of a senior PHP developer, even though it is nice that PHP allows you to do a lot of stuff a compiled language would not (such as returning two completely different objects from a method), it leads to bad code. Hence in many cases, it is better to just write your database layer and not be dependent on an already existing solution with static methods etc. If you do build this layer, you might consider writing tests for that as well, to make sure what you wrote works.

Generally speaking, there's never too early to start writing unit tests, but there's a point where it becomes too late and unnecessary. Such as unit testing your controlers. I have seen people do that and that is not what unit test should do. Your controllers are a procedure, containing factories for services, instantiating them, working with your domain objects, they are not units. If you want to test your controllers, use integration test suites instead.

What should always be tested then?

You want to have unit tests for your domain, your business logic. If you have that and your business rules are indeed only there, you do not really need to worry about the rest of the application, as it should only perform basic CRUD operations on data, which is valid (thanks to tests and good domain models).

TDD From the life-cycle point of view

TDD means you write tests first and then you write code. When you are working on a project, you go through several stages.

Chosing the right technology - You do not know which programming language you are going to choose, yet, thus cannot simply write tests.

Chosing your architectural model - You chose the programming language, but have no idea how your project will be structured. Will it be modules, services, MVC? In your case it is most likely going to be the MVVM pattern. Is your whole architecture considered a unit? I don't think so. You do not need to test architecting your application.

Designing your domain layer - this is the part, where you take user functional and non-functional requirements along with the rules from the client and implement them. Before this stage you are supposed to write tests and then provide implementation to make them pass.

(optional) Designing services, which use your domain models - You may create services uniting more domain operations into one process, much like a facade. You may write tests before designing these services, but it's an optional task.

As said before, to make sure your application (the wiring part) works as intended, you should use integration tests instead of unit testing.


问:
Efficient Repeating Alarm Clock in Low Level Language like C
I was thinking about it and I was curious as to how one would code an efficient repeating alarm clock in C? Would you set an alarm time and then offset the time with the ms time equivalent of a day (or two days or a week depending on how often it needed to repeat)? And then poll periodically to see if the times are equal? That sounds like a very inefficient solution, to me at least. I was am interested in how an alarm clock would work programatically.</p>

答:
There's numerous ways to acheive this, all depending on what kind of environment you're working with. Another concern is of course the latency you can afford.

If you are working on a modern operating system, you most likely have an API that will put your thread to sleep until the given time has arrived. Posix has nanosleep() and C11 has the thread_sleep() function to do this.

If you're on more primitive operating systems or programming directly for embedded hardware you may have to resort to waiting for periodic interrupts, or even using busy loops.

Update: To handle multiple alarms using the thread_sleep() approach, you could for instance store all coming alarms in a sorted list. Sleep until the first alarm triggers, do what you're supposed to and then calculate the time until the next alarm and go back to sleep. This approach uses only one timer thread, which will be very efficient as long as it satisfies your latency requirements.


答:
At what point in that process should I really begin testing?

Well, you asked specifically about tdd, so there's really only one correct answer: Before you do anything else.

Test-Driven Development and Design is called Test-Driven, because the Tests drive the development and design. The tests tell you when to start writing code. They tell you what to write. They tell you how to write it. They tell you what to write next. Very importantly, they tell you when you are done writing.

In order to do that, they have to exist. The very first thing you do, before you do anything else, is writing a test.

Note: I'm not saying that this is the only way to go about this, but you asked about TDD, and if you don't follow this, then it's not TDD.

The general TDD cycle looks like this (it's actually 4 cycles, nested 3 levels deep):

Pick a user story (how you do this is outside the scope of TDD, you can use Scrum or XP, for example, for figuring out which story to pick next).

Write the simplest acceptance test that could possibly fail for the acceptance criteria of that user story.

Run your acceptance tests.

Watch the acceptance test (and only that test!) you just wrote fail.

Verify that it fails for the right reasons.

As long as the test fails, repeat:

Pick an independent unit of behavior

Write the simplest unit test that could possibly fail for that unit of behavior

Run your unit tests.

Watch the unit test (and only that test!) you just wrote fail.

Verify that it fails for the right reasons.

As long as the test fails, repeat:

Write the simplest code that could possibly change the error message

As soon as the test passes, as long as there is something to improve, repeat:

Refactor Mercilessly

Keith Braithwaite has created an exercise he calls TDD As If You Meant It. It consists of a set of rules (based on Uncle Bob Martin's Three Rules of TDD, but much stricter) that you must strictly follow and that are designed to steer you towards applying TDD more rigorously. It works best with pair programming (so that your pair can make sure you are not breaking the rules) and an instructor.

You can read about it more in these two questions:

How to do Test Driven Development

Cheap implementations in fundamental TDD

Title: At what point in a projects life-cycle do you begin writing tests?

Body:
I'm not in the field, so I don't have any professional experience from projects following the TDD design. I am trying to adopt this pattern, but I'm confused as to when I start actually writing the tests. In my example, a personal blogging app. I'm starting from complete scratch using ASP.NET 5, MVC 6. I've built the main functionality such as displaying the homepage, allowing login using Identity, allowing the posting of a blog post, and retrieval of those blog posts through an MVC controller as well as an API.

This is all done using the Repository pattern, and MVVM.

At what point in that process should I really begin testing?

Do I test that the repository does what it should do? That smells weird to me, since repositories are injectable.

Do I test that the ViewModel has certain properties?

Or is it acceptable to simply start with testing whether a valid ViewModel allows creation of a new BlogPost, and an invalid does not?


问:
Why does the overriding rule of C++ not care about visibility changes?
In C++, it is possible to write an overriding for a base class's method even if the visibility declaration of the two don't match.
What are the possible design considerations under the decision of not considering the visibility in the overriding rule?

Consider this piece of code as an example:

```<code>class A{
    public: virtual void f() { cout << "A::f" << endl; }
};

class B : public A {
    private: void f() { cout << "B::f" << endl; }
};

int main() {
    A* a = new B;
    a->f();
}
</code>```

The above compiles in clang, and running it prints B::f, showing that it is possible to call a private function of B from outside the class, thus breaking encapsulation.

I don't really see why this type of behavior should be allowed. It is clearly not for performance/efficiency reasons, since checking statically that two visibility declarations match is trivial. Does anybody have an idea or hypothesis about what could possibly be the design decision behind this?

答:
The above compiles in clang, and running it prints B::f, showing that
  it is possible to call a private function of B from outside the class,
  thus breaking encapsulation.

The encapsulation isn't broken. It's B that's semi-broken. B publicly inherits from A. A's public interface is B's public interface. The real question is why B should be permitted to even create a private override of a public function.

Simple fact is, there's just no real reason to ban it. If you're writing B and do so correctly, this should never happen in reality. Unless you explicitly intended it for some reason, in which case, congratulations.


问:
Handling Multiple Collections in C#
I'm currently trying to learn C# and want to enhance my understanding of Object Oriented Programming (OOP). I'm hoping to accomplish this by experimenting with a small program that keeps track of my school assignments/information. I've constructed classes relating to my Institutions, Semesters(Terms), Courses, and Assignments. My question is whether or not I have created and implemented my classes correctly in regards to the information they represent. My thinking suggests that my classes should not inherit from one another in a parent/child like fashion because they are physically unrelated. However accessing objects through multilevel lists seems impractical (I think).. Is there a better way of doing this that doesn't force me to access object by iterating through collections, but still implements OOP best practices?

Program Source Code

Entry Point / Main

```<code>static void Main(string[] args)
{
    List<Institution> Institutions = new List<Institution>();
    Institutions.Add(new Institution("My college"));
    Institutions[0].AddNewTerm("2016", "Spring");
    Institutions[0].Terms[0].AddNewCourse("Math 210");
    Institutions[0].Terms[0].Courses[0].AddNewAssignment("Chapter 1");
    MessageBox.Show(Institutions[0].Terms[0].Courses[0].Assignments[0].Name);
}
</code>```

Class List

Institution

```<code>class Institution
{
    public string Name { get; set; }
    public List<Term> Terms { get; set; }

    public Institution(string UP_Name)
    {
        this.Name = UP_Name;
        this.Terms = new List<Term>();
    }

    public void AddNewTerm(string NewTermYear, string NewTermSeason)
    {
        Terms.Add(new Term(NewTermYear, NewTermSeason));
    }
}
</code>```

Term

```<code>class Term
{
    public string Name { get; set; }
    public string Year { get; set; }
    public string Season { get; set; }
    public List<Course> Courses { get; set; }

    public Term(string NewSeason, string NewYear)
    {
        this.Season = NewSeason;
        this.Year = NewYear;
        this.Courses = new List<Course>();
        this.Name = (this.Season + " " + this.Year);

    }

    public void AddNewCourse(string NewCourseName)
    {
        this.Courses.Add(new Course(NewCourseName));
    }
}
</code>```

Course

```<code>class Course
{
    public string Name { get; set; }

    public List<Assignment> Assignments { get; set; }

    public Course(string UP_Name)
    {
        this.Name = UP_Name;
        this.Assignments = new List<Assignment>();
    }

    public void AddNewAssignment(string NewAssignmentName)
    {
        Assignments.Add(new Assignment(NewAssignmentName));
    }

}
</code>```

Assignment

```<code>class Assignment
{
    public string Name { get; set; }

    public Assignment(string UP_Name)
    {
        this.Name = UP_Name;
    }
}
</code>```

答:
I do have some further insight that I can provide. First, about your classes, since the name of an institution should probably remian the same and not change, upon instantiation is the only time that you should allow external implementation to modify that string for the Name -- make it immutable from the class perspective. This would be proper encapsulation; a getter which is publicly accessible and any setter functionality as private. Same principle applies to other fields within other classes. Additionally, overriding the ToString() method for user-defined objects is usually always fairly useful in cases where the object has a string representation.

Keep in mind, you can also create your own collection types by implementing a class that implements IList or ICollection for instance, among other interfaces. If you want your object to be enumerable via a foreach loop then consider IEnumerable as well. Unless you have specific guidelines as to how your class should be used, the idea is generally to keep the implementation as general as possible for scalability reasons.

As for the naming conventions, there are .NET naming conventions that you might want to follow and make part of your habit from MSDN (https://msdn.microsoft.com/en-us/library/ms229002(v=vs.110).aspx). Typically locals use camelCase rather than PascalCase.

If your intention is to gear the implementation towards strings, then indexed properties as mentioned before may be the best case for this. As most examples show, the paradigm looks a lot similar to any of the .NET provided TryParse() methods to avoid an exception from being thrown but allow indication of whether the action succeeded or not too.

I don't see a reason for Aggregation here because the heirchy to me looks like it should be as follows: Institution -> Semester -> Terms -> Courses -> Assignments. None of the lower level objects should exist without a parent in my opinion. A semester from my past experience was the equivalent of 2 terms. What you probably want in this case in terms of object relationship is Composition.

Title: Handling Multiple Collections in C#


答:
It's absolutely intentional. Changing the visibility must (at most) change whether your code compiles or doesn't compile. It must never, ever change what the code does. If B::f() were public, then you would expect B::f() to be called. The fact that you made b::f() private cannot change this, according to the rule above; it is only allowed to change whether code compiles. Since the caller didn't even need to know about class B, the code must compile and call B::f(). </p>

<p>There is no breaking of encapsulation here. In class A you declared that f is a virtual function which can be called by anyone through an instance of A. Subclasses cannot do anything to change that. If a developer thought that makeing B::f() private prevented the virtual function from being called, then that developer is just deluded. </p>

Title: Why does the overriding rule of C++ not care about visibility changes?

Body:
In C++, it is possible to write an overriding for a base class's method even if the visibility declaration of the two don't match.
What are the possible design considerations under the decision of not considering the visibility in the overriding rule?

Consider this piece of code as an example:

```<code>class A{
    public: virtual void f() { cout << "A::f" << endl; }
};

class B : public A {
    private: void f() { cout << "B::f" << endl; }
};

int main() {
    A* a = new B;
    a->f();
}
</code>```

The above compiles in clang, and running it prints B::f, showing that it is possible to call a private function of B from outside the class, thus breaking encapsulation.

I don't really see why this type of behavior should be allowed. It is clearly not for performance/efficiency reasons, since checking statically that two visibility declarations match is trivial. Does anybody have an idea or hypothesis about what could possibly be the design decision behind this?

Body:
It's absolutely intentional. Changing the visibility must (at most) change whether your code compiles or doesn't compile. It must never, ever change what the code does. If B::f() were public, then you would expect B::f() to be called. The fact that you made b::f() private cannot change this, according to the rule above; it is only allowed to change whether code compiles. Since the caller didn't even need to know about class B, the code must compile and call B::f().

There is no breaking of encapsulation here. In class A you declared that f is a virtual function which can be called by anyone through an instance of A. Subclasses cannot do anything to change that. If a developer thought that makeing B::f() private prevented the virtual function from being called, then that developer is just deluded.


答:
Usually you can't write a test for a method before at least the declaration of the method has been written, because the test won't compile. And you can't run the test before at least an empty definition for the method is written, because the test won't link. So the best order is: </p>

<p>(a) Plan what you want to do. (b) Write the declaration for the method. (c) Write the unit test. (d) Write an empty definition of the method. (e) Run the unit test, making sure that a failure is reported. (f) Implement the method. (g) Run unit tests again to make sure that they succeed. (h) With your new insight into the problem improve the unit tests, and improve the method as needed. </p>

Body:
Usually you can't write a test for a method before at least the declaration of the method has been written, because the test won't compile. And you can't run the test before at least an empty definition for the method is written, because the test won't link. So the best order is:

(a) Plan what you want to do. (b) Write the declaration for the method. (c) Write the unit test. (d) Write an empty definition of the method. (e) Run the unit test, making sure that a failure is reported. (f) Implement the method. (g) Run unit tests again to make sure that they succeed. (h) With your new insight into the problem improve the unit tests, and improve the method as needed.


问:
Should `Vector<float>.Equals` be reflexive or should it follow IEEE 754 semantics?
When comparing floating point values for equality, there are two different approaches:

NaN not being equal to itself, which matches the IEEE 754 specification.

NaN being equal to itself, which provides the mathematical property of Reflexivity which is essential to the definition of an Equivalence relation

The built in IEEE floating point types in C# (float and double) follow IEEE semantics for == and != (and the relational operators like <) but ensure reflexivity for object.Equals, IEquatable<T>.Equals (and CompareTo).

Now consider a library that provides vector structs on top of float/double. Such a vector type would overload ==/!= and override object.Equals/IEquatable<T>.Equals.

What everybody agrees on is that ==/!= should follow IEEE semantics. The question is, should such a library implement the Equals method (which is separate from the equality operators) in a way that's reflexive or in a way that matches the IEEE semantics.

Arguments for using IEEE semantics for Equals:

It follows IEEE 754

It's (possibly much) faster because it can take advantage of SIMD instructions

I've asked a separate question on stackoverflow about how you'd express reflexive equality using SIMD instructions and their performance impact: SIMD instructions for floating point equality comparison

Update: It seems like it's possible to implement reflexive equality efficiently using three SIMD instructions.

The documentation for Equals doesn't require reflexivity when involving floating point:

The following statements must be true for all implementations of the Equals(Object) method. In the list, x, y, and z represent object references that are not null.

x.Equals(x) returns true, except in cases that involve floating-point types. See ISO/IEC/IEEE 60559:2011, Information technology -- Microprocessor Systems -- Floating-Point arithmetic.

If you're using floats as dictionary keys you're living in a state of sin and should not expect sane behaviour.

Arguments for being reflexive:

It's consistent with existing types, including Single, Double, Tuple and System.Numerics.Complex.

I don't know any precedent in the BCL where Equals follows IEEE instead of being reflexive. Counter examples include Single, Double, Tuple and System.Numerics.Complex.

Equals is mostly used by containers and search algorithms which rely on reflexivity. For these algorithms a performance gain is irrelevant if prevents them from working. Don't sacrifice correctness for performance.

It breaks all hash based sets and dictionaries, Contains, Find, IndexOf on various collections/LINQ, set based LINQ operations (Union, Except, etc.) if the data contains NaN values.

Code that does actual computations where IEEE semantic is acceptable usually works on concrete types and uses == / != (or more likely epsilon comparisons).

You currently can't write high performance computations using generics since you need arithmetic operations for that, but these aren't available through interfaces/virtual methods.

So a slower Equals method wouldn't affect most high performance code.

It's possible to provide an IeeeEquals method or an IeeeEqualityComparer<T> for the cases where you either need the IEEE semantics or you need to performance advantage.

In my opinion these arguments strongly favour a reflexive implementation.

Microsoft's CoreFX team plans to introduce such a vector type in .NET. Unlike me they prefer the IEEE solution, mainly due to the performance advantages. Since such a decision certainly won't be changed after a final release, I want to get feedback from the community, on what I believe to be a big mistake.

答:
There is a problem: IEEE754 defines relational operations and equality in a way that is well-suited to numerical applications. It is not well-suited to sorting and hashing. So if you want to sort an array based on numerical values, or if you want to add numerical values to a set or use them as keys in a dictionary, you either declare that NaN values are not allowed, or you don't use IEEE754 built-in operations. Your hash table would have to make sure that all NaNs are matched to the same value, and compare equal to each other. </p>

<p>If you define Vector then you have to make the design decision whether you want to use it for numerical purposes only or whether it should be compatible with sorting and hashing. I personally think that the numerical purpose should be much more important. If sorting / hashing is needed then you can write a class with Vector as a member and define hashing and equality in that class the way you like. </p>

Body:
There is a problem: IEEE754 defines relational operations and equality in a way that is well-suited to numerical applications. It is not well-suited to sorting and hashing. So if you want to sort an array based on numerical values, or if you want to add numerical values to a set or use them as keys in a dictionary, you either declare that NaN values are not allowed, or you don't use IEEE754 built-in operations. Your hash table would have to make sure that all NaNs are matched to the same value, and compare equal to each other.

If you define Vector then you have to make the design decision whether you want to use it for numerical purposes only or whether it should be compatible with sorting and hashing. I personally think that the numerical purpose should be much more important. If sorting / hashing is needed then you can write a class with Vector as a member and define hashing and equality in that class the way you like.


答:
The point about splitting functions is all about one thing: simplicity.

A reader of code cannot have more than about seven things in mind simultaneously. Your functions should reflect that.

If you build too long functions, they will be unreadable because you have much more than seven things inside your functions.

If you build a ton of one-line functions, readers similarly get confused in the tangle of functions. Now you would have to keep more than seven functions in your memory to understand the purpose of each one.

Some functions are simple even though they are long. The classic example is when a function contains one big switch statement with many cases. As long as the handling of each case is simple, your functions is not too long.

Both extremes (the Megamoth and the soup of tiny functions) are equally bad, and you have to strike a balance in between. In my experience, a nice function has something around ten lines. Some functions will be one-liners, some will exceed twenty lines. The important thing is that each function serves an easily understandable function while being equally understandable in its implementation.


问:
Java need to call many methods systematically
I have a group of methods that is going to be very large. I need to be able to call methods systematically from a large group, in two different ways.
The methods create a new item object with variables specific to the type of item created, for instance the rubber(); method makes an item with

```<code>itemId = 12, weight = 1, name = "Rubber", ...
</code>```

for 20+ more variables.
I am currently able to call these by name

```<code>object.rubber();
</code>```

I want to be able to call them by itemId

```<code>object.getById(12);
</code>```

I need to be able to process them by itemId for situations like this:

```<code>/* itemId:
1: ruined copper
2: weak copper
3: refined copper
4: ruined iron
5: weak iron
6: refined iron
7: ruined brass
-(More metals in this pattern)-
36: sturdy aluminum
*/

//within furnace class

public void smelt(item input, inventory furnace){
//input is the item to smelt, furnace is the furnace's crucible.

    if(input.getId() < 36 && input.getId()%3 = 1){
    //if the imput's ID is less than 36, it's a metal, and if ID % 3 = 1, it's a ruined metal, meaning it is smeltable.

        furnace.addItem(handler.list.addById(input.getId() + 1))
        //add an item to the furnace with an ID one higher than that of the input, which will be a 'weak' metal of the same type

        furnace.removeItem(input);
        //delete the input item
    }
}
</code>```

The metals are all regularly ordered, so if I can call them by ID it will be possible to manipulate them with very little code, whereas otherwise the furnace will need an if statement for each individual metal to determine what it smelts into. Many other processes will need to be able to work similarly.

I've found two possible solutions so far:

one would be to use reflect to call the methods, but I've been warned that it's notoriously unstable and difficult to figure out.

the other would be to overhaul my current system and store the item properties on a text file, something like

```<code>Ruined_Copper false 4 256 ...
Weak_Copper false 4 128 ...
etc.
</code>```

and then have a filereader open the file and count lines until the line number equaled the target itemId. It would then split the line by whitespace and assign the values to variables, ie:

```<code>newItem.setName(lineOutput(1));
newItem.setIsContainer(lineOutput(2));
...
</code>```

This would output an item with

```<code>name=Ruined_Copper, isContainer = false, etc.
</code>```

I'd prefer to figure this out early in development so I don't have to change thousands of items to a new format in the future.
Which one of these will go faster? Which one will be more stable? Is there a better way alltogether?

EDIT: To clarify, I realize that it would be a bad idea to have metals 0-36, woods 37-56, etc. My goal is to allow systematic or player-created items to be added by player actions in game, so the finished product will have space between catagories, ie 0-60 are metals, 61-999 are blank, 1000-1085 are wood types, 1086-1999 are blank, etc.

答:
When developing games it is often a good idea to separate the game engine from the game content by moving such information to external files. It allows to tinker with values without having to recompile the game, it allows non-programmers to edit these files and it makes the game more modding-friendly.

However, keep in mind that file access is very slow compared to memory access. Therefor, you should parse such files once at startup and store the information in memory.

If you want to look up objects by number, you can use an ArrayList<ItemType>. If you want to look up objects by name, you could use a HashMap<String, ItemType>.

Using ID numbers with certain "magic" ranges will bite you back sooner or later. When the items 0-36 are metal, what will you do if you some day decide that you want to add even more kinds of metals to the game? You would have to extend that range into a range which might already be taken by non-metal items, which then need to be renumbered. This can turn quite ugly, for example with backward-compatibility of savegames. Or what if you decide that you would like to have metals with more or less than three quality levels?

A better design would be if the item ID number itself carries no inherent information and that information is also read from the config file:

```<code>name="Ruined Copper", weight=1, category="metal", qualityLevel=0, smeltsTo="Weak Copper"
name="Weak Copper", weight=2, category="metal", qualityLevel=1
</code>```

Body:
When developing games it is often a good idea to separate the game engine from the game content by moving such information to external files. It allows to tinker with values without having to recompile the game, it allows non-programmers to edit these files and it makes the game more modding-friendly.

However, keep in mind that file access is very slow compared to memory access. Therefor, you should parse such files once at startup and store the information in memory.

If you want to look up objects by number, you can use an ArrayList<ItemType>. If you want to look up objects by name, you could use a HashMap<String, ItemType>.

Using ID numbers with certain "magic" ranges will bite you back sooner or later. When the items 0-36 are metal, what will you do if you some day decide that you want to add even more kinds of metals to the game? You would have to extend that range into a range which might already be taken by non-metal items, which then need to be renumbered. This can turn quite ugly, for example with backward-compatibility of savegames. Or what if you decide that you would like to have metals with more or less than three quality levels?

A better design would be if the item ID number itself carries no inherent information and that information is also read from the config file:

name="Ruined Copper", weight=1, category="metal", qualityLevel=0, smeltsTo="Weak Copper"
name="Weak Copper", weight=2, category="metal", qualityLevel=1


答:
```<code>if(input.getId() < 36 && input.getId()%3 = 1){
//if the imput's ID is less than 36, it's a metal, and if ID % 3 = 1, it's a ruined metal, meaning it is smeltable.
</code>```

Giving magic meaning to the id numbers is asking for trouble. What if you want add a new type of metal? What about removing one? What about adding a new state? Multiply this across all the different types of items in your game, and you have disaster looming.

one would be to use reflect to call the methods, but I've been warned
  that it's notoriously unstable and difficult to figure out.

Unstable usually means either something that crashes a lot or something that changes a lot. Neither of these are true of reflection. Its also really not difficult. However, reflection is slow, prevents the compiler from checking your code as much, renders refactoring tools ineffective, and generally indicates a poor design.

the other would be to overhaul my current system and store the item
  properties on a text file

I'm a big fan of configuration. Whenever possible, I like to put details in configuration rather than code. This reduces duplication and boilerplate. It follows the rule of least power. There are a few different ways to do this:

One way is a text file as you  mention. I wouldn't recommend a plain text file, I'd use YAML or JSON as a basic syntax. That you get the parsing for free, and various tools to help you work with it.

Another way is java enums. Java enums are objects and you can attach extra data and methods to them. I've soured on enums a bit because its tempting to switch on them when you should add a property, and can't create enums at runtime. (It's useful to be able to construct arbitrary combinations of properties in tests)

Another way is simple to create immutable objects in java. With the text file approach, you eventually create java objects from the data. You could also just create the java objects directly. This is somewhat nice because you don't have to switch out of java to modify your objects. On the other hand, its harder to develop/use tools that manipulate the data.

Title: Java need to call many methods systematically

Body:
I have a group of methods that is going to be very large. I need to be able to call methods systematically from a large group, in two different ways.
The methods create a new item object with variables specific to the type of item created, for instance the rubber(); method makes an item with

```<code>itemId = 12, weight = 1, name = "Rubber", ...
</code>```

for 20+ more variables.
I am currently able to call these by name

```<code>object.rubber();
</code>```

I want to be able to call them by itemId

```<code>object.getById(12);
</code>```

I need to be able to process them by itemId for situations like this:

```<code>/* itemId:
1: ruined copper
2: weak copper
3: refined copper
4: ruined iron
5: weak iron
6: refined iron
7: ruined brass
-(More metals in this pattern)-
36: sturdy aluminum
*/

//within furnace class

public void smelt(item input, inventory furnace){
//input is the item to smelt, furnace is the furnace's crucible.

    if(input.getId() < 36 && input.getId()%3 = 1){
    //if the imput's ID is less than 36, it's a metal, and if ID % 3 = 1, it's a ruined metal, meaning it is smeltable.

        furnace.addItem(handler.list.addById(input.getId() + 1))
        //add an item to the furnace with an ID one higher than that of the input, which will be a 'weak' metal of the same type

        furnace.removeItem(input);
        //delete the input item
    }
}
</code>```

The metals are all regularly ordered, so if I can call them by ID it will be possible to manipulate them with very little code, whereas otherwise the furnace will need an if statement for each individual metal to determine what it smelts into. Many other processes will need to be able to work similarly.

I've found two possible solutions so far:

one would be to use reflect to call the methods, but I've been warned that it's notoriously unstable and difficult to figure out.

the other would be to overhaul my current system and store the item properties on a text file, something like

```<code>Ruined_Copper false 4 256 ...
Weak_Copper false 4 128 ...
etc.
</code>```

and then have a filereader open the file and count lines until the line number equaled the target itemId. It would then split the line by whitespace and assign the values to variables, ie:

```<code>newItem.setName(lineOutput(1));
newItem.setIsContainer(lineOutput(2));
...
</code>```

This would output an item with

```<code>name=Ruined_Copper, isContainer = false, etc.
</code>```

I'd prefer to figure this out early in development so I don't have to change thousands of items to a new format in the future.
Which one of these will go faster? Which one will be more stable? Is there a better way alltogether?

EDIT: To clarify, I realize that it would be a bad idea to have metals 0-36, woods 37-56, etc. My goal is to allow systematic or player-created items to be added by player actions in game, so the finished product will have space between catagories, ie 0-60 are metals, 61-999 are blank, 1000-1085 are wood types, 1086-1999 are blank, etc.

Body:
if(input.getId() < 36 && input.getId()%3 = 1){
//if the imput's ID is less than 36, it's a metal, and if ID % 3 = 1, it's a ruined metal, meaning it is smeltable.

Giving magic meaning to the id numbers is asking for trouble. What if you want add a new type of metal? What about removing one? What about adding a new state? Multiply this across all the different types of items in your game, and you have disaster looming.

one would be to use reflect to call the methods, but I've been warned
  that it's notoriously unstable and difficult to figure out.

Unstable usually means either something that crashes a lot or something that changes a lot. Neither of these are true of reflection. Its also really not difficult. However, reflection is slow, prevents the compiler from checking your code as much, renders refactoring tools ineffective, and generally indicates a poor design.

the other would be to overhaul my current system and store the item
  properties on a text file

I'm a big fan of configuration. Whenever possible, I like to put details in configuration rather than code. This reduces duplication and boilerplate. It follows the rule of least power. There are a few different ways to do this:

One way is a text file as you  mention. I wouldn't recommend a plain text file, I'd use YAML or JSON as a basic syntax. That you get the parsing for free, and various tools to help you work with it.

Another way is java enums. Java enums are objects and you can attach extra data and methods to them. I've soured on enums a bit because its tempting to switch on them when you should add a property, and can't create enums at runtime. (It's useful to be able to construct arbitrary combinations of properties in tests)

Another way is simple to create immutable objects in java. With the text file approach, you eventually create java objects from the data. You could also just create the java objects directly. This is somewhat nice because you don't have to switch out of java to modify your objects. On the other hand, its harder to develop/use tools that manipulate the data.


问:
Trying to understand P vs NP vs NP Complete vs NP Hard
I am trying to understand these classifications and why they exist. Is my understanding right? If not, what?

P is polynomial complexity, or O(nk) for some non-negative real number k, such as O(1), O(n1/2), O(n2), O(n3), etc. If a problem belongs to P, then there exists at least one algorithm that can solve it from scratch in polynomial time. For example I can always figure out if some integer n is prime by looping over 2 <= k <= sqrt(n) and checking at each step if k divides n.

NP is non-deterministic polynomial complexity. I don't really know what it means for it to be non-deterministic. I think it means it is easy to verify in polynomial time, but may or may not be polynomial time to solve from scratch if we didn't already know the answer. Since it may be solvable in polynomial time, all P problems are also NP problems. Integer factorization gets quoted as an example of NP, but I don't understand why it's not P, personally, since trial factorization takes O(sqrt(n)) time.

NP-Complete I don't understand at all, but the Traveling Salesman Problem is quoted as an example of this. But in my opinion the TSP problem might just be NP, because it takes something like O(2n n2) time to solve, but O(n) to verify if you are given the path up front.

NP-Hard I assume is just full of unknowns. Hard to verify, hard to solve.

答:
Integer factorization gets quoted as an example of NP, but I don't
  understand why it's not P, personally, since trial factorization takes
  O(sqrt(n)) time.

For the purposes of complexity classes, the n is the length of the input. So if you want to factor integer k, n is not k but log k, the number of bits (or whatever) it takes to write down the number. So integer factorization is O(sqrt(k)) as you say, but this is O(sqrt(2n)) which is O(2(n/2)).

NP-Hard I assume is just full of unknowns. Hard to verify, hard to
  solve.

No. NP-Hard is merely about how hard a problem is to solve.

NP-Hard problems are at least hard as the hardest problem in NP. We know they are at least that hard, because if we had a polynomial-time algorithm for an NP-Hard problem, we could adapt that algorithm to any problem in NP.

NP-Complete I don't understand at all

NP-Complete means that a problem is both NP and NP-Hard. It means that we can verify a solution quickly (NP), but its at least as hard as the hardest problem in NP (NP-Hard).

I don't really know what it means for it to be non-deterministic.

Non-determinism is an alternative definition of NP. A non-deterministic turing machine effectively is able to duplicate itself at any time, and have each duplicate take a different execution path. Under this definition, NP is the set of the problems that can be solved in polynomial time by a computer than can freely duplicate itself. It turns out this is exactly the same set of problems that can be verified in polynomial time.


答:
You're basically correct about P and NP, but not about NP-hard and NP-complete.

For starters, here are the super-concise definitions of the four complexity classes in question:

P is the class of decision problems which can be solved in polynomial time by a deterministic Turing machine.

NP is the class of decision problems which can be solved in polynomial time by a non-deterministic Turing machine. Equivalently, it is the class of problems which can be verified in polynomial time by a deterministic Turing machine.

NP-hard is the class of decision problems to which all problems in NP can be reduced to in polynomial time by a deterministic Turing machine.

NP-complete is the intersection of NP-hard and NP. Equivalently, NP-complete is the class of decision problems in NP to which all other problems in NP can be reduced to in polynomial time by a deterministic Turing machine.

And here's a Euler diagram from Wikipedia showing the relationships between these four classes (assuming that P is not equal to NP):

The part that I assume you're most unfamiliar with or confused by is the notion of a "polynomial time reduction" from problem X to problem Y. A reduction from X to Y is simply an algorithm A which solves X by making use of some other algorithm B which solves problem Y. This reduction is called a "polynomial time reduction" if all parts of A other than B have a polynomial time complexity. As a trivial example, the problem of finding the smallest element in an array is constant-time reducible to the sorting problem, since you can sort the array and then return the first element of the sorted array.

One thing that's easy to miss about the NP-hard definition is that the reduction goes from NP problems to the NP-hard problem, but not necessarily vice versa. This means that NP-hard problems might be in NP, or in a much higher complexity class (as you can see from the Euler diagram), or they might not even be decidable problems. That's why people often say something like "NP-hard means at least as hard as NP" when trying to explain this stuff informally.

The halting problem is a good example of an NP-hard problem that's clearly not in NP, as Wikipedia explains:

It is easy to prove that the halting problem is NP-hard but not NP-complete. For example, the Boolean satisfiability problem can be reduced to the halting problem by transforming it to the description of a Turing machine that tries all truth value assignments and when it finds one that satisfies the formula it halts and otherwise it goes into an infinite loop. It is also easy to see that the halting problem is not in NP since all problems in NP are decidable in a finite number of operations, while the halting problem, in general, is undecidable.

Title: Trying to understand P vs NP vs NP Complete vs NP Hard

Body:
I am trying to understand these classifications and why they exist. Is my understanding right? If not, what?

P is polynomial complexity, or O(nk) for some non-negative real number k, such as O(1), O(n1/2), O(n2), O(n3), etc. If a problem belongs to P, then there exists at least one algorithm that can solve it from scratch in polynomial time. For example I can always figure out if some integer n is prime by looping over 2 <= k <= sqrt(n) and checking at each step if k divides n.

NP is non-deterministic polynomial complexity. I don't really know what it means for it to be non-deterministic. I think it means it is easy to verify in polynomial time, but may or may not be polynomial time to solve from scratch if we didn't already know the answer. Since it may be solvable in polynomial time, all P problems are also NP problems. Integer factorization gets quoted as an example of NP, but I don't understand why it's not P, personally, since trial factorization takes O(sqrt(n)) time.

NP-Complete I don't understand at all, but the Traveling Salesman Problem is quoted as an example of this. But in my opinion the TSP problem might just be NP, because it takes something like O(2n n2) time to solve, but O(n) to verify if you are given the path up front.

NP-Hard I assume is just full of unknowns. Hard to verify, hard to solve.

ContentLicense: CC BY-SA 4.0


答:
My solution is have a config file where you have a property associated with the method in  config. This will be used in a builder class.

And also have a config where you give the properties in a xml/properties/json.

eg

Builder Config
name=setName()
category=setCategory
qualityLevel=setQualityLevel

Value Config
name=Jack
category=metal
qualityLevel=1

Pseduo Code
  Read BuilderCOnfig and store.

While ( Value Config.hasElements() )
{
   method= BuilderConfig.getMethod()
   call object.method();
}

This makes everything configurable for future additions to properties/methods. Also takes care when some properties are missing.

The builder element can be done with if you use Spring which auto wires the methods if they are named consistently.
And all you need is a bunch of xml files.


问:
How does the copy and paste mechanism work and is it a standard design pattern as in GoF?
How does the current copy and paste work on a computer?  Such as being able to copy some formatted text together with an image, and then when pasted to a text editor, it will intelligently paste only ASCII or UTF-8 text, while if pasted to some webapps or Microsoft Word or Pages on a Mac, it will paste the text together with the formatting info as well as the image.  (Is this actually one of the GoF Design Pattern or a design pattern that is well defined that actually has a name to it?)</p>

答:
The trick here is that when you start a drag operation, the application whose data you're dragging will give the operating system that data in one or more specific formats. Then, the application you drop the data on will ask the OS if it has data in one or more specific formats. Thus, when dropping "the same data" on two different applications results in two different pieces of data appearing, that simply means those two target applications made different choices out of the range of data formats provided by the source application.

For maximum interoperability, it's generally encouraged to provide your drag data in as many formats as possible. The OS might even "fill in" some extra formats for you where possible, or allow you to register your own custom data formats in addition to the standard ones it provides.

Since I feel like citing a source with some more concrete system-specific details, here is the MSDN page on clipboard data formats in Windows. I assume Mac and Linux have much of the same functionality.

As for design patterns, I'm not aware of anything you could call a "design pattern" that would be inherently appropriate for implementing this functionality. And I have no idea whether the big three operation systems actually contain any in their implementations.