答:
Ok so the code for Count() in C# would be:

public static int Count<T>(this IEnumerable<T> enumerable)
{
    var count = 0;

    using (var enumerator = enumerable.GetEnumerator())
    {
        while (enumerator.MoveNext())
            count += 1;
    }
}
```

<p>It's pretty easy to imagine that if this gets inlined, the predicate is pushed into the <code>while</code> condition:</p>

<pre class="lang-cs prettyprint-override"><code>var result = false;
{
    var count = 0;

    using (var enumerator = enumerable.GetEnumerator())
    {
        while (!result && enumerator.MoveNext())
        {
            count += 1;
            result = count > x;
        }
    }
}

if (result) // the original condition featuring Count() > x
</code>```

EDIT: This is not possible though unless the compiler/optimizer can devirtualize the IEnumerator<T> as it can have side effects and the loop cannot be cut short unless the compiler can be sure that nothing changes by that.</edit>

Besides, I'm afraid the optimization options are limited to the given language runtime - JITed can hope for the inline, compiled can get this optimization through whole-program analysis after linkage and functional - no idea there...

But I'm afraid that the compiler won't be able to do much since this will usually be used from external binaries. And those see the implementation only in link-time.

If you're doing a framework and want this, these are some ideas:

Put as much compiler-inline-this-please attributes as you can

Create two versions: Count() and CountUntil(Predicate<int>)

Have higher hopes about your users :)

Or possibly

Don't implement the Count() at all - make the users explicitly create a collection and .Count it or use foreach. Not very friendly though...

Title: How to optimize iterable queries with external arguments

Body:
I will use C# here as an example, but my question is about any language.

My question is from framework to compiler perspective (i.e the solution can be by implementing given idea inside compiler)

Consider such code:

```<code>if (sequence.Any()) ...
</code>```

and let's say the sequence "holds" 1 million items. This condition will be executed pretty fast nevertheless (with single check -- either iterator moves or not). Now, slight change:

```<code>if (sequence.Count() > 1) ...
</code>```

now the sequence will be iterated over 1 million items and after that the result will be "oh yes, we have at least 1 item".

Question: how it could be optimized in such way, that the excessive iterations will not be made. On the other hand I would like to avoid polluting framework with plethora of "optimized" methods -- CountAtMost, CountAtLeast -- and so on.

Of source Count is just example, another aggregation queries come to mind -- consider expression (wrong example I am keeping it for historical reasons) collection.Sum() > 1000.

I am not asking about C#-specific optimizations, the question is completely general -- iterable sequences are present in a lot of languages. Iterable sequences can come from generators as well, so the question is how to optimize aggregation query with external (comparing to query) arguments.

Body:
Ok so the code for Count() in C# would be:

public static int Count<T>(this IEnumerable<T> enumerable)
{
    var count = 0;

    using (var enumerator = enumerable.GetEnumerator())
    {
        while (enumerator.MoveNext())
            count += 1;
    }
}

It's pretty easy to imagine that if this gets inlined, the predicate is pushed into the while condition:

var result = false;
{
    var count = 0;

    using (var enumerator = enumerable.GetEnumerator())
    {
        while (!result && enumerator.MoveNext())
        {
            count += 1;
            result = count > x;
        }
    }
}

if (result) // the original condition featuring Count() > x

EDIT: This is not possible though unless the compiler/optimizer can devirtualize the IEnumerator<T> as it can have side effects and the loop cannot be cut short unless the compiler can be sure that nothing changes by that.</edit>

Besides, I'm afraid the optimization options are limited to the given language runtime - JITed can hope for the inline, compiled can get this optimization through whole-program analysis after linkage and functional - no idea there...

But I'm afraid that the compiler won't be able to do much since this will usually be used from external binaries. And those see the implementation only in link-time.

If you're doing a framework and want this, these are some ideas:

Put as much compiler-inline-this-please attributes as you can

Create two versions: Count() and CountUntil(Predicate<int>)

Have higher hopes about your users :)

Or possibly

Don't implement the Count() at all - make the users explicitly create a collection and .Count it or use foreach. Not very friendly though...


问:
Use Queue<T> or stick to native f# lists
I need something that represents a queue in F#.

The queue will be filled with items once, and (as the application progresses) items will be taken from this queue and moved to other lists.

Should I use the Queue class in .NET, or should I avoid it, and use the native lists in F# instead? Is there a better solution?

Why should I use one, or the other, in a functional language such as F#?

答: If you use a native queue, you can wrap it inside a MailboxProcessor, so that mutation will be synchronized across threads, without needing locks.

ContentLicense: CC BY-SA 3.0


问:
Design - shallow routes for an API
I am building an API that will connect to multiple databases. I am using Emberjs on the front end and the default rest adapter seems to prefer shallow routes. Say, I have the following routes

```<code>api/databases
api/databases/1/employees
</code>```

At this point, my routes are already 2 levels deep. Any further nesting makes it hard to deal with

```<code>api/databases/1/employees/2/tasks
</code>```

In the above URL, I'd like to be able to eliminate the 'databases/1/' portion which will make the rest of the resources easy to access within one or two levels but I am not sure how to pass in the information about the database. I thought about using query parameters but that seems like bad design

```<code>api/employees/2/tasks?database=1
</code>```

Any feedback would be appreciated.

答:
I assume that you will be using some sort of authentication in your API.  Let's say (for argument's sake) that you're providing an API key (GUID) to each user that they put into the HTTP header when accessing this API:

```<code>GET /employees HTTP/1.1
Host: foobar.com
Accept: application/json
Content-Type: application/json
X-Api-Key: AAAABBBB-CCCC-DDDD-EEEE-FFFFFFFFFFFF
</code>```

Since 70% of API users will always access the same database, you could provide a 1:1 mapping (in your user database) which maps API keys to databases.  The API key then fulfils 2 purposes:

Identify and authenticate the user

Choose the correct database to use

For the 30% of users who need to access multiple databases, simply provide them with different keys for each database.

What this means:

You can take out any references to the database in the URI

Database-local IDs (e.g. employee) now become globally unique within the context of a particular API call.

This means you can now provide simpler URIs such as the following:

```<code>/employees
/employees/2
/employees/2/tasks
/employees/2/tasks/3
</code>```

Title: Design - shallow routes for an API

Body:
I assume that you will be using some sort of authentication in your API.  Let's say (for argument's sake) that you're providing an API key (GUID) to each user that they put into the HTTP header when accessing this API:

GET /employees HTTP/1.1
Host: foobar.com
Accept: application/json
Content-Type: application/json
X-Api-Key: AAAABBBB-CCCC-DDDD-EEEE-FFFFFFFFFFFF

Since 70% of API users will always access the same database, you could provide a 1:1 mapping (in your user database) which maps API keys to databases.  The API key then fulfils 2 purposes:

Identify and authenticate the user

Choose the correct database to use

For the 30% of users who need to access multiple databases, simply provide them with different keys for each database.

What this means:

You can take out any references to the database in the URI

Database-local IDs (e.g. employee) now become globally unique within the context of a particular API call.

This means you can now provide simpler URIs such as the following:

/employees
/employees/2
/employees/2/tasks
/employees/2/tasks/3


问:
Using a bytearray rather than a string to store password in memory
Using a bytearray datatype to store a password (in memory) has an advantage over using a string datatype for a password in that a bytearray is mutable and can be overwritten with 0x00 values when the password is no longer needed for processing and until the password variable is garbage collected.  It's not clear to me, however, whether overwriting 0x00 values will achieve what is intended.  When a password is no longer needed, it should be wiped from memory, prior to GC.  Is this possible in python 3.4 using bytearray?</p>

答:
Erasing content in a mutable bytearray is doable. However, depending on your usage, the downstream function which consumes a password may expect only a string, not a bytearray. In that case, you are stuck with using string, and there won't be a real way to erase the password in string.

See also discussions about erasing password in Python string in this Q&A.


问:
How to optimize iterable queries with external arguments

I will use C# here as an example, but my question is about any language.

My question is from framework to compiler perspective (i.e the solution can be by implementing given idea inside compiler)

Consider such code:

```<code>if (sequence.Any()) ...
</code>```

and let's say the sequence "holds" 1 million items. This condition will be executed pretty fast nevertheless (with single check -- either iterator moves or not). Now, slight change:

```<code>if (sequence.Count() > 1) ...
</code>```

now the sequence will be iterated over 1 million items and after that the result will be "oh yes, we have at least 1 item".

