答:
Is the maintenance hit real, or does it just bother you?
If it only bothers you, leave it alone.

Is the performance issue real, or did the previous developer only think it was?
Performance problems, more often than not, are not where they are thought to be, even when a profiler is used. (I use this technique to reliably find them.)

So there is a possibility that you have an ugly solution to a non-problem, but it could also be an ugly solution to a real problem.
When in doubt, leave it alone.

Title: Is template "metaprogramming" in Java a good idea?

Body:
There is a source file in a rather large project with several functions that are extremely performance-sensitive (called millions of times per second). In fact, the previous maintainer decided to write 12 copies of a function each differing very slightly, in order to save the time that would be spent checking the conditionals in a single function.

Unfortunately, this means the code is a PITA to maintain. I would like to remove all the duplicate code and write just one template. However, the language, Java, does not support templates, and I'm not sure that generics are suitable for this.

My current plan is to write instead a file that generates the 12 copies of the function (a one-use-only template expander, practically). I would of course provide copious explanation for why the file must be generated programmatically.

My concern is that this would lead to future maintainers' confusion, and perhaps introduce nasty bugs if they forget to regenerate the file after modifying it, or (even worse) if they modify instead the programmatically-generated file. Unfortunately, short of rewriting the whole thing in C++, I see no way to fix this.

Do the benefits of this approach outweigh the disadvantages? Should I instead:

Take the performance hit and use a single, maintainable function.

Add explanations for why the function must be duplicated 12 times, and graciously take the maintenance burden.

