问:
How to extract the active code path from a complex algorithm
I have been puzzled lately by an intruiging idea.

I wonder if there is a (known) method to extract the executed source code from a large complex algorithm. I will try to elaborate this question:

Scenario: There is this complex algorithm where a large amount of people have worked on for many years. The algorithm creates measurement descriptions for a complex measurement device.

The input for the algorithm is a large set of input parameters, lets call this the recipe. Based on this recipe, the algorithm is executed, and the recipe determines which functions, loops and if-then-else constructions are followed within the algorithm. When the algorithm is finished, a set of calculated measurement parameters will form the output. And with these output measurement parameters the device can perform it's measurement.

Now, there is a problem. Since the algorithm has become so complex and large over time, it is very very difficult to find your way in the algorithm when you want to add new functionality for the recipes. Basically a person wants to modify only the functions and code blocks that are affected by its recipe, but he/she has to dig in the whole algorithm and analyze the code to see which code is relevant for his or her recipe, and only after that process new functionality can be added in the right place. Even for simple additions, people tend to get lost in the huge amount of complex code.

Solution: Extract the active code path? I have been brainstorming on this problem, and I think it would be great if there was a way to process the algorithm with the input parameters (the recipe), and to only extract the active functions and codeblocks into a new set of source files or code structure. I'm actually talking about extracting real source code here.

When the active code is extracted and isolated, this will result in a subset of source code that is only a fraction of the original source code structure, and it will be much easier for the person to analyze the code, understand the code, and make his or her modifications. Eventually the changes could be merged back to the original source code of the algorithm, or maybe the modified extracted source code can also be executed on it's own, as if it is a 'lite' version of the original algorithm.

Extra information: We are talking about an algorithm with C and C++ code, about 200 files, and maybe 100K lines of code. The code is compiled and build with a custom Visual Studio based build environment.

So...: I really don't know if this idea is just naive and stupid, or if it is feasible with the right amount of software engineering. I can imagine that there have been more similar situations in the world of software engineering, but I just don't know.

I have quite some experience with software engineering, but definitely not on the level of designing large and complex systems.

I would appreciate any kind of answer, suggestion or comment.

Thanks in advance!

答:
The issue seems to be similar to writing test cases with good code coverage
There are tools for automatic test case generation that are based on code analysis.

Here is a link to a paper on a tool for C programs:

Klee paper (also as pdf)

The tool generates test input data that is supposed to cover different branches in  the code.

I never worked with it, but maybe it can be tweaked to do what you are looking for. I am not shure how this fits with Visual Studio ...


问:
Hamming Distance using a dictionary
First time poster. I'm currently programming a hamming distance program using a dictionary.

So if we start with the word "cat" and we want to transform it into "dog", the sequence is cat-->cot-->dot-->dog, and "full" to "tree" is full-->fuel-->feel-->teel-->tyee-->tree. All intermediates must exist in a dictionary.  I've implemented that part and it works quite well. My question is about the fringe cases. Some words have no transformations, such as dragon and cosmo. But that's fine, I implemented a quick check.

The real problem is there are lots of paths in which transformations are impossible and I can't seem to find a way to check whether they are impossible. For example, heist to flame is heist-->feist-->feast-->feaseX --> flame. Getting to the end point is impossible and an infinite loop occurs.

My possible options are that after around 20 transformations, I stop the calculation and throw an error, which is fine. Or, there might be way to detect a dead path before the program is ran, this is the best option, I'm not optimistic this is possible.

答: To solve the question you pose, you must understand complete search, and for that you have to understand recursive algorithms. This simply means that you must reduce e.g. the problem of reaching "tree" from "full" to the problem of reaching "free" from "full", and handle the intermediate data correctly.

ContentLicense: CC BY-SA 3.0

Title: Hamming Distance using a dictionary


问:
What does the "t" in int32_t signify?
In C, what meaning, if any does the t at the end of integer types like uint8_t and int32_t have? Where did it originate? Why wasn't the type just called int32?

答:
The _t data types are typedef types in the stdint.h header, while int is a built-in fundamental data type to C. The _t datatypes are only available if stdint.h exists. The fundamental data types like int, however, are guaranteed to exist.

Basically, it really doesn't mean much of anything. It's just how C decided to name things.

Title: What does the "t" in int32_t signify?


问:
In C++, when should I use final in virtual method declaration?
I know that final keyword is used to prevent virtual method from being overriden by derived classes. However, I can't find any useful example when I should really use final keyword with virtual method. Even more, it feels like usage of final with virtual methods is a bad smell since it disallows programmers to extend class in future.

My question is next:

Is there any useful case when I really should use final in virtual method declaration?

答:
It enables lot of optimisations, because it may be known at compile time which function is called.

Be careful throwing the word "code smell" around. "final" doesn't make it impossible to extend the class. Double click on the "final" word, hit backspace, and extend the class. HOWEVER final is an excellent documentation that the developer doesn't expect you to override the function, and that because of that the next developer should be very careful, because the class might stop working properly if the final method gets overridden that way.


问:
bool accepts int literals, char literals, string literals - why?
Programming: Practices and Principles - Bjarne Stroustrup

Drill in Ch 5 - Errors

He wants us to correct the code:

```<code>boo c = "fool"<s;
</code>```

On correcting boo to bool, this is a comparison, so that's fine. c will be assigned either true or false. But if I edit it to

```<code>bool c = "fool";
</code>```

It also evaluates to true. Then I tried "", 'd', 235, and they all evaluate to true. Shouldn't there be a type error? Narrowing conversion? Something? (I tried {} for checking narrowing conversions.)

答:
I think the boolean operators are defined for these types to provide backwards compatibility with C code. In C it's legal to use integers in if-s

```<code>int i = 1;
if (i) {
    // Will step into, unless i is set to 0
}
</code>```

Given these operators the "C-styled" code above compiles too. Also, in C++ :

```<code>if (/*Whatever you pass in, it's operator bool() is called here*/) {
    // And will step into if it's true
}
</code>```

Read the chapter called "Operator Overloading".

Body:
I think the boolean operators are defined for these types to provide backwards compatibility with C code. In C it's legal to use integers in if-s

int i = 1;
if (i) {
    // Will step into, unless i is set to 0
}

Given these operators the "C-styled" code above compiles too. Also, in C++ :

if (/*Whatever you pass in, it's operator bool() is called here*/) {
    // And will step into if it's true
}

Read the chapter called "Operator Overloading".


答:
An example of why you would need such a thing:

Suppose class A defines a virtual function prepareEnvelope().

And suppose that class B extends A and overrides prepareEnvelope(), implementing it as a sequence of calls to its own virtual methods stuffEnvelope(), lickEnvelope() and sealEnvelope().

Obviously, since these new methods are virtual, class B intends to allow derived classes to override them to provide their own implementations; however class B probably does not want to allow a derived class to also override prepareEnvelope() and thus potentially change the order of stuff, lick, seal, or omit invoking one of them.

So, in this case class B would declare prepareEnvelope() as final.