Question: how it could be optimized in such way, that the excessive iterations will not be made. On the other hand I would like to avoid polluting framework with plethora of "optimized" methods -- CountAtMost, CountAtLeast -- and so on.

Of source Count is just example, another aggregation queries come to mind -- consider expression (wrong example I am keeping it for historical reasons) collection.Sum() > 1000.

I am not asking about C#-specific optimizations, the question is completely general -- iterable sequences are present in a lot of languages. Iterable sequences can come from generators as well, so the question is how to optimize aggregation query with external (comparing to query) arguments.

答: I think I found the solution -- the key is to follow deferred execution of sequences (iterables). Count should not return int type, but some Counted type which would keep reference to the sequence. With implicit conversion to int it would integrate smoothly, but having overloaded some operators it could process even infinite sequences.


问:
REST Standard for changing SPA Model after fetched from REST API
Let's imagine. I have following data from database.

======================================
id    |  Title     |   parentId
======================================
100      Asia          NULL
--------------------------------------
101      India         100
--------------------------------------
102      Tamil Nadu    101
--------------------------------------
103      Chennai       102
--------------------------------------
104      Karnataka     101
--------------------------------------
105      Bengalaru     104
--------------------------------------
```

<p>Which can be rendered as like below JSON Format. Lets keep this as first format.</p>

```{
  "children": [{
    "id": 100,
    "title": "Asia",
    "parentId": ""
  }, {
    "id": 107,
    "title": "India",
    "parentId": 100
  }, {
    "id": 108,
    "title": "Tamil Nadu",
    "parentId": 107
  }, {
    "id": 109,
    "title": "Karnataka",
    "parentId": 107
  }, {
    "id": 112,
    "title": "Chennai",
    "parentId": 108
  }, {
    "id": 113,
    "title": "Bengalaru",
    "parentId": 109
  }]
}
```

<p>I would like to have below JSON Format which is good for recursive drill down menu and keep this as second format.</p>

```{
  "children": [{
    "id": 100,
    "title": "Asia",
    "children": [{
      "title": "India",
      "children": [{
        "title": "Tamil Nadu",
        "children":[{
          "title": "Chennai"
        }]
      }, {
        "title": "Karnataka",
        "children":[{
          "title": "Bengaluru"
        }]
      }]
    }, {
      "title": "China"
    }]
  }]
}
```

My question here which format is REST Standard / best practice in REST. Using first format and modifying through JavaScript model / using second format.

答:
Neither Format Is REST Standard.

REST does not define representation standards.

REST does not specify the format of resources.

REST is an "architectural style" not a standard. Fielding Dissertation - The Original Document Describing REST

It is your application's decision whether to use a hierarchical representation or a flat representation, or to offer both, just as it is your decision whether to use JSON or XML or Protocol Buffers or HTML, or all of them, for example.

Neither Representation Is Best Practice.

It depends on your applications' needs or your clients' needs.

There really is no one size fits all best practice for this. You will find a range of opinions. There are potentially great reasons to do it either way, depending on your requirements, tools, team proficiencies, etc.

You really just have to consider the pros and cons in your situation, and don't worry about it too much. Either choice will work with most tools.

REST Questions You Should Ask

What are these resources? What will the resource identifiers look like? (URI's) A simple, efficient, appropriately cacheable URI model is at the heart or foundation of a good REST service. How will a client specify what media type, representation it wants?

Will you need to retrieve more detail on the individual states (of India) and capitals? Is this a collection and are those states individual resources?

If the application will need to GET or PUT, say "Karnataka" how will it know what URI to use? That is not included in your representation.

If this is not a read only resource, how will use use the HTTP commands (GET, PUT, POST, etc.) to act on it? Using those commands properly is at the heart of REST over HTTP.

After that, look up HATEOAS. Then have another coffee. Read it again, then post questions here if needed. Seriously HATEOAS seems to throw people for a loop.

Now you are ready for the versioning wars. How will you evolve your api? Will you version it? (The REST thought police will get me for even asking that question.)

There's No Law That Says Good APIs Have To Use The REST Style

Fielding is happy to remind us of this, if we need a respected voice.

Really doing REST is a commitment to some intellectual effort, and some discipline in designing, testing and evolving your API. It's not needed for every API.

Sometimes you just have to build stuff that works and ship it. Refactor on the next iteration when you know more.


问:
Is it a good practice to avoid constants by using getters?
Is it a good practice to replace constants used outside of classes by getters?

As an example, is it better to use if User.getRole().getCode() == Role.CODE_ADMIN or if User.getRole().isCodeAdmin()?

That would lead to this class:

```<code>class Role {
    constant CODE_ADMIN = "admin"
    constant CODE_USER = "user"

    private code

    getRoleCode() {
       return Role.code
    }

    isCodeAdmin () {
       return Role.code == Role.CODE_ADMIN
    }

    isCodeUser () {
       return Role.code == Role.CODE_USER
    }
}
</code>```

答:
It seems daft to have a function to check whether the code that is stored is the admin code. What you really want to know is whether that person is an admin. So if you don't want to expose the constants, then you also shouldn't expose that there is a code, and call the methods isAdmin () and isUser ().

That said, "if User.getRole().getCode() == Role.CODE_ADMIN" really is a handful just for checking that a user is an admin. How many things does a developer have to remember to write that line? He or she has to remember that a user has a role, a role has a code, and the Role class has constants for codes. That's a lot of information that is purely about the implementation.


答:
First off, please note that doing something like entity.underlyingEntity.underlyingEntity.method() is considered a code smell according to the Law of Demeter. This way, you're exposing a lot of implementation details to the consumer. And each need of extension or modification of such a system will hurt a lot.

So given that, I'd recommend you to have a HasRole or IsAdmin method on the User as per CodesInChaos' comment. This way, the way how the roles are implemented on the user remains implementation detail for the consumer. And also it feels more natural to ask the user what his role is instead of asking him about details of his role and then deciding based on that.

Please also avoid using strings unless where necessary. name is a good example of string variable because the contents are unknown beforehand. On the other hand, something like role where you have two distinct values that are well known at compilation time, you'd better use strong typing. That's where enumeration type comes into play...

Compare

public bool HasRole(string role)
```

<p>with</p>

<pre class="lang-cs prettyprint-override"><code>public enum Role { Admin, User }

public bool HasRole(Role role)
</code>```

The second case gives me a lot more idea of what I should be passing around. It also prevents me from erroneously passing in an invalid string in case I had no idea about your role constants.

Next is the decision on how will the role look. You can either use enum directly stored on the user:

public enum Role
{
    Admin,
    User
}

public class User
{
    private Role _role;

    public bool HasRole(Role role)
    {
        return _role == role;
    }

    // or
    public bool IsAdmin()
    {
        return _role == Role.Admin;
    }
}
```

<p>On the other hand, if you want your role to have a behaviour itself, it should definitely again hide the details of how its type is being decided:</p>

<pre class="lang-cs prettyprint-override"><code>public enum RoleType
{
    User,
    Admin
}

public class Role
{
    private RoleType _roleType;

    public bool IsAdmin()
    {
        return _roleType == RoleType.Admin;
    }

    public bool IsUser()
    {
        return _roleType == RoleType.User;
    }

    // more role-specific logic...
}

public class User
{
    private Role _role;

    public bool IsAdmin()
    {
        return _role.IsAdmin();
    }