Attempt to use generics as templates (they probably don't work that way).

Yell at the old maintainer for making code so performance-dependent on a single function.

Other method to maintain performance and maintainability?

P.S. Due to the poor design of the project, profiling the function is rather tricky... however, the former maintainer has convinced me that the performance hit is unacceptable. I assume by this he means more than 5%, though that is a complete guess on my part.

Perhaps I should elaborate a bit. The 12 copies do a very similar task, but have minute differences. The differences are in various places throughout the function, so unfortunately there are many, many, conditional statements. There are effectively 6 "modes" of operation, and 2 "paradigms" of operation (words made up by myself). To use the function, one specifies the "mode" and "paradigm" of operation. This is never dynamic; each piece of code uses exactly one mode and paradigm. All 12 mode-paradigm pairs are used somewhere in the application. The functions are aptly named func1 to func12, with even numbers representing the second paradigm and odd numbers representing the first paradigm.

I'm aware that this is just about the worst design ever if maintainability is the goal. But it seems to be "fast enough", and this code hasn't needed any changes for a while... It's also worth noting that the original function has not been deleted (although it is dead code as far as I can tell), so refactoring would be simple.


问:
Is template "metaprogramming" in Java a good idea?
There is a source file in a rather large project with several functions that are extremely performance-sensitive (called millions of times per second). In fact, the previous maintainer decided to write 12 copies of a function each differing very slightly, in order to save the time that would be spent checking the conditionals in a single function.

Unfortunately, this means the code is a PITA to maintain. I would like to remove all the duplicate code and write just one template. However, the language, Java, does not support templates, and I'm not sure that generics are suitable for this.

My current plan is to write instead a file that generates the 12 copies of the function (a one-use-only template expander, practically). I would of course provide copious explanation for why the file must be generated programmatically.

My concern is that this would lead to future maintainers' confusion, and perhaps introduce nasty bugs if they forget to regenerate the file after modifying it, or (even worse) if they modify instead the programmatically-generated file. Unfortunately, short of rewriting the whole thing in C++, I see no way to fix this.

Do the benefits of this approach outweigh the disadvantages? Should I instead:

Take the performance hit and use a single, maintainable function.

Add explanations for why the function must be duplicated 12 times, and graciously take the maintenance burden.

Attempt to use generics as templates (they probably don't work that way).

Yell at the old maintainer for making code so performance-dependent on a single function.

Other method to maintain performance and maintainability?

P.S. Due to the poor design of the project, profiling the function is rather tricky... however, the former maintainer has convinced me that the performance hit is unacceptable. I assume by this he means more than 5%, though that is a complete guess on my part.

Perhaps I should elaborate a bit. The 12 copies do a very similar task, but have minute differences. The differences are in various places throughout the function, so unfortunately there are many, many, conditional statements. There are effectively 6 "modes" of operation, and 2 "paradigms" of operation (words made up by myself). To use the function, one specifies the "mode" and "paradigm" of operation. This is never dynamic; each piece of code uses exactly one mode and paradigm. All 12 mode-paradigm pairs are used somewhere in the application. The functions are aptly named func1 to func12, with even numbers representing the second paradigm and odd numbers representing the first paradigm.

I'm aware that this is just about the worst design ever if maintainability is the goal. But it seems to be "fast enough", and this code hasn't needed any changes for a while... It's also worth noting that the original function has not been deleted (although it is dead code as far as I can tell), so refactoring would be simple.

答:
This is a very bad situation, you need to refactor this ASAP - this is technical debt in it's worst - you don't even know how important the code really is - only speculate that it's important.

As to solutions ASAP:

Something that can be done is adding a custom compilation step. If you use Maven that is actually fairly simple to do, other automated build systems are likely to cope with this as well. Write a file with a different extension than .java and add a custom step that searches your source for files like that and regenerates the actual .java. You may also want to add a huge disclaimer on the auto-generated file explaining not to modify it.

Pros vs using a once-generated file: Your developers will not get their changes to the .java working. If they actually run the code on their machine before committing they will find that their changes have no effect (hah). And then maybe they will read the disclaimer. You are absolutely right in not trusting your teammates and your future self with remembering that this particular file has to be changed in a different way. It also allows automatic testing as wel, as JUnit will compile your program before running tests (and regenerate the file as well)

EDIT

Judging by the comments the answer came off as if this is a way to make this work indefinitely and maybe OK to deploy to other performance critical parts of your project.

Simply put: it is not.

The extra burden of creating your own mini-language, writing a code-generator for it and maintaining it, not to mention teaching it to future maintainers is hellish in the long run. The above only allows a safer way to handle the problem while you are working on a long-term solution. What that will take is above me.

ContentLicense: CC BY-SA 3.0


答: If the function in question is large, turning the "mode/paradigm" bits into an interface and then passing an object that implements that interface as a parameter to the function can work. GoF calls this the "Strategy" pattern, iirc. If the function is small, the increased overhead may be significant... did somebody mention profiling yet?... more people should mention profiling.</p>


问:
Should a variable name be changed if its purpose changes?
I'll change my personal code often and not worry about going back and changing the associated variable names.

Should variable names be maintained in case of meaning changes?

```<code>var accountCurrentValue = x;
var accountYesterdayValue = y;
var accountValueChange = accountCurrentValue - accountYesterdayValue;
</code>```

--> accountPastValue becomes instead the previous month's value

```<code>var accountCurrentValue = x;
var accountLastMonthValue = y;
var accountValueChange = accountCurrentValue - accountLastMonthValue;
</code>```

答:
Code is written to be executed by machine, but to be read by humans. The latter case is more important.

By all means keep identifiers in the code as accurately reflecting their purpose as possible.

Where I now am, a typical and legit kind of code review complaint is 'please rename this variable / function to be more descriptive'.


答:
Definitely yes, change variable names when relevant (especially variables whose scope is bigger than what fits in a screen). The name of a variable is an important part of its documentation!

Computers (e.g. compilers) don't care about variable names. You could name all your variables like x01, x02 etc..., and the compiler nearly won't notice and the binary program would behave like before. But humans don't grasp these!

Source code is -by definition- read and improved by humans. It is the prefered form for human developers to work on software (this is why naming and comments are important).

Title: Should a variable name be changed if its purpose changes?

Body:
I'll change my personal code often and not worry about going back and changing the associated variable names.

Should variable names be maintained in case of meaning changes?

```<code>var accountCurrentValue = x;
var accountYesterdayValue = y;
var accountValueChange = accountCurrentValue - accountYesterdayValue;
</code>```

--> accountPastValue becomes instead the previous month's value

```<code>var accountCurrentValue = x;
var accountLastMonthValue = y;
var accountValueChange = accountCurrentValue - accountLastMonthValue;
</code>```


问:
Why aren't databases integrated as a language feature?
Are there any programming languages that have a built-in database as a first-class language feature rather than connecting to an external SQL (or other) database? What would be the drawbacks and benefits to such a feature? What would such a feature look like and how would it change the way we program?</p>

答:
Err.

Well, first, you're asking why the framework the language operates in doesn't provide a database. A language is simply a means of expressing something that you want done in set grammers; it doesn't really provide services like that. :)

That said, there are several reasons.

Building an efficient database storage system is a hard problem, probably on the order of or greater than building the .NET Framework (for instance). If a team tried to include a database in their framework, that would be all they ended up working on.

A database that gets load should be on its own separate machine and not in the process of the code that's accessing it.

ORMs provide a lot of the type safety and compile time checking that would be the benefit of such an action, without actually having the framework try to be a database.

That said, I guess it would be neat to include some sort of SQLite implementation within the framework that applications with smaller needs for data access could operate against. I'm not sure it would be useful in non-trivial applications, however.

ContentLicense: CC BY-SA 2.5


问:
How viable is to create a mini documentation inside the source code
So, I work as a developer. We are a small team. The majority of the people (everyone except the project manager and the senior developer) are still in university. We have very flexible work hours, sometimes I don't see some of the people for 3-4 days.

You can imagine that communication is key here. We write a lot of emails and use a bug tracking system and as long as you are somewhat connected to the task you can be well informed. (as long as you read all the correspondence).

One of the weak points of the team is the documentation that people leave behind. The code is reasonably well written and as long as you take the time to read it in it's entirety you will understand it. (problem: this usually takes quite a bit of time when tackling modules of a couple of thousand lines of code)
Note: There is very good documentation for the users which is written to the end users, however we are discussing the documentation shared between the programmers.

When a new person has to enter some of the things a part of the team is working on, or when someone has to modify old code or someone's old code things get a bit complicated. As I mentioned before sometimes we don't see eachother for days so unless the project manager knows(and remembers) the details of the code the newcommer will have the following options:

1 Read the source

2 Read the old emails with the discussions.

When you have to refactor large pieces of the code This is fine (esp the first thing) however when an algorithm needs to be changed or someone just has to use an old module as part of new module or script or whatever you can imagine that waiting to meet the guy who created the module or reading tons of emails will waste time.

I have started adding small documentation in the beginning of each module. It consists of:

2-3 sentences about what the module does

A bit of information for each function that is not a part of another function. Basically what it does and some specific information about the arguments it takes if the arguments are objects. If they aren't I just write "see the source for more on the arguments"

Since I don't know if I am on the right track the question is simple: What should such a minimal documentation contain so it can give a general idea about what the module does and how people can use it?

答:
At the very least, add -perhaps after the copyright notice- a comment in a few paragraphs describing what your source file does. This is helpful (for the future persons working on the same code). Also add a README file!

Look inside the source code of small free software projects for inspiration!


答:
This is the set of guidelines I have seen used in multiple teams:

Class: Document what the responsibility of the class is (and usually a class must have one responsibility).

Method: Document what goes in the method, what method does with it, and what comes out.

Inside code: Do not document what a developer can understand by skimming through the code, rather focus on assumptions, or things that are harder to discover, or a brief explanation of a complex piece of code.

This also forces a little bit of better design, because if the class has too many responsibilities, then there's a problem. The purpose of the documentation is to find out when the classes and methods are expected to be used without reading the code. If someone has to read the code, then documentation is usually a waste and you are duplicating code in English.

We use C# heavily, so C# code documentation tags and auto-generation of the documentation helps significantly. We produce MSDN-style documentation using SandCastle and put it on an internal share so that the developers can look at it. That acts as a forcing function. You may be able to find such a tool for whatever you are working on. And I have also been asked to find out if we can likewise generate documentation extracted from our XSD (which is also documented inline using the xs:annotation tags).

Lastly, if possible, especially for classes that are exposed out of the DLL and to be used by other DLLs, I encourage (and personally try to add) example code in the comments. This can be rather onerous, especially keeping the evolution of code in mind, so it is something we wouldn't do if the usage can be found by looking at other code including tests.

Title: How viable is to create a mini documentation inside the source code

Body:
So, I work as a developer. We are a small team. The majority of the people (everyone except the project manager and the senior developer) are still in university. We have very flexible work hours, sometimes I don't see some of the people for 3-4 days.

You can imagine that communication is key here. We write a lot of emails and use a bug tracking system and as long as you are somewhat connected to the task you can be well informed. (as long as you read all the correspondence).

One of the weak points of the team is the documentation that people leave behind. The code is reasonably well written and as long as you take the time to read it in it's entirety you will understand it. (problem: this usually takes quite a bit of time when tackling modules of a couple of thousand lines of code)
Note: There is very good documentation for the users which is written to the end users, however we are discussing the documentation shared between the programmers.

When a new person has to enter some of the things a part of the team is working on, or when someone has to modify old code or someone's old code things get a bit complicated. As I mentioned before sometimes we don't see eachother for days so unless the project manager knows(and remembers) the details of the code the newcommer will have the following options:

1 Read the source

2 Read the old emails with the discussions.

When you have to refactor large pieces of the code This is fine (esp the first thing) however when an algorithm needs to be changed or someone just has to use an old module as part of new module or script or whatever you can imagine that waiting to meet the guy who created the module or reading tons of emails will waste time.

I have started adding small documentation in the beginning of each module. It consists of:

2-3 sentences about what the module does

A bit of information for each function that is not a part of another function. Basically what it does and some specific information about the arguments it takes if the arguments are objects. If they aren't I just write "see the source for more on the arguments"

Since I don't know if I am on the right track the question is simple: What should such a minimal documentation contain so it can give a general idea about what the module does and how people can use it?


问:
Bug Report System - Getting people to use it
I've built already a bug report system. It looks like this:

It is accessed using a secret key combination detected by the JavaScript code. Not hard. It has everything - sends the standard emails to management and testers, logs the Javascript variables and current DOM HTML. We are also improving the backend of the system to act as a full bug report system. Previously, it was only via email.

The problem is, unfortunately, the bug reporters still preferred email. Even when I refused to answer their queries until they sent a bug report, they would not consistently send them.

I don't understand it, because, for them it should be easy, but they act like it was a big deal. (The appearance was slightly more complex before, but still, all they had to do, minimally, was type a subject and press SUBMIT). I can't ask them, because they really have no idea.

The second issue, more difficult, is to create a way to manage these issues that will be suitable to us developers. I actually have been satisfied managing new issues and bugs via Gmail inbox but my co-worker would like to use a system. He gets more mail than I do and has other reasons.

I am completely at a loss for what to do. My problem is solved as much as I need it to be. When I look at other bug report systems, they both look terrible and are often expensive. Moreover, if even one person reports a bug via email, it will be a disaster! We can't refuse every bug via email and then will have two bug reporting systems.

Sorry to put out all these complaints here, but maybe someone has some insightful advice that hasn't already been said.

答:
It seems you are "influencing" a change in the culture, that takes time. In addition, bug management systems are a heavy cost, primarily because we have our email accounts open all day in the background, but for a bug management system, a user is asked to open yet another system which they have to learn to use, etc.

A few things you can try:

Get project leader involved and discuss the importance of not losing bugs.

If there were any bugs that were missed, bring that up as a case study.

You can have regular status meetings (or triage) that are run only by the bug reporting system.

Send team-wide reports (esp. if your project leader can do it), that shows who opened how many bugs and how many are assigned to each engineer, that will have people realize the "benefit" they get (i.e. testers will be happy when they get fame because of the bug publicity, etc. As a tester, this was a great feature of bug management systems for me :-))

I have used tools that automatically generate bug reports and send them to the team or have desktop widgets, etc.

You can consider integrating your bug management system with the emails so if an email is sent to the team along with a special address, it will automatically open a bug.

If someone sees an email that's a bug, they can add the bug management system alias to cc and there you go. Many incident management systems take this approach.

Despite all of this, you could still have some bugs that will be missed because people tend to start email discussions asking a behavior and very soon it turns out its a bug, and no one opens one in the bug management system. Having that email integration may help, but then such issues just have to be managed along the way...


问:
How to structure REST api service that accepts POST parameters in the body
Everything I've read says to pass parameters to a REST service in the URI, whether by template, or query string:

```<code>https://www.myapp/my/login/api/authenticate/ganders/mypassword
</code>```

or

```<code>https://www.myapp/my/login/api/authenticate?user=ganders&password=mypassword
</code>```

But obviously those are exposing my username and password in clear view.

Our security guy is saying that we need to pass the parameters in the body of the request. How do I do that? Examples, or just a link to an example is sufficient because apparently my googling skills are not very high.

One thing that I've found so far is that if you decorate your service methods with the attribute [FromBody], like this:

```<code>public AuthenticationResult Authenticate(**[FromBody]**LoginData loginData)
{
    return AuthenticationResult.Authenticated;
}
</code>```

that will grab them from the body. My other task is trying to test this? Is this a task for Fiddler? Or Chrome Dev tools?

Another thing I've found so far is that you can only have 1 parameter in the post, is that accurate?

Sorry, lot's of questions here. Spent all day yesterday trying to research this and obviously didn't get very far...

Edit:

So here's what I have so far, this is the "GET" version that we need to convert to a POST (this is Angular calling C# REST API)

```<code>$http.defaults.headers.common.Authorization = 'Basic ' + encoded;

var url = $rootScope.serviceBaseUrl + "login/get" + "?username=" + user + "&password=" + password + "&accesstoken=";

$http({method: 'Get', url: url}).success(.....).error(......);
</code>```

And the REST service:

```<code>[HttpGet]
    public AuthenticationResult Get([FromUri]LoginModel login)
    {
        try
        {
            AuthenticationService authService = new AuthenticationService();
            AuthenticationResult result = authService.IsAuthenticated(login);

            if (result.IsAuthenticated)
                return result;
            else
            {
                return new AuthenticationResult()
                {
                    IsAuthenticated = false,
                    User = new User()
                    {
                        UserId = login.Username
                    }
                };
            }
        }
        catch(Exception ex)
        {
            return new AuthenticationResult()
            {
                IsAuthenticated = false,
                User = new User()
                {
                    UserId = login.Username,
                    Token = ex.Message
                }
            };
        }
    }
</code>```

Edit2: I'm getting closer. I've got the response to go through (via Fiddler), but my json array of data that I'm passing is not getting mapped to my complex type. Here's what I've got:
 In Fiddler:

```<code>User-Agent: Fiddler
Host: localhost:42761
Content-Length: 73
Content-Type: application/json
Accept: application/json
</code>```

"Request Body":

```<code>{
"Username": "ganders",
"Password": "hashedPassword"
}
</code>```

My "LoginData" object is instantiated on the service-side, but my two properties are null...

答:
Everything I've read says to pass parameters to a REST service
  in the URI, whether by template, or query string:

Nobody that understands REST would recommend that.

URL (uniform resource locator) is a subtype of URI (uniform resource identifier). A URL is meant to be a string representing the identity of the resource you're interacting with; a URL therefore must contain everything that is necessary to identify a resource and nothing more. While one's username may be argued to be part of the identity of user resource, a password does not and should not be found anywhere in the URL.

The ideal REST/HTTP way to logging into service is through WWW-Authenticate/Authorization headers. If you absolutely cannot implement this as Authorization, an acceptable workaround would be to either POST to an authentication resource /login/ and have both username and password contained in the body; or to POST to the user resource /users/username with the password in the body. Whether to use URL encoding or JSON or XML or other formats for the request's Content-Type, does not matter in REST, pick one that's most convenient to you. Under no circumstances should the password be in the URL. This is irrespective of any security considerations that can arise when putting password in the URL due to logging or caches.


答:
What should such a minimal documentation contain so it can give a general idea about what the module does and how people can use it?

Nothing.

Needing documentation to describe what your code does is a sign that your code is poorly named, poorly structured, and/or overly complex. Sure, there are times when there are no good names, or the code needs to be complex because the problem is complex. But that's a exceeding minority of any codebase.

In all honesty, I don't even read comments at the top of files/classes/methods anymore (comments in methods can be useful though). Comments lie. They quickly get out of date. The code can be misleading due to poor naming. The code can be confusing due to poor structuring. But the code can't out and out lie about what it actually does.


答:
I will suggest a different approach to tackle this problem.

I am guessing that you don't have enough abstraction levels and that you have modules of code that are too large.  Consider adding abstraction layers and/or objects that, by fully descriptive names, effectively provide the developers that read it with good documentation.

For example, in Ruby, I will frequently see classes with hundreds of methods and methods themselves with thousands of lines.  Frequently for the User god class.  Such code, no matter how well written will take some time to understand.  However refactoring into classes no bigger than 100 lines and methods no bigger than 5 lines ('Sandi Metzs rules') can help with this.  Almost every time I refactor code with techniques like Extract Method, Extract Class or tackle problems like Too Many Parameters I find that the code afterwards is easier to read.


问:
Sub routing in a SPA site
I have a SPA site that I'm working on, I have a requirement that you can have subroutes for a page view model. Im currently using this 'pattern' for the site

```<code>MyApp.FooViewModel = MyApp.define({
    meta: {
        query: MyApp.Core.Contracts.Queries.FooQuery,
        title: "Foo"
    },
    init: function (queryResult) {

    },
    prototype: {
    }
});
</code>```

In the master view model I have a route table

```<code>this.navigation(new MyApp.RoutesViewModel({
    Home: {
        model: MyApp.HomeViewModel,
        route: String.empty
    },
    Foo: {
        model: MyApp.FooViewModel
    }
}));
</code>```

The meta object defines which query should populate the top level view model when its invoked through sammyjs, this is all fine but it does not support sub routing

My plan is to change the meta object so that it can (optional offcourse) look like this

```<code>meta: {
    query: MyApp.Core.Contracts.Queries.FooQuery,
    title: "Foo",
    route: {
        barId: MyApp.BarViewModel
    }
}
</code>```

When sammyjs detects a barId in the query string the Barmodel will be executed and populated through its own meta object.

Is this a good design?

edit: Hmm, just noticed that above design is not always enough, the parent view model might need to do some processing when the subRoute triggers, so I added a object to the definition sent into MyApp.define like

```<code>meta: {
    query: MyApp.Core.Contracts.Queries.FooQuery,
    title: "Foo",
    route: {
        barId: MyApp.BarViewModel
    }
},
onRoute: {
   barId: function(barViewModel) {
      //act on bar route
   }
}
</code>```

答:
You don't need to role your own, Angular combined with ui-router is a great SPA framework for that sort of thing.

```<code>$stateProvider
  .state('home', {
      url: "/",
      templateUrl:'/home.html'
  })
  .state('foo', {
      url: "/foo",
      templateUrl:'/foo.html',
      resolve:{
         bar:  function(){
            return {'value': 'baz'};
         }
      },
      controller: ['$scope', 'bar', function($scope, bar) {
        $scope.bar = bar;
      }]
  })
  .state('foo.bar', { //sub routing
      url: "/bar",  //actual /foo/bar
      templateUrl:'/bar.html',
      resolve:{
         baz:  function(){
            return {'value': 'buzz'};
         }
      },
      controller: ['$scope', 'baz', function($scope, baz) {
        //$scope.bar still = bar;
        $scope.baz = baz;
      }]
  })
</code>```

;

It already allows great separation of concerns and has built-in dependency injection.

See this plunkr, for an example:

http://plnkr.co/edit/1mXGdrl8612Vyyo0WrUF?p=preview

Title: Sub routing in a SPA site

Body:
You don't need to role your own, Angular combined with ui-router is a great SPA framework for that sort of thing.

$stateProvider
  .state('home', {
      url: "/",
      templateUrl:'/home.html'
  })
  .state('foo', {
      url: "/foo",
      templateUrl:'/foo.html',
      resolve:{
         bar:  function(){
            return {'value': 'baz'};
         }
      },
      controller: ['$scope', 'bar', function($scope, bar) {
        $scope.bar = bar;
      }]
  })
  .state('foo.bar', { //sub routing
      url: "/bar",  //actual /foo/bar
      templateUrl:'/bar.html',
      resolve:{
         baz:  function(){
            return {'value': 'buzz'};
         }
      },
      controller: ['$scope', 'baz', function($scope, baz) {
        //$scope.bar still = bar;
        $scope.baz = baz;
      }]
  })

;

It already allows great separation of concerns and has built-in dependency injection.

See this plunkr, for an example:

http://plnkr.co/edit/1mXGdrl8612Vyyo0WrUF?p=preview


问:
How to make a random-access archive of text files?
I wrote an application that tests the performance of evolutionary algorithms. This application performs a run of the algorithm which consists of several generations. The data which is produced by my application looks like this:

```<code>run1.run             // text file containing metadata
run1_data            // folder containing experimental data
   -statistics1      // text file containing some specific statistics
   -statistics2
   -generation0
   -generation10     // snapshot of the algorithm at generation10
   -generation20
   ...
</code>```

Once this data is written, it is never changed.

When I want to examine the data, my application reads the metadata file (.run), opens the _data directory and reads the rest of the data.

This was all fine until recently. I now have hundreds of thousands of these files and I ran out of inodes on my system and also the loading of the data and copying is extremely slow, even though there are only a few gigabytes. My data seems to be too fragmented, since the files are quite small.

My application is written in C++ and uses the Qt library for filesystem operations. I was thiking of using the <system> header to issue a tar command to archive data after writing and un-archive before reading, but I found out that tar must read the entire archive to find the contents. This is a problem for me, since to save operating memory and time I sometimes load only Statistics1, sometimes only generation10...

I was considering to change the format of my data so that there would be only one file, which would have something like a table of contents at the beginning, followed by all data files concatenated. The table of contents would indicate the beginning and end of each concatenated file. However I am not sure if this is a good solutions since the std::ifstream class that I use to read the files cannot make random jumps.

I am a beginner programmer and I do not want to waste a lot of time on developing something that would not work so I ask for any advice on how to solve my problem.

答:
The sqlite suggestion is good if you believe that your data is relational. You can squeeze the data into sqlite if even if it is not relational, however, a nosql database may be a better choice. For example Mongodb might be a good choice or redis may be good choices.

By the way, fstream is fine with random access. See seekg.


答:
Really make sure than under real, production, conditions (realistic memory consumption, that triggers Garbage Collection realistically, etc), all those separate methods really make a performance difference (as opposed to having only one method). This will take a few days out of your time, but may save you weeks by simplifying the code you work with from now on.

Also, if you do discover that you need all the functions, you might want to use Javassist to generate the code programatically. As other have pointed out, you can automate it with Maven.


答:
You can also use a zip file.  It's like tar, but the index is held at the end of the file, and is found by seeking to the end of the file.

If you don't compress when creating the zip, then it's just like a tar, but with the abilily to seek to any file inside, and you can even mmap the entries.

It's better than sqlite because it's easy to browse a zip file, and many file utilities can treat a zipfile like a folder.  BeyondCompare can even compare two zip files just like comparing two folders.

Title: How to make a random-access archive of text files?

Body:
I wrote an application that tests the performance of evolutionary algorithms. This application performs a run of the algorithm which consists of several generations. The data which is produced by my application looks like this:

```<code>run1.run             // text file containing metadata
run1_data            // folder containing experimental data
   -statistics1      // text file containing some specific statistics
   -statistics2
   -generation0
   -generation10     // snapshot of the algorithm at generation10
   -generation20
   ...
</code>```

Once this data is written, it is never changed.

When I want to examine the data, my application reads the metadata file (.run), opens the _data directory and reads the rest of the data.

This was all fine until recently. I now have hundreds of thousands of these files and I ran out of inodes on my system and also the loading of the data and copying is extremely slow, even though there are only a few gigabytes. My data seems to be too fragmented, since the files are quite small.

My application is written in C++ and uses the Qt library for filesystem operations. I was thiking of using the <system> header to issue a tar command to archive data after writing and un-archive before reading, but I found out that tar must read the entire archive to find the contents. This is a problem for me, since to save operating memory and time I sometimes load only Statistics1, sometimes only generation10...

I was considering to change the format of my data so that there would be only one file, which would have something like a table of contents at the beginning, followed by all data files concatenated. The table of contents would indicate the beginning and end of each concatenated file. However I am not sure if this is a good solutions since the std::ifstream class that I use to read the files cannot make random jumps.

I am a beginner programmer and I do not want to waste a lot of time on developing something that would not work so I ask for any advice on how to solve my problem.


问:
What happens if you're unable to solve a problem?
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?

答:
My sequence of solving problems (every next spet is performed only if the previous did not work):

Try to google

Ask someone

Search SO directly (bypassing Google)

Think

Smoke (== clear head)

Ask a question on SO

Wait till morning (== clear head even more)

Use that dirty hack and feel bad about myself :(

Nasty problems are solved on steps 5-6.

Really-really bad problems usually need some time (step 7 is THE solution to most 'seems-that-i-cannot-do-anything' problems). And I mean it - switch to another task for the rest of the day and try to solve the problem first thing in the morning. That does wonders.

And only then comes step 8.


答: How old is the program? Most probably newer hardware would remove the bottleneck and you could switch to a more maintainable version. But there needs to be a reason for maintenance, so unless your task is to improve the codebase, leave it be as it is working.</p>


问:
Measuring performance of a network simulator?
I have written a python program to test a new network routing algorithm, that uses a Content Centric Network Approach for handling requests (CCN), where the CCN router keeps 3 data structures:

A PIT or Pending Interest Table, that holds requests for which a router has not yet received a response.

A FIB or Forwarding Interest Base, which maps requests to the next router to which the request can be forwarded.

A Content store to which the router can cache content from previous requests.

The Simulator is simple:
- It follows the Event-Based design where 'Dummy Packets' are sent from server object to other server objects containing data of what content is being requested and the destination of where the content object is.

Specifically, how could I design my simulator or tests to get a birds eye view of how my new algorithm matches up against standard IP routing?

My hunch is that I will need to test speed, which I believe can be done by timing the round trip time for a request. But I don't know how I would test other aspects of this algorithm.

I have little to no networking experience so any advice or direction is appreciated.

答:
As MichaelT pointed out you need to be clear on metrics that you are trying to measure and the ones that make sense to you. Some common metrics when it comes to measuring network performance are

Throughput.

Latency.

Server and client response time.

In my opinion just measuring RTT is not sufficient to measure performance of routing because the RTT is influenced by lots of external factors like link performance not necessarily routing performance also your RTT for the same link and same router may be different over number of trial. Throughput on the other hand will give you fairly better idea over how your network performs(keeping the network very minimal is the key to get exact routing throughput).

To answer your second part of the question:

Any homegrown system to measure traffic performance will require a bit of an effort and time and may not be able to provide accurate numbers, if you have budget try looking for commercial solutions like Ixia, Spirent or shenick.

If you do not have the budget I cannot think of a single tool that will help you get all the metrics but can integrate different tools to a wholesome system.

I have found pmacct to be very powerful and flexible to account for traffic,It collects different metrics about the data flows,The issue with this is it also includes layer 7 data so your numbers will be a bit skewed on the lower side(routing throughput will be way higher than the actual application throughput).

But if you are not really concerned about publishing the numbers to your customers this will help you get a fairly decent baseline to compare against different routing protocols.

A much simpler solution will be to use bwm-ng which will display the traffic rate on an interface.It gives only throughput data nothing else, at least nothing that I know of.

Generating traffic to push to the limit of the link will be a challenge you will probably need a fairly huge machine(like a Dell 8000 series) to pump around a gig of data.There are lots of open source traffic generation tools like curl-loader, scapy etc.. which will help you generate traffic.


问:
Nested objects in REST
I have simple set of resources, not more than 10 types, with some one-to-many relationships.
For example

An order has many entries

An entry has many comments

A machine can have multiple entries associated

A material can have multiple orders associated

All the model objects are identified by a unique Primary Key

I communicate using REST HTTP calls. How should the objects be modeled?

Option 1: Nesting objects

The relationships can result in nested objects:

```<code>entry{
  PK: '_',
  prop1: '_',
  prop2: '_',
  machine:{
    PK: '_',
    prop3: '_'
  },
  order: {
    PK: '_',
    material: {
      PK: '_',
      prop4: '_'
    }
  }
}
</code>```

And similarly for the other objects

Option 2: Reference by PK

This approach "flattens" the objects:

```<code>entry{
  PK: '_',
  prop1: '_',
  prop2: '_',
  machinePK: '_',
  orderPK: '_'
}
</code>```

What is the best approach? obviously both have clear advantages and disadvantages. Is an hybrid approach a viable solution? If so, which criteria should I follow to chose between "flat" or "nested" objects? Could it possibly depend by the technology I use to implement that (Changing the model because of the technologies smells like bad practice though...)?

To give some context, I am using ASP.NET WebApi 2 for the backend and AngularJS in Typescript for the frontend

答:
It depends on the experience you want the programmer to have as well as complexity and performance impact in your application.

If the single object is large, and the consumer of the API does not need all the data upfront, then you might want to break it into multiple chunks, and have them call back if they want a related object.

With larger objects, processing and performance on the server may increase, which might itself be an issue, so you may want to keep that lowered.

On the other hand, if your object is really "incomplete" without the sub-objects, then you could consider sending them down in one go.

I do not think PK is necessarily a standard term that is understood by people other than those who deal with databases. For REST APIs, more suitable names might be EntryId, OrderId, MachineId etc., or more genericically Id and ObjectId, etc.

Also, you do not always need to send ObjectIds for the nested elements, the API itself will reveal the relationships (that is kind of the purpose of rest), and thus, from your example, the entry would like this:

```<code>entry{
  Id: "42",
  prop1: '_',
  prop2: '_',
}
</code>```

If someone wanted to find all the orders for an entry, they will issue something like this:

```<code>https://www.example.com/entries/42/orders
</code>```

This will get all the orders for the entry # 42 (with paging etc. if needed).

You might want to see this page for REST URL best practices, and this page for links to other best practices on Rest APIs. You might also want to look at OData since that deals primarily with data and is built on top of REST APIs. Do remember to obviously validate and get other opinions.

Title: Nested objects in REST

Body:
It depends on the experience you want the programmer to have as well as complexity and performance impact in your application.

If the single object is large, and the consumer of the API does not need all the data upfront, then you might want to break it into multiple chunks, and have them call back if they want a related object.

With larger objects, processing and performance on the server may increase, which might itself be an issue, so you may want to keep that lowered.

On the other hand, if your object is really "incomplete" without the sub-objects, then you could consider sending them down in one go.

I do not think PK is necessarily a standard term that is understood by people other than those who deal with databases. For REST APIs, more suitable names might be EntryId, OrderId, MachineId etc., or more genericically Id and ObjectId, etc.

Also, you do not always need to send ObjectIds for the nested elements, the API itself will reveal the relationships (that is kind of the purpose of rest), and thus, from your example, the entry would like this:

entry{
  Id: "42",
  prop1: '_',
  prop2: '_',
}

If someone wanted to find all the orders for an entry, they will issue something like this:

https://www.example.com/entries/42/orders

This will get all the orders for the entry # 42 (with paging etc. if needed).

You might want to see this page for REST URL best practices, and this page for links to other best practices on Rest APIs. You might also want to look at OData since that deals primarily with data and is built on top of REST APIs. Do remember to obviously validate and get other opinions.


问:
How to handle versioning with multiple independent pull requests in a Git repository?
Let's say Alice has a Git repository, and the version is kept track of inside the repository (e.g. package.json for npm).

Bob sends a pull request to Alice which increments the version number from 0.1.0 to 0.1.1.

Carol also sends a pull request to Alice (independently from Bob's request) which increments the version number to 0.1.1 as well.

How can Alice deal with this situation?

答:
If Alice is the maintainer of the project, then Alice and Alice alone should be the one that increments the version. Increasing the version number means a release, and Alice is the one to decide when to release - not Bob and Carol.

Whatever code Bob and Carol contribute, you can be 99.99% certain it'll still work even if they don't increment the version number. The remaining 0.01% is because one can always query for the version number and crash the program if it's below the new value. This can be neglected though - Alice should reject any pull request that does that...

ContentLicense: CC BY-SA 4.0


答:
If bug reporters are ordinary users, I can see why they would prefer to contact you by email. Let's imagine I'm an ordinary user and I want to report a bug.

Bug report form

First, the Report a bug form itself. Despite your attempts, it's not intuitive.

What should be the priority of the bug I want to report? If I put it too high, I'm afraid that the developers will blame me that I consider bugs I report to be more important than other bugs. If I put it too low, developers may never read them.

What's the subject? Hm. No idea. What about "A bug"? Sounds stupid.

The form asks to describe the bug. Should I start by saying hello to the person who will read the report, or keep it impersonal? Should I specify the context, given that the form asks to talk only about the bug itself?

The form asks me to attach a screenshot. But the bug is not visual. Can I skip this step? The form doesn't tell me if I can.

Email. Ok. What if I don't care about the response, and I'm afraid you will send me spam?

If I check that I want to notify everyone, would it notify every developer on a team? Every person in charge of reading bugs? Or maybe the bug report will become public and anyone will be able to read it? This looks scary.

Bug report process

Talking about the environment:

I want to keep a trace of the bug report, because there is some other company which received hundred bug reports from me, never answered and never solved them. When I contacted their support, they told that they never received anything from me. What a shame. With emails, I could have shown them that I actually did report something.

What would actually happen once I submit the form?

Is there a person behind that? Talking to a person is one thing. Filling a form without knowing if it's read by anyone is a different thing. You may say that having to write to bugs@example.com is quite impersonal as well; that's why in many products, you may contact a person.

"Bug" term

Finally, the terminology. What should be reported?

If it's an unhandled exception in a software product, why would I report it? Shouldn't it be reported automatically?

Actually, it should. This is exactly the behavior of the products such as VLC or Chrome.

If it's an HTTP 500 in a web application, why should I report it? It should be done automatically.

If it's an actual bug which doesn't cause an unhandled exception or an HTTP 500, then and only then the form can be used.

If it's a feature I need, I would rather contact the company by email rather than reporting a bug, since it's not a bug.

If it's a typo, a wrong translation, an accessibility issue, etc., again, few would qualify it as a bug. Thus, the form is irrelevant for that, and emails look more appropriate.

If it's a legal request ("Your app erased all my files so I'll sue you."), it should be done by mail, or in some cases by email, not by filling a bug report.

If it's something else, a feedback by email seems again more appropriate than a bug report.

Conclusion

Bug reporters may not be inclined to use the form because:

They always did this way (see the answer by Omer Iqbal),

They may have tried, and were trapped in those terribly complicated bug tracking systems,

The form is not intuitive,

The form doesn't give a hint about what will happen later,

The form talks about bugs, which excludes a bunch of things which can be subject to feedback but which are not exactly bugs, such as typos or accessibility issues.

To encourage the users to actually use the form, you may:

Make it more intuitive,

Make it less impersonal,

Explain better what will happen once the bug is submitted,

Change the terminology, if needed.

Finally, why not mixing both emails and reporting through a form? FogBugz does that.

Or if reports by email really annoy you and you can afford being unfriendly with bug reporters, then:

just bounce the emails back to them with a brief message: "Please put this in the bug database. I can't keep track of email."

Title: Bug Report System - Getting people to use it

Body:
I've built already a bug report system. It looks like this:

It is accessed using a secret key combination detected by the JavaScript code. Not hard. It has everything - sends the standard emails to management and testers, logs the Javascript variables and current DOM HTML. We are also improving the backend of the system to act as a full bug report system. Previously, it was only via email.

The problem is, unfortunately, the bug reporters still preferred email. Even when I refused to answer their queries until they sent a bug report, they would not consistently send them.

I don't understand it, because, for them it should be easy, but they act like it was a big deal. (The appearance was slightly more complex before, but still, all they had to do, minimally, was type a subject and press SUBMIT). I can't ask them, because they really have no idea.

The second issue, more difficult, is to create a way to manage these issues that will be suitable to us developers. I actually have been satisfied managing new issues and bugs via Gmail inbox but my co-worker would like to use a system. He gets more mail than I do and has other reasons.

I am completely at a loss for what to do. My problem is solved as much as I need it to be. When I look at other bug report systems, they both look terrible and are often expensive. Moreover, if even one person reports a bug via email, it will be a disaster! We can't refuse every bug via email and then will have two bug reporting systems.

Sorry to put out all these complaints here, but maybe someone has some insightful advice that hasn't already been said.


问:
Entity Framework 6 Conventions
I use the Entity Framework often, but I have one area of confusion I would like to understand better.

If I wanted to have a navigation property in an Entity such as

```<code>public virtual ExampleObject Example {get;set;}
</code>```

it is also the done thing to have an Id property

```<code>public int ExampleId {get;set;}
</code>```

My undertsanding is this creates a FK, but if I omit it, the functionality is the same and the FK seems to be created anyway. So, is there a reason for the additional field?

答:
I've never used Entity Framework, nor am I familiar with it's implementation details, but it's quite common that ORMs will not resolve foreign keys into objects unless either they are explicitly instructed to do so or the user tries to access these objects. This makes sense - populating the Example property is much more expansive than populating ExampleId, since the ID is column of the containing entity's table but for the full ExampleObject you need to query another table.

While it seems like ExampleId is only useful for resolving the full ExampleObject, there can be cases where you need just the ID. For example, if Student has Course with the CourseId foreign key, and Assignment also has Course with the CourseId foreign key, you might want to use Student's CourseId directly to get all the Assignments with the same CourseId. You don't need the full Course object for that.

Title: Entity Framework 6 Conventions


问:
What does it mean when code "runs on" the .NET CLR?
The .NET CLR is not an interpreter, since code gets compiled to native code by the JIT compiler. So I find the usual description of code "running on" the CLR confusing.

How does the native code interact with the CLR?  Does the compiler insert calls into CLR methods at the beginning and end of your methods, for example?

I have no idea.

答:
There's a decent overview of the .NET Common Language Runtime on MSDN. There are a few key paragraphs that may get you started understanding the process:

The common language runtime provides the infrastructure that enables
  managed execution to take place and services that can be used during
  execution. Before a method can be run, it must be compiled to
  processor-specific code. Each method for which MSIL has been generated
  is JIT-compiled when it is called for the first time, and then run.
  The next time the method is run, the existing JIT-compiled native code
  is run. The process of JIT-compiling and then running the code is
  repeated until execution is complete.

During execution, managed code receives services such as garbage
  collection, security, interoperability with unmanaged code,
  cross-language debugging support, and enhanced deployment and
  versioning support.

In Microsoft Windows XP and Windows Vista, the operating system loader
  checks for managed modules by examining a bit in the COFF header. The
  bit being set denotes a managed module. If the loader detects managed
  modules, it loads mscoree.dll, and _CorValidateImage and
  _CorImageUnloading notify the loader when the managed module images are loaded and unloaded. _CorValidateImage performs the following
  actions:

Ensures that the code is valid managed code.

Changes the entry point in the image to an entry point in the runtime.


答: Alice should handle this situation by rejecting the pull requests which also change the version number (both of them). Collaborators who are not the maintainer should not be changing the version number - that is the job of the project maintainer.</p>

Title: How to handle versioning with multiple independent pull requests in a Git repository?

Body:
Let's say Alice has a Git repository, and the version is kept track of inside the repository (e.g. package.json for npm).

Bob sends a pull request to Alice which increments the version number from 0.1.0 to 0.1.1.

Carol also sends a pull request to Alice (independently from Bob's request) which increments the version number to 0.1.1 as well.

How can Alice deal with this situation?


答:
No sane Java method can be long enough to have 12 variants... and JITC hates long methods - it simply refuses to optimize them properly. I've seen a speed up factor of two by simply splitting a method into two shorter ones. Maybe this is the way to go.

OTOH having multiple copies may make sense even if there were identical. As each of them gets used in different places, they get optimized for different cases (the JITC profiles them and then places the rare cases on an exceptional path.

I'd say that generating code is no big deal, assuming there's a good reason. The overhead is rather low, and properly named files lead immediately to their source. Some long time ago as I generated source code, I put // DO NOT EDIT on every line... I guess that's save enough.


问:
Custom Domain or Attribute Reference Table or Both?
I'm designing my first real database and I'm weighing the pros and cons of how to enforce uniformity in my data. My first option is to create a custom domain and program my UI to only allow certain options. My second option is to create an "attribute reference table" that would store allowed values. My UI could query that table for allowed values and display them in a drop down box. Or I could do both

My thoughts on the first is that it would be more difficult to maintain the UI. If the domain were to change, then I would need to alter the UI (unless there is a way to query the domain for values?). I don't know whether there is, but my thought is this would process and return results faster than having to query a second table.

An attribute table seems beneficial in that I can design the UI to adapt on the fly, but less optimal in the sense that the data values are not controlled by the DBMS and it requires an additional query.

Doing both would add all of the complexity, increase processing time, and increase UI maintenance.

答:
Though specific problems are missing in the question provided, I would try to answer in a more generic way of how to design DB based on my personal experience.

First step would be identifying entities and their relationships.

Try normalizing data based on normalization rules so that your table structure doesn't allow redundant data & data dependency make sense. You may take a cue about this from Data Normalization @ Wikipedia

Now talking about specifics its always a choice or trade off between keeping things dynamic and tying them in structure. Since the exact problem is not mentioned i'll take an example of my choice. Lets say you want to input a country name and based on it some more attributes and it could be dynamic. But since there could be FINITE number of countries it would make sense by having a master table of countries whose data doesn't change and you may use it as reference in your real data. But if you were to have a list of N attributes with M types (where M is also infinite like N, which again is a rare possibility) you would have to go with the former option provided in your question.

Just a hint, key here would be to identify the types of attributes / entities.


问:
When to stop reviewing code?
I am working in a team of 4 members. we have started reviewing code 2 months ago. we are using Gerrit as code review tool. while reviewing code initially we have found lot's of problem in the code i.e. no proper code comments. method are too big. no null pointer checking. no proper exception handling etc.

but now a days it looks code has improved. so when i am reviewing code i am not getting that much problem in the code.

so my question is should we continue code review even there is not that much flaws in the code? or will we stop?

答:
You can do whatever works for you, but don't your code reviews show up real bugs (and not only "beauty issues")? I have seldom seen a situation where new code did not have enough bugs to justify a review.

Besides that, don't your reviews make sure there is at least one second person (apart from the author) who knows the code? And if you would stop doing regular code reviews, don't you expect the issues you have listed above will probably come back (at least, occasionally)?

So answer those question for yourself, then you know if stopping regular code reviews is a good or bad idea.

Title: When to stop reviewing code?


答:
You can have two good sources of documentation in your code. The first is inline comments that use a standard format, like Javadoc or the aforementioned C# code documentation tags. These should accompany each class and each method that may be used by others (you don't need to do this with private methods/classes, though it may help in some cases). Because they are a standard format, many programmers are already familiar with them, or can become familiar with them quickly. Additionally, tools are able to recognize and extract data from these specially formatted comment blocks. You could write Javadoc for a method like Math.abs as follows:

```<code>/**
 * <p>
 * Returns the absolute value of an int value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.
 * <p>
 * Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.
 *
 * @param a the argument whose absolute value is to be determined
 * @return the absolute value of the argument.
 */
public static int abs(int a)
{ ...
</code>```

and using Java's built-in Javadoc tool, you can generate something like this. Some IDEs are able to read formatted comments and provide embedded documentation. For comments like these, it is important to focus on behavior not implementation. What your method does is unlikely to change, but how it does it may change frequently. Focusing on what it does means less potential for drift between comments and code.

The second source of documentation in your code is your tests. Someone should be able to figure out what your methods do by looking at the tests. Rspec and other behavior-driven test frameworks are designed to read like a natural language to reduce the barrier to entry, but a capable programmer can get what they need to know from any valid test framework. To test our Math.abs method, we could have the following test (with JUnit):

```<code>@Test
public void testAbs() {
    assertEquals(5, Math.abs(5));
    assertEquals(5, Math.abs(-5));
    assertEquals(0, Math.abs(0));
    assertEquals(Integer.MIN_VALUE, Math.abs(Integer.MIN_VALUE));
}
</code>```

From this test, I can see that positive values are returned as-is, negative values are returned negated, zero is returned as-is, and Integer.MIN_VALUE is returned as-is (in accordance with the documentation we wrote for the method). Additionally, if I was still not clear about what happens for a particular input (say Integer.MAX_VALUE), I can easily add another test and find out, without interfering with anything else. While tests are not always as plainly clear as comments, they provide executable verifiability. That is, I can prove that the code does what the tests say by running the tests and seeing that they pass. Tests generally cannot drift from the code as comments can, since drift would manifest as failing tests.

If you find yourself having to read a lot of code just to find out what a method does, you also need to put more effort towards making your code as self-documenting as possible. Descriptive class, method, and variable names can improve legibility significantly. Small methods that you can essentially treat as black boxes (like Math.abs above, where we don't know the actual implementation) can also help by hiding complexity behind a friendlier name.

Body:
You can have two good sources of documentation in your code. The first is inline comments that use a standard format, like Javadoc or the aforementioned C# code documentation tags. These should accompany each class and each method that may be used by others (you don't need to do this with private methods/classes, though it may help in some cases). Because they are a standard format, many programmers are already familiar with them, or can become familiar with them quickly. Additionally, tools are able to recognize and extract data from these specially formatted comment blocks. You could write Javadoc for a method like Math.abs as follows:

/**
 * <p>
 * Returns the absolute value of an int value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.
 * <p>
 * Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.
 *
 * @param a the argument whose absolute value is to be determined
 * @return the absolute value of the argument.
 */
public static int abs(int a)
{ ...

and using Java's built-in Javadoc tool, you can generate something like this. Some IDEs are able to read formatted comments and provide embedded documentation. For comments like these, it is important to focus on behavior not implementation. What your method does is unlikely to change, but how it does it may change frequently. Focusing on what it does means less potential for drift between comments and code.

The second source of documentation in your code is your tests. Someone should be able to figure out what your methods do by looking at the tests. Rspec and other behavior-driven test frameworks are designed to read like a natural language to reduce the barrier to entry, but a capable programmer can get what they need to know from any valid test framework. To test our Math.abs method, we could have the following test (with JUnit):

@Test
public void testAbs() {
    assertEquals(5, Math.abs(5));
    assertEquals(5, Math.abs(-5));
    assertEquals(0, Math.abs(0));
    assertEquals(Integer.MIN_VALUE, Math.abs(Integer.MIN_VALUE));
}

From this test, I can see that positive values are returned as-is, negative values are returned negated, zero is returned as-is, and Integer.MIN_VALUE is returned as-is (in accordance with the documentation we wrote for the method). Additionally, if I was still not clear about what happens for a particular input (say Integer.MAX_VALUE), I can easily add another test and find out, without interfering with anything else. While tests are not always as plainly clear as comments, they provide executable verifiability. That is, I can prove that the code does what the tests say by running the tests and seeing that they pass. Tests generally cannot drift from the code as comments can, since drift would manifest as failing tests.

If you find yourself having to read a lot of code just to find out what a method does, you also need to put more effort towards making your code as self-documenting as possible. Descriptive class, method, and variable names can improve legibility significantly. Small methods that you can essentially treat as black boxes (like Math.abs above, where we don't know the actual implementation) can also help by hiding complexity behind a friendlier name.


问:
Does inserting/removing random characters in a string count as cryptography?
I'm making an iOS game. All developers need to determine whether their app uses cryptography or not.

My game saves files in the Documents folder. They are .plist files representing dictionaries. They are encoded in base 64.

From what I gather, encoding is not encrypting. So we're fine there.

However, the values inside the dictionary (after decoding) are a bit tricky. Suppose that your score is 250. In the dictionary the value is a string like:

```<code>@2@5@0@
</code>```

So for the game to read your score, it removes the @ characters (and when saving the game, it puts them back).

That's just an example. Does that count as cryptography?

NOTE: I'm not asking about Apple's policies. I mentioned it for context.

答:
No. This is also just encoding.

Cryptography is well-defined, and according to no definition of encryption do you have a ciphertext. Per Wikipedia,

Cryptography is the practice and study of techniques for secure
  communication in the presence of third parties (called
  adversaries).

Unless you believe adding the @ can make your communication secure, you're good :-)


问:
How can we make agile enjoyable for developers that like to personally, independently own large chunks from start to finish
We’re roughly midway through our transition from waterfall to agile using scrum; we’ve changed from large teams in technology/discipline silos to smaller cross-functional teams.

As expected, the change to agile doesn’t suit everyone. There are a handful of developers that are having a difficult time adjusting to agile. I really want to keep them engaged and challenged, and ultimately enjoying coming to work each day. These are smart, happy, motivated people that I respect on both a personal and a professional level.

The basic issue is this: Some developers are primarily motivated by the joy of taking a piece of difficult work, thinking through a design, thinking through potential issues, then solving the problem piece by piece, with only minimal interaction with others, over an extended period of time. They generally complete work to a high level of quality and in a timely way; their work is maintainable and fits with the overall architecture. Transitioning to a cross-functional team that values interaction and shared responsibility for work, and delivery of working functionality within shorter intervals, the teams evolve such that the entire team knocks that difficult problem over. Many people find this to be a positive change; someone that loves to take a problem and own it independently from start to finish loses the opportunity for work like that.

This is not an issue with people being open to change. Certainly we’ve seen a few people that don’t like change, but in the cases I’m concerned about, the individuals are good performers, genuinely open to change, they make an effort, they see how the rest of the team is changing and they want to fit in. It’s not a case of someone being difficult or obstructionist, or wanting to hoard the juiciest work. They just don’t find joy in work like they used to.

I’m sure we can’t be the only place that hasn’t bumped up on this. How have others approached this? If you’re a developer that is motivated by personally owning a big chunk of work from end to end, and you’ve adjusted to a different way of working, what did it for you?

答:
If Joe (your Hero developer) is a bit flexible, then I don't see a problem:

As said above, let the team self-organize: If some problems are best tackled by letting Joe chew on it by himself, then you would expect an open-minded self-organizing team to reach that conclusion on their own.

The only challenges that remain within the few constraints that Scrum imposes:

Delivering functionality at regular intervals: If you let Joe chew on a problem for months, with nothing to show until the very end, then Joe is indeed not agile: He is taking the product owner hostage and not allowing him an opportunity to re-spec that part of the product. With this practice there is also a risk that he is running late, and nobody is noticing it. (But according to your description that is not so likely). Remedy: Would it be too much to ask from Joe, to sit together with the PO, break up the user story and agree on intermediate deliverables, preferably (but not necessarily) with user value?

Honoring the priorities set by the product owner: If pieces of code are owned by experts, then you risk a situation where the evolution of the product is determined by the availability of each expert, rather than the commercial priorities: The rest of the team might be working on less important features, whereas the top 3 features are stalling because "only Joe can do it". That's bad. At that moment, the team should (temporarily) change their habit and divide the Joe work over more team members.

In short:
If Joe, the hero-developer, agrees with the PO how he will show progress each sprint, then the team can assign certain stories to him and leave him alone.
But if PO has too much work for Joe, and not enough for the team (or vice-versa), then Joe and the team have to adapt, not the PO.

OwnerDisplayName: Kris


答:
no proper code comments. method are too big. no null pointer checking. no proper exception handling etc.

Some of these are just small problems that code review can catch.

Big methods and wrong exception are indeed problems, and it sounds like you are not doing unit testing (or at least not properly).

What is more important are big things :

design issues - it is important to detect design issues sooner, rather then later

to familiarize with other's code - you never know when someone is going to leave

learn something new - someone may suggest new ideas

Title: When to stop reviewing code?

Body:
I am working in a team of 4 members. we have started reviewing code 2 months ago. we are using Gerrit as code review tool. while reviewing code initially we have found lot's of problem in the code i.e. no proper code comments. method are too big. no null pointer checking. no proper exception handling etc.

but now a days it looks code has improved. so when i am reviewing code i am not getting that much problem in the code.

so my question is should we continue code review even there is not that much flaws in the code? or will we stop?


问:
How can I rewrite this linked-list manipulation as tail-recursive?
Given a liked list, I'd like to swap every pair of nodes as follows:

input: a-b-c-d-e-f-g

output: b-a-d-c-f-e-g

If there's an odd number of nodes then the last node is tacked on as-is. This should be done in-place. Implement the method: Node* SwapTo(Node* start)

I'm using this Node definition:

```<code>class Node {
    public:
        char data;
        Node* next;
};
</code>```

Here's the unoptimized recursive solution:

```<code>Node* SwapTwo(Node* start) {
    if (!start) {
        return start;
    }

    Node* second = start->next;
    if (!second) {
        return start;
    }

    Node* third = second->next;
    second->next = start;
    start->next = SwapTwo(third);
    return second;
}
</code>```

What is the tail-recursive solution?

答:
Since you tagged the question with language-agnostic, here's a solution in a language suited to recursive functions and data structures:

```<code>let rec swapTwo lst acc =
    match lst with
    | a::b::tail -> swapTwo tail (a::b::acc)
    | h::tail -> swapTwo tail (h::acc)
    | [] -> List.rev acc
</code>```

As for a solution in C++, I don't fancy doing the pointer twiddling details, but I'd start with a function with the following signature:

```<code>Node* SwapTwo (Node* start, Node *prev, Node *curr)
</code>```

Where start would be the head of the list and curr would be what start is in your snippet - the first of the two elements to swap. Then you also need prev, the last node of the previous 'block' to set the next pointer on it.

Probably the prev bit is the most tricky, since you have to update the previous block when you're already processing the next one. The key part to remember when making stuff tail-recursive is that you don't have the stack to utilize in building your computation, you have to pass everything around explicitly to the next recursive call. In your case, that part is where you assign SwapTwo result to start->next.

This should more or less cover it. I don't think I have to comment much on which of those two solutions I find preferable.

Body:
Since you tagged the question with language-agnostic, here's a solution in a language suited to recursive functions and data structures:

let rec swapTwo lst acc =
    match lst with
    | a::b::tail -> swapTwo tail (a::b::acc)
    | h::tail -> swapTwo tail (h::acc)
    | [] -> List.rev acc

As for a solution in C++, I don't fancy doing the pointer twiddling details, but I'd start with a function with the following signature:

Node* SwapTwo (Node* start, Node *prev, Node *curr)

Where start would be the head of the list and curr would be what start is in your snippet - the first of the two elements to swap. Then you also need prev, the last node of the previous 'block' to set the next pointer on it.

Probably the prev bit is the most tricky, since you have to update the previous block when you're already processing the next one. The key part to remember when making stuff tail-recursive is that you don't have the stack to utilize in building your computation, you have to pass everything around explicitly to the next recursive call. In your case, that part is where you assign SwapTwo result to start->next.

This should more or less cover it. I don't think I have to comment much on which of those two solutions I find preferable.


问:
Architecture of large-scale API (User Management)
We are currently designing an API that will hide different services (Product, Content, User etc) that will be used by our own website, our own apps etc. It is not a public API.

We are looking into using ServiceStack as a foundation, and that might be right.

However, the biggest concern is how to manage the users (each user has 30-50 attributes) and hopefully 100 000+ users.

As I've understand AspNet Identity is nothing for Production so therefore we need to create our own implementation of AspNet Identity.

What is your experience of creating a Custom Identity Provider (any examples)?

We would like to use several external auth services (OpenId, twitter etc), how should that be managed?

How will that then affect the structure of the API (Lets say we are using WebApi instead of ServiceStack). I would like to use as much standard UI as possible.

Any ideas, solutions or examples are appreciated.

答:
ASP.NET Identity comes in two flavors:

You can use your own signin, which will essentially become a 'private IDP' for you.

You an use external IDPs (Facebook, Twitter, LinkedIn, etc.) via ASP.NET Identity, which will handle all the complexity.

I am not sure which option is "nothing for Production" in your opinion. If you can explain the concerns, the response here can be better.

Even when you use external IDPs, ASP.NET Identity can/will create a database with the user so the application can store additional attributes.

In any case, 100K+ users with 30-50 attributes seems something that a single server should be able to handle easily (with or without ASP.NET identity).

Custom IDPs

The general issue with custom IDPs is that a dedicated engineer (or team) is needed to ensure all is in place.

There is cost for initial implementation, esp. with ensuring that all the security requirements are met.

There are support costs associated with forgotten passwords, hacked accounts, etc.

There are engineering improvements needed for new features (two-factor auth, SMS, then email, then something else), security improvements (e.g. a crypto algorithm considered vulnerable suddenly) and production issues.

If the system is compromised or shown as weak by someone else, it is a significant public relations issue for the company.

Using External IDPs

You can achieve this using several technologies or providers: ASP.NET Identity, Azure Access Control Service, OpenID, Auth0 to name a few. All of these will provide a single interface for your application, or you can write directly against Google, Facebook, Twitter, Microsoft Account.

Once a user logs in, whichever service you use, it will provide you claims which you can consume in your application to find a user's email address, first name, last name, etc.

The advantage of using a unifying service (such as Access Control Service) is that it will use only one protocol, and send tokens in a fixed token format regardless of what was used for authentication, and so the application has to communicate using one interface only.

If external IDPs are used directly (e.g. Google, Facebook, Twitter, etc.) the application needs to parse and understand each token, which can vary in the claims contained in them for the same user attribute (e.g. one token may have first_name, another one may have givenName, etc.)

The application may also need to handle multiple protocols (such as OAUTH, SAML) unless it is restricted to a single protocol, which would be OAUTH for most social IDPs, including Microsoft Account, Facebook, Google, Twitter, LinkedIn, etc.

Effect on the structure of the API

Authentication should not affect the public facing API that an app builds. In fact, authentication is handled in the way it is today (i.e. via IDPs) so it can be disconnected from the actual application, which can vary regardless of how the users authenticate.


问:
Trivially Sortable Encoding for Arbitrary-Precision Decimals
I'm looking for a reasonably(*) space-efficient way to encode arbitrary-precision decimals (e.g. BigDecimal), such that when sorting the bit-pattern of the encodings lexicographically, the numbers will be sorted numerically. This is related to this Stackoverflow question.

One simple/naive approach to this would be to convert the number to some IEEE-like representation with some 8-byte exponent (which is what RR in the NTL does?), but obviously this is quite an inefficient(*) representation.

Is there perhaps some other approach to this? Are there any optimizations possible for arbitrary-precision Integers? The encoding need not support any other operations than sorting (and, if possible, decoding the number again).

(*) By reasonably speace-efficient I don't mean cramming bits together into bytes like IEEE-754 does. I just don't want to have any unnecessarily large fields that will remain mostly empty in a large number of situations (as would be the case with an 8-byte exponent). The motive for this is that the (encoded) number will later on be processed by this scheme, which takes a few milliseconds per byte to run.

The runtime-efficiency of the encoding/decoding on the other hand isn't much of an issue (anything less than 10 ms for 128 bytes of data will still be overshadowed by the runtime of the OPE scheme liked above).

(Also note, this should be a decimal representation, so there are to precision-issues due to "binary stuff".)

答:
The general scheme for sorting BigDecimal works as follows:

Sort the sign bit.

Note: if the sign bit is negative, the sort order of the subsequent steps must be negated.

Remove the sign bit and convert the remaining bits into absolute value.

In other words, a sign-magnitude representation is used.

Sort by the position of the "highest bit set".

If A > 0 and B > 0, and highestNonZeroBit(A) > highestNonZeroBit(B), then A > B.

For other bases such as decimals, use highestNonZeroDigit of the corresponding base.

If the highest nonzero bit index are the same for A and B, resolve the tie by sorting the rest of the bits. This may require examining as many bits as are in the numbers.

The reason why sorting by the IEEE representation works (as mentioned in OP's link to the Stackoverflow question ) is that the IEEE representation follows the scheme outlined above, provided that the byte-endian issue has been taken care of.

The "wastefulness" issue of an 8-byte IEEE-754-like exponent field can be solved by encoding it in one of the sortable Universal code. In particular, Elias delta coding seems to be useful for your application.

If the bitstring is stored without any field or bit delimiter (as is the case for Elias delta coding), the search for the highest non-zero digit will need to be modified as follows.

Assume that the overall representation is still "sign-magnitude", or "sign-exponent-magnitude", or "sign-exponent-exponent-magnitude".

As stated previously, a negative sign shall cause subsequent sort order to be reversed.

Starting with the most significant bit on the left, search for the first bit that is set.

Subtract this value (index of the first nonzero bit) from the length of the bitstring. This difference can then be used for comparison.


问:
Microeconomical simulation: coordination/planning between self-interested trading agents
In a typical perfect-information strategy game like Chess, an agent can calculate its best move by searching the state tree for the best possible move, while assuming that the opponent will also make the best possible move (i.e. Mini-max).

I would like to use this approach in a "game" modeling economic activity, where the possible "moves" would be to buy or sell for a given price, and the goal, rather than a specific class of states (e.g. Checkmate), would be to maximize some function F of the agent's state (e.g. F(money, widget) = 10*money + widget).

How to handle buy/sell actions that require coordination between both parties, at the very least agreement upon a price?

The cheap way out would be to set the price beforehand, maybe based upon the current supply -- but the idea of this simulation is to examine how prices emerge when freely determined by "perfectly rational" agents.

A great example of what I do not want is the trading algorithm in SugarScape -- paraphrasing from Growing Artificial Societies p101-102:

when a pair of agents interact to trade, they each compute their internal valuations of the goods, then a bargaining process is conducted and a price is agreed to. If this price makes both agents better off, they complete the transaction

The protocol itself is beautiful, but what it cannot capture (as far as I can tell) is the ability for an agent to pay more than it might otherwise for a good, because it knows that it can sell it for even more at a later date -- what appears to be called "strategic thinking" in this pape at Google Books Multi-Agent-Based Simulation III: 4th International Workshop, MABS 2003... to get realistic behavior like that, it seems one would either (1) have to build an outrageously-complex internal valuation system which could at best only cover situations that were planned for at compile-time, or otherwise (2) have some mechanism to search the state tree... which would require some way of planning future trades.

Note: The chess analogy only works as far as the state-space search goes; the simulation isn't intended to be "zero sum", so a literal mini-max search wouldn't be appropriate -- and ideally, it should work with more than two agents.

答: Have you considered using an agent or market maker to facilitate the transaction? This is how it works in real stock exchanges. Shares are rarely traded person to person but through a middle man. You mention examining the ability of the system to make one party pay more than absolutely necessary, if they had had access to all the information in the system, which is exactly what happen with the 'spread', the price difference between the offer and bid prices. </p>


问:
Is hadoop designed only for "simple" data processing jobs, where communications between the distributed nodes are sparse?
I am not a professional coder, but rather an engineer/mathematician that uses computer to solve numerical problems. So far most of my problems are math-related, such as solving large scale linear systems, perform linear algebra operations, fft, mathematical optimization etc.. At smaller scale, these are best handled by Matlab (and similar high-level math packages). At large scale, however, I have to resort to old-fashioned (and VERY TEDIOUS) lower-level languages such as Fortran or C/C++. That is not all, when the problem become excessively large, parallelization becomes necessary, and MPI in that regard is a nightmare to wrestle through.

I have been hearing about hadoop and "big data" recently on a regular basis. But my impression was hadoop is NOT a general-purpose parallel computing paradigm, in the sense that it handles data that need minimal mutual communications (correct me if I am wrong). For example, in a general LA operation on a large data set distributed among many nodes, rather than processing one's own piece of data independently, each node must communicate with EVERY other node to send/get info before it's own data can be correctly processed, and the whole data set is updated only after ALL communications have been done. I hope I made my point clear: in numerical applications, data-processing is naturally GLOBAL, and the "graph" for communication often is a FULL GRAPH (though there ARE exceptions).

My question is, is hadoop suitable for such purpose, or is it only designed for "simple" data processing jobs, where communications between the distributed nodes are sparse?

答:
The canonical use for Hadoop processes as a tree.  The initial query range is split into sub-ranges.  The query for each sub-range is sent to the node which stores the data for that sub-range.  The job runs on the node for that node's sub-range of data and reports its answer back.  The sub-answers are aggregated at the higher lever to answer the initial question.  So, in general it does not support your "full graph" case.

I say "query" since that's the typical case.  The framework can process any workload which can be dispersed and amalgamated.

The algorithm is known as Map Reduce.  Here's an SO question on it.


问:
Is this database design sound and fully normalised?
I'm creating a database to store words. The intended usage is to query the database to find a word matching a set of filters. E.g. if I wanted to find a word with < 10 letters, < 3 syllables, rhymes with 'at' and matches the tag 'animal', it would return 'cat', 'bat', 'wombat'...

Unnormalised, the table would look like this: (primary key is marked by PK, contextual information is given in square brackets)

```<code>Word(
    WordID PK,
    Word,
    AltSpelling, [another accepted variant e.g. "color"/"colour"]
    Rhyme, [the rhyme part of the word, e.g. for "wombat" the rhyme is "at"]
    Pronunciation, [how the word is pronounced in IPA]
    SyllableCount,
    Tags, [tags relate to meaning of the word, e.g. "apple" would have the tags "round", "fruit", "plant" etc.]
    Categories, [categories are how the word would be hierarchically categorised, e.g. cat comes under the category "animal"]
    WordClasses [the word class that a word can be used as, e.g. "rest" can be Noun and Verb]
)
</code>```

This is the Entity-Relationship diagram to describe how the database should work:

And finally, this is the solution I've come up with for a normalised database design. FK indicates foreign key, CPK is Composite Primary Key.

```<code>Word(WordID PK, Word, OtherSpelling, RhymeID FK, SyllableCount)
Rhyme(RhymeID PK, Rhyme)
Pronunciation(PronID PK, WordID FK, Pron, DialectApplicable [the dialect in which the pronunciation is used, e.g. RP, SE, BrE, AmE])
Tag(TagID PK, TagName, TagReferentCount [the number of words to which the tag applies])
WordTag(WordID CPK FK, TagID CPK FK)
Category(CategoryID PK, CategoryName, CategoryReferentCount [cf. TagReferentCount for categories])
WordCategory(WordID CPK FK, CategoryID CPK FK)
Class(ClassID PK, ClassName, ClassReferentCount [cf. TagReferentCount for word classes])
WordClass(WordID CPK FK, ClassID CPK FK)
</code>```

The question is twofold: is this database design fully normalised? And more importantly, is it sound? I have no practical experience with databases, so I'd like to know if I've made any mistakes, or if the design can be improved/optimised.

答:
is it fully normalised? no.

are there problems with it? possibly yes.

Just one example: "otherspelling" as a field in the word table breaks both normalisation AND is a problem.

What if a word has multiple alternative spellings?

And oh, you shouldn't aim for complete normalisation. Complete normalisation is itself a potential problem, especially for performance.

Normalise where it makes sense, denormalise where it makes sense.


答:
The most obvious violation of normalization in your DB are the reference counting attributes - they introduce redundant information and could get "out of sync" with the real number of references.

"OtherSpelling" might be a violation of normalization, or it might not, this depends indeed on the data you are going to store.

I think it is debatable if, since entities like Tag, Category or Otherspelling are words for themselves as well, you should really store them in separate tables, or instead use a back reference from the WordTag table or WordCategory table to the Word table.

Title: Is this database design sound and fully normalised?

Body:
I'm creating a database to store words. The intended usage is to query the database to find a word matching a set of filters. E.g. if I wanted to find a word with < 10 letters, < 3 syllables, rhymes with 'at' and matches the tag 'animal', it would return 'cat', 'bat', 'wombat'...

Unnormalised, the table would look like this: (primary key is marked by PK, contextual information is given in square brackets)

```<code>Word(
    WordID PK,
    Word,
    AltSpelling, [another accepted variant e.g. "color"/"colour"]
    Rhyme, [the rhyme part of the word, e.g. for "wombat" the rhyme is "at"]
    Pronunciation, [how the word is pronounced in IPA]
    SyllableCount,
    Tags, [tags relate to meaning of the word, e.g. "apple" would have the tags "round", "fruit", "plant" etc.]
    Categories, [categories are how the word would be hierarchically categorised, e.g. cat comes under the category "animal"]
    WordClasses [the word class that a word can be used as, e.g. "rest" can be Noun and Verb]
)
</code>```

This is the Entity-Relationship diagram to describe how the database should work:

And finally, this is the solution I've come up with for a normalised database design. FK indicates foreign key, CPK is Composite Primary Key.

```<code>Word(WordID PK, Word, OtherSpelling, RhymeID FK, SyllableCount)
Rhyme(RhymeID PK, Rhyme)
Pronunciation(PronID PK, WordID FK, Pron, DialectApplicable [the dialect in which the pronunciation is used, e.g. RP, SE, BrE, AmE])
Tag(TagID PK, TagName, TagReferentCount [the number of words to which the tag applies])
WordTag(WordID CPK FK, TagID CPK FK)
Category(CategoryID PK, CategoryName, CategoryReferentCount [cf. TagReferentCount for categories])
WordCategory(WordID CPK FK, CategoryID CPK FK)
Class(ClassID PK, ClassName, ClassReferentCount [cf. TagReferentCount for word classes])
WordClass(WordID CPK FK, ClassID CPK FK)
</code>```

The question is twofold: is this database design fully normalised? And more importantly, is it sound? I have no practical experience with databases, so I'd like to know if I've made any mistakes, or if the design can be improved/optimised.


问:
Power of 2 and performance in SQL Server
Many mathematical operation (such as division, multiplication, etc.) are supposed to be computed faster when dealing with power of two numbers (C++, C#?, ...)

For instance 15 * 256 = 0x0e right shifted (fast) 8 bits = 0x0e00 = 3840

Whereas 15 * 255 = 0x0e multiplied by (slow) 0xff = 0x0ef1 = 3825

Does this kind of optimization even happen in SQL Server?

I don't think there are, I tried measuring a difference of execution time of queries such as those:

```<code>SET STATISTICS TIME ON

SELECT
    AVG(N / 256)
FROM DBO.V_VIRTUAL_NUMBERS
WHERE N < 1048576

SELECT
    AVG(N / 255)
FROM DBO.V_VIRTUAL_NUMBERS
WHERE N < 1000000

SET STATISTICS TIME OFF
</code>```

which resulted in:

```<code> SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.
SQL Server parse and compile time:
   CPU time = 0 ms, elapsed time = 0 ms.

(1 row(s) affected)

 SQL Server Execution Times:
   CPU time = 203 ms,  elapsed time = 207 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.
SQL Server parse and compile time:
   CPU time = 0 ms, elapsed time = 0 ms.

(1 row(s) affected)

 SQL Server Execution Times:
   CPU time = 218 ms,  elapsed time = 206 ms.
</code>```

答:
Many mathematical operation (such as division, multiplication, etc.) are supposed to be computed faster when dealing with power of two numbers.

For instance 15 * 256 = 0x0e right shifted (fast) 8 bits = 0x0e00 = 3840

Whereas 15 * 255 = 0x0e multiplied by (slow) 0xff = 0x0ef1 = 3825

Does this kind of optimization even happen in SQL Server?

I very much doubt it.

If you were to explicitly use bit-wise operators (can't recall if SqlServer even has them) then yes, you might see some improvement but just handing SqlServer an arithmetic expression to work with then no; it will simply perform the [floating-point] calculation and be done with it.

The alternative is to parse each and every expression looking for multiplication or division operations that involve values that just happen to be some power of two and then to rewrite that expression to use bit-wise operators.

Given modern processors, that's probably more of an overhead than just crunching the numbers in the first place.