The example above is a case of the template method pattern (https://en.wikipedia.org/wiki/Template_method_pattern) where class B implements prepareEnvelope() as a template method to achieve a certain goal, and presumably also contains other functionality (e.g. fields) to support that goal. Any derived class should conform to that template, otherwise the supported functionality is provided in vain, and in certain cases failure to use that functionality may cause malfunction. (If the lickEnvelope() method is not invoked, then no saliva will be consumed, so who knows, the saliva container might overflow.) So, if you want to build a class which deviates from the pattern established by B, then you should not be deriving from B, you should be deriving from the basemost class A.

Another example:

The same thing can be seen in a more simple scenario which most programmers encounter at some point: Let's say the basemost class A has a cleanUp() method, and derived class B overrides cleanUp() to perform some very important actions which absolutely must be performed or else the Universe will self-destruct. In this case, class B may not want to leave it up to derived classes to decide whether their overrides of cleanUp() will invoke B::cleanUp() or not. To this effect, class B may make cleanUp() final, and declare an empty protected virtual method onCleanUp() which is invoked from within cleanUp() to allow descendants to override it in order to do their own cleanup. This means that when cleanUp() is invoked on the object, method B::cleanUp() will always be invoked, and thus the Universe will be saved, while overrides of onCleanUp() may forget invoking B::onCleanUp(), and nothing bad will happen, because it is empty.

Generally:

In the general case, a class declares a method as final if the class contains functionality which requires that the method must be invoked and must work exactly as defined. In these cases, derived classes must not be allowed to override the method, because the overrides may work differently, or they may omit invoking the base method.

Title: In C++, when should I use final in virtual method declaration?

Body:
I know that final keyword is used to prevent virtual method from being overriden by derived classes. However, I can't find any useful example when I should really use final keyword with virtual method. Even more, it feels like usage of final with virtual methods is a bad smell since it disallows programmers to extend class in future.

My question is next:

Is there any useful case when I really should use final in virtual method declaration?

ContentLicense: CC BY-SA 4.0


答:
I assume you are using recursion for this. Every transformation is a unit of work to be done, hopefully it is handled in one method, or group of methods.

When you jump to next word, keep track of all the words that you have already been at during this specific path and check the available options against the list of those words to exclude the ones that you already visited.

Example:

heist-(1)->feist-(2)->feast-(3)->feaseX -(4)-> flame

* Numbers signify the execution cycle of the same method. Simplified version for demonstration purposes.

```<code>public string[] previouslyUsedWords = new String[]();

public string transformNext(string currentWord) {
    var possibleOptions = _optionsProvider.GetOptions(currentWord);

    foreach(var word in possibleOptions) {
        if(!previouslyUsedWords.Contains(word)) {
            previouslyUsedWords.Add(word);
            return word;
        }
    }

    throw new Exception("No options left, this is a dead end!");
}
</code>```

Combine this with a tree-traversal algorithm(some paths are dead ends and that's why you need to go back and try other paths) and you should accomplish this task in no time.

Title: Hamming Distance using a dictionary

Body:
First time poster. I'm currently programming a hamming distance program using a dictionary.

So if we start with the word "cat" and we want to transform it into "dog", the sequence is cat-->cot-->dot-->dog, and "full" to "tree" is full-->fuel-->feel-->teel-->tyee-->tree. All intermediates must exist in a dictionary.  I've implemented that part and it works quite well. My question is about the fringe cases. Some words have no transformations, such as dragon and cosmo. But that's fine, I implemented a quick check.

The real problem is there are lots of paths in which transformations are impossible and I can't seem to find a way to check whether they are impossible. For example, heist to flame is heist-->feist-->feast-->feaseX --> flame. Getting to the end point is impossible and an infinite loop occurs.

My possible options are that after around 20 transformations, I stop the calculation and throw an error, which is fine. Or, there might be way to detect a dead path before the program is ran, this is the best option, I'm not optimistic this is possible.

Body:
I assume you are using recursion for this. Every transformation is a unit of work to be done, hopefully it is handled in one method, or group of methods.

When you jump to next word, keep track of all the words that you have already been at during this specific path and check the available options against the list of those words to exclude the ones that you already visited.

Example:

heist-(1)->feist-(2)->feast-(3)->feaseX -(4)-> flame

* Numbers signify the execution cycle of the same method. Simplified version for demonstration purposes.

public string[] previouslyUsedWords = new String[]();

public string transformNext(string currentWord) {
    var possibleOptions = _optionsProvider.GetOptions(currentWord);

    foreach(var word in possibleOptions) {
        if(!previouslyUsedWords.Contains(word)) {
            previouslyUsedWords.Add(word);
            return word;
        }
    }

    throw new Exception("No options left, this is a dead end!");
}

Combine this with a tree-traversal algorithm(some paths are dead ends and that's why you need to go back and try other paths) and you should accomplish this task in no time.


答:
As can be found here, there is a conversion happening:

Prvalues of integral, floating-point, unscoped enumeration, pointer, and pointer-to-member types can be converted to prvalues of type bool.

The value zero (for integral, floating-point, and unscoped enumeration) and the null pointer and the null pointer-to-member values become false. All other values become true.

Title: bool accepts int literals, char literals, string literals - why?

Body:
Programming: Practices and Principles - Bjarne Stroustrup

Drill in Ch 5 - Errors

He wants us to correct the code:

```<code>boo c = "fool"<s;
</code>```

On correcting boo to bool, this is a comparison, so that's fine. c will be assigned either true or false. But if I edit it to

```<code>bool c = "fool";
</code>```

It also evaluates to true. Then I tried "", 'd', 235, and they all evaluate to true. Shouldn't there be a type error? Narrowing conversion? Something? (I tried {} for checking narrowing conversions.)


问:
Work out which parcel deliveries we ship ourselves and which we outsource
Firstly, I hope I'm asking this in the right place. I work for a large online retailer in UK. We ship approaching 2000 orders each day and are growing very quickly.

We currently use multiple delivery firms to handle all our deliveries. We're planning to launch our own fleet of delivery vans soon for deliveries local to our distribution centre.

When we launch our own delivery fleet, one of the first tasks for the computer systems behind it will be to decide which parcels should be delivered by us and which parcels we should outsource the delivery of to one of our delivery partners. Once that has been worked out, we can worry about which parcels go onto which vans and in which order they will be delivered (the Vehicle Routing Problem (VRP)).

I looking for some advice here on the first part of that (which parcels we deliver ourselves and which we outsource). I'm not looking for help with the VRP at the moment (we're intending to build a system upon OSRM and Optaplanner and are comfortable with how that will work), although if you know of a good solution to solve both problems in one go, that would be great.

I have considered some fairly obvious things to determine the orders we deliver ourselves:

All deliveries within x miles radius of our distribution centre.

All deliveries within x minutes drive of our distribution centre.

All deliveries within x minutes drive of our distribution centre and then all deliveries within y minutes drive of any delivery we are going to. Recursively. With a maximum distance from our distribution centre (so we don't have a line of deliveries up the country and end up 500 miles away!)

As with number 3 but calculating x and y based on the cost of us using a 3rd party to make the delivery on our behalf (i.e. we'd be happy to send one of our vans further for a heavier/larger parcel).

I'm going to give it some more thought, but there has to be a better way than any of those options above. Does anyone have an experience with this as I'm totally new to it? Is there a name for this problem? Much like the names of Traveling Salesman Problem (TSP) and Vehicle Routing Problem (VRP) which would aid my Googling? I'm sure there will be a way to use Optaplanner to come up with a good solution but I'm not sure how. Ideally we would factor into the decision process the cost of delivering the order with our cheapest delivery partner.

You can assume that we know the following for all parcels:

Lat/long for each delivery point.

The actual driving time and distance between any two delivery points (and/or our distribution centre).

The cost of using a 3rd party to make each delivery.

We use linux based systems and love open source projects (and have contributed fixes/improvements back to many). We're up for using open or closed source applications to make our life easier, and even things that only run on Windows if we really need to. We'd also happily code the entire thing in-house. If you know if any good packages to look at then please do say.

Thank you for your help.

答:
What you need is something that does Linear Programming. The various variables you would be using are called "Decision Variables" in the context of these methods. Linear Programming is a very mature technique and there are many packages and platforms available. There are also legions of resources for learning the techniques behind it as well if you want to scratch build something.

There are various other methods of optimization you can use as well if linear methods prove insufficient. For instance, Stochastic Optimization covers cases where some or all of the variables are random.


问:
What is the actual value of a consistent code style
I am part of a consultant team implementing a new solution for a customer. I am
responsible for the majority of code reviews on the client-side codebase (React and javascript).

I have noticed that some team members use unique coding patterns to a point that I could pick a file at random at tell who was the author from the style alone.

Example 1 (one-off inline functions)

```<code>React.createClass({
  render: function () {
    var someFunc = function () {
      ...
      return someValue;
    };
    return <div>{someFunc()}</div>
  }
});
</code>```

The author argues that by assigning a meaningful name to someFunc the code will be easier to read. I believe that by inlining the function and adding a comment instead the same effect could be achieved.

Example 2 (unbound functions)

```<code>function renderSomePart(props, state) {
    return (
      <div>
        <p>{props.myProp}</p>
        <p>{state.myState}</p>
      </div>
    );
}

React.createClass({
  render: function () {
    return <div>{renderSomePart(this.props, this.state)}</div>;
  }
});
</code>```

This is how we usually do it (avoids having to pass state and props):

```<code>React.createClass({
  renderSomePart: function () {
    return (
      <div>
        <p>{this.props.myProp}</p>
        <p>{this.state.myState}</p>
      </div>
    );
  },
  render: function () {
    return <div>{this.renderSomePart()}</div>;
  }
});
</code>```

While these coding patterns are technically correct they are not consistent with the rest of the codebase nor with the style and patterns that Facebook (the author of React) hints at in tutorials and examples.

We need to keep a fast pace in order to deliver on time and I don't want to burden the team unnecessarily. At the same time we need to be on a reasonable quality level.

I am trying to imagine myself as the customers' maintenance developer faced with inconsistencies like these (every component might require you to understand another way of doing the same thing).

Question:

What is the value as perceived by the customer and its maintenance developers of a consistent code base vs. allowing inconsistencies like these to remain and potentially spread?

答:
Code Transfer Advantage

Following patterns provided by a library, React in your case, means that the product you deliver will be easily picked up and maintained by other developers who are also familiar with React.

Potential Backward Compatibility Issues

Some libraries would have a new major version out, and backward compatibility might be compromised if your patterns are significantly different, thus slowing/halting your future upgrade. I am not sure how React would deal with new releases, but I have seen this happen before.

New Members on The Team Start Being Productive Quicker

If you follow what is provided by the author, you are more likely hiring talented developers using your framework and start them off quicker with your system rather than teaching new patterns.

Potential Undiscovered Issues

There might be issues in the future that you haven't discovered yet with your approach, that are solved by the author's approach.

That being said, innovation is always a risk, if you strongly feel that your approach is better and it works for your team, go for it!


答:
size_t is read as 'size type'

_t usually means type, and sometimes typedef.

Why wasn't the type just called int32

So it could be distinguished from a built in type, stdint.h is supposed to choose the proper built in type to be the given size depending on the platform. N.b. some compilers int32_t aliases a compiler specific notation like i_32 or something similar.

Microsoft took a different approach and their standard is based on #defines, with values like INT32, DWORD, etc.

Title: What does the "t" in int32_t signify?

Body: In C, what meaning, if any does the t at the end of integer types like uint8_t and int32_t have? Where did it originate? Why wasn't the type just called int32?


答:
The code may be well written yet not perfectly consistent, so some clients won't care. When things start to go bad, do you want to give them another knock against you? If I hired a company to work on a multi-developer project and they didn't indicate to me that they have a coding standard and follow it, I would be skeptical.

We need to keep a fast pace in order to deliver on time and I don't
  want to burden the team unnecessarily.

As long as the coding standards aren't too crazy, it shouldn't be that hard for everyone to get on board. Projects get stalled because people don't know what code to write or not write and not because of typing and formatting. You'll know you've gone to far when it takes a disproportionate amount of time to adhere to. Hopefully, this isn't your first rodeo.

Conduct your own test
All you need to do is switch assignments midway from one dev to the other and have them finish someone else's file. Do they spend time completely reformatting things to their version? Is it too difficult to follow? It will get worse for your client's maintenance team.

Title: What is the actual value of a consistent code style

Body:
I am part of a consultant team implementing a new solution for a customer. I am
responsible for the majority of code reviews on the client-side codebase (React and javascript).

I have noticed that some team members use unique coding patterns to a point that I could pick a file at random at tell who was the author from the style alone.

Example 1 (one-off inline functions)

```<code>React.createClass({
  render: function () {
    var someFunc = function () {
      ...
      return someValue;
    };
    return <div>{someFunc()}</div>
  }
});
</code>```

The author argues that by assigning a meaningful name to someFunc the code will be easier to read. I believe that by inlining the function and adding a comment instead the same effect could be achieved.

Example 2 (unbound functions)

```<code>function renderSomePart(props, state) {
    return (
      <div>
        <p>{props.myProp}</p>
        <p>{state.myState}</p>
      </div>
    );
}

React.createClass({
  render: function () {
    return <div>{renderSomePart(this.props, this.state)}</div>;
  }
});
</code>```

This is how we usually do it (avoids having to pass state and props):

```<code>React.createClass({
  renderSomePart: function () {
    return (
      <div>
        <p>{this.props.myProp}</p>
        <p>{this.state.myState}</p>
      </div>
    );
  },
  render: function () {
    return <div>{this.renderSomePart()}</div>;
  }
});
</code>```

While these coding patterns are technically correct they are not consistent with the rest of the codebase nor with the style and patterns that Facebook (the author of React) hints at in tutorials and examples.

We need to keep a fast pace in order to deliver on time and I don't want to burden the team unnecessarily. At the same time we need to be on a reasonable quality level.

I am trying to imagine myself as the customers' maintenance developer faced with inconsistencies like these (every component might require you to understand another way of doing the same thing).

Question:

What is the value as perceived by the customer and its maintenance developers of a consistent code base vs. allowing inconsistencies like these to remain and potentially spread?


答:
Inconsistencies make you stop and think why, which and where:

When you read part of the code and see that it uses a different style from the rest of the code, it makes you wonder - why is this particular part different? Does it have a special reason that I need to be aware of? This is dangerous, because if there really is a reason for that part to be different you need to be aware of it or else you might create some nasty bugs. So instead of thinking on the original problem that made you go touch that code you now waste time thinking on why it's different, and you can't figure that out so you go to the original author to ask them, wasting their time too, and even worse - in the process you both loose the mental model of the problems you were working on.

Multiply by every other developer in the team that needs to touch/read that code.

When you need to add to a code that use multiple styles, you need to stop and decide which style to use for your addition. You have to make enough decisions that matter - it's a waste of time to waste time thinking about decisions that don't matter.

When the style is consistent, it's easy to navigate around the code, because the consistency helps you quickly find where stuff is located. With inconsistent style even grepping becomes harder because you don't know what style the thing you are looking for is using.


问:
Do objects in OOP have to represent an entity?
Does an object have to represent an entity?

By an entity I mean something like a Product, Motor, a ParkingLot etc, a physical, or even a clear-cut non-physical conceptual object -- something that is well defined, with some core data clearly belonging to the object, and some functions/methods that clearly operate on the core data.

For example, I can have an object of a Demon, an entity in itself, an imaginary one perhaps and not physical but an entity nevertheless

Can an object be just a collection of methods, a common set of procedures that tie in with a common goal?

Example:  can a class be called MotorOperations or MotorActions, where there is no entity, but methods inside the class do things like

getMotorDataFromHTMLForm()

getMotorManufacturers()

selectMotorFromUserRequirements($requirements)

canMotorCanHandleOperatingConditions($conditions)

computePowerConsumptionForMotor($id)

A class is typically defined as data central to the object + operations on data.  So for a Motor there may be some motor variables relating to motor specifications, and there can be operations that combine those data to produce something.

In my case it is more like I have a class with operations on data + data that is passed through the class, there is no data centric to "Motor Operations", other than temporary pass-through-the-class data.

Question

Can classes represent entity-less objects?
If not, why they are bad/incomplete/non-OOP-centric?  Are there ways they need to be changed/improved conceptually to be in line with OOP?

答:
Can classes represent entity-less objects? If not, why they are bad/incomplete/non-OOP-centric? Are there ways they need to be changed/improved?

In short, you can do anything, but this specific scenario would be against OOP principles :)

What you are describing is sometimes called a "utility" class - usually a sign of code smell. You want to avoid creating classes for the sake of keeping some methods together.

Not every object in your application has to be linked to a real-life entity like a motor, or car; those are business objects. In your application, you are likely to use many of your business objects, but you would also need some more segregation for other operations that are not part of business entities, like the ones you listed.

You should have a look at common architectural patterns - one of them is MVC (Model-View-Controller).

If I was to distribute the methods you listed using MVC, here is what I would do:

View Class:

GetMotorDataFromHTMLForm()

Model Class (Motor Essentially):

GetMotorManufacturer()

CanMotorHandleOperationConditions()

CalculatePowerConsumption()

Controller Class(MotorsController):

GetAllMotors()

GetMotorById()

GetMotorByUserRequirements()

It seems like you are using PHP; a good MVC framework to have a look at is Laravel. In their examples they illustrate well where what methods belong to.

Another, more generic source of information how to decide where the methods belong are GRASP and SOLID principles.


答:
Can classes represent entity-less objects?

Can? Yes. Should? Probably not - or at least, not how you're phrasing things.

Objects actually are best when not representing a physical object directly since reality so infrequently maps nicely to code. But they do need to represent a cohesive concept or code-object. They need to represent a single cohesive responsibility.

Just bundling a bunch of tangentially related functions together is a namespace or a module - not an object in OOP parlance. Those can be useful, but they're not the same, and require a different sort of usage/thinking to work with effectively.

Title: Do objects in OOP have to represent an entity?

Body:
Does an object have to represent an entity?

By an entity I mean something like a Product, Motor, a ParkingLot etc, a physical, or even a clear-cut non-physical conceptual object -- something that is well defined, with some core data clearly belonging to the object, and some functions/methods that clearly operate on the core data.

For example, I can have an object of a Demon, an entity in itself, an imaginary one perhaps and not physical but an entity nevertheless

Can an object be just a collection of methods, a common set of procedures that tie in with a common goal?

Example:  can a class be called MotorOperations or MotorActions, where there is no entity, but methods inside the class do things like

getMotorDataFromHTMLForm()

getMotorManufacturers()

selectMotorFromUserRequirements($requirements)

canMotorCanHandleOperatingConditions($conditions)

computePowerConsumptionForMotor($id)

A class is typically defined as data central to the object + operations on data.  So for a Motor there may be some motor variables relating to motor specifications, and there can be operations that combine those data to produce something.

In my case it is more like I have a class with operations on data + data that is passed through the class, there is no data centric to "Motor Operations", other than temporary pass-through-the-class data.

Question

Can classes represent entity-less objects?
If not, why they are bad/incomplete/non-OOP-centric?  Are there ways they need to be changed/improved conceptually to be in line with OOP?


答:
Because all identifiers ending with _t are reserved for future additional types.

The int32_t family of types was added in the C99 standard, so they used the reserved names to avoid conflict with already existing software.

You can find a nice overview of reserved names in the glibc documentation.

Note:

Since Microsoft is not the C standards committee, they are right in not using the _t family of names, opting for the unreserved INT32 instead.

Title: What does the "t" in int32_t signify?


答:
No. (Title edited to ask the opposite question!)

eg:

```<code>Public class MyRepository
{
    public MyObject GetObject(string id)
    {
        //get data from the DB and build an object
    }
}
</code>```

or

```<code>Public class MyService
{
    public MyObject3 ProcessData(MyObject1 obj1, MyObject2 obj2)
    {
         //perform a process which is not a sole responsiblity of obj1 or obj2
    }
}
</code>```

However, in general the ideal behind OOP is to move away from

```<code>public struct Car
{
    public Wheel[] Wheels;
}

public int CountWheelsOnCar(MyCarStruct car)
{
   return car.Wheels.Length;
}
</code>```

to

```<code>public class Car
{
    private Wheel[] wheels;
    Public int CountWheels()
    {
        return this.wheels.Length;
    }
}
</code>```

Body:
No. (Title edited to ask the opposite question!)

eg:

Public class MyRepository
{
    public MyObject GetObject(string id)
    {
        //get data from the DB and build an object
    }
}

or

Public class MyService
{
    public MyObject3 ProcessData(MyObject1 obj1, MyObject2 obj2)
    {
         //perform a process which is not a sole responsiblity of obj1 or obj2
    }
}

However, in general the ideal behind OOP is to move away from

public struct Car
{
    public Wheel[] Wheels;
}

public int CountWheelsOnCar(MyCarStruct car)
{
   return car.Wheels.Length;
}

to

public class Car
{
    private Wheel[] wheels;
    Public int CountWheels()
    {
        return this.wheels.Length;
    }
}


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
You can use an eraser on the drafting
  table or a sledgehammer on the
  construction site - Frank Lloyd Wright

Not exactly a programming quote but it most certainly applies.

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


答:
It seems that what you're really trying to do is figure out if two nodes in a graph are in the same connected component. Specifically the graph is an undirected one in which the words of your dictionary are nodes, and two nodes are connected to each other by a vertex when they differ by exactly one letter, and are the same length. The root of the problem is that this graph is not be totally connected. It may be a disconnected graph of mutually unreachable connected components. In fact, it seems from your description that any words with a different number of letters would have to be in separate components.

The italicized keywords above are too technical to explain completely in an answer here, but you will find them on Wikipeida, or in any computer science text that covers graph algorithms. The algorithms you should consider for solving your problem are reachability algorithms for disconnected, undirected graphs.

Title: Hamming Distance using a dictionary


问:
Bad practice - switch case to set environment
In the last three years that I have worked as developer, I have seen a lot of examples where people use a switch statement to set the path (both in back-end and front-end) for a URL. Below is an example of this:

Back-end example (C#):

public static string getHost(EnvironmentEnum environment){
    var path = String.Empty;
    switch (environment)
    {
        case EnvironmentEnum.dev:
            path = "http://localhost:55793/";
            break;
        case EnvironmentEnum.uat:
            path = "http://dev.yourpath.com/";
            break;
        case EnvironmentEnum.production:
            path = "http://yourpath.com/";
            break;
    }
    return path;
}
```

<p>Front-end example (JavaScript):</p>

<pre class="lang-js prettyprint-override"><code>(function () {
    if (window.location.host.indexOf("localhost") !== -1) {
        window.serviceUrl = "http://localhost:57939/";
    }
    else if (window.location.host.indexOf("qa") !== -1) {
        window.serviceUrl = "http://dev.yourpath.com/";
    }
    else {
        window.serviceUrl = "http://yourpath.com/";
    }
})();
</code>```

It has been discussed whether it is a good or bad practice, and I think it is a bad practice, because we must avoid this kind of code and set a proper configuration. But to be honest I really don't know the proper answer and why is it not recommended and what is the correct way to implement this.

can someone explain it the pros and cons of the above practice?

答:
It's a BAD PRACTICE.

A basic principle of software design:
Don't hard-code configuration values inside your programs. This is especially true for anything that has a reasonable chance of changing in the future.

The program code that you develop should be the same code that goes into any environment such as QA testing, UAT, and production.  If somebody needs to change the configuration later because the environment has changed, or they need to use it in a new environment, fine. But they should never have to touch your program code to do so.  And you should not have different versions of code for each environment. If your program has changed since it was tested, then you haven't tested that version. Ask any software engineer, any software quality assurance professional, any I.T. project management professional, any I.T. auditor.

Someone could move testing to another server.  Someone might decide the also want a user training environment, or an environment for sales demonstrations.  They shouldn't have to go to a programmer for administrative configuration.

Software should be flexible and robust enough to handle unexpected situations, within reason.

Furthermore, software should not be written simply however seems easiest for you at the moment.  The cost of software development is small compared to the cost of software maintenance over its lifetime.  And let's say a year from now, you might not be the person working on that code.  You should be thinking of what you're leaving for the next poor fool who has to pick up whatever mess you you may have left behind, perhaps years after you've gone on to greener pastures.  Or you may be the one who picks up the code years later, not believing what you did back then.

Code things properly, as best you can. It's less likely to become a problem later.


答:
Yes, you can do this.  But you're essentially creating a class to provide the same functionality as a procedural library.  The only reason to do that is if your language lacks procedural modules (e.g., Java or Ruby).

In a language with procedural modules (I think PHP has procedural modules), you might consider just using a procedural module.

You could also consider re-designing your class so an instance of the class represents a coherent object.

But only use OO notation when it's giving you extra power, not just for the sake of being OO!


答:
This seems like a decision for business people to make, not developers. They do calculations and determine the rules by which your application will decide what parcel gets shipped by you, and what parcel gets shipped by third party.

If I was to implement it, here is how I would go about it:

Get quotes for each delivery company you can use.

Factor in your own estimates for your fleet. (Can be $/mile or $/hour).

Decide which one yields more profit.

This should probably be done offline, in some sort of processing queue so user doesn't wait for the decision.

Title: Work out which parcel deliveries we ship ourselves and which we outsource

Body:
Firstly, I hope I'm asking this in the right place. I work for a large online retailer in UK. We ship approaching 2000 orders each day and are growing very quickly.

We currently use multiple delivery firms to handle all our deliveries. We're planning to launch our own fleet of delivery vans soon for deliveries local to our distribution centre.

When we launch our own delivery fleet, one of the first tasks for the computer systems behind it will be to decide which parcels should be delivered by us and which parcels we should outsource the delivery of to one of our delivery partners. Once that has been worked out, we can worry about which parcels go onto which vans and in which order they will be delivered (the Vehicle Routing Problem (VRP)).

I looking for some advice here on the first part of that (which parcels we deliver ourselves and which we outsource). I'm not looking for help with the VRP at the moment (we're intending to build a system upon OSRM and Optaplanner and are comfortable with how that will work), although if you know of a good solution to solve both problems in one go, that would be great.

I have considered some fairly obvious things to determine the orders we deliver ourselves:

All deliveries within x miles radius of our distribution centre.

All deliveries within x minutes drive of our distribution centre.

All deliveries within x minutes drive of our distribution centre and then all deliveries within y minutes drive of any delivery we are going to. Recursively. With a maximum distance from our distribution centre (so we don't have a line of deliveries up the country and end up 500 miles away!)

As with number 3 but calculating x and y based on the cost of us using a 3rd party to make the delivery on our behalf (i.e. we'd be happy to send one of our vans further for a heavier/larger parcel).

I'm going to give it some more thought, but there has to be a better way than any of those options above. Does anyone have an experience with this as I'm totally new to it? Is there a name for this problem? Much like the names of Traveling Salesman Problem (TSP) and Vehicle Routing Problem (VRP) which would aid my Googling? I'm sure there will be a way to use Optaplanner to come up with a good solution but I'm not sure how. Ideally we would factor into the decision process the cost of delivering the order with our cheapest delivery partner.

You can assume that we know the following for all parcels:

Lat/long for each delivery point.

The actual driving time and distance between any two delivery points (and/or our distribution centre).

The cost of using a 3rd party to make each delivery.

We use linux based systems and love open source projects (and have contributed fixes/improvements back to many). We're up for using open or closed source applications to make our life easier, and even things that only run on Windows if we really need to. We'd also happily code the entire thing in-house. If you know if any good packages to look at then please do say.

Thank you for your help.


答:
I think that visualizing something in the real world is helpful when coding classes but not necessary.

In fact, depending on how literal you want to be, many objects we work with don't have physical representations at all.  For instance--consider MVC architecture.  In the real world there is no Model or Controller even though they are generally represented by classes.  The three together often represent something, but not always--but as I said you could probably force a fit into something if you really want to (and being able to imagine SOMETHING helps!  I visualize most objects in some way--just not anything you'd ever see in the real world).

Mostly these "Rules" you will learn about OO are just guidelines meant to get you oriented into thinking in OO not necessarily things you worry about much once you are using it to code on a daily basis.

By the way OO itself isn't some panacea and it doesn't help you much at all during your first pass at coding some solution, but I think that if done right it is a truly fantastic way to organize code so it can be more readily understood later. Writing maintainable code is probably one of the hardest tasks in software development and in many cases (anything that requires ongoing debugging/maintenance) it is by far the most important.


答:
No, an object does not have to represent an entity.

In fact, I would argue that when you stop thinking about objects as physical entities is when you finally get the benefits that OOP promises.

This isn't the best example, but the Coffee Maker design is probably where the light started to come on for me.

Objects are about messages.  They're about responsibilities.  They're not about Cars, Users, or Orders.

I know we teach OO this way, but it becomes apparent after a few tries how fundamentally frustrating it is to figure out where things go when you try to do MVC, MVVM or MVWhatever.  Either your models become ridiculously bloated or your controllers do.  For navigability, it's great to know that anything that touches Vehicles is in the Vehicle.ext file, but when your application is about Vehicles, you inevitably end up with 3000 lines of spaghetti in that file.

When you have a new message to send, you have at least one new object, and perhaps a pair of them.  So in your question about a bundle of methods, I would argue that you're potentially talking about a bundle of messages.  And each one could be its own object, with it's own job to do.  And that's ok.  It will become apparent as you split things apart which things really, really need to be together.  And you put them together.  But you don't immediately drop every method in a vaguely appropriate drawer for convenience sake if you want to enjoy OO.

Let's talk about bags of functions

An object can be just a collection of methods and still be OO, but my "rules" are pretty strict.

The collection should have a single responsibility, and that responsibility can't be as generic as "Does stuff to motors".  I might do such a thing as a service-layer facade, but I'm acutely aware that I'm being lazy for navigability/discovery reasons, not because I'm trying to write OO code.

All the methods should be at a consistent layer of abstraction.  If one method retrieves Motor objects and another returns Horsepower, that's probably too far apart.

The object should work on the same "kind" of data.  This object does stuff to motors(start/stop), this one does things with crank lengths, this one handles ignition sequencing, this one takes an html form.  This data could conceivably be fields on the object and it would seem cohesive.

I generally build objects of this sort when I'm doing transforms,  composition, or just don't want to worry about mutability.

I find focusing on object responsibilities leads me towards cohesion.  There has to be some cohesion to be an object, but there doesn't need to be any fields nor very much behavior for it to be an object.  If I was building a system that needed those 5 motor methods, I would start out with 5 different objects that do those things.  As I found commonality, I would either start to merge things together or use common "helper" objects.  That moves me into open/closed concerns - how can I extract this bit of functionality so I never have to modify that particular file again but still use it where needed?

Objects are about messages

Fields barely matter to an object - getting and setting registers doesn't change the world outside the program.  Collaborating with other objects gets the work done.  However, the strength of OO is that we can create abstractions so we don't have to think about all the individual details at once.  Abstractions that leak or don't make sense are problematic, so we think deeply (too much, maybe) about creating objects that match our mental models.

Key question:  Why do these two objects need to talk to each other?

Think of the object as an organ in a person - it has a default purpose and only changes behavior when it receives a specific message that it cares about.

Imagine a scenario where you're in the crosswalk and a car is coming fast.  As the brain object, I detect a stressor.  I tell the hypothalamus to send corticotrophin-releasing hormone.  The pituitary gland gets that message and releases adrenal corticotrophic hormone.  The adrenal glands get that message and create adrenaline.  When the muscle object gets that adrenaline message it contracts.  When the heart get the same message, it beats faster.  There's a whole chain of players involved in starting the complex behavior of sprinting across the street and it's the messages that matter.  The brain object knows how to get the hypothalamus to send out the alert, but it doesn't know the chain of objects that will eventually make the behavior happen.  Likewise the heart has no idea where adrenaline comes from, it just knows to do something different when that shows up.

So in this (simplified) example, the adrenal gland object only needs to know how to take ACTH and make adrenaline.  It doesn't need any fields to do that, yet it still seems like an object to me.

Now if our application is designed only to sprint across the street, I may not need the pituitary gland and the adrenal gland objects.  Or I only need a pituitary gland object that only does a small part of what we might conceptually see as the "pituitary gland model".  These concepts all exist as conceptual entities, but it's software and we can make the AdrenalineSender or MuscleContractor or whatever and not worry much about the "incompleteness" of our model.


问:
How can I rank teams based off of head to head wins/losses
I'm trying to write an algorithm (specifically in Ruby) that will rank teams based on their record against each other. If a team A and team B have won the same amount of games against each other, then it goes down to point differentials.

Here's an example:

```<code>A beat B two times
B beats C one time
A beats D three times
C bests D two times
D beats C one time
B beats A one time
</code>```

Which sort of reduces to

```<code>A[B] = 2
B[C] = 1
A[D] = 3
C[D] = 2
D[C] = 1
B[A] = 1
</code>```

Which sort of reduces to

```<code>A[B] = 1
B[C] = 1
A[D] = 3
C[D] = 1
D[C] = -1
B[A] = -1
</code>```

Which is about how far I've got

I think the results of this specific algorithm would be:

```<code>A, B, C, D
</code>```

But I'm stuck on how to transition from my nested hash-like structure to the results.

My psuedo-code is as follows (I can post my ruby code too if someone wants):

```<code>For each game(g):
  hash[g.winner][g.loser] += 1
</code>```

That leaves hash as the first reduction above

```<code>hash2 = clone of hash
For each key(winner), value(losers hash) in hash:
  For each key(loser), value(losses against winner):
    hash2[loser][winner] -= losses
</code>```

Which leaves hash2 as the second reduction

Feel free to as me question or edit this to be more clear, I'm not sure of how to put it in a very eloquent way. Thanks!

答:
Rating the relative strengths of teams/contestants is sort of a solved problem, so why re-invent the wheel?

There is the Elo rating system, originally devised for chess, and there is also the Glicko (pdf) rating system.

Both systems try to model the probability that one contestant will win against another, and produce a score representing their relative strength. I.e. higher rating means a stronger player.

The Elo system is zero-sum, and has a few thorny edge cases.

The Glicko system is not zero-sum, but it also models the confidence of the score as well; i.e. a player with a single data point isn't weighted as high as a player with many data points. It tries to fix some of the downsides of the Elo system.

Based on your question you probably want one of these systems, even if you don't realize it yet.


答: I think you should probably use a union-find algorithm to find all connected groups of n-letter words that can transform into each other.  Preprocess you dictionary with it, and before you start searching see if the two end words are in the same connected group.  The preprocessing will only take time proportional to the number of valid word-to-word transitions, so you could get away with doing it every time you load your dictionary.  You would need to store the group id of every word, so that would take a little more space.</p>

Title: Hamming Distance using a dictionary


问:
How does the post increment operator work in GNU C?
While the run the below program in Turbo C compiler, I am getting the expected output, however, when I run the same program it using "gcc" compiler in linux, it is giving an unexpected output!

```<code>int main(){

    int i=1;

    i=2+2*i++;
    printf("i : %d\n",i);

    return 0;
}
</code>```

Output in Turbo C => i : 5  (This is as expected!)

Output in GCC => i : 4 ( Why is the post increment ignored in this case?)

Can someone please explain what exactly happens in the compilation process?

答:
3 things are happening:

The value of i is being read into a register, call it R

2+2*R is being stored into i

R+1 is being stored into i.

The tricky thing is that you are not guaranteed that #2 will happen before #3, or that #3 will happen before #2.  This is an example of undefined order of operations.


问:
What false ideas are there that puts people off using threads?
Implementing threading in a program is hard, yes, however why is it that some people will not implement them even when there is an obvious need for it.

An example: Program has to load a dataset from a database, the thing to do would be to make the connection and get the data from the database in a worker thread and then load it into the GUI, leaving the GUI thread responsive for the user.

But no, I've talked to people whom seem to think that threads are evil and bad and whatnot and one should avoid them at all costs.  I've even heard that some class instructor advised against to use of threads and therefore did not want cover their use. WHAT???

With the hardware going into multi-core, I think that we need to understand threads better and not be afraid to use them. I find it a fascinating subject personally.

So what are things you've heard about threading that are false?

答:
It's not the threading part that's hard but the need for synchronization and everything else that comes with using threads. In your GUI example how do you tell the main thread the dataset is ready to be accessed? Do you pass around a whole bunch of callbacks? Do you scatter a whole bunch of check variables throughout your code? In some GUI models, e.g. Silverlight, there's something called thread affinity which means you don't get to access GUI elements sitting on the main thread from other threads so you have to get out of your way to let the main thread know certain information is ready to be processed further.

I haven't really heard any false things about threads. I've just read a whole bunch of situational case studies about synchronization being a bitch when whatever algorithm you are using isn't inherently parallel.


答:
As others commented, this i=2+2*i++; is undefined behavior. Please read the wikipage explaining it.

See this answer to understand a bit more about UB.

Then read Chris Lattner's blog entries What Every Programmer should know about Undefined Behavior.

To understand the actual behavior of your buggy C program, you need to dive into implementation details (and you don't want to). If you really want to understand what has happened when using GCC, you might compile your badub.c  program with gcc -fdump-tree-all -O -fverbose-asm -S badub.c  and then lose weeks of your time understanding the (hundreds) of badub.* files that this compilation command produced. Is it worth your time?

The lesson is avoid UB at all cost

To help more about avoiding UB, recent GCC compilers are sometimes able to emit warnings about it. You should at least compile with gcc -Wall -Wextra -g  to get all warnings and debug info. Learn to use the debugger. Learn about various -fsanitize=  options to recent GCC. Learn and use valgrind

BTW, it is the year 2015. Don't use TurboC, which is non-standard compliant, not efficient, not giving good warnings, buggy, proprietary, compiler of the previous century. Use a good free software compiler (like recent GCC or Clang/LLVM. Both can give better code and better warnings -when asked to- than your old crappy TurboC...)

Title: How does the post increment operator work in GNU C?

Body:
While the run the below program in Turbo C compiler, I am getting the expected output, however, when I run the same program it using "gcc" compiler in linux, it is giving an unexpected output!

```<code>int main(){

    int i=1;

    i=2+2*i++;
    printf("i : %d\n",i);

    return 0;
}
</code>```

Output in Turbo C => i : 5  (This is as expected!)

Output in GCC => i : 4 ( Why is the post increment ignored in this case?)

Can someone please explain what exactly happens in the compilation process?


答:
A class should model something - otherwise it's pointless. However, what's being modeled may not be a physical "thing"; instead, it may be a representation of something which is not 'real', but which is needed to control the system being modeled. For example, in a traffic light control system you could very well have some sort of ControlSignal class, representing a signal sent from one portion of the system to another to indicate that some action needs to be performed. In "the real world" these signals might consist of electrical impulses transmitted across wires from one box to another. The process of modeling something which isn't "real" as a concrete object is referred to as "reification".

Best of luck.


问:
Using Statement lambda in exception handling
Following is a code snippet from MVP Win Forms application and this explanation would be helpful when answering the questions.

My DAL doesn't handle exceptions and it will be propagated up to the calling method in the presenter classes where the exception will be handled.

I'm using a single handler called ExecutAction(Action action) so I'm catching exceptions in one place rather than repeating code in every method.

At the moment, I'm not logging errors. Just alert the user for an action and try to keep the system alive if possible.

When showing messages to users, Presenters will use a static class called MessagingService. (ShowErrorMessage()). So that I can customize all massage boxes in one place.

```<code>        private void Search()
        {
            ExecutAction(() =>
            {
                var info = _DataService.GetByACNo(_model.AccountNumber);

                    if (info != null)
                    {
                        _Model = info ;
                        this.SetViewPropertiesFromModel(_Model, _View);
                    }
                    else
                    {
                        MessageBox.Show ("Bank account not found");
                    }
                });
            }

            private void ExecutAction(Action action)
            {
                try
                {
                    action();
                }

                catch (NullReferenceException e) { MessagingService.ShowErrorMessage(e.Message); }
                catch (System.Data.SqlTypes.SqlTypeException e) { MessagingService.ShowErrorMessage(e.Message); }
                catch (System.Data.SqlClient.SqlException e) { MessagingService.ShowErrorMessage(e.Message); }
            }
        }
</code>```

Should I include general exception handler to this, to be able to handle any unforeseen exceptions?

Also could you show me a better way to handle showing messages than using a static?

Does use of lambda statements in every method call (ExecutAction(() =>) degrade code readability?

When showing user messages how to show a custom message like "Check the server connection" etc. first and then if the user wants more information (like StackTrace / technical details) he /she could press a button like More Info which is in the MessageBox dialog?

答:
First of all, you should copy the reference of action delegate instance before invoking it to prevent threading issues, like this:

```<code>private void ExecutionAction(Action action)
{
    var handler = action;
    if (handler == null)
    {
        return;
    }

    try
    {
        handler();
    }
    catch (System.Data.SqlTypes.SqlTypeException e)
    {
        MessagingService.ShowErrorMessage(e.Message);
    }
    catch (System.Data.SqlClient.SqlException e)
    {
        MessagingService.ShowErrorMessage(e.Message);
    }
}
</code>```

Secondly, you shouldn't be catching NullReferenceExceptions. NREs almost always indicate a programming bug and it is better to fail fast instead of showing an error message without rethrowing it.

Body:
First of all, you should copy the reference of action delegate instance before invoking it to prevent threading issues, like this:

private void ExecutionAction(Action action)
{
    var handler = action;
    if (handler == null)
    {
        return;
    }

    try
    {
        handler();
    }
    catch (System.Data.SqlTypes.SqlTypeException e)
    {
        MessagingService.ShowErrorMessage(e.Message);
    }
    catch (System.Data.SqlClient.SqlException e)
    {
        MessagingService.ShowErrorMessage(e.Message);
    }
}

Secondly, you shouldn't be catching NullReferenceExceptions. NREs almost always indicate a programming bug and it is better to fail fast instead of showing an error message without rethrowing it.


问:
how do interpreters differ for statically- or dynamically-typed languages?
Writing an interpreter for a dynamically typed language usually involves creating an Environment, a data structure which stores mappings of variable names to their values. Values are boxed in some kind of wrapper type, which might look like this in C:

```<code>typedef struct value {
  type_t type;
  void * datum;
} value_t;
</code>```

where type_t explicitly stores the type of the given object. A dictionary from strings to value_t could be used as the environment for the language interpreter.

OCaml and Haskell are both strongly-typed languages, for which there are both compilers and interpreters. How do interpreters for statically typed languages differ from those of dynamically typed languages, if at all?

My first thought was that there could be one environment which maps variables to a descriptor of their types (type_t in the example above), followed by a separate environment for each type seen so far. However, I can't imagine how one would actually go about implementing such a thing. Also, after skimming the source code for the OCaml interpreter, it looks like the same kind of boxing/unboxing of values familiar from dynamic languages is used there too.

答:
Of course, there's a lot of variance in how one does these things. It is generally the case though that you have two passes of the interpreter

Static semantics

This controls type checking but also might generate a more optimized intermediate form for the code to speed up interpretation later

Dynamic semantics

This actually does the evaluation and might in fact be type free. After type checking we know that the types are going to line up and so in many a statically typed language we just erase them. This means that we can represent all our values with a big union in our environment.

Eg we have a type of all values and an map of names to that type. However, in a type safe language doing unions can be tricky so we often enforce tagged unions which have the benefit of being able to tell you what case it's in. In order to use such things we pattern match on an expression, quite a common occurrence in OCaml which I believe accounts for what you saw in their interpreter.


问:
What is the difference between web components and custom elements?
"Web Components" and "Custom elements" are often mixed up, and web searches for the title of this question don't yet produce much clarity. Let's fix that.</p>

答:
Custom elements are a specification part of the Web Components standard, along with Shadow DOM, Templates and HTML imports.

From the spec:

Custom elements provide a way for authors to build their own fully-featured DOM elements. Although authors could always use non-standard elements in their documents, with application-specific behaviour added after the fact by scripting or similar, such elements have historically been non-conforming and not very functional. By defining a custom element, authors can inform the parser how to properly construct an element and how elements of that class should react to changes.

History

The specification is now at v1. The previous version, v0, had been supported since Chrome 33, and had a different API, using document.registerElement - which is now deprecated.

Usage

Custom elements can either be autonomous (creating a new element from scratch (that is, extending HTMLElement), or can customize an existing HTML element (such as HTMLButtonElement).

```<code>// autonomous element
customElements.define("flag-icon", FlagIcon);
// customized <button> element
customElements.define("plastic-button", PlasticButton, { extends: "button" });
</code>```

The second parameter to the customElements.define() call is the name of the class implementing the behavior of the element. See the examples in the spec for autonomous elements and for customized built-in elements.

```<code>class PlasticButton extends HTMLButtonElement {
  constructor() {
    super();

    this.addEventListener("click", () => {
      // Draw some fancy animation effects!
    });
  }
}
</code>```

Custom elements are supported natively in some modern browsers, and can be polyfilled for older browsers going back to Safari 7+ and IE11. See also the v1 polyfill.

Templates and Shadow DOM

By using Templates and Shadow DOM in a custom element, you can make the element easier to handle and resusable.

Templates allow using HTML to declare the structure of custom elements:

```<code><!-- Template Definition -->
<template id="fancy-element-template">
  <style>
    ...
  </style>
  <div id="container">
    <p>Some fancy markup goes here...</p>
  </div>
</template>

<!-- Custom Element usage -->
<fancy-element></fancy-element>
</code>```

Shadow DOM allows styles, ids and classes of the content to be scoped to itself. This prevents CSS bleeding or access to the custom element's internals from outside it.

```<code>customElements.define('fancy-element', class extends HTMLElement {
  constructor() {
    super();
    let shadowRoot = this.attachShadow({mode: 'open'});
    const t = document.querySelector('#fancy-element-template');
    const instance = t.content.cloneNode(true);
    shadowRoot.appendChild(instance);
  }
  ...
});
</code>```

Learn more

Google Developers articles:

Custom elements v1: reusable web components

Shadow DOM: self-contained web components

Body:
Custom elements are a specification part of the Web Components standard, along with Shadow DOM, Templates and HTML imports.

From the spec:

Custom elements provide a way for authors to build their own fully-featured DOM elements. Although authors could always use non-standard elements in their documents, with application-specific behaviour added after the fact by scripting or similar, such elements have historically been non-conforming and not very functional. By defining a custom element, authors can inform the parser how to properly construct an element and how elements of that class should react to changes.

History

The specification is now at v1. The previous version, v0, had been supported since Chrome 33, and had a different API, using document.registerElement - which is now deprecated.

Usage

Custom elements can either be autonomous (creating a new element from scratch (that is, extending HTMLElement), or can customize an existing HTML element (such as HTMLButtonElement).

// autonomous element
customElements.define("flag-icon", FlagIcon);
// customized <button> element
customElements.define("plastic-button", PlasticButton, { extends: "button" });

The second parameter to the customElements.define() call is the name of the class implementing the behavior of the element. See the examples in the spec for autonomous elements and for customized built-in elements.

class PlasticButton extends HTMLButtonElement {
  constructor() {
    super();

    this.addEventListener("click", () => {
      // Draw some fancy animation effects!
    });
  }
}

Custom elements are supported natively in some modern browsers, and can be polyfilled for older browsers going back to Safari 7+ and IE11. See also the v1 polyfill.

Templates and Shadow DOM

By using Templates and Shadow DOM in a custom element, you can make the element easier to handle and resusable.

Templates allow using HTML to declare the structure of custom elements:

<!-- Template Definition -->
<template id="fancy-element-template">
  <style>
    ...
  </style>
  <div id="container">
    <p>Some fancy markup goes here...</p>
  </div>
</template>

<!-- Custom Element usage -->
<fancy-element></fancy-element>

Shadow DOM allows styles, ids and classes of the content to be scoped to itself. This prevents CSS bleeding or access to the custom element's internals from outside it.

customElements.define('fancy-element', class extends HTMLElement {
  constructor() {
    super();
    let shadowRoot = this.attachShadow({mode: 'open'});
    const t = document.querySelector('#fancy-element-template');
    const instance = t.content.cloneNode(true);
    shadowRoot.appendChild(instance);
  }
  ...
});

Learn more

Google Developers articles:

Custom elements v1: reusable web components

Shadow DOM: self-contained web components


问:
Strategy for fixing signed/unsigned warnings
I'm working on obtaining a clean compile with -Wsign-conversion for existing library code. The library is 25 years old or so. Eventually, this higher bar will be a security gate, and all check-ins will need to meet it or be rejected.

The existing library code does a fair amount of the following (a gross simplification that captures the essence):

class SHA1 : <inherited interfaces (contracts) and classes (behaviors)>
{
    ...
    enum {DIGEST_SIZE = 20U};
    unsigned int MaxDigestSize() { return DIGEST_SIZE; }
    ...
    int m_digestSize;
}
```

<p>Then, the library does things like (the interaction is more complex, but this captures the essence):</p>

<pre class="lang-none prettyprint-override"><code>if(m_digestSize == -1)
    m_digestSize = MaxDiegstSize();
</code>```

External callers may use it like:

```<code>SHA1 sha;
...

// Calculate truncated digest
sha.Final(buffer, 8 /*signed or unsigned*/);
// Calculate using full digest
sha.Final(buffer, -1 /*signed*/);
// Calculate using full digest
sha.Final(buffer, sha.MaxDigestSize() /*unsigned*/);
</code>```

The reason -1 is popular is because the following "just works" (notice the switch from SHA-1 to SHA-512):

```<code>SHA512 sha;

// Calculate using full digest
sha.Final(buffer, -1 /*signed*/);
</code>```

For the library, we want to convert to unsigned types to squash the warning. Then, setup an enum {DEFAULT_DIGEST_VALUE=...}; to handle the case of "default digest" that was compatible with the existing "-1 pattern". Finally, remove the compares to -1 and use a compare with DEFAULT_DIGEST_VALUE.

But enum {DEFAULT_DIGEST_VALUE=std::numeric_limits<unsigned int>::max()}; turned out to be a dead end due to limitations in numeric_limits.

Someone suggested to use UINT_MAX, but I'm not sure if I should use it (OS X lacks <cstdint>, so it introduces a C header dependency). Other potential candidates are __INT_MAX__ * 2U + 1 (from <limits> on OS X), and ~(0) (popular in lots of library code, but maybe not correct). In fact, I'm not sure this is the proper path in general.

What is the proper or best way to:

switch to unsigned for consistency and eventual security gate

handle the "-1 pattern" for existing, non-library callers

provide a portable, C++ solution

address potential issues with bit patterns

My apologies for asking a simple question. I am a security architect by trade. I need the help of the software architects because I don't have the software engineering experience.

From the comments, here's some more information regarding constraints:

Existing Code - The library already exists, and its called Crypto++. It was authored in the 1990s, and it enjoys continued development. It is cross platform, and runs on the BSDs, Linux, OS X, Solaris, Windows. The solution needs to support older standards like C++98 and C++03. We can drop support for C++98 if the community agrees.

ABI Changes - we can change the API if the community agrees. I'm fairly certain that will happen when we make the policy change of a "clean compile as a security gate." We don't need to have 100% compatibility, but we do need to handle an existing code base of users using -1 in the field. We can even give users warning to modify their code with the preprocessor macro CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY. But in the end, things have to "just work" for them.

答:
Well from my point of view, you're trying to fix the wrong problem. You use the error-code "-1" to signalize that the MaxDigestSize should be used. This is a technique that Robert C. Martin calls "Mental mapping" in his book Clean Code. Your signed/unsigned conflict is solely caused by the fact that you're using this "error-code". So the problem that you should be fixing instead is "How do I avoid using an error-code".

Lets get into it:

Easiest approach: make m_digestSize and the parameter for the sha.Final() both unsigned ints. This ensures that the Final method can only accept valid values. Now instead of giving your method an error-code, just overload with a default-parameter like:

```<code>Final(byte* buffer, unsigned int digest = DEFAULT_DIGEST);
</code>```

In the example you provided this DEFAULT_DIGEST is based on the immutable value of MaxDigestSize() and would therefore be 20.

EDIT:

Based on the new information in the comments and edits: It appears to me that the big problems are the warnings. Best solution: check for -1 before assigning the parameter to the member variable. Additionally, as mentioned in the comments, you should wrap the primitive into a small structure and offer that as an alternative while marking the old function as deprecated:

```<code>Final(byte* buffer, int digest = DEFAULT_DIGEST) // Mark as deprecated
{
    if(digest < MINIMUM_DIGEST)
    {
        digest = DEFAULT_DIGEST;
    }
    m_digestSize = static_cast<unsigned int>(digest);
    [...]
}

Final(byte* buffer, Digest digest = Digest())
{
    m_digestSize = digest;
    [...]
}

class Digest
{
    public:
    Digest(usigned int value = DEFAULT_DIGEST)
    :digestValue(value){};

    unsigned int GetValue()
    {
        return digestValue
    };

    private:
    unsigned int digestValue;
}
</code>```

Body:
Well from my point of view, you're trying to fix the wrong problem. You use the error-code "-1" to signalize that the MaxDigestSize should be used. This is a technique that Robert C. Martin calls "Mental mapping" in his book Clean Code. Your signed/unsigned conflict is solely caused by the fact that you're using this "error-code". So the problem that you should be fixing instead is "How do I avoid using an error-code".

Lets get into it:

Easiest approach: make m_digestSize and the parameter for the sha.Final() both unsigned ints. This ensures that the Final method can only accept valid values. Now instead of giving your method an error-code, just overload with a default-parameter like:

Final(byte* buffer, unsigned int digest = DEFAULT_DIGEST);

In the example you provided this DEFAULT_DIGEST is based on the immutable value of MaxDigestSize() and would therefore be 20.

EDIT:

Based on the new information in the comments and edits: It appears to me that the big problems are the warnings. Best solution: check for -1 before assigning the parameter to the member variable. Additionally, as mentioned in the comments, you should wrap the primitive into a small structure and offer that as an alternative while marking the old function as deprecated:

Final(byte* buffer, int digest = DEFAULT_DIGEST) // Mark as deprecated
{
    if(digest < MINIMUM_DIGEST)
    {
        digest = DEFAULT_DIGEST;
    }
    m_digestSize = static_cast<unsigned int>(digest);
    [...]
}

Final(byte* buffer, Digest digest = Digest())
{
    m_digestSize = digest;
    [...]
}

class Digest
{
    public:
    Digest(usigned int value = DEFAULT_DIGEST)
    :digestValue(value){};

    unsigned int GetValue()
    {
        return digestValue
    };

    private:
    unsigned int digestValue;
}


问:
Correct approach for creating api contract
I am trying to design an API. For creating contracts below are the two approaches:

Approach 1:

```<code>public class MyController
{
  public void MyAction1(Dictionary<string, dynamic> input)
  {
    //Use input like below
    //Read from input dictionary and apply minimal business logic if needed
    //And Call CustomDataProvider library with input object itself(DataProvider designed in such a way that it takes Dictionary and used values as procedure input. Dictionary key is same as procedure arguments.)
  }

  public void MyAction2(Dictionary<string, dynamic> input)
  {
    //Use input like below
    //Read from input dictionary and apply minimal business logic if needed
    //And Call CustomDataProvider library with input object itself(DataProvider designed in such a way that it takes Dictionary and used values as procedure input. Dictionary key is same as procedure arguments.)
  }
}
</code>```

In this case we don't need data contract at all.

Approach 2:

```<code>public class MyController
{
    public void MyAction1(MyContractBusinessObject1 input)
    {
        //Do normal business logic processing using input object and call DBProvider by creating a dictionary from business object
    }
    public void MyAction2(MyContractBusinessObject2 input)
    {
        //Do normal business logic processing using input object and call DBProvider by creating a dictionary from business object
    }
}
</code>```

In this case we'll have different business classes as contract for different action inputs. Which of the above approaches is better and why?

Let me give an example. Suppose My actions are doing login and new account creation. In first case input will be

```<code>new Dictionary<string, dynamic>{
    {"Name","myname"},
    {"Passowrd",'mypassword'}
}

new Dictionary<string, dynamic>{
    {"Name","myname"},
    {"Passowrd",'mypassword'},
    {"Age",myage},
    {"otherInfo",myotherinfo}
}
</code>```

but in approach 2 input will be

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

class NewAccount{
    public string Name{get; set;}
    public string Password{get; set;}
    public int Age{get; set;}
    public OtherInfo OtherInfo{get; set;}
}
</code>```

答:
So the question is: should I have a single method that takes generic parameters, or many methods that take specific parameters?

Entirely up to you, but note: the generic method requires much validation that you'd partially get for free by using specific parameter types. Note also that the generic method will be acting as a broker, taking the generic types and translating them into specific types to pass to helper functions anyway (similar to how a web server has a single routine that accepts requests, parses them, and passes them on to a routine specific to the requested page).

Its entirely subjective, I've seen both styles used in different circumstances, and both work.

OwnerDisplayName: Ashutosh Pandey


答:
It looks like you have C code, so forget c++ifying it and stick with what it is.

Converting all to unsigned is a good idea, getting your types right is a good thing. I would take the opportunity to remove int and replace with a known size type, such a long or __int32 so you know how many bytes of data are being manipulated (int is usually 32-bits, but sometimes isn't). I'd say that was important for security software.

Next, if you knwo your int is 32-bits, you can set your max_digest to 0xffffffff (which is what ~0 is doing, its inverting each bit, so all the 0s become 1s - of 0x0 becomes 0xffffffff, without having to know how many bits are involved)

Title: Strategy for fixing signed/unsigned warnings

Body:
I'm working on obtaining a clean compile with -Wsign-conversion for existing library code. The library is 25 years old or so. Eventually, this higher bar will be a security gate, and all check-ins will need to meet it or be rejected.

The existing library code does a fair amount of the following (a gross simplification that captures the essence):

class SHA1 : <inherited interfaces (contracts) and classes (behaviors)>
{
    ...
    enum {DIGEST_SIZE = 20U};
    unsigned int MaxDigestSize() { return DIGEST_SIZE; }
    ...
    int m_digestSize;
}
```

<p>Then, the library does things like (the interaction is more complex, but this captures the essence):</p>

<pre class="lang-none prettyprint-override"><code>if(m_digestSize == -1)
    m_digestSize = MaxDiegstSize();
</code>```

External callers may use it like:

```<code>SHA1 sha;
...

// Calculate truncated digest
sha.Final(buffer, 8 /*signed or unsigned*/);
// Calculate using full digest
sha.Final(buffer, -1 /*signed*/);
// Calculate using full digest
sha.Final(buffer, sha.MaxDigestSize() /*unsigned*/);
</code>```

The reason -1 is popular is because the following "just works" (notice the switch from SHA-1 to SHA-512):

```<code>SHA512 sha;

// Calculate using full digest
sha.Final(buffer, -1 /*signed*/);
</code>```

For the library, we want to convert to unsigned types to squash the warning. Then, setup an enum {DEFAULT_DIGEST_VALUE=...}; to handle the case of "default digest" that was compatible with the existing "-1 pattern". Finally, remove the compares to -1 and use a compare with DEFAULT_DIGEST_VALUE.

But enum {DEFAULT_DIGEST_VALUE=std::numeric_limits<unsigned int>::max()}; turned out to be a dead end due to limitations in numeric_limits.

Someone suggested to use UINT_MAX, but I'm not sure if I should use it (OS X lacks <cstdint>, so it introduces a C header dependency). Other potential candidates are __INT_MAX__ * 2U + 1 (from <limits> on OS X), and ~(0) (popular in lots of library code, but maybe not correct). In fact, I'm not sure this is the proper path in general.

What is the proper or best way to:

switch to unsigned for consistency and eventual security gate

handle the "-1 pattern" for existing, non-library callers

provide a portable, C++ solution

address potential issues with bit patterns

My apologies for asking a simple question. I am a security architect by trade. I need the help of the software architects because I don't have the software engineering experience.

From the comments, here's some more information regarding constraints:

Existing Code - The library already exists, and its called Crypto++. It was authored in the 1990s, and it enjoys continued development. It is cross platform, and runs on the BSDs, Linux, OS X, Solaris, Windows. The solution needs to support older standards like C++98 and C++03. We can drop support for C++98 if the community agrees.

ABI Changes - we can change the API if the community agrees. I'm fairly certain that will happen when we make the policy change of a "clean compile as a security gate." We don't need to have 100% compatibility, but we do need to handle an existing code base of users using -1 in the field. We can even give users warning to modify their code with the preprocessor macro CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY. But in the end, things have to "just work" for them.


问:
PHP filesystem best practice
I'm writing a PHP script which communicates with another program via files. I wonder if there is some policy or standard on where to put such files? I assume choosing a path like C:\foo\bar\ isn't the best? If nothing else it's not portable.

Would $_SERVER['HOME'] be a good place or is there something more appropriate? The temp folder is not good as the files technically aren't temporary.

For a Windows application I think you would typically use %appdata%\\{company name}\\{app name} but that's obviously not that great for PHP.

答:
Typically the right place for a file exchange folder would be outside of the webroot where both web applications have access to. So it's anywhere, except where other files reside.

Files will generally be FTP'ed or SFTP'ed (FTP over SSH) to the server, or share the same folder on the host if they are served from the same machine (actual machine or VM).

Make sure that you remove the files after they have served their usefulness. Last thing you want is a big bulk of files in a folder that you will never (ever) use again...

Hope it helps

Title: PHP filesystem best practice


问:
Is it safe to only use intval to sanitize user input for a database select?
Is it safe to only use intval to sanitize the user input for a database select, as in the following example?</p>

```<code>$id = intval($_GET['id']);

$query = "SELECT * FROM table WHERE id='$id'";
</code>```

答:
Rule of thumb is: If the input comes from anywhere else than from the code itself, the data  provided is to be considered 'tainted'. You will have to make sure the value is what you expect and would not mess up your SQL statement (injection).

Though I question why you're not using/utilizing PDO and use markers in your statement so these things are handled automatically.

But I would choose to do something like this (using a ternary operator):

```<code>$id = (is_numeric($id) && $id > 0) ? $id : false;

if ($id !== false) {
   ... code goes here ...
}
</code>```

It doubles the possibility of $id being a realistic integer.

Body:
Rule of thumb is: If the input comes from anywhere else than from the code itself, the data  provided is to be considered 'tainted'. You will have to make sure the value is what you expect and would not mess up your SQL statement (injection).

Though I question why you're not using/utilizing PDO and use markers in your statement so these things are handled automatically.

But I would choose to do something like this (using a ternary operator):

$id = (is_numeric($id) && $id > 0) ? $id : false;

if ($id !== false) {
   ... code goes here ...
}

It doubles the possibility of $id being a realistic integer.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
Yes, there is plenty of evil to be had. For example:</p>

```<code>Type1 variable1 = function12()
variable5 = variable1.myMethod(variable1+aGlobal);
variable2.otherMethod(anotherGlobal);
</code>```

Title: Is anything in programming truly evil?

Body:
Yes, there is plenty of evil to be had. For example:

Type1 variable1 = function12()
variable5 = variable1.myMethod(variable1+aGlobal);
variable2.otherMethod(anotherGlobal);


问:
Is it possible to make something open-source without publishing it?
I've been working on some piece of software while being "employed" by company A. I now want to continue working on the same software while being employed by company B. Company B wants the software to become open-source to prevent any future legal issues between company A and them. I will consult company A's lawyer to make sure it's fine by them, but I suspect it will be alright as company A is actually a public university which looks favorably on industry connections.

However, I am concerned by potential competitors getting access to that code before we make its results public. Is it possible to make the software open-source without sharing it with anyone but company B (neither in binary nor source form), or do I have to publish the software the minute it is made open-source or shared with anyone?

If the answer depends on the specific open-source license used, please be kind and provide details about the differences.

答:
If you are the copyright holder, you can do whatever you like. That's because the only one who can sue you for a license violation is the copyright holder, and if you are the copyright holder, unless you are schizophrenic, nobody can sue you.

If you use the GPL license, you have three choices: One, you can accompany every copy that you distribute with the source code. Then nobody in the world can demand anything from you. If I download your application and forget to download the source as well, I have no right to ask you for it. So that is what you should do: Always give people the application and the source code together, then you have no legal obligation whatsoever.

Two, every copy of your application is accompanied by a promise to deliver the source code. That's NOT what you want, because in that case everybody in the world has the right to ask you for the source code, whether they got the application from you or not.

Three, doesn't apply to you, if you distribute an unmodified copy of someone else's GPL product, and that someone else has application and source available for download, then you can distribute the unmodified copy and point to that other person or organisation.

In any case, anybody who has the application and source code can pass them on to anybody they like. (If they don't have the source code, only if case 3 applies).


问:
Is the use of set / get prefix discouraged for methods if they don't actually mutate / access fields
This could be a quirk of the IDE I am using, Android Studio, or it could be something more nuanced that I don't understand.

I have a method setCustomFont that appears as a property in the Structure view in my IDE. It appears that AS is making this decision to class it as a property based on its signature and the set / get prefix of the method name. The field that it thinks I am mutating is customFont however this does not exist.

I changed the method name to applyCustomFont and now the Structure view in AS reflects something closer to the truth in my class.

I was wondering if this is by design? Should I try and stay clear of set / get unless I have an associated field?

Edit: I am also wondering about sensible method names regardless of whether the IDE has a Structure view.

答:
Given the popularity of different kinds of frameworks that rely on Java Beans convention, I think we should avoid prefixing the methods with get/set if they don't represent the object's properties.

It happened to me in a few occasions that I unintentionally added a useless attribute in a JSON response of a service, just because I added a new helper get method to the object being serialized. Sometimes it's just an extra useless information, but sometimes it causes NullPointerExceptions or similar.

Rather, I prefer using other equivalent prefixes, so instead of:

```<code>circle.getArea();
</code>```

I would have:

```<code>circle.calcArea();
</code>```

This way I also more explicitly indicate that some calculation is done in the method, rather than just returning a stored value.

Body:
Given the popularity of different kinds of frameworks that rely on Java Beans convention, I think we should avoid prefixing the methods with get/set if they don't represent the object's properties.

It happened to me in a few occasions that I unintentionally added a useless attribute in a JSON response of a service, just because I added a new helper get method to the object being serialized. Sometimes it's just an extra useless information, but sometimes it causes NullPointerExceptions or similar.

Rather, I prefer using other equivalent prefixes, so instead of:

circle.getArea();

I would have:

circle.calcArea();

This way I also more explicitly indicate that some calculation is done in the method, rather than just returning a stored value.


问:
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.

答:
There are several possible negatives when considering custom header fields.

Browser based testing will be difficult

Proxies sometimes remove/mangle headers fields

It breaks HTTP cacheing

Other developers will not expect it

When returning a dynamic list, you will want cacheing disabled, so that shouldn't be a problem.

If you never expect to use a browser to test your endpoints, you know all the proxies which will be used, and you feel you can document the behavior so future developers won't be surprised by this novel behavior, then try it out.

I've had similar ideas before for HTTP header fields, but they've never worked out. You might have better luck.

Title: REST API paging via headers