    public bool IsUser()
    {
        return _role.IsUser();
    }
}
</code>```

This is however quite verbose and the complexity would rise with each role addition - that's usually how the code ends up when you try to fully adhere to the Law of Demeter. You should improve the design, based on the concrete requirements of the system being modeled.

According to your question, I guess you'd better go with the first option with enum directly on User. Should you need more logic on the Role, the second option should be considered as a starting point.

Title: Is it a good practice to avoid constants by using getters?

Body:
Is it a good practice to replace constants used outside of classes by getters?

As an example, is it better to use if User.getRole().getCode() == Role.CODE_ADMIN or if User.getRole().isCodeAdmin()?

That would lead to this class:

```<code>class Role {
    constant CODE_ADMIN = "admin"
    constant CODE_USER = "user"

    private code

    getRoleCode() {
       return Role.code
    }

    isCodeAdmin () {
       return Role.code == Role.CODE_ADMIN
    }

    isCodeUser () {
       return Role.code == Role.CODE_USER
    }
}
</code>```

Body:
First off, please note that doing something like entity.underlyingEntity.underlyingEntity.method() is considered a code smell according to the Law of Demeter. This way, you're exposing a lot of implementation details to the consumer. And each need of extension or modification of such a system will hurt a lot.

So given that, I'd recommend you to have a HasRole or IsAdmin method on the User as per CodesInChaos' comment. This way, the way how the roles are implemented on the user remains implementation detail for the consumer. And also it feels more natural to ask the user what his role is instead of asking him about details of his role and then deciding based on that.

Please also avoid using strings unless where necessary. name is a good example of string variable because the contents are unknown beforehand. On the other hand, something like role where you have two distinct values that are well known at compilation time, you'd better use strong typing. That's where enumeration type comes into play...

Compare

public bool HasRole(string role)

with

public enum Role { Admin, User }

public bool HasRole(Role role)

The second case gives me a lot more idea of what I should be passing around. It also prevents me from erroneously passing in an invalid string in case I had no idea about your role constants.

Next is the decision on how will the role look. You can either use enum directly stored on the user:

public enum Role
{
    Admin,
    User
}

public class User
{
    private Role _role;

    public bool HasRole(Role role)
    {
        return _role == role;
    }

    // or
    public bool IsAdmin()
    {
        return _role == Role.Admin;
    }
}

On the other hand, if you want your role to have a behaviour itself, it should definitely again hide the details of how its type is being decided:

public enum RoleType
{
    User,
    Admin
}

public class Role
{
    private RoleType _roleType;

    public bool IsAdmin()
    {
        return _roleType == RoleType.Admin;
    }

    public bool IsUser()
    {
        return _roleType == RoleType.User;
    }

    // more role-specific logic...
}

public class User
{
    private Role _role;

    public bool IsAdmin()
    {
        return _role.IsAdmin();
    }

    public bool IsUser()
    {
        return _role.IsUser();
    }
}

This is however quite verbose and the complexity would rise with each role addition - that's usually how the code ends up when you try to fully adhere to the Law of Demeter. You should improve the design, based on the concrete requirements of the system being modeled.

According to your question, I guess you'd better go with the first option with enum directly on User. Should you need more logic on the Role, the second option should be considered as a starting point.


问:
Enforcing order for two consecutive statements
I have the following code:

```<code>subroutine foo(int index)
{
    // Check A.
    // Critical: Check A must precede Check B below.
    if (index == 1)
    {
        return true;
    }

    // Check B.
    if (index - 2 < 0)
    {
        return false;
    }

    return true;
}
</code>```

The code is a simplified representation of a real-life scenario where I am checking for validity of punctuation marks in a string.

My question: Is there a construct in any language which would guarantee that the order of the two if statements are maintained as is?  (Without having to place a comment in the code as I have done and hope that it is heeded.)

For the case where index is 1, if Check B is moved before Check A, Check A will never be caught and foo() will always return false, which is bad.

Again, my concern is for the maintenance of the code by future programmers.  There are about 10 if statements in the code, one after another, and their order is important.

EDIT 1:

I am an experienced developer, and I am really asking whether there are any new developments in languages that would allow for what I am asking above.  I am sorry that I did not make this clear.

EDIT 2:

In response to comments suggesting index < 2 instead of index - 2 < 0: I don't agree.  index - 2 indicates that I am interested if there is an item two locations before the current index, while index < 2 does not convey the same information.  (Of course, this is my opinion!)

答:
Anyone who can  edit the source code can remove anything that you might put in there to "protect" them. You can do two things:

Choose a good name for the function that conveys your intention

Provide Unit Tests that will break if someone ever changes what the function does

Both do not prevent future programmers from changing anything if they need to, but they will have some guidance in how the function was intended to behave.

Another option would be to turn these temporal dependencies into structural ones by having the first one generate/return something that the second one requires as input. But that is likely overkill for something as simple as your example. Robert C. Martin mentions this technique in his book "Clean Code".


答:
In probably all relevant languages, the statements are processed in order.

And that's valid for the whole program code. Even the simplest programs wouldn't work otherwise.

If someone is allowed to change the code but doesn't understand anything about it, there's not much you can do about it, except removing his rights to do so.

Nothing wrong with a comment in the code if it is hard to understand, or refactoring the code to make its intents more clear, of course.

Edit (as in comment):

The easier understandable your code, the lesser the chances of messing around with it. For example, (index < 2) would be much easier to read and understand for me. And in this case, it's the same as (index < 0).
So this function always returns true for positive numbers, so the whole function is as simple as return index > 0.

Make your logic as easy to follow as possible.

And - as another answer has pointed out - this should be captured by a unit test anyway.

Title: Enforcing order for two consecutive statements

Body:
I have the following code:

```<code>subroutine foo(int index)
{
    // Check A.
    // Critical: Check A must precede Check B below.
    if (index == 1)
    {
        return true;
    }

    // Check B.
    if (index - 2 < 0)
    {
        return false;
    }

    return true;
}
</code>```

The code is a simplified representation of a real-life scenario where I am checking for validity of punctuation marks in a string.

My question: Is there a construct in any language which would guarantee that the order of the two if statements are maintained as is?  (Without having to place a comment in the code as I have done and hope that it is heeded.)

For the case where index is 1, if Check B is moved before Check A, Check A will never be caught and foo() will always return false, which is bad.

Again, my concern is for the maintenance of the code by future programmers.  There are about 10 if statements in the code, one after another, and their order is important.

EDIT 1:

I am an experienced developer, and I am really asking whether there are any new developments in languages that would allow for what I am asking above.  I am sorry that I did not make this clear.

EDIT 2:

In response to comments suggesting index < 2 instead of index - 2 < 0: I don't agree.  index - 2 indicates that I am interested if there is an item two locations before the current index, while index < 2 does not convey the same information.  (Of course, this is my opinion!)


答:
In addition to what others have posted already, you should keep in mind that using the constant directly has another drawback: if anything changes how you handle user rights, all those places needs to be changed, too.

And it makes it horrible to enhance. Maybe you'd like to have a super user type at one point, that obviously also has admin rights. With encapsulation, it's basically a one-liner to add.

It's not only short and clean, it's also easy to use and understand. And - maybe most of all - it's hard to get wrong.


答:
So, you're asking how to protect your code from clumsy future devs?  That's a tough task which is usually handled by applying code organisation techniques and not language constructs.

In this specific case, I would simply make sure that reorderring the if blocks didn't functionally change my method.  Like this:

```<code>subroutine foo(int index)
{
    bool checkA = (index == 1);
    bool checkB = (index - 2 < 0);

    if (checkA)
    {
        return true;
    }

    if (!checkA && checkB)
    {
        return false;
    }

    return true;
}
</code>```

Of course, you could accomplish the same thing by putting CheckB in CheckA's else block, but then we're nesting ifs, which I don't like.

Body:
So, you're asking how to protect your code from clumsy future devs?  That's a tough task which is usually handled by applying code organisation techniques and not language constructs.

In this specific case, I would simply make sure that reorderring the if blocks didn't functionally change my method.  Like this:

subroutine foo(int index)
{
    bool checkA = (index == 1);
    bool checkB = (index - 2 < 0);

    if (checkA)
    {
        return true;
    }

    if (!checkA && checkB)
    {
        return false;
    }

    return true;
}

Of course, you could accomplish the same thing by putting CheckB in CheckA's else block, but then we're nesting ifs, which I don't like.


问:
Questions about developing for azure
We currently have a .Net MVC web app with a SQL server back-end database and two web services that perform periodically some computing tasks in the database.

I am thinking of packaging this app for the cloud, where a client would "instantiate" it as a whole package. This process would allocate automatically the pieces needed to run the whole thing, i.e. the site, the database and the other two services.

I've been reading quite a bit about azure and I am having a very hard time getting my head around the whole azure development, testing and deployment process, then upgrading and applying changes to existing deployments. I am used to having control of all the pieces. First I like to have everything local on my workstation. We use git and we have our own self managed repository. I find it weird to have a dev environment on a remote cloud computer. I think source code is one of the most valuable assets of a company along with the data (the data more so).

In the current environment we build the apps manually (I know it's far from being ideal, we will automate this process and I am not worried about it for now) and we deploy by simply copying the new version of top of the old one. We also do backups, recompile database stored procedures and apply scripts that massage data, change tables structures or add indexes and so on. There is some downtime allocated while the upgrades are done. Before we deploy to production we deploy to the integration and test environments.

How does all this translate to an azure architecture?

Here is my mental model:

Development and integration are done locally.

The software is packaged locally as a SAAS and uploaded to the cloud. I assume the cloud will take a manifest that includes all the resources the app needs and will allocate them when the app is created the first time in the cloud. This process will have to be tested in the cloud by us.

As for upgrades, the upgrades would have to be applied by the client to existing deployments. I guess another option would be to create a new instance and migrate the data from the old one. I see the upgrades as packages that can be dropped onto existing deployments and they would perform certain tasks, much like a setup software that performs an upgrade on an older version. The upgrades would have be tested as well in the cloud.

I kind of assumed that the app can have some minor downtime. I realize that other apps might not have this luxury, but I don't want to go there now.

Anyway, is this doable in the azure world? Should anything be done differently? And how would one charge in this model?

Thanks

An update: I was thinking more about it and I guess another model would be to build a monolithic app that would allow users to sign up for the service (much like an email app) and it would allocate resources accordingly. I guess in this case the charging model is easier. The downside is that the app would have to be designed to be multi-tenant and it would have its own set of challenges. I am still fuzzy about how the whole development->test->production cycle would work in this case.

答:
Part of the problem with Azure is that there are often several ways to achieve the same result - in the case of a web site your options range from App Services to Virtual Machines.

Your solution is probably best deployed as an App Service - basically what was once called an Azure Web Site and what sound like two Web Jobs along with an SQL Database.

In order to keep the model simple (i.e. consistent with your current usage) you can have as many of these as you want (within reason) and there's scope for scaling within Azure App services and SQL Servers (elastic database pools).

There are several deployment models - detailed here: Deploy your app to Azure App Service and similarly you can connect to Azure SQL server instances in the same way as any other to do the manipulation you need. So basically you can do the same thing you do now i.e. copy the files using FTP or something a bit more creative along the same lines (OneDrive/Dropbox). You'll probably end up with web deploy. You absolutely do not have to use git deploy (in fact you probably don't want to...)

I haven't been playing enough to be confident, but you can group azure resources - I'd guess this could be done on a per customer and for test and qa instances.

If it were me... I'd think about the build / deploy process - automate, start to use a build server, have the build server generate packages for deployment, promote those packages through test and integration and then deploy as suits to your client instances. Similarly look at automating the schema changes - fundamentally this means automating running the scripts and ensuring that you run them in the right sequence and once each only (this is basically a solved problem, there are tools...)

In all of this automation is you friend - automation == repeatability and (mostly) takes stress away. Tools like AppVeyor (a build server) and Octopus deploy (a deployment tool) understand Azure and will help.

Title: Questions about developing for azure


问:
Is it a good practice to use List of Enums?
I am currently working on a system where there are Users, and each user have one or multiple roles. Is it a good practice to use List of Enum values on User? I can't think of anything better, but this doesn't feel alright.</p>

```<code>enum Role{
  Admin = 1,
  User = 2,
}

class User{
   ...
   List<Role> Roles {get;set;}
}
</code>```

答:
If a system — might it be a software, an operation system or an organization — deals with roles and permission, there comes a time when it is useful to add roles and manage permissions for them.

If this can be archived by altering the source code, it might be ok, to stick with enums. But at some point the system's user wants to be able to manage roles and permissions. Than enums become unusable.

Instead you will want to have a configurable data structure. i.e. a UserRole class that also holds a set of permission assigned to the role.

A User class would have a set of roles. If there is the need to check user's permission, a union set of all roles permissions is created and checked if it contains the permission in question.


问:
Web Api design - Using Nouns vs verbs
I have this design situation at work. We have a internal Web-Api application and a Asp.Net Web forms application(UI). The web-application is calling Web-Api to update a Contractor.

```<code>public Class Contractor {
    public string Id {get;set;}
    public string Name {get;set;}
    <<Ton of other Properties>>
    public string Status {get;set;}
}
</code>```

Typically the UI app can update the complete contractor by sending in all the details, except for the status. A user can change the status to closed by clicking on a Special "Close" button on the screen.
In this case the architect on the UI team doesn't want to send the complete contractor with status as closed. Also before a Contractor is closed there a a set of Business rules that need to be satisfied. So this is not a direct update.

So can we provide a route like "/api/Contractor/{id}/Close"? Isn't this against the RESTFul principle of not using Verbs in the nouns and dealing with Resources instead of actions. Can I make an exception in this case?

答:
Isn't this against the RESTFul principle of not using Verbs in the nouns and dealing with Resources instead of actions.

No - REST doesn't care about how you spell your identifiers.

It's violates URI design guidelines, for exactly the reason you specify -- you are naming an entity (a noun) with a verb.  HTTP is already giving you verbs, so you don't need them in the identifier.

The most common solution to this sort of problem is to create a resource that represents the specific noun you want to manipulate, for instance

```<code>/api/Contractor/{id}/status
</code>```

Also before a Contractor is closed there a a set of Business rules that need to be satisfied.

This suggests that the resource that is being manipulated isn't a status, but an event or a command -- for example: ContractorDismissed, and the change to the status is a side effect.

Title: Web Api design - Using Nouns vs verbs

Body:
Isn't this against the RESTFul principle of not using Verbs in the nouns and dealing with Resources instead of actions.

No - REST doesn't care about how you spell your identifiers.

It's violates URI design guidelines, for exactly the reason you specify -- you are naming an entity (a noun) with a verb.  HTTP is already giving you verbs, so you don't need them in the identifier.

The most common solution to this sort of problem is to create a resource that represents the specific noun you want to manipulate, for instance

/api/Contractor/{id}/status

Also before a Contractor is closed there a a set of Business rules that need to be satisfied.

This suggests that the resource that is being manipulated isn't a status, but an event or a command -- for example: ContractorDismissed, and the change to the status is a side effect.


问:
Balanced folder increment
I want to map an integer (let's say 32bits) to a valid path.
The integer is an autoincrement value stored in the database.

I also don't want at any case any folder to have more than N subfolders.
That is because in WIN-NTFS (for example) after a specific number (around 1000) things are going really slow.

So I devised a pattern where each integer is mapped to hex groupped in two digits.
That creates 4 folders for each integer

For example:

```<code>1 -> '00/00/00/01'
2000 -> '00/00/07/D0'
70000 -> '00/01/11/70'
etc
</code>```

All nice and well.

But if you notice after creating the first 257 entries

```<code>the folder '00/00/00' will have 256 entries ('00' to 'FF')
folder '00/00/01' will have one entry
folder '00/00' will have 2 entries ('00' and '01')
and last folder '00' will have just one entry.
</code>```

The graph is higly unbalanced, the OS to finally find the folder '00/00/00/55' will have to search between 1+1+2+256 = 260 entries. If the graph was balanced it would be a search of 4 * Pow(257,1/4) =~ 16 entries

And my question is:

Is anyway I can transform the integer A to an integer A' that has the following properties:

It's 1:1 transformation

Can be inversed (for each A' I can can easily find A)

For each 1..N, creating folders using the A' hex value, each folder has no more than Pow(N,1/4) entries

EDIT:
I did test the two ciphers. The problem is that crypt functions output the whole 32bit range. I mean after 1000 increments and after each byte has a random value, the root folder has 256 different values (subfolders) and each of them have 1 or 2 entries. It's the same situation I started with. It's only inversed

答:
It's not entirely obvious, but the type of algorithm you're looking for is called a space filling curve. The space here is the namespace of folders.

XKCD had a 2D example a long time ago. It shows how the first 4 files would end up in /00/00 to /01/01 and the first 16 in in /00/00 to /03/03. Expanding the algorithm, the first 256 files end in /00/00 to /0F/0F.

In a 3D example, a space filling curve maps the first 8 entries from /00/00/00/ to /01/01/01 and the first 64 to /00/00/00/ to /03/03/03. Expansion to N dimensions is straightforward from there, but as I mentioned in the comment suffers from excessive disks seeks.

Title: Balanced folder increment


问:
Generics vs common interface?
I don't remember when I wrote generic class last time. Every time I think I need it after some thinking I make a conclusion I don't.

The second answer to this question made me to ask for clarification (since i can't comment yet, i made a new question).

So let's take given code as an example of case where one needs generics:

```<code>public class Repository<T> where T : class, IBusinessOBject
{
  T Get(int id)
  void Save(T obj);
  void Delete(T obj);
}
</code>```

It has type constraints: IBusinessObject

My usual way of thought is: the class is constrained to use IBusinessObject, so are the classes that use this Repository are. Repository stores these IBusinessObjects, most likely clients of this Repository will want to get and use objects through IBusinessObject interface. So why not just to

```<code>public class Repository
{
  IBusinessOBject Get(int id)
  void Save(IBusinessOBject obj);
  void Delete(IBusinessOBject obj);
}
</code>```

Tho, the example is not good, as it is just another collection type and generic collection is classics. In this case type constraint looks odd too.

In fact the example class Repository<T> where T : class, IBusinessbBject looks
pretty much similar to class BusinessObjectRepository to me. Which is the thing generics are made to fix.

The whole point is: are generics good for anything except collections and don't type constraints make generic as specialized, as the use of this type constraint instead of generic type parameter inside the class does?

答:
"most likely clients of this Repository will want to get and use objects through IBusinessObject interface".

No, they won't.

Let's consider that the IBusinessObject has the following definition:

```<code>public interface IBusinessObject
{
  public int Id { get; }
}
</code>```

It just define the Id because it is the only shared functionality between all business objects.
And you have two actual business objects: Person and Address (since Persons don't have streets and Addresses dont have names you can't constrain both of them to a commom interface with funcionality of both. That would be a terrible design, violating the Interface Segregation Principle, the "I" in SOLID)

```<code>public class Person : IBusinessObject
{
  public int Id { get; private set; }
  public string Name { get; private set; }
}

public class Address : IBusinessObject
{
  public int Id { get; private set; }
  public string City { get; private set; }
  public string StreetName { get; private set; }
  public int Number { get; private set; }
}
</code>```

Now, what happens when you use the generic version of the repository:

```<code>public class Repository<T> where T : class, IBusinessObject
{
  T Get(int id)
  void Save(T obj);
  void Delete(T obj);
}
</code>```

When you call the Get method on the generic repository the returned object will be strongly typed, allowing you to access all the class members.

```<code>Person p = new Repository<Person>().Get(1);
int id = p.Id;
string name = p.Name;

Address a = new Repository<Address>().Get(1);
int id = a.Id;
string cityName = a.City;
int houseNumber = a.Number;
</code>```

On the other hand, when you use the non-generic Repository:

```<code>public class Repository
{
  IBusinessOBject Get(int id)
  void Save(IBusinessOBject obj);
  void Delete(IBusinessOBject obj);
}
</code>```

You will only be able to access the members from the IBusinessObject interface:

```<code>IBussinesObject p = new Repository().Get(1);
int id = p.Id; //OK
string name = p.Name; //Oooops, you dont have "Name" defined on the IBussinesObject interface.
</code>```

So, the previous code won't compile because of the following lines:

```<code>string name = p.Name;
string cityName = a.City;
int houseNumber = a.Number;
</code>```

Sure, you can cast the IBussinesObject to the actual class, but you'll lose all the compile time magic that generics allows (leading to InvalidCastExceptions down the road), will suffer from cast overhead unnecessarily... And even if you don't care about compile time checking neither performance (you should), casting after will definitely not give you any benefit over using generics on the first place.

Title: Generics vs common interface?

Body:
"most likely clients of this Repository will want to get and use objects through IBusinessObject interface".

No, they won't.

Let's consider that the IBusinessObject has the following definition:

public interface IBusinessObject
{
  public int Id { get; }
}

It just define the Id because it is the only shared functionality between all business objects.
And you have two actual business objects: Person and Address (since Persons don't have streets and Addresses dont have names you can't constrain both of them to a commom interface with funcionality of both. That would be a terrible design, violating the Interface Segregation Principle, the "I" in SOLID)

public class Person : IBusinessObject
{
  public int Id { get; private set; }
  public string Name { get; private set; }
}

public class Address : IBusinessObject
{
  public int Id { get; private set; }
  public string City { get; private set; }
  public string StreetName { get; private set; }
  public int Number { get; private set; }
}

Now, what happens when you use the generic version of the repository:

public class Repository<T> where T : class, IBusinessObject
{
  T Get(int id)
  void Save(T obj);
  void Delete(T obj);
}

When you call the Get method on the generic repository the returned object will be strongly typed, allowing you to access all the class members.

Person p = new Repository<Person>().Get(1);
int id = p.Id;
string name = p.Name;

Address a = new Repository<Address>().Get(1);
int id = a.Id;
string cityName = a.City;
int houseNumber = a.Number;

On the other hand, when you use the non-generic Repository:

public class Repository
{
  IBusinessOBject Get(int id)
  void Save(IBusinessOBject obj);
  void Delete(IBusinessOBject obj);
}

You will only be able to access the members from the IBusinessObject interface:

IBussinesObject p = new Repository().Get(1);
int id = p.Id; //OK
string name = p.Name; //Oooops, you dont have "Name" defined on the IBussinesObject interface.

So, the previous code won't compile because of the following lines:

string name = p.Name;
string cityName = a.City;
int houseNumber = a.Number;

Sure, you can cast the IBussinesObject to the actual class, but you'll lose all the compile time magic that generics allows (leading to InvalidCastExceptions down the road), will suffer from cast overhead unnecessarily... And even if you don't care about compile time checking neither performance (you should), casting after will definitely not give you any benefit over using generics on the first place.

ContentLicense: CC BY-SA 4.0


问:
Is there a standard for use case specifications?
I've been discussing about whether "logging in" is a use case and I've been wondering: is there some "official" standard where to look up the definition of a use case or what the point of a use case specification is?

答: There is a UML specification, published by the OMG, that defines use cases.  See section 18 of UML 2.5.  However, it's all very technical, and says very little about what use cases are for, or how to identify them.


问:
Why use tuples as function parameters in languages that support currying?
In languages that support currying, I can't think of many cases where using a tuple as function input parameters would be better than breaking the tuple apart into multiple parameters, which then allows you to enjoy the full power of currying. In which situations is keeping a tuple as function parameter better than breaking it apart? (Apart from the situation where the input originally was already in tuple form) Does such situation occur a lot in production code?</p>

答:
There's multiple reasons:

Some functions will return tuples and it's useful to compose such functions directly with other functions that accept tuples.

Often when values are bundled in a tuple they're conceptually one unit, i.e. you almost always pass all of them together. In other words, there's certain functions you wouldn't curry often.

It's trivial to write functions that turn a tuple-accepting function in a curried function and vice-versa, so it's never a big issue even if you need to curry a tuple-accepting function.


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

I have two possibilities:

Access the database directly from the Desktop Application

Create a REST API and connect to this

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

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

Disadvantages:

Takes longer to develop

More complex

The server does more work

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

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

Advantages:

Migrating to other platforms is easier

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

Same goes for complexity

Security (as mentioned by tkausl in the comments)

Maintainability (as mentioned by WindRaven in the comments)

答:
Look at it this way, it definitely is a common pattern and might reasonably be described as best practice.

Depending on your platform you may find tooling that almost makes the problem go away - Microsoft have ODATA support for connected apps that should makes forms over data straightforward once you've climbed the learning curve.

More pragmatically - define the API you need for your data layer in the desktop application and code to that API. Put all the database access behind that API - which actually makes things better from the perspective of developing the application - and then the location of the actual database access code becomes less significant (the same API could be implemented by code that talks directly to the database or by code that talks indirectly to the database via a rest endpoint). If you start with a direct implementation then the REST version is substantially going to be a wrapper round the same API so you'll not be too badly penalised...

Its probably not quite as simple as I'd like to make it out to be - but its a good pattern, it gives you the flexibility you may need without going to far down the YAGNI route.


问:
Is there a reason for support multiple different releases?
I have a discussion with my team recently and I heard a suggestion for deploying multiple releases. Such as version (newest) and version (old).
But I am thinking what would be the reason for customer want to use the older version. What if the bug was introduced in the older version we would have to make additional support to it.

I see there are benefits of using older version. Maybe I am wrong but what would be the reason why people want the older releases?? and if the trade off wasnt worth it (support vs demand) then why are we plan to support multiple releases?

答:
There are many reasons a customer may be reticent to push on to the latest software version. Some reasons I've come across:

Known quantity

The customer may simply be very happy with a legacy version. They know all the foibles, how to fix things should they go wrong and how to get the very best out of the software.

Time

The customer may not have time to install/learn the new software. There may also need to be a time window for new software to be installed which in turn may require authorisation.

Test lag

Larger companies can insist that new software is put thru its paces by a test dept before general release. There may be a time lag while this arranged and processed.

3rd party software

3rd party software may only integrate with older versions of your software until such time as they've played catch up.

No desirable features

You may think new features X, Y & Z are the best thing since sliced bread, but if your customer doesn't see their value - why should they upgrade?

Interface

Even the best software companies are known to drop the ball occasionally with endless interface tinkering e.g. Microsoft's Office ribbon. Wholesale changes to the software interface can be hugely unpopular.

Technical assets

If your software generates assets such as XML files, data in databases and various log files, these may be of value to the customer outside the sphere of your software. In a previous job we used bug tracking software that dumped log files whenever it went over. The vendor was based in the USA so we sometimes had a 2 day turnaround for them to look the logs over and resolve the issue. Trawling thru the log files ourselves often allowed us to cast light on the issue. A proposed upgrade to the software hid these away so we stuck with the old version.


问:
Is it bad to refer to access array elements via pointer arithmetic instead of the [] operator?
I've just started learning to program in C, and to improve my understanding of pointers and arrays, I tried to refer to the elements of an array without creating any pointer at all:

```<code>for(k1 = 0; k1 < ROW; k1++){
    for(k2 = 0; k2 < COLUMN; k2++){

        array[k1][k2] = k1*COLUMN + k2 + 1;

        printf("[%d][%d] = %d\n", k1, k2, *(array[k1] + k2));

    }
}
</code>```

The entire code compiles and runs flawlessly.

I imagine having to create a pointer for every single array in a big source code seems to be highly inefficient.

So, rather than having the address of an array stored and retrieved by using a pointer, is it a bad programming practice to use the address of the array directly, as shown above?

答:
Cool your learning  c, you just discovered one of c little tongue twisters. You are not doing pointer arithmetic on an array, but an array of pointers. Doing pointer arithmetic on arrays is not possible. An array decays to a pointer but is not a pointer type it self.
What you my  have (see comment by cmaster)  is

```<code>int *array[]; //This is a array to pointers of type *int.

array[k1] + k2; //This is pointer arithmetic on one pointer stored in the array
</code>```

Dereferencing this pointer gives the value your just calculated pointer, points to. There is generally no point in doing what you are doing. But you can linearised the array and then a stride in it, like this.

```<code>int array[y_dim*x_dim];
int index = x_dim*y + x;
array[index]; //Gives you the element in x, y!
</code>```

Stride her is x_dim.
Hope my answer is clarifying!

Body:
Cool your learning  c, you just discovered one of c little tongue twisters. You are not doing pointer arithmetic on an array, but an array of pointers. Doing pointer arithmetic on arrays is not possible. An array decays to a pointer but is not a pointer type it self.
What you my  have (see comment by cmaster)  is

int *array[]; //This is a array to pointers of type *int.

array[k1] + k2; //This is pointer arithmetic on one pointer stored in the array

Dereferencing this pointer gives the value your just calculated pointer, points to. There is generally no point in doing what you are doing. But you can linearised the array and then a stride in it, like this.

int array[y_dim*x_dim];
int index = x_dim*y + x;
array[index]; //Gives you the element in x, y!

Stride her is x_dim.
Hope my answer is clarifying!


问:
Keeping agile with zero-bug/defect policy
In our project we work in a zero-bug (a.k.a zero-defect) methodology. The basic idea is that bugs are always higher in priority than features. If you're working on a story and it has a bug it must be resolved in order for the story to get accepted. If a bug is found during the sprint for an older story we need to put it next on our backlog and resolve it - top priority.

The reason I'm saying resolve is that we not always fix the bug. Sometime we just declare it "won't fix" as it's not that important. All-in-all it sounds great. We're shipping high-quality products and don't carry "a hump" in the form of a huge bug backlog.

But i'm not sure this approach is correct. I do tend to agree that we always need to fix serious bugs ASAP and we need to throw-away non-interesting bugs. But what about bugs that are important but not as important as new features? I tend to think they should be filed in the backlog with a suitable priority.

I'll give an example in order for it to be clearer - in my project we work with a UI written in flex. We have a wizard screen that opens at the same size for every screen resolution. It turns out that when we extend the wizard window, one of the pages does not look good (there is a vertical scroll bar that does not disappear although the wizard can now present everything and does not require the scrollbar). I think this bug is ugly. I'm sure it MUST be fixed. But we're on a tight schedule and we have a lot of features that we're afraid won't make the cut and enter the release. I feel that we can live with such bug. It does need to be fixed but on lower priority than other features (so, in case we won't be able to complete it, at least we didn't leave out more important features). But, we work in a 0-bug policy and it must be fixed now (even though we spent more than a day trying to resolve it and we'll need at lease another one).

I would love to hear opinions about how to manage with bugs that I don't want to mark as "won't fix" but also are not of highest importance.

答:
You get into trouble when you try to be too literal or adamant about anything in software development as much as we all really want things to be cut and dry. Bugs should get fixed before new features are added, but I would still consider the importance of each when making this decision along with the scope of the problem. There are exceptions to everything.

Some applications are so large they have sections that are not related at all. I don't see why every new feature of the accounts payable module have to be put on hold, because there a couple of annoying bugs in the employee benefits GUI. If some wizard step GUI annoyance was located in the purchasing section of the company website, fix it, but many bugs may have to go unfixed if the added feature is a result of an additional security, business need, and especially changes in regulations.

Other than a large discrepancy in the time and resources to complete either one, it's best to get some user/customer input. If they can live with the bug if it means getting the new feature, add the feature. The goal should be to avoid letting bugs pile up, so have a stop gap. At some point many little problems become a major one.


答:
This is not a direct answer but it does not fit in a comment. I just want to elaborate MSalters comment - internally, NTFS already does what you are trying to do.

It is a wrong impression about huge NTFS folder being slow. The wrong impression is usually due to the way some users interact with the folder - windows file explorer, which loads all entries when a folder is opened and it is supposedly to be slow. However, if you query one file with a specific name, it's instantaneous. Now you may ask, even if the program can always access the folder with specified file name, how about maintenance and support - say a support member needs to verify the existence of a file? In that case, go to command line and "cd" into the folder, use "dir filename". The result is still instantaneous. Of course, if you try "dir *21", then you will be served with the "table-scan" performance.

I once worked on a project involving a huge NTFS folder. It was all good until some manager decided to split the folder into smaller ones. Needless to say, it complicated the program unnecessarily and slowed down both the program and me when I need to do some support. In return, more developers and users felt comfortable with the folder when they needed to look up a file in that folder, which is actually one valid reason to split a NTFS folder.

Title: Balanced folder increment

Body:
I want to map an integer (let's say 32bits) to a valid path.
The integer is an autoincrement value stored in the database.

I also don't want at any case any folder to have more than N subfolders.
That is because in WIN-NTFS (for example) after a specific number (around 1000) things are going really slow.

So I devised a pattern where each integer is mapped to hex groupped in two digits.
That creates 4 folders for each integer

For example:

```<code>1 -> '00/00/00/01'
2000 -> '00/00/07/D0'
70000 -> '00/01/11/70'
etc
</code>```

All nice and well.

But if you notice after creating the first 257 entries

```<code>the folder '00/00/00' will have 256 entries ('00' to 'FF')
folder '00/00/01' will have one entry
folder '00/00' will have 2 entries ('00' and '01')
and last folder '00' will have just one entry.
</code>```

The graph is higly unbalanced, the OS to finally find the folder '00/00/00/55' will have to search between 1+1+2+256 = 260 entries. If the graph was balanced it would be a search of 4 * Pow(257,1/4) =~ 16 entries

And my question is:

Is anyway I can transform the integer A to an integer A' that has the following properties:

It's 1:1 transformation

Can be inversed (for each A' I can can easily find A)

For each 1..N, creating folders using the A' hex value, each folder has no more than Pow(N,1/4) entries

EDIT:
I did test the two ciphers. The problem is that crypt functions output the whole 32bit range. I mean after 1000 increments and after each byte has a random value, the root folder has 256 different values (subfolders) and each of them have 1 or 2 entries. It's the same situation I started with. It's only inversed


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

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

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

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

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

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

Arguments for using IEEE semantics for Equals:

It follows IEEE 754

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

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

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

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

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

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

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

Arguments for being reflexive:

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

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

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

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

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

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

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

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

In my opinion these arguments strongly favour a reflexive implementation.

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

答:
I would argue that the IEEE behavior is correct. NaNs are not equivalent to one another in any way; they correspond to ill-defined conditions where a numeric answer isn't appropriate.

Beyond the performance benefits that come from using IEEE arithmetic that most processors support natively, I think there's a semantic problem with saying that if isnan(x) && isnan(y), then x == y. For instance:

```<code>// C++
double inf = std::numeric_limits<double>::infinity();
double x = 0.0 / 0.0;
double y = inf - inf;
</code>```

I would argue that there's no meaningful reason why one would consider x equal to y. You could hardly conclude that they are equivalent numbers; they aren't numbers at all, so it just seems like an invalid concept entirely.

Furthermore, from an API design perspective, if you're working on a general-purpose library that is intended to be used by many programmers, it just makes sense to use the most industry-typical floating-point semantics. The goal of a good library is to save time for those who use it, so building in nonstandard behavior is ripe for confusion.

Body:
I would argue that the IEEE behavior is correct. NaNs are not equivalent to one another in any way; they correspond to ill-defined conditions where a numeric answer isn't appropriate.

Beyond the performance benefits that come from using IEEE arithmetic that most processors support natively, I think there's a semantic problem with saying that if isnan(x) && isnan(y), then x == y. For instance:

// C++
double inf = std::numeric_limits<double>::infinity();
double x = 0.0 / 0.0;
double y = inf - inf;

I would argue that there's no meaningful reason why one would consider x equal to y. You could hardly conclude that they are equivalent numbers; they aren't numbers at all, so it just seems like an invalid concept entirely.

Furthermore, from an API design perspective, if you're working on a general-purpose library that is intended to be used by many programmers, it just makes sense to use the most industry-typical floating-point semantics. The goal of a good library is to save time for those who use it, so building in nonstandard behavior is ripe for confusion.


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

```<code>    2568 Fix heating issue

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

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

答:
Yes, this is a good idea and fairly standard (but not universal) practice.

The specific software engineering goal you are achieving with this is requirements traceability. The idea is you want to be able to trace a requirement through the entire software process:

Business requirements

Functional requirements

Technical requirements

Code artifacts

QA feedback

Development fixes

By using ticket or requirement numbers (e.g. Jira story IDs) in commit messages and any correspondence, you are working toward that software engineering goal.

If I come back a year later and see the commit message, I can look up that number in another system to get the full background behind the requirement or ticket, including anything that occurred after the commit.


答:
If your system tracks all features/bugs then you likely will have a ticket of some sort. But if your system only tracks bugs (for some reason?) and all new development is a free for all.

Some significant advantages:

Some VCS/ticket systems allow auto hyperlinks for the ticket number when browsing the commits in the issue tracker (this is super useful, see github, redmine)

It provides some context for the inevitable "why did Simon do this? Makes no sense!" question

Often this might be years later...

Context for changes can take a lot of work multiple years in the future. Having a ticket with an explanation for why the code was changed can be super, super useful

Helps keep people working on value-add things

"Oh, I'm going to refactor this.. and this.. and this... and... oh I've not done any value-add work in a week!"

Can allow searches to find commits related to an issue

The only disadvantage is if your team doesn't really use tickets or a tracking system. Then it'd be harder to find the ticket number. Or if  your VCS and issue tracker don't integrate well.

And... you should track all efforts somewhere, so, if that's why you are not using a ticket system for nearly all of your work I'd strongly suggest doing so, regardless of whether you have it included in your commit messages.

Title: Is there any downside to commit messages containing the ticket number

Body:
I was wondering if it would be good practice for commit messages to contain the ticket number they were apart of. It would be like

```<code>    2568 Fix heating issue

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

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


问:
Developing an app using Django. Do I design front-end after app? Or develop Django to fit UI?
Edit: this differs from a similar question because I'm interested specifically in how Django works with the front-end. I.e. what is considered best practice when developing using the Django framework.

I am learning Python at university and need to produce an implementation project.  I'd like to write a web application using Python with the Django web framework.

I've been learning as much HTML, CSS and Javascript as possible so I know what's going on at the front-end.

I've found some nice designs on Codepen which would be useful in what I'm designing, but can I use them and design a Django app around it?  Or do I need to get the back-end together first and then design the front-end to fit.

答:
I would say that this depends on what your app does, and what are its strong suites. Lets say for the sake of simplicity that your app does one of the 3 things:

Combines standard/non-ground-breaking code chunks/practices into a
cool new way of organizing or viewing data for users (like, "Twitter
for pets!")

Reveals some awesome new technology that you have unique control
over that differentiates your app from its competitors (like, "Our
new search engine indexes text from pictures in public Facebook
pages!"

Is just a prototype of other apps that you are using as a learning
experiment to develop your coding skills, and won't actually be
commercially viable on its own.

For #1, you should develop the UI first, because what you are building isn't earth-shattering in terms of its back-end, it just needs to hook user in with it slick/easy interface. Therefor, the UI is the most important piece and needs to drive the functionality.

For #2, invert the statements in #1. Your UI will prob just be a reflection of what cool new thing you can do in the backend, so start on the backend first.

For #3, it doesn't really matter, although my personal preference is to work on the UI first.


答:
While I largely agree with the suggestions to avoid constants and have a method isFoo() etc., one possible counterexample.

If there are hundreds of these constants, and the calls are little used, it might not be worth the effort to write hundreds of isConstant1, isConstant2, methods.  In this particular, unusual case, using the constants is reasonable.

Note that using enums or hasRole() avoids the need to write hundreds of methods, so it is the best of all possible world's.


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

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

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

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

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

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

Fetching a resource

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

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

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

GET /companies/1

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

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

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

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

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

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

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CompanyParser companyParser;

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

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

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

    private String name;

    private String industry;

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

    // getters and setters
}
```

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

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

    private String name;

    private Integer companyId;

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

    // getters and setters
}
```

Updating a resource

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

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

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

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

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

答:
IMHO, I think you're missing the point.

First, the REST API and DB performance are unrelated.

The REST API is just an interface, it does not define at all how you do stuff under the hood. You can map it to any DB structure you like behind it. Therefore:

design you API so that it's easy for the user

design your database so that's it can scale reasonably:

ensure that you have the right indexes

if you store objects, just ensure they're not too huge.

That's it.

...and lastly, this smells like premature optimization. Keep it simple, try it out, and adapt it if need be.


答:
The downside is that people will write less complete commit comments because someone can go to the ticket for more details. This is only really a problem if you say switch to a different ticketing system and can't keep the history or someone doesn't have ticketing system but does have access to the repository. </p>

<p>If the branch is already named for the ticket I wouldn't bother putting it in the commit, that does seem redundant. </p>

Body:
The downside is that people will write less complete commit comments because someone can go to the ticket for more details. This is only really a problem if you say switch to a different ticketing system and can't keep the history or someone doesn't have ticketing system but does have access to the repository.

If the branch is already named for the ticket I wouldn't bother putting it in the commit, that does seem redundant.


问:
Are there compilers which optimize the use of mathematical functions?
Today while programming I stumbled upon the following question - are there any compilers which optimize based on mathematical assumptions?

For instance in cases like

```<code>unsigned int i,b;
(i,b not constant)
if(sqrt(i) == b)
...
</code>```

In this case it would be a lot more effective to use

```<code>unsigned int i,b;
(i,b not constant)
if(i == b*b)
...
</code>```

Assuming a sqrt() function, that handles unsigned integers and rounds sensefully.

Since I was not able to find useful information (probably because I did not know what to search for specifically), can someone please tell me or point me to a relevant source?

Are there compilers (for imperative languages) who optimize such things using some kind of heuristic? Or more specifically - what about gcc and microsoft visual c++ and matlab?

答:
Compilers routinely engage in strength reduction.

One common example of which is reducing multiples to adds (as adds are typically faster than multiplies).

i*2 transformed to i+i is faster on many machines, (and this is sometimes transformed to i<<1 instead).

Implicit multiplies commonly happen in for-loops over arrays (whose element size is > 1 byte), and can sometimes be reduced to adding, with optimization induction variable, which is similar in that the mathematical relationship between multiply and add is involved.


问:
Divide the world map into fixed sized blocks
I am developing an app where I need to divide the entire world map into fixed sized square blocks. For simplicity, think of it as a problem of dividing the google maps into a fixed sized block. I can choose any arbitrary point in the map and my app needs to create a block of fixed size around that point.

The primary concern here is when i choose a point and define a block around it, there should never be an overlap between this block and any other blocks that were defined previously. In other words, any point can belong to one and only one block.

What is the best algorithm I can use to do this? I am guessing this is a problem that has been solved before and doesn't require me to reinvent the wheel.

Right now, all I am doing is when the user selects a point, I get the latitude and longitude of the point and define a square block around it. While doing so, I am making a check to see whether the new block would overlap with other blocks around it or not.

Any help would be greatly appreciated.

答:
You can't map the surface of a sphere onto a plane square grid, whilst at the same time preserving distance, area and angles - there has to be some sort of compromise. See here for more details.

If you really want "equal sized elements", a better solution might be to use a spherical co-ordinate system - latitude and longitude with elements of equal arc length. That way, any point on the surface can be assigned to a single element. However this means that the elements are not perfectly square so there will be a little distortion if you treat them as such. Also, all of the elements will have the same height, but they will become progressively narrower as you move away from the equator.

Assuming the earth is a perfect sphere of radius 6371 Km, and using a 1 degree granularity, each element will be 111.19 km from north to south. Those along the equator will be 111.19 Km along the southern edge but 111.17 Km along the northern edge. You'd be hard pressed to notice this 0.02% difference though if you just treated it as a square.

As you move further north, the difference between the length northern and southern edges becomes more pronounced.

for example :-

Guatemala City (15 deg north) 107.89 - 107.41 Km (0.45%)

San Antonio (30 deg north) 97.25 - 96.26 Km (0.98%)

Lyon (45 deg north) 78.62 - 77.24 Km (1.76%)

Oslo (60 deg north) 57.27 - 55.60 Km (2.92%)

So you could draw a 5 element high grid centred on any of these cities with limited distortion, just with the elements becoming more rectangular as you move north, so you need more elements for the same horizontal distance. It's only as you get towards the poles that you start to get big problems, with the final element effectively being a triangle, coming to a point at the pole.

If you were to zoom in by using a smaller granularity, say 0.1 degree of arc, then the "squareness" of the elements improves. You'd have to go to 80.2 deg north before you get even a 1% difference between the lengths of the northern and southern edges, although these elements will have an aspect ratio of 5.8:1 - 11.1 x 1.89 km. This is almost enough to cover the northernmost permanently inhabited place in the world - Albert, Canada is 82.5 deg north.


问:
Is it a good practice to avoid constants by using getters?
Is it a good practice to replace constants used outside of classes by getters?

As an example, is it better to use if User.getRole().getCode() == Role.CODE_ADMIN or if User.getRole().isCodeAdmin()?

That would lead to this class:

```<code>class Role {
    constant CODE_ADMIN = "admin"
    constant CODE_USER = "user"

    private code

    getRoleCode() {
       return Role.code
    }

    isCodeAdmin () {
       return Role.code == Role.CODE_ADMIN
    }

    isCodeUser () {
       return Role.code == Role.CODE_USER
    }
}
</code>```

答:
I don't think either of the options you presented is fundamentally wrong.

I see you have not suggested the one thing that I would call flatly wrong: hard-coding the role codes in functions outside the Role class. That is:

```<code>if (user.getRole().equals("Administrator")) ...
</code>```

I'd say is definitely wrong. I've seen programs that do this and then get mysterious errors because someone mis-spelled the string. I recall one time that a programmer wrote "stock" when the function was checking for "Stock".

If there were 100 different roles, I'd be very reluctant to write 100 functions to check for every possible one. You would presumably create them by writing the first function and then copying and pasting it 99 times, and how much you want to bet that in one of those 99 copies you'd forget to update the test or you'd get off by one when you ran through the list, so you now have

```<code>public bool isActuary() { return code==Role.ACTUARY; }
public bool isAccountant() { return code==Role.ACTUARY; }
... etc ...
</code>```

Personally, I'd also avoid the chains of calls. I'd rather write

```<code>if (user.getRole().equals(Role.FOOBATER))
</code>```

then

```<code>if (user.getRole().getRoleCode()==Role.FOOBATER_CODE)
</code>```

and at that point why note write:

```<code>if (user.hasRole(Role.FOOBATER))
</code>```

Then let the User class know how to check a role.

Body:
I don't think either of the options you presented is fundamentally wrong.

I see you have not suggested the one thing that I would call flatly wrong: hard-coding the role codes in functions outside the Role class. That is:

if (user.getRole().equals("Administrator")) ...

I'd say is definitely wrong. I've seen programs that do this and then get mysterious errors because someone mis-spelled the string. I recall one time that a programmer wrote "stock" when the function was checking for "Stock".

If there were 100 different roles, I'd be very reluctant to write 100 functions to check for every possible one. You would presumably create them by writing the first function and then copying and pasting it 99 times, and how much you want to bet that in one of those 99 copies you'd forget to update the test or you'd get off by one when you ran through the list, so you now have

public bool isActuary() { return code==Role.ACTUARY; }
public bool isAccountant() { return code==Role.ACTUARY; }
... etc ...

Personally, I'd also avoid the chains of calls. I'd rather write

if (user.getRole().equals(Role.FOOBATER))

then

if (user.getRole().getRoleCode()==Role.FOOBATER_CODE)

and at that point why note write:

if (user.hasRole(Role.FOOBATER))

Then let the User class know how to check a role.


问:
Design consideration on JSON schema for an API
I have an API endpoint that retrieve data from 3 SQL tables on the server-side. At the moment, I do a SELECT with joins, consolidate/reorganize the selected data based on a JSON schema, and then send the JSON to client. The point here is that, almost none of the data values is changed, only their structure is transformed from the SQL schema to the JSON schema.

On the client side, I also maintain 3 SQL tables that are very similar to those on the server. At the moment, I parse the JSON, re-transform the data, and save them into those tables.

I wonder, on the server-side, whether we could simply dump the the data from each of the 3 tables into JSON without any transformation, so that both server and client can save doing any transformation/restructuring, considering the tables on both sides (more or less) match in schema.

The (only?) benefit of this idea is obvious, but I do wonder if there is any serious drawback. For examples:

We lose data abstraction on the server-side.

We sort of rely on the close matching between schemas of tables on both sides, which probably makes it harder in the future to change/add columns to those tables on either side.

This may be OK for an internal API that is consumed by clients I control, but probably is not so great for external clients/developers in the future.

So far I can only come up with the above, and I am not 100% sure how severe each of the problems is.

答:
I think that, exactly like you've pointed out, the big considerations would be

What would happen if the implementation on the client or server side changes.

How would future developers extend the API if it was written that way

How would this design impact modularity/reuseability of the API

What you're proposing would tightly couple part of the API to the database schema, which in general is something to avoid.  Check out this API keynote from Joshua Bloch. One of the general principles in there is that the implementation should not impact the API. It's not a "rule", but unless you have a good reason to do so, I would keep the implementation and the API decoupled as much as possible.


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

For instance:

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

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

f3()
{
   // Logic here
}

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

versus:

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

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

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

答:
The rationale behind splitting functions is not how many times (or how often) they will be called, it's keeping them small and preventing them from doing several different things.

Bob Martin's book Clean Code gives good guidelines on when to split a function:

Functions should be small; how small? See the bullet bellow.

Functions should do only one thing.

So if the function is several screens long, split it. If the function does several things, split it.

If the function is made of sequential steps aimed to a final result, then no need to split it, even if it's relatively long. But if the function does one thing, then another, then another, and then another, with conditions, logically separated blocks, etc., it should be split. As a result of that logic, functions should be usually small.

If f1() does authentication, f2() parses input into smaller parts, if f3() makes calculations, and f4() logs or persist results, then they obviously should be separated, even when every one of them will be called just once.

That way you can refactor and test them separately, besides the added advantage of being easier to read.

On the other hand if all the function does is:

```<code>a=a+1;
a=a/2;
a=a^2
b=0.0001;
c=a*b/c;
return c;
</code>```

then there is no need to split it, even when the sequence of steps is long.

Body:
The rationale behind splitting functions is not how many times (or how often) they will be called, it's keeping them small and preventing them from doing several different things.

Bob Martin's book Clean Code gives good guidelines on when to split a function:

Functions should be small; how small? See the bullet bellow.

Functions should do only one thing.

So if the function is several screens long, split it. If the function does several things, split it.

If the function is made of sequential steps aimed to a final result, then no need to split it, even if it's relatively long. But if the function does one thing, then another, then another, and then another, with conditions, logically separated blocks, etc., it should be split. As a result of that logic, functions should be usually small.

If f1() does authentication, f2() parses input into smaller parts, if f3() makes calculations, and f4() logs or persist results, then they obviously should be separated, even when every one of them will be called just once.

That way you can refactor and test them separately, besides the added advantage of being easier to read.

On the other hand if all the function does is:

a=a+1;
a=a/2;
a=a^2
b=0.0001;
c=a*b/c;
return c;

then there is no need to split it, even when the sequence of steps is long.