答:
Edit: This answer is not specifically geared toward project-specific naming, but I believe that the principle can be applied as well. In one of my applications, I have three separate VS projects which I do not separate with either namespaces nor class prefixes as a naming convention. Namespaces would be a possible way to separate the entities by project, and would be my preferred method of separation if I actually had a need for it.

In my experience in C#, namespaces exist for this very reason.

If you define a class Dog and class Cat, it is logical to put them in a namespace called Animals or Housepets (depending on your program's purpose).

It is not, however, logical to prefix the classes with what you would normally use a namespace for: e.g. AnimalCat as a class name.

The fact that namespaces can be defined inside other namespaces means that you have a great ability to create hierarchical organization. If you use prefixes for class names, that prospect promptly disappears. Consider the following two examples:

Class Name Prefixes

```<code>public class LanguageExtendedDictionary
{
    public SortedDictionary<string> wordList { get; set; } // quick spell-check
    public SortedDictionary<string, LanguageWord> dictionary { get; set; } // full entries
}

public class LanguageWord
{
    public string word { get; set; }
    public string definition { get; set; }
}
</code>```

With this, naming schemas get cluttered real fast. In any large-ish application, you might have 50+ classes. Can you imagine trying to pass around data types like SortedDictionary<LanguageWord>? In my experience, long class names are hard to read, and harder to code down the line. Class names should (in my opinion) be as short as possible to accurately represent the entity that it is modeling.

Imagine if we had support in our application for many languages. Would you want to create a class with the name LanguageFrenchWord to dinstinguish between that and English? I certainly wouldn't.

This method leaves no room for class organization, which is extremely important, especially in languages like C#, Java, etc.

Namespaces

```<code>namespace Language
{
    public class ExtendedDictionary
    {
        public SortedDictionary<string> wordList { get; set; } // quick spell-check
        public SortedDictionary<string, Word> dictionary { get; set; } // full entries
    }

    public class Word
    {
        public string word { get; set; }
        public string definition { get; set; }
    }
}
</code>```

You could initialize the instances like:

var word = new Language.Word(); // if declared outside of namespace

or even simply

var word = new Word(); // if declared inside namespace

This allows you to separate what entities are in what relationship, and to set them apart. These entities are grouped logically because they have to deal with language(s). This makes sense when the complexity increases. Maybe I would have a namespace for things that relate to French, and I would add French as a nested namespace under Language; e.g. Language.French.

With a using statement, like using Language or using Language.French, you can eliminate the need to call Language.Word(), and instead call Word().

I'll also mention that, as you see in the above example I don't need to use the prefix Language. while inside that namespace. So in ExtendedDictionary, I don't need to use Language.Word as the type in in the dictionary variable, because both entities are in the same namespace. This reduces a lot of name clutter. With the class prefix method, you can't avoid the clutter. With namespaces, it's part of the feature of the language and makes things inherently more readable.

As the complexity increases, using prefixes causes a lot of name clutter, and a huge lack of organization. There are likely lots of neat things that you can do with namespaces in C# as well that I am simply unaware of. They were created for a reason, and this is my primary use case for them. It seems like this is what your boss is trying to emulate (the behavior), so why not use the tools that are provided in the language to accomplish that?

A side note: as far as I know, the entire .NET library uses namespaces to separate classes; e.g. System.Text, System.Threading, etc. They seem like the appropriate structure to use!

Title: Project based prefix for class names

Body:
My project leader uses project based prefixes for class names, lets say projects name ABC, he create User class name as ABCUser. and he says he do this becasuse if he wants to make User.aspx Users get mixed. so I told him why not use namespace (Entity.User ie.) to make it specific but he against it. I would like to hear from you guys' opinion on this subject.

We code c#.net and using visual studio for projects.

Body:
Edit: This answer is not specifically geared toward project-specific naming, but I believe that the principle can be applied as well. In one of my applications, I have three separate VS projects which I do not separate with either namespaces nor class prefixes as a naming convention. Namespaces would be a possible way to separate the entities by project, and would be my preferred method of separation if I actually had a need for it.

In my experience in C#, namespaces exist for this very reason.

If you define a class Dog and class Cat, it is logical to put them in a namespace called Animals or Housepets (depending on your program's purpose).

It is not, however, logical to prefix the classes with what you would normally use a namespace for: e.g. AnimalCat as a class name.

The fact that namespaces can be defined inside other namespaces means that you have a great ability to create hierarchical organization. If you use prefixes for class names, that prospect promptly disappears. Consider the following two examples:

Class Name Prefixes

public class LanguageExtendedDictionary
{
    public SortedDictionary<string> wordList { get; set; } // quick spell-check
    public SortedDictionary<string, LanguageWord> dictionary { get; set; } // full entries
}

public class LanguageWord
{
    public string word { get; set; }
    public string definition { get; set; }
}

With this, naming schemas get cluttered real fast. In any large-ish application, you might have 50+ classes. Can you imagine trying to pass around data types like SortedDictionary<LanguageWord>? In my experience, long class names are hard to read, and harder to code down the line. Class names should (in my opinion) be as short as possible to accurately represent the entity that it is modeling.

Imagine if we had support in our application for many languages. Would you want to create a class with the name LanguageFrenchWord to dinstinguish between that and English? I certainly wouldn't.

This method leaves no room for class organization, which is extremely important, especially in languages like C#, Java, etc.

Namespaces

namespace Language
{
    public class ExtendedDictionary
    {
        public SortedDictionary<string> wordList { get; set; } // quick spell-check
        public SortedDictionary<string, Word> dictionary { get; set; } // full entries
    }

    public class Word
    {
        public string word { get; set; }
        public string definition { get; set; }
    }
}

You could initialize the instances like:

var word = new Language.Word(); // if declared outside of namespace

or even simply

var word = new Word(); // if declared inside namespace

This allows you to separate what entities are in what relationship, and to set them apart. These entities are grouped logically because they have to deal with language(s). This makes sense when the complexity increases. Maybe I would have a namespace for things that relate to French, and I would add French as a nested namespace under Language; e.g. Language.French.

With a using statement, like using Language or using Language.French, you can eliminate the need to call Language.Word(), and instead call Word().

I'll also mention that, as you see in the above example I don't need to use the prefix Language. while inside that namespace. So in ExtendedDictionary, I don't need to use Language.Word as the type in in the dictionary variable, because both entities are in the same namespace. This reduces a lot of name clutter. With the class prefix method, you can't avoid the clutter. With namespaces, it's part of the feature of the language and makes things inherently more readable.

As the complexity increases, using prefixes causes a lot of name clutter, and a huge lack of organization. There are likely lots of neat things that you can do with namespaces in C# as well that I am simply unaware of. They were created for a reason, and this is my primary use case for them. It seems like this is what your boss is trying to emulate (the behavior), so why not use the tools that are provided in the language to accomplish that?

A side note: as far as I know, the entire .NET library uses namespaces to separate classes; e.g. System.Text, System.Threading, etc. They seem like the appropriate structure to use!


问:
How would I change the precision of a variable in Python?
I'm working on a 2D-physics engine, and I need a certain variable to be precise only to the hundredths. Are there any methods for basically shaving off all of that unneeded precision?

I have tried things like

```<code>"{0:.2f}".format(a)
</code>```

but that obviously produces a string, not a number.

I'm moving an object based upon its speed, and I want it to(obviously) stop when its value is 0.0, but it keeps going because its speed is really something like 0.0000562351.

答:
Try using decimal module.

It allows to manipulate precision. With local context you should get enough flexibility.

Example taken from docs:

```<code>from decimal import localcontext

with localcontext() as ctx:
    ctx.prec = 42   # Perform a high precision calculation
    s = calculate_something()
s = +s  # Round the final result back to the default precision

with localcontext(BasicContext):      # temporarily use the BasicContext
    print Decimal(1) / Decimal(7)
    print Decimal(355) / Decimal(113)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Try using decimal module.

It allows to manipulate precision. With local context you should get enough flexibility.

Example taken from docs:

from decimal import localcontext

with localcontext() as ctx:
    ctx.prec = 42   # Perform a high precision calculation
    s = calculate_something()
s = +s  # Round the final result back to the default precision

with localcontext(BasicContext):      # temporarily use the BasicContext
    print Decimal(1) / Decimal(7)
    print Decimal(355) / Decimal(113)


问:
How to store Role Based Access rights in web application?
Currently working on a web based CRM type system that deals with various Modules such as Companies, Contacts, Projects, Sub Projects, etc.  A typical CRM type system (asp.net web form, C#, SQL Server backend).  We plan to implement role based security so that basically a user can have one or more roles.

Roles would be broken down by first the module type such as:

-Company

-Contact

And then by the actions for that module for instance each module would end up with a table such as this:

```<code>Role1 Example:

    Module   Create  Edit        Delete   View
    Company   Yes    Owner Only    No     Yes
    Contact   Yes    Yes           Yes    Yes
</code>```

In the above case Role1 has two module types (Company, and Contact).  For company, the person assigned to this role can create companies, can view companies, can only edit records he/she created and cannot delete.  For this same role for the module contact this user can create contacts, edit contacts, delete contacts, and view contacts (full rights basically).

I am wondering is it best upon coming into the system to session the user's role with something like a:

List<Role> roles;

Where the Role class would have some sort of List<Module> modules; (can contain Company, Contact, etc.).?  Something to the effect of:

```<code>class Role{
string name;
string desc;
List<Module> modules;
}
</code>```

And the module action class would have a set of actions (Create, Edit, Delete, etc.) for each module:

```<code>class ModuleActions{
List<Action> actions;
}
</code>```

And the action has a value of whether the user can perform the right:

```<code>class Action{
string right;
}
</code>```

Just a rough idea, I know the action could be an enum and the ModuleAction can probably be eliminated with a List<x, y>.  My main question is what would be the best way to store this information in this type of application: Should I store it in the User Session state (I have a session class where I manage things related to the user).  I generally load this during the initial loading of the application (global.asax).  I can simply tack onto this session.

Or should this be loaded at the page load event of each module (page load of company etc..).  I eventually need to be able to hide / unhide various buttons / divs based on the user's role and that is what got me thinking to load this via session.

Any examples or points would be great.

答:
I used to work on a system with fixed number of tables/directories (different from yours), so I didn't use role-base security schema like the one of yours (or of file system, or of SQL DB). I used linear access level. At high level, the thing is similar though, especially with your question.

Nevertheless, wherever and however you store Access Right on the client side, there is no guarantee that it is an accurate reflection of what is on the source (the DB).

Load the access right when the user logs in. Storing access right in a session object is fine.

Validate each action on the logic layer at the backend

Extra: when an action is not completed, the backend will send the feedback about change in access right

Extra Option1: when feedback is received, the backend can also send another chunk to encode new access rights

Extra Option2: when the feedback is received, the front-end suggests the user to re-login


问:
How often should a manager meet with his subordinate who is a team leader?
Ours is a software concern and we have a team structured like so: manager->team leads->team members. We are following the agile programming model and trying to develop a product in a collaborative fashion. We have daily morning meetings with team members and their team leads to discuss progress and issues.

When it comes to TL->Manager, most of the time they do not have items to discuss on a daily basis since TL goals would be for weekly plan and such. Most of the time, we just discuss about resources and it is less technical. I just want suggestions on how the manager & team lead interaction should be and whether the current system we have is fine. Please share your thoughts or ideas.

答:
I'm in the same situation: teamleader with a 8 people team and a manager.

I discuss with the manager on a daily basis, and we go together to some meetings. Most of the meetings anyway either are political and I won't participate or are strictly technical and he won't participate.

I got a lot of insightful information from the book "The Effective Executive" of P.Drucker.

Note that in the book definition every programmer is an executive, because he have to take executive decisions.

ContentLicense: CC BY-SA 2.5


问:
What is a good C++ API Design for HW registers?
I am designing an API for a driver that manipulates HW. I have done the following:

```<code>namespace HWRegister
{
    //private:
    namespace Data
    {
        //accessible only within this namespace

        //Represents one of the four HW blocks.
        enum EHWUnit
        {
            Block0,
            Block1,
            Block2,
            Block3
        };

        enum EHWSet
        {
            Rx0,
            Rx1,
            Rx2,
            Rx3,
            Tx0,
            Tx1,
            Tx2,
            Tx3
        };
    }

    using namespace Data;

    //Returns Error Code
    int32_t enableHWUnit( const EHWUnit aHWNumber, const EHWSet aHWSet );
    //Returns Error Code.
    int32_t disableHWUnit( const EHWUnit aHWNumber );
</code>```

I would like to get peoples opinion on this. I am wondering if those enums are a good idea, I declare them here and therefore people who use my API are forced to use them, will this cause more problems for the callers of my API? Can I improve this API somehow? I will add more documentation into the API when I am sure it is looking good.

答:
Enums are always good to use, since they make code easier to understand.

But, you have several problems there :

if your code snipet is in a header, then the namespace must have a name

I would use strongly typed enum enum class, instead of just enum

your enum values are not descriptive enough, and sounds very generic. You may want to give better names, instead of just for example Tx1. With strongly typed enums, this is not an issue

not a big deal, but your functions return an error code. An exception may be more approriate

Why not create a class, which initializes your HW in constructor, and disable in destructor? Your API looks more like C


问:
C# server side application 100 GB dataset + Garbage Collection
If I have server with 256 Gb of ram. I was wondering can I create a C# application which has a 100 GB of memory footprint?

I want to create a dictionary like

Dictionary<DateTime,Dictionary<string,Dictionary<string,DataClass>>
```

<pre class="lang-none prettyprint-override"><code>Fist dictionary
DateTime - Max 40 distinct values

Second Dictionary
string : 2000 distinct values

Third dictionary
string : 100 distinct values
</code>```

Object will be removed from the DateTime part (after every say 1 hour), till 1 hour, various internal members are populated.

With Java I am told even if the server has large memory, JVM will stall because of GC.

答:
CLR Limits

32-bit CLR is limited to around 2GB of memory.

With Windows Enterprise edition, you can get to 8TB of virtual memory with 64-bit:

A 64-bit process running on a 64-bit machine can acquire up to 8 TB of virtual memory. (See last paragraph.)

If I have to pick up a particular platform (i.e. CLR) because 100 GB of memory stalls another one (JVM) and I cannot use it for this reason, then I need to take a hard look at my software design, explore all the alternatives and then justify such a decision. (I discuss alternatives in the concluding section).

Performance Analysis Considerations

In addition to CLR/process limits, your question has multiple aspects to it:

If there are other processes allocating a large amount of memory (say close to 156GB or more as an example), then 100GB will not be sufficient. Rule no. 1: It depends on how much free memory does your machine have when you are attempting to allocate 100GB.

Whether the machine or CLR stalls is a function of how the operating system treats such a large object as well. One example is page file, if it is not suitably configured, the OS may too aggressively swap page file or, on the other hand, page file size may not be sufficient. As a result, you may not only lose the performance you were hoping to achieve by allocating such a large object in memory, but the performance may be worse than if it were in a DB because of the OS behavior. Rule no. 2: It depends on how the OS is configured (or designed) to treat such a large memory footprint.

The performance evaluation criteria has to be defined in measurable terms. What does "stall" mean? Does that mean that you are asking whether CLR will crash or not, or whether some functionality in your program (such as user response) is so much seconds, or the impact of your program on machine or other processes is so much. Rule no. 3: Performance criteria should ideally be measurably defined.

These rules lead one to the overarching principle used in performance evaluation: prototype and measure. Without measuring on the specific platform with your specific needs (i.e. the size of objects that are allocated and how garbage collector treats them), it is very hard to predict whether this will work or "stall". In addition, even if your initial results in performance are not up to your requirements, you might be able to tune the system to achieve more.

Metrics

On the metrics front, the maximum number of entries based no your data is about 8 million. Assuming that each entry in your dictionary is on average 1 KB, the total memory that you are looking for values is around 8 GB. However, since pretty much everything in the CLR is an object, there are a number of function pointers that are allocated alongside. So if instead of 8 GB, your actual data is 100 GB, then you are looking at a much larger memory footprint than 100 GB. The difference between 8 GB and 100 GB is significant enough that I would do an in-depth analysis of how much memory is really needed.

Finally, if you intend to create such a large object, you might want to about the Large Object Heap (LOH) in the .NET Framework. Depending on how you allocate the objects that go in the dictionary, whether they are allocated on the LOH or not will vary (e.g. CLR could consider them too many small objects and thus allocate them on Small Object Heap).

Concluding Remarks

If I were doing this, I would consider putting this data on disk or in a DB and measure that, perhaps as a primary option. I see a few issues with the model that you proposed to store such data in memory:

What if the server crashes (or needs to be rebooted for maintenance), is it safe to lose the data?

If the schema needed to be changed and the data needed to be moved from current object schema that you have to a new one, what does that transition look like (assuming we can't shut the process in the middle).

If the data in memory were to be needed (e.g. data is considered to have been corrupted, or needed for a bug investigation), how would someone look at the data in the server. This is much easier if the data is on disk.

Once these are clarified, there may be a follow up set depending on responses to these. (e.g. if it is not OK to lose the data in the case of server crash, then we have the question of backups, etc.)

With a classical DB, a file system, or NoSQL design, these issues are easier to resolve, especially the continuity one (i.e. data cannot be lost in the case of server crash). In addition, it makes the solution platform/language (i.e. could be C#, Java, PHP, Python, whatever) agnostic which is indicative of a better design.


问:
Is there a benefit in compiling your code as you go along?
I recently had a job interview in which they gave me an hour to write some real code.  It wasn't a huge amount, probably less than 100 lines.  After about 45 minutes, I compiled, ran it, and got it to work.  I may have spent 5-10 minutes working out compile errors and a couple minor bugs, but overall it was very smooth.  (Incidentally, I did get an offer from them.)

However, what puzzled me was that after I handed over the completed code, the interviewer told me that the only thing I did wrong was "not compiling as I go along".  I asked him what the difference is, and he said "what would you have done if you finished the code and it didn't compile in time".

In my understanding that's an invalid argument, because "getting code to compile" for a given length of code generally involves fixing a constant number of compile errors and takes a fairly constant amount of time, which should be the same whether you do it after you finish writing the code, or if you interleave it with your coding time.  If anything, interrupting your coding to search for missing semicolons would probably be detrimental to your efficiency.  Except in extreme circumstances when I'm experimenting with obscurities around edge-cases on things like virtual functions in derived classes, etc. it seems reasonable to expect that code written by a an experienced developer will compile, minus the occasional typing error, and even if it doesn't, it's not as if I would have to rewrite a portion of the code in order to fix the compile error.

In another similar incident, I was given an incomplete codebase in an interview, and asked to finish it and make necessary modifications to get it running.  I started by reading through the existing code, and then after a few minutes (even before I had finished looking at the code), the interviewer told me that's enough.  When I asked him what he would have done (i.e. "what did I do wrong"), he told me that he would have started by immediately getting the code to compile.

Why is that even relevant?  In my opinion and in my experience, whether or not a piece of code compiles is essentially random, involving things like whether or not semicolons are missing, and has little to do with the correctness of the underlying program.  (To me, focusing on compiling is like running an article through a spell-check without proofreading to check the grammar.)

If you give me a piece of incomplete code, the first thing I do will be to read it.  I won't even try to compile it until I know what the code is doing and I know the algorithm is correct.

Anyway, these have been just a couple recent incidents, but in general I've heard many developers talk about compiling their code as they go along, and yet nobody has been able to tell me the benefit of doing so.  I understand the benefits of testing your code as you go along, but why compiling?

So my question is this: Is there something I missed?  Is there actually a benefit to compiling as you go along?  Or is this some sort of myth propagated by the software community that you must compile your code frequently?

答:
For a sufficiently experienced programmer compiling code is never the bottleneck.

Once you know a language well enough (i.e. when you no longer have to think about the syntax and instead just code for functionality) you tend not to make simple syntactical errors. Those you do make are usually typos or copy-paste bugs, and they can be cleaned up in short order with just a few compilation passes.

I regularly write code all day without compiling, then I'll compile and just fix up what syntax errors and warnings the compiler reports before I commit my code (with a note that says "needs to be tested!").  I have no problem cleaning up 1,000+ lines of C or C++ code in just a few minutes.

Debugging and testing on the other hand is what takes a while. Logic errors arise for all sorts of reasons and I have yet to meet a compiler that will tell me about the subroutine I totally forgot to write, or will notice that my binary tree doesn't work because I pasted node->left when it should have been node->right.

While I think it's generally unwise to fight with an interviewer, I'd say if you felt your style was worth defending you should have pointed out that you left yourself enough time to debug the code you'd written.  That's the thing no good programmer ever neglects.

p.s. - If I had been watching you review code by reading it, I would have hired you on the spot.  That's what a pro does, every time.


答:
The best way to provide feedback would be to use the agile practices that already exists:

Iteration demo. This is where the team demonstrates actual working software and explains how the iteration went. Everyone is invited and are free to ask questions.

Big Visible Charts. Progress about the current iteration should be transparent and visible for all to see, including managers. They should only have to glance at the status board to get a feeling for how things are going.

That should be enough, really.

Besides, there is no "team lead" role in XP or Scrum. The fundamental roles are team members (programmers), customer (product owner) and coach (scrum master).

Title: How often should a manager meet with his subordinate who is a team leader?

Body:
Ours is a software concern and we have a team structured like so: manager->team leads->team members. We are following the agile programming model and trying to develop a product in a collaborative fashion. We have daily morning meetings with team members and their team leads to discuss progress and issues.

When it comes to TL->Manager, most of the time they do not have items to discuss on a daily basis since TL goals would be for weekly plan and such. Most of the time, we just discuss about resources and it is less technical. I just want suggestions on how the manager & team lead interaction should be and whether the current system we have is fine. Please share your thoughts or ideas.


问:
Is PHP the only popular language that mixes simple and associative arrays into a single type?
I'm doing a research on PHP and wondering if there any other commonly used programming langues that use an associative array for both simple indexed element storage and key-value functionality. Does it make PHP unique in this sense?

For example, a language like C# distinguishes clearly between a simple array and a map\dictionary\hash

```<code>T[] array = new T[];
Dictionary<T, S> map = new Dictionary<T, S>();
</code>```

Meanwhile PHP makes no such distinction (at design time)

```<code>$array = array(1, 2, 3);
$map = array("one" => 1, "two" => 2, "three" => 3)
</code>```

答:
Lua too has this trait. Lua's tables can be treated as both maps and arrays. (Internally, a Lua table is implemented by having two parts (the user isn't aware of this), the array part and the map part, so it's efficient.)

(JavaScript has some kind of this duality too: since every object can serve as a map, and every array is an object, arrays can serve as maps too. But, I think, the opposite isn't true: objects that aren't arrays can't serve as efficient arrays (please correct me if I'm wrong; maybe it's implementation-dependent?), so JavaScript isn't a candidate for you.)


问:
Database design - Store state or compute state every time?
Let's say I have a relational database application and a "user" object and a "message" object. Now I want to show the number of unread messages to this user.

What's the best way to archive this? Do I introduce a field in the user and count it up if the user receives a message and decrease the count if he reads one? Or do I execute a query every time to compute the number of messages for the user that are flagged as unread?

I think the first approach is more complicated and error prone, but will perform better than the second approach.

How is this normally done or what's the better approach?

答:
How is this normally done or whats the better approach?

The best approach is to try it first without an extra field, measure the performance, and if it really turns out to be too slow, you try to optimize. This could mean to switch to your first approach using an extra field, but you should consider to test other options as well, for example, putting an extra index on the combined fields ("unread", "userID") on your messages.


答:
The way I would do it is by executing a query every time, i.e. your second approach. Just make sure you add an index in your message table on the column that acts as a foreign key to the users table to improve the performance of your query.

Then as Doc says, measure the performance of this approach and then you will be able to tell whether you need to take a different path.

Title: Database design - Store state or compute state every time?

Body:
Let's say I have a relational database application and a "user" object and a "message" object. Now I want to show the number of unread messages to this user.

What's the best way to archive this? Do I introduce a field in the user and count it up if the user receives a message and decrease the count if he reads one? Or do I execute a query every time to compute the number of messages for the user that are flagged as unread?

I think the first approach is more complicated and error prone, but will perform better than the second approach.

How is this normally done or what's the better approach?


答:
The textbook solution acccording to database theory would be to have no values in your database which depend on the values of other data, because these are transitive dependencies. Having fields which are computed values based on other fields is a violation of normalization, because it leads to redundant information.

However, sometimes what the textbook says and what is the most practical method in practice differ. Counting the number of unread messages each pageview could be a quite expensive operation. Caching the number in the user-table would be much better  for performance. The cost would be that it is possible for inconsistencies to exist in the database: It might be possible for a message get deleted, added or read without remembering to also update the unread-counter.


问:
Any real use of pointers in C#?
What is a situation while coding in C# where using pointers is a good or necessary option? I'm talking about unsafe pointers.

答:
From the developer of C# himself:

The use of pointers is rarely required in C#, but there are some situations that require them. As examples, using an unsafe context to allow pointers is warranted by the following cases:

Dealing with existing structures on disk

Advanced COM or Platform Invoke scenarios that involve structures with pointers in them

Performance-critical code

The use of unsafe context in other situations is discouraged.

Specifically, an unsafe context should not be used to attempt to write C code in C#.

Caution:
"Code written using an unsafe context cannot be verified to be safe, so it will be executed only when the code is fully trusted. In other words, unsafe code cannot be executed in an untrusted environment. For example, you cannot run unsafe code directly from the Internet."

You may go through this for reference

Title: Any real use of pointers in C#?


问:
Is there any benefit to just artificially reducing WIP in a Kanban system?
So imagine this scenario:

There is only 1 developer, who also is the bottleneck (testers, etc are busy on other contracts).
There is a nontrivial backlog of tickets, most of which are blocked for not being reproducible, unintelligible requirements, unsolvable (with current ideas, staff and technologies).

Is there any particular benefit to creating a system that parcels out the tickets to the sole developer one or two at a time?  The system so far has immediately created slack on account of delays in assigning new tickets after current tickets are worked. When blocked tickets are assigned, they now sit on the developer's desk blocked until they are moved back to unassigned tickets.

Are there any benefits to this "artificial low-WIP" system and how could/should it have been implemented?

答:
Real Kanban - as practiced outside the software industry - doesn't have this problem. Kanban in the software world is largely a "push" system, exactly contrary to Ohno's original model.

In proper Kanban, the developer can't start another ticket because the quota of untested fixes downstream from them is too high. That calls attention to a need for more testers, more efficient testing, or some other improvement in the testing process.  Unless the reason fixes aren't being tested is that the testers are blocked by their downstream consumer.  And so on.  That is one of the key ideas of Kanban - that waste built into the process becomes obvious and can be fixed.


问:
Setting global parameters: is this a reasonable use of const_cast and volatile?
I have a program that I run repeatedly with various parameter sets. Different parameters are used in different parts of the program (including different source files). The same parameter may also be used in different places. However, all parameters are constant during run-time after they have been set.

I discovered very quickly that declaring the parameters locally does not make sense (it involves having to remember where every parameter is defined, etc.), so I resorted to using a params.h where I declared and defined all the parameters: const int Param1 = 42;, etc.

The downside of this is that I have to recompile every time I change a parameter. So  I'm thinking of using the method below. It relies on usingvolatile and const_cast, which is normally considered "dirty", but it ensures once the parameters have been set in main, they are not accidentally changed anywhere else in the program.

I'm wondering whether people think this is OK, because eventually I want to open-source my code.

In params.h:

```<code>namespace Params
{
extern volatile const int Param1;
// etc.
}
</code>```

In main.cpp:

```<code>#include "params.h"

volatile const int Params::Param1 = 0;

int main(int argc, char* argv[])
{
    int* const pParam1 = const_cast<int*>(Params::Param1);
    *pParam1 = // Get value from argv[] or some config.ini file.
    // etc.
}
</code>```

答:
It is not only unreasonable, it is forbidden by the standard to modify a const variable.

[dcl.type.cv]/4 tells (emphasize mine) :

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

The idea is still good. Declare a variable extern, and define it in a source file. When you need to change it, you don't have files to recompile.

If you don't want to recompile, you have several options :

load parameters from a file

read environment variable

pass as parameter to the program


答: "Popular" is in the eye of the beholder.  The Rexx language is very popular in the mainframe communities, and it has associative arrays (called "compound variables") as a first-class language element.</p>

Title: Is PHP the only popular language that mixes simple and associative arrays into a single type?

Body:
I'm doing a research on PHP and wondering if there any other commonly used programming langues that use an associative array for both simple indexed element storage and key-value functionality. Does it make PHP unique in this sense?

For example, a language like C# distinguishes clearly between a simple array and a map\dictionary\hash

```<code>T[] array = new T[];
Dictionary<T, S> map = new Dictionary<T, S>();
</code>```

Meanwhile PHP makes no such distinction (at design time)

```<code>$array = array(1, 2, 3);
$map = array("one" => 1, "two" => 2, "three" => 3)
</code>```


答:
The potential problem is performance and you don't have a performance problem, yet. There are many things you can do depending on the database of choice to handle this in solution #1: indexing, hardware, caching, etc. This all depends on how frequently the user needs to get a current unread message count. Many of these choices don't require custom coding on the app side, so you can implement them with a code change or very little. Makes it easier to grow with the app.

Once a user connects/logs in, getting the count from the database once is not that bad. Will your app maintain a constantly updating list of messages like email? Getting an unread count from here doesn't require another trip to the database and to get new messages is going to take a db trip anyway.

Taking a trip to the db every time a message is read to flag the IsRead? field is enough without a recalculation of another field.

With solution #2 (keeping a count in a field/on disk), will you need a routine to periodically rebuild/recalc this field when there is a problem? And there are always problems. Are you going to wrap all of this in a transaction?  Each time someone sends someone else a message it could fail because it can't update the receiving user's UnreadCount due to a lock of the User table? Or are you going to create a separate table for this field?


问:
Why do APIs generally consist of interfaces?
I am starting out in Java API design and in reading existing code bases, I have found that most APIs consist of interfaces only with their implementations bundled in a different package.

Having read that interfaces are generally more  problematic to use/maintain than abstract classes, why aren't abstract classes used instead of interfaces?

答: Not sure where you read that interfaces are more problematic to use or maintain. You can only inherit from one base class, but you can implement as many interfaces as you want, so interfaces are inherently more flexible. E.g. Consider what would happen if Closeable and Readable were abstract classes; you'd have no way of making, say, a FileReader that subclasses both.


答:
The main reason is that Interfaces allow you to provide a common ground between your implementation and who ever is making use of your code. There are scenarios where you do not want the caller to know how you are executing certain pieces of logic. The reasons for this can be security or proprietary algorithms, to mention a few.

When you define an interface, you outline what functions you will be offering. In most cases, the caller will not care how you have implemented, say, a sorting mechanism. The caller simply cares that it works.

Coding to an interface also gives you a relatively large degree of freedom since you are, at no point, constraining yourself to implemented logic. So, if your method yields a List instead of an ArrayList, you are giving the freedom to the caller to resolve that to any class which implements list.

As @Benjamin Rogge said, I would also like to see where you read that abstract classes are more difficult to maintain.

Title: Why do APIs generally consist of interfaces?

Body:
I am starting out in Java API design and in reading existing code bases, I have found that most APIs consist of interfaces only with their implementations bundled in a different package.

Having read that interfaces are generally more  problematic to use/maintain than abstract classes, why aren't abstract classes used instead of interfaces?


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

答:
Depends on the language and the platform. For instance, it is quite trivial for me to use a variety of databases while working with C, I just use the appropriate library.

A language must maintain its standard implementation, and that typically means providing the minimum amount needed for someone to be able to build whatever they want to build. Everything else becomes a library, or perhaps an extension to the language that is maintained by others.

At least, this is the case for languages that follow standards established by organizations such as ISO.


问:
How to modify ELO algorithm when number of games is low to reduce outliers
I've developed the standard ELO implementation that can be found here, but the problem I'm running into is that my players will only have between 10 and 40 games in a "season". Since my first season has already completed (I'm just now starting my OWN rating system for my game), I know what the rank of my players ELO ratings should be, or at least very close to that. My problem is, after implementing that base algorithm, I have a some outliers that are way off.

Since I only have 10 to 40 games, my first thought to remedy this situation was to implement a loop around this process, taking the end result ELO rating from one cycle, and use that as the starting point for the next cycle (for each individual player). Then, repeat these cycles until the average or max deviation of ELO ratings from previous to current cycles is not greater than X. This helped to resolve some of the big outliers. There are still some smaller outliers that I'm still not comfortable with...

As an example, I have 7 divisions, for division 1, the guy that should be ranked #1 based on his ELO, ends up being ranked 5th, for division 2, the guy that should be ranked #1 is 3rd. The top 10 or so for each division are actually pretty close, except for these kinds of outliers.

How can I modify my algorithm, or what approach can I take to try and reduce the outliers?

Side note #1. For division 1, the guy that should be #1, that ends up #5, is actually ranked #1 for the entire season by the other rating system. I just don't know how that one is calculated (and it may not be calculated, it could be based on, I know x player is this good, so he's ranked #1).

Side note #2. I have made a modification to the algorithm. I want to "weight" the wins/losses by how dominant they were. If player A beats player B 20-0, I want that weighted more heavily, especially if they ratings are very close, but if their ratings are further apart (where a is already greater than B), then the ELO change shouldn't be that much anyway since they were expected to win in the first place. So, what I did was instead of using the k factor/value of 400 like the original formula uses, I changed it to be 100 + ((score difference) * 2). So the max k factor would be 140 (20-0 is the biggest win, multiply by 2, add to 100).

What other strategy could I implement to include weight results, as well as correct some of those outliers?

Without having the data in front of me (everything is at home), I'll try and sum up the scenario...

Division I

```<code>#1 Elo Rating of 2250
#2 Elo Rating of 2200
#3 Elo rating of 2190
#4 Elo rating of 2175
#5 Elo rating of 2170
</code>```

Where #5 guy just beat the #1 to win the tournament, and his "body of work" seems more complete than the #1 guy (aka he played against, and beat stronger opponents than the #1 guy did). Maybe it's because the "weighted" k factor is throwing this off because #5 had lots of wins that were by only 2 to 5 points, where #1 wins were by a higher margin, say 5 to 10 points.

Maybe I just need to play around with my "weighted" k factor to see if I can get my calculated results closer to the actual results...

答:
Here's what I've done to try and solve the scenario of the outliers. Re-simulating my entire season, knowing what each player SHOULD be ranked at the end of the regular season, and season ending tournament. Obviously when there are "upsets" in the season-ending tournament, it won't come out exact, but I feel this gave me the closest results that work for ALL players.</p>

```<code>private double GetKFactor(double winnerRating, double scoreDifference, int winningPlayerMatchCount)
    {
        var kFactor = 32.0;

        if (winningPlayerMatchCount >= 11 && winningPlayerMatchCount < 21)
            kFactor = kFactor * .75;
        else if (winningPlayerMatchCount < 11)
            kFactor = kFactor * .5;

        return kFactor + scoreDifference;
    }
</code>```

Body:
Here's what I've done to try and solve the scenario of the outliers. Re-simulating my entire season, knowing what each player SHOULD be ranked at the end of the regular season, and season ending tournament. Obviously when there are "upsets" in the season-ending tournament, it won't come out exact, but I feel this gave me the closest results that work for ALL players.

private double GetKFactor(double winnerRating, double scoreDifference, int winningPlayerMatchCount)
    {
        var kFactor = 32.0;

        if (winningPlayerMatchCount >= 11 && winningPlayerMatchCount < 21)
            kFactor = kFactor * .75;
        else if (winningPlayerMatchCount < 11)
            kFactor = kFactor * .5;

        return kFactor + scoreDifference;
    }


问:
REST API Structure to request multiple items
I have a REST API that looks something like the below where a person can belong to an organisation (but doesn't have to) and a person has many items. The items may also belong to the organisation instead of the person.

```<code>/people/:personId
/people/:personId/items
/organisations/:orgId/items
/organisations/:orgId/people/:personId/items
</code>```

There is a scenario where we want to query the items for multiple people within an organisation, what's the correct URL structure to use?

Option 1

```<code>/organisations/:orgId/people/items?personId=1&personId=2
</code>```

Option 2

```<code>/organisations/:orgId/items?personId=1&personId=2
</code>```

Option 3

```<code>/items?personId=1&personId=2
</code>```

答:
It really doesn't matter that much. Your URL is just a 'unique resource locator' the format you use is up to you. Go with what you are most confortable with and your users will understand.

Having said that I'd go with ?personId=1&personid=2 just because its easy to parse/read

take a look at this similar question


问:
Is it bad to use the same class or idiom names as in a third-party API that you're using?
FlashPunk is a third-party graphics API for simple game development in AS3, and they take what are effectively sprites or display objects of some sort and refer to them as "Entities".  Entity is the actual class name, and it's the predominant class to use to animate something such as a character moving on the screen.

There's a bit of a convention right now in which you refer to things like barriers, enemies, characters, etc. as "entities".  So that being said, if you're using FlashPunk for your graphics, is it bad to create a base class to represent such things and name it Entity as well?  (In particular, does this violate a widely-held coding convention?)

Obviously it would be in a different package, and most people would probably separate the graphics from the game's actual state, so there's not a lot of overlap there.  It's just using the same title.

What about scenarios like this in general with programming?  Is there a particular convention?

答:
This problem was essentially solved decades ago.

If your language allows it, simply keep the third party API and your own code in separate namespaces (Packages in Ada, namespaces in C++, modules in Modula-2 etc).

Where it isn't obvious which Entity you are using, refer to all Entities using qualified names, e.g. FlashPunk.Entity or MyApp.Entity (Ada), or MyApp::entity (C++)

Where you are almost exclusively referring to one namespace, that gets too verbose. Then you can use MyApp (Ada) or using namespace MyApp (C++) to make that namespace available in the current scope, then you only need to qualify only the names from the other namespace.

It can sometimes aid clarity to qualify some of the names from the used namespace e.g. when entities from both namespaces are used in the same statement, or any oddity of their use might confuse the reader.


问:
Gitlab workflow, forcing code review or merge request on branch
I'm working towards implementing Gitlab at my company with a workflow strategy. My idea is that developers will be given access to repositories but, anytime they try to commit, their code must be reviewed.

I know I can have them create a branch before committing, and then create a Merge Request after it's been pushed to the repo. I'm still unclear about certain things... The idea that we rely on people to create a branch and then a merge request seems faulty, is there a solution that forces some sort of policy that the master branch can stay clean unless an "admin" approves the code that's about to merge into it. I've read "github team workflow" but it doesn't seem to offer a viable solution. Any advice about process or your own best practice is appreciated. Thanks!

答:
I've started working with gitlab, reading the HELP section provides a workflow layout. At this point, this seems to be the best solution to my question. If anyone has experience with this workflow or advice, please add any additional info.

From the HELP section:

Workflow

Clone project

git clone git@example.com:project-name.git

Create branch with your feature

git checkout -b $feature_name

Write code. Commit changes

git commit -am "My feature is ready"

Push your branch to GitLab

git push origin $feature_name

Review your code on commits page

Create a merge request

Your team lead will review the code & merge it to the main branch

In the commits section of your repository, you're actually able to protect branches which forces developers to follow the process above, creating a branch and submitting a merge request.


问:
Architecture for maintaining/executing multiple versions of same strategy / functionality in live application
So I am working with a customer who has an older application that has quite a few interesting quirks. Among other things, it has its own code version system for business functions, by storing the entire algorithm version in a database. The data is then retrieved and compiled on request (this is a web application, and yes, it compiles a ton of code each time you try to buy something).

For obvious reasons, this isn't exactly fast. I am looking into migrating the code into normal code projects, but as you can imagine, this creates an interesting challenge in regards to versions of the algorithms.

It is a business requirement that old quotes / deals that are up for review must use the same algorithm that was used when it was first created. Said quote should then be able to recalculate, with changed input etc (so we can't just store the results).

How would you approach this problem? They are having such massive issues in production now that I have simply decided we will create a hot-fix by moving all the code to actual libraries and calling functions with name versioning (someAlgortihm6Jun2014 or whatever) which will solve the problem of immense bandwith use and wasted compilation time, but it is far from elegant.

While I will be looking to implement much larger architectural changes in the future, for now I am simply looking for a good way to maintain multiple versions of the same algorithm in static code, without resorting to this naming convention. Thoughts?

答:
As far as I understand you, there is no maintenance for those older versions to do - only for the newest version (changing of older version is forbidden, right?). That means, even if the function names become very technical after versioning, this should not be too much of a problem, since you never have to touch that code again.

You need to store the functions in compiled form out of the database, so the obvious place is in an assembly of your application. Put the older versions of those functions in a separate assembly, as part of the versioning process, so you get them out of your way when you make changes to the newest version.

Use a rigorous naming scheme for your functions appropriate to your business requirements (there must be also a way for your users to distinguish between older and newer functions as well - why not just name your functions with a kind of prefix according to your users scheme of "doing things")? If the criteria is a date, then it is date which gets part of your function name - if that's used in the production process, it will be the best you can come up with. And instead of a big pile of if/else/switch/case, use a dispatch table.

If each of your "functions" are is not really just one function, but a bunch of functions and data, you may also consider to encapsulate them in command or strategy objects (as some commenters have suggested). That shifts the versioning and naming problem from the function level to the class level. The general idea keep the same.

It may be also of interest how and how often new versions of your functions are created. Is this done just manually by a developer? Then the versioning of a function can probably done manually, too (maybe supported by some self-made tools, renaming the function in stake, moving the source code to the "versioned functions project" and extending your dispatch table).

There is another option, of course: keep everything in the database where it is now, but cache the compiled output locally. So before getting the source code and compiling the same function again, check if there is already a locally cached pendant available, and if so, use the copy from the cache (you should make some checksum test to assure the local compiled copy is related to the source code in your db). This will not prevent compiling and database access completely, but it may probably be the solution you are looking for. And its has the advantage, that you can easily deploy new functions or function versions into production without deploying the full application.


答:
What's an API ? It is an interface by definition.

Consider the software you're using as a blackbox. You're not supposed to know how things are done internally, nor are you supposed to want that, or you would just build things yourself.
Besides, trying to extend an API class yourself may break the tool's behaviour (which, once again, you don't really know).

The software you are using and your own softwares are two different softwares, so the only thing you should need is the link between them, namely the interface. See what an interface means in computer science and you should understand why it applies to the OOP meaning of the word.

Now as for your abstract class argument, it seems completely subjective. As far as I'm concerned, a class in Java can implement several interfaces but extend only one base class.


答:
You have to remember that the designers at Microsoft are smart people and everything they add to C# has at least 1 use case. The FParsec project uses unsafe code to bring out every last drop of performance that C# is capable of. Take notice of the usage of fixed and stackalloc.

```<code>private char* ReadCharsFromStream(char* buffer, int maxCount, out string overhangChars) {
    Debug.Assert(maxCount >= 0);
    fixed (byte* byteBuffer = ByteBuffer) {
        overhangChars = null;
        try {
            while (maxCount >= MaxCharCountForOneByte) {// if maxCount < MaxCharCountForOneByte, Convert could throw
                int nBytesInByteBuffer = FillByteBuffer();
                bool flush = nBytesInByteBuffer == 0;
                int bytesUsed, charsUsed; bool completed = false;
                Decoder.Convert(byteBuffer + ByteBufferIndex, nBytesInByteBuffer,
                                buffer, maxCount, flush,
                                out bytesUsed, out charsUsed, out completed);
                ByteBufferIndex += bytesUsed; // GetChars consumed bytesUsed bytes from the byte buffer
                buffer += charsUsed;
                maxCount -= charsUsed;
                if (flush && completed) return buffer;
            }
            if (maxCount == 0) return buffer;

            char* cs = stackalloc char[MaxCharCountForOneByte];
            for (;;) {
                int nBytesInByteBuffer = FillByteBuffer();
                bool flush = nBytesInByteBuffer == 0;
                int bytesUsed, charsUsed; bool completed;
                Decoder.Convert(byteBuffer + ByteBufferIndex, nBytesInByteBuffer,
                                cs, MaxCharCountForOneByte, flush,
                                out bytesUsed, out charsUsed, out completed);
                ByteBufferIndex += bytesUsed;
                if (charsUsed > 0) {
                    int i = 0;
                    do {
                        *(buffer++) = cs[i++];
                        if (--maxCount == 0) {
                            if (i < charsUsed) overhangChars = new string(cs, i, charsUsed - i);
                            return buffer;
                        }
                    } while (i < charsUsed);
                }
                if (flush && completed) return buffer;
            }
        } catch (DecoderFallbackException e) {
            e.Data.Add("Stream.Position", ByteIndex + e.Index);
            throw;
        }
    }
}
</code>```

Title: Any real use of pointers in C#?

Body: What is a situation while coding in C# where using pointers is a good or necessary option? I'm talking about unsafe pointers.

Body:
You have to remember that the designers at Microsoft are smart people and everything they add to C# has at least 1 use case. The FParsec project uses unsafe code to bring out every last drop of performance that C# is capable of. Take notice of the usage of fixed and stackalloc.

private char* ReadCharsFromStream(char* buffer, int maxCount, out string overhangChars) {
    Debug.Assert(maxCount >= 0);
    fixed (byte* byteBuffer = ByteBuffer) {
        overhangChars = null;
        try {
            while (maxCount >= MaxCharCountForOneByte) {// if maxCount < MaxCharCountForOneByte, Convert could throw
                int nBytesInByteBuffer = FillByteBuffer();
                bool flush = nBytesInByteBuffer == 0;
                int bytesUsed, charsUsed; bool completed = false;
                Decoder.Convert(byteBuffer + ByteBufferIndex, nBytesInByteBuffer,
                                buffer, maxCount, flush,
                                out bytesUsed, out charsUsed, out completed);
                ByteBufferIndex += bytesUsed; // GetChars consumed bytesUsed bytes from the byte buffer
                buffer += charsUsed;
                maxCount -= charsUsed;
                if (flush && completed) return buffer;
            }
            if (maxCount == 0) return buffer;

            char* cs = stackalloc char[MaxCharCountForOneByte];
            for (;;) {
                int nBytesInByteBuffer = FillByteBuffer();
                bool flush = nBytesInByteBuffer == 0;
                int bytesUsed, charsUsed; bool completed;
                Decoder.Convert(byteBuffer + ByteBufferIndex, nBytesInByteBuffer,
                                cs, MaxCharCountForOneByte, flush,
                                out bytesUsed, out charsUsed, out completed);
                ByteBufferIndex += bytesUsed;
                if (charsUsed > 0) {
                    int i = 0;
                    do {
                        *(buffer++) = cs[i++];
                        if (--maxCount == 0) {
                            if (i < charsUsed) overhangChars = new string(cs, i, charsUsed - i);
                            return buffer;
                        }
                    } while (i < charsUsed);
                }
                if (flush && completed) return buffer;
            }
        } catch (DecoderFallbackException e) {
            e.Data.Add("Stream.Position", ByteIndex + e.Index);
            throw;
        }
    }
}


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

答:
I'd structure it by moving it inside the json fields if HTTP basic auth isn't an option.

For example:

```<code>POST https://my.server/login
{ "username": "user",
  "secret": "someSecureHashAndNotThePlaintextPasswordSeriouslyDontDoThat" }
</code>```

Body:
I'd structure it by moving it inside the json fields if HTTP basic auth isn't an option.

For example:

POST https://my.server/login
{ "username": "user",
  "secret": "someSecureHashAndNotThePlaintextPasswordSeriouslyDontDoThat" }


问:
Best books on the theory and practice of software architecture?
I have a couple of developers at my company who wish to move from programming into architecture. What are the best books out there on the theory and practice of software architecture? Include a cover picture if you can.

Feel free to include general books, and also books that relate to a specific technology.

答:
A collection classic papers every sw architect should read
http://www.amazon.co.uk/Software-Fundamentals-Collected-Papers-L-Parnas/dp/0201703696/ref=sr_1_7?ie=UTF8&qid=1291810946&sr=8-7</p>


问:
Combining asynchronous and synchronous programming
I've got trouble wrapping my head around a certain problem:

In my data-flow app (a visual editor), I have both autonomous objects which communicate though ports via unordered simultaneous messages and thus represent an asynchronous system.

Still, I also want to use functions which are synchronous, e.g they need input to compute it's value

Now the problem is - how do I combine both with a non-trivial system?

In this picture, f needs x and y to compute its value, but during any point in time, only one input may be present (suppose x is present, y is not). Generalize this to higher dimensions

I can see a possible way out:

make x an array X = (x,y) and combine the first two objects resulting
in a Type-1 like system ..

or make f an active object, which caches x,y and then computes

or make f always compute its value (e.g when only x is present, compute x*y = x*0 ...)

So the possibility of futures was mentioned. I'M using Java, so i'll frame my possible solution via Objects

 create future (maybe a copy of f) waiting for y">
X is sent, y is missing -> create future (maybe a copy of f) waiting for y

答:
What you are describing is a common issue in reactive programming. The idiom is for asynchronous code to produce a Future which acts as a rendezvous point for other code. The code that depends on the results uses call-backs (or call-forwards, depending on your point of view), which take the value as it will be produced in the future.

With suitable language support (Erlang, Scala), the use of these Futures becomes quite simple and straightforward. You might also want to investigate Actors in Akka. This provides a toolkit for much more complex systems.


答:
Promises were made to solve problems like this; they work really well in functional languages (I've personally used them extensively in Javascript, where curiously jQuery actually has the worst implementation of them - see this comparison). The weird thing about using promises is accepting that things are easier when you make everything use them. I will frame my answer in JavaScript terms using the promise library Q, since that's what I know best - apologies if that's not your cup o' tea, and double apologies for answering a language agnostic question with a specific language and library to boot.

A promise is a wrapper for a callback function. In many libraries, this is called a .then() function. In simplest terms, a promise waits for a return, and then calls the function passed to then(). The simplicity was confusing for me in the beginning, so lets use your example. Let me upgrade x and y to functions. If they are functions that return promises (as many asynch heavy libraries do, like a NodeJS database accessor), this becomes trivial.

Q.all([x(), y()]).then(function(results) {
  // Do some stuff with results, which is an enumerable collection containing
  // the in-order results of the promises passed in.
});
```

<p>The trouble is, what if <code>x()</code> and <code>y()</code> <em>don't</em> return promises? As I mentioned, your life gets easier if you <em>make</em> them return promises. Fortunately, any half-decent promise library provides tools for this as well. In fact, there are several ways to do this in Q.</p>

<pre class="lang-js prettyprint-override"><code>// Upgrade x into a promise returning function
function promise_x(/*x params...*/) {
  return Q.fcall(x(/*x params...*/));
}

// Upgrade x into a promise with a deferred
// Useful if you have some standard error handling specific to x-like functions
function defer_x(/*x params...*/) {
  var deferred = Q.defer();
  // If x is asynch, assume it takes a callback function with params of (error, result)
  x(/*x params...*/), function (error, result) {
    if (error) {
      deferred.reject(new Error(error));
    } else {
      // If you have some processing to do with the result of x (and not y), you can do
      // it here and return the modified result instead
      deferred.resolve(result);
    }
  });
  return deferred.promise;
}
</code>```

If you repeat that code for the y() function, you get back to where you can use Q.all() to wait for both x() and y() to complete.

Q also provides an API for creating promises, which is like a wrapper function for Q.defer().

However, the best feature a promise library provides is aggregated error handling. Expanding on our first Q.all example, what happens if x or y throw an error? As that code is written now, it gets lost. Consider the following:

MyOverallFunction() {
  Q.all([x(), y()]).then(function(results) {
    // Do some stuff with results, which is an enumerable collection containing
    // the in-order results of the promises passed in.
    var combinedResult = synchronousFunction(result[0], result[1]);
    anotherAsyncPromiseFn(combinedResult)
      .then(function(result)) {
        return result;
      });
  }).then(function(result) {
     // Here, result is the return value of anotherAsyncPromiseFn
  }).error(function(err) {
     // This is the cool part. Any error from x, y, synchronousFunction, or
     // anotherAsyncPromiseFn will propagate to here. If you don't want to
     // handle it, just re-throw it (after logging it, if you prefer).
  });
}
```

You'll also notice in the above example there are several places where combining sync and async methods is demonstrated.

Ultimately, the tools that are at your disposal depend upon your language and environment. Promises have been implemented in more languages than just JS, and another closely related idiom from async/functional programming is Futures. Admittedly, if your language of choice does not have a Promise library, this answer will be pretty useless to you, but hopefully you at least find it interesting.

Update: Now that you mention Java, it looks like there is a decent promise library in JDefered. I've not used it, but it looks like my examples could be applied with it in a fairly straightforward manner.

Title: Combining asynchronous and synchronous programming

Body:
I've got trouble wrapping my head around a certain problem:

In my data-flow app (a visual editor), I have both autonomous objects which communicate though ports via unordered simultaneous messages and thus represent an asynchronous system.

Still, I also want to use functions which are synchronous, e.g they need input to compute it's value

Now the problem is - how do I combine both with a non-trivial system?

In this picture, f needs x and y to compute its value, but during any point in time, only one input may be present (suppose x is present, y is not). Generalize this to higher dimensions

I can see a possible way out:

make x an array X = (x,y) and combine the first two objects resulting
in a Type-1 like system ..

or make f an active object, which caches x,y and then computes

or make f always compute its value (e.g when only x is present, compute x*y = x*0 ...)

So the possibility of futures was mentioned. I'M using Java, so i'll frame my possible solution via Objects

 create future (maybe a copy of f) waiting for y">
X is sent, y is missing -> create future (maybe a copy of f) waiting for y

Body:
Promises were made to solve problems like this; they work really well in functional languages (I've personally used them extensively in Javascript, where curiously jQuery actually has the worst implementation of them - see this comparison). The weird thing about using promises is accepting that things are easier when you make everything use them. I will frame my answer in JavaScript terms using the promise library Q, since that's what I know best - apologies if that's not your cup o' tea, and double apologies for answering a language agnostic question with a specific language and library to boot.

A promise is a wrapper for a callback function. In many libraries, this is called a .then() function. In simplest terms, a promise waits for a return, and then calls the function passed to then(). The simplicity was confusing for me in the beginning, so lets use your example. Let me upgrade x and y to functions. If they are functions that return promises (as many asynch heavy libraries do, like a NodeJS database accessor), this becomes trivial.

Q.all([x(), y()]).then(function(results) {
  // Do some stuff with results, which is an enumerable collection containing
  // the in-order results of the promises passed in.
});

The trouble is, what if x() and y() don't return promises? As I mentioned, your life gets easier if you make them return promises. Fortunately, any half-decent promise library provides tools for this as well. In fact, there are several ways to do this in Q.

// Upgrade x into a promise returning function
function promise_x(/*x params...*/) {
  return Q.fcall(x(/*x params...*/));
}

// Upgrade x into a promise with a deferred
// Useful if you have some standard error handling specific to x-like functions
function defer_x(/*x params...*/) {
  var deferred = Q.defer();
  // If x is asynch, assume it takes a callback function with params of (error, result)
  x(/*x params...*/), function (error, result) {
    if (error) {
      deferred.reject(new Error(error));
    } else {
      // If you have some processing to do with the result of x (and not y), you can do
      // it here and return the modified result instead
      deferred.resolve(result);
    }
  });
  return deferred.promise;
}

If you repeat that code for the y() function, you get back to where you can use Q.all() to wait for both x() and y() to complete.

Q also provides an API for creating promises, which is like a wrapper function for Q.defer().

However, the best feature a promise library provides is aggregated error handling. Expanding on our first Q.all example, what happens if x or y throw an error? As that code is written now, it gets lost. Consider the following:

MyOverallFunction() {
  Q.all([x(), y()]).then(function(results) {
    // Do some stuff with results, which is an enumerable collection containing
    // the in-order results of the promises passed in.
    var combinedResult = synchronousFunction(result[0], result[1]);
    anotherAsyncPromiseFn(combinedResult)
      .then(function(result)) {
        return result;
      });
  }).then(function(result) {
     // Here, result is the return value of anotherAsyncPromiseFn
  }).error(function(err) {
     // This is the cool part. Any error from x, y, synchronousFunction, or
     // anotherAsyncPromiseFn will propagate to here. If you don't want to
     // handle it, just re-throw it (after logging it, if you prefer).
  });
}

You'll also notice in the above example there are several places where combining sync and async methods is demonstrated.

Ultimately, the tools that are at your disposal depend upon your language and environment. Promises have been implemented in more languages than just JS, and another closely related idiom from async/functional programming is Futures. Admittedly, if your language of choice does not have a Promise library, this answer will be pretty useless to you, but hopefully you at least find it interesting.

Update: Now that you mention Java, it looks like there is a decent promise library in JDefered. I've not used it, but it looks like my examples could be applied with it in a fairly straightforward manner.

ContentLicense: CC BY-SA 4.0


问:
Using class like an object in Python
I am learning from Learn Python the hard way where I have come across a study drill where they want to know that whether a class can be used like an object.

As I have experimented:

```<code>class A(object):
    def __init__(self):
        print "in here"
    def cat(self,name):
        print "my cat ",name
</code>```

Here if I write A.cat(A(),"Tom"), it works and found out that its call unbound method. Now, does that mean I can assume that classes can be used like an object?

答:
Everything in Python is an object, including classes.

This means you can reference classes, passing them around like arguments, store them in attributes, (extra) names, lists, dictionaries, etc.

This is perfectly normal in Python:

```<code>class_map = {
    'foo': A,
    'bar': SomeOtherClass,
    'baz': YetAnother,
}

instance = class_map[some_variable]()
</code>```

Now it depends on some_variable what class was picked to create an instance; the class_map dictionary values are all classes.

Classes are themselves instances of their type; this is called their metaclass. You can produce a new class by calling type() with a name, a sequence of base classes, and a mapping defining the attributes of the class:

```<code>type('DynamicClass', (), {'foo': 'bar'})
</code>```

creates a new class object, with a foo attribute set to bar, for example. The class produced can itself then be used to create instances. So classes are produced by metaclasses, just as instances are produced by classes.

You can produce your own metaclasses by inheriting from type, opening a weird and wonderful world of class behaviour.

Calling an unbound method by passing in a separate instance is not really a good example of using classes as an object. All you did was use the initial reference (the class name) to look up the method, then pass in an instance of the class as the first parameter to stand in for self.

Title: Using class like an object in Python

Body:
Everything in Python is an object, including classes.

This means you can reference classes, passing them around like arguments, store them in attributes, (extra) names, lists, dictionaries, etc.

This is perfectly normal in Python:

class_map = {
    'foo': A,
    'bar': SomeOtherClass,
    'baz': YetAnother,
}

instance = class_map[some_variable]()

Now it depends on some_variable what class was picked to create an instance; the class_map dictionary values are all classes.

Classes are themselves instances of their type; this is called their metaclass. You can produce a new class by calling type() with a name, a sequence of base classes, and a mapping defining the attributes of the class:

type('DynamicClass', (), {'foo': 'bar'})

creates a new class object, with a foo attribute set to bar, for example. The class produced can itself then be used to create instances. So classes are produced by metaclasses, just as instances are produced by classes.

You can produce your own metaclasses by inheriting from type, opening a weird and wonderful world of class behaviour.

Calling an unbound method by passing in a separate instance is not really a good example of using classes as an object. All you did was use the initial reference (the class name) to look up the method, then pass in an instance of the class as the first parameter to stand in for self.


问:
Is there any sorting algorithm which is not inherently sequential and is task distributable?
After googling for a couple hours, I came to a conclusion that all sorting algorithms are inherently sequential which can be data distributed but not task distributable.

Is there any algorithm which is not inherently sequential and is task distributable?

答: See Knuth's discussion of polyphase merge sort with replacement selection in volume 2 of ACP.  Or google "external sort".  These sorts go way back to the early days of computing when computers often didn't have enough memory to sort all the data, but had multiple tape drives attached.  If you replace tape drives with inter-process data flows, the algorithms still work wonderfully.  I implemented this algorithm in the early 1980s for a system that did not have an OS-supplied sorting program.</p>


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

答:
You could consider using some indexed file library like gdbm (or something else).

You could also perhaps consider using sqlite (it is a bit of overkill, but learning some tiny SQL skills is useful!) - or even using a real database system (e.g. postgresql or mongodb). Don't forget to backup & dump the data in database (i.e. SQL) format.

You might also be interested in textual serialization formats like JSON (there are libraries for them, e.g. jsoncpp, and it is nice to handle textual data). You could put JSON data inside GDBM or sqlite containers (see this example of mine).

BTW, if you want to keep having many files, perhaps organizing them in directories (i.e. dir01/data0020 ....) might help.

You probably would want to make a helper application to browse or access your data... Think also about backing up your data in textual (not binary) format!

There are some libraries handling tar format like libtar but I guess you should not use them.

Look also if your field (evolutionary algorithms) has not defined some conventions or formats. Document your format (even for yourself!).


问:
Web Application: Combining View Layer Between PHP and Javascript-AJAX
I'm developing web application using PHP with CodeIgniter MVC framework with a huge real time client-side functionality needs. This is my first time to build large scale of client-side app. So I combine the PHP with a large scale of Javascript modules in one project.

As you already know, MVC framework seperate application modules into Model-View-Controller.

My concern is about View layer.

I could be display the data on the DOM by PHP built-in script tag by load some data on the Controller. Otherwise I could use AJAX to pulled the data -- treat the Controller like a service only -- and display the them by Javascript.

Here is some visualization

I could put the data directly from Controller:

```<code><label>Username</label> <input type="text" id="username" value="<?=$userData['username'];?>"><br />
<label>Date of birth</label> <input type="text" id="dob" value="<?=$userData['dob'];?>"><br />
<label>Address</label> <input type="text" id="address" value="<?=$userData['address'];?>">
</code>```

Or pull them using AJAX:

```<code>$.ajax({
  type: "POST",
  url: config.indexURL + "user",
  dataType: "json",
  success: function(data) {
    $('#username').val(data.username);
    $('#dateOfBirth').val(data.dob);
    $('#address').val(data.address);
  }
});
</code>```

So, which approach is better regarding my application has a complex client-side functionality?

In the other hand, PHP-CI has a default mechanism to put the data directly from Controller, so why using AJAX?

答: You can refer more detail about ajax. Ajax allow to respond user's request without refresh the whole page or go to a new page. In some situations it might has better user experience to use ajax. For traditional php post request, it allow to bring user to other page. Hence, you can apply both ways into your project base on different situation.</p>


问:
is JS a gradually typed language?
I was researching on statically typed and dynamically typed concepts and found out there is another type system called gradually typed.

From wikipedia

Gradual typing is a type system in which variables may be typed either at compile-time (static typing) or at run-time (dynamic typing), allowing software developers to choose either type paradigm as appropriate, from within a single language.

In particular, gradual typing uses a special type named dynamic to represent statically-unknown types and gradual typing replaces the notion of type equality with a new relation called consistency (aka. compatibility) that relates the dynamic type to every other type. The consistency relation is symmetric but not transitive

If I understand those concepts correctly, "Javascript" is a gradually typed language. Am I correct?

答:
To elaborate on why JavaScript is not gradually typed, let's look in the other direction at C#, which is statically typed with implicit typing.

According to MSDN, C# introduced a var keyword with version 3.0 released in 2007. It is only allowed on "variables that are declared at method scope", what I would call local variables. The var keyword falls short of being a dynamic type, because it allows the compiler to figure out what type the declaration should, but then treats all references to that variable as the given type exactly as if you had declared it statically yourself.

Here are some examples of how it can and cannot be used.

```<code>class MyClass {
    // Standard member variable
    public string MyName = "Patrick";

    // Illegal declaration - var cannot be used here even though the type may be inferred
    // from the literal definition; compiler throws an error
    private var LuckyNumber = 7;
    // Have to do it like this:
    private int LuckyNumber = 7;

    private MyClass(int luckyNumber) {
         LuckyNumber = luckyNumber;
    }

    public MyClass MyClassFactory(int newLucky) {
         // Legal - myInstance is in the method scope
         var myInstance = new MyClass(newLucky);
         // Not legal - myInstance is not a dynamic type just because we declared it with var
         myInstance = new MyOtherClass();

         // We can return myInstance because its type matches the method signature
         return myInstance;
     }
}
</code>```

In other words, C# does not provide a way to declare an variable that can hold an arbitrary type. The closest you can get is with polymorphism, where assignments are restricted to the inheritance tree.

Note that in sharp contrast, JavaScript would allow the illegal line in MyClassFactory. The following is perfectly legal in JS:

```<code>var foo = "foo";
foo = 1;
foo = 2.0;
foo = new Date();
foo = [];
foo = {};
foo = function() {};
</code>```

Every line changes the type of foo. Furthermore, there is no way to declare foo as a type that may not be changed.

Note that there are ways to shoehorn static typing into JavaScript, but they are actually wrapper layers around the actual JS code, which ends up every bit as dynamically typed as if you had written it by hand. There are way more ways than I would have imagined, as it turns out: here is a comprehensive-seeming list of languages (or more properly syntaxes or parsers) that can churn out JavaScript. Of these, CoffeeScript is the most common in my experience.

Finally, a language must provide both dynamic and static declarations in order to be considered dynamically typed. In other words, the following must be possible with some syntax:

```<code>// Statically typed declaration
Integer myNumber = 3;
// May be legal if the language provides for auto-conversion or dynamic-casting; may
// throw an error. It depends on the language
myNumber = 7.5;

// Static type declaration of an object class
MyParentType instance = new MyParentType();
// legal if MyChildType inherits/extends MyParentType - illegal otherwise
instance = new MyChildType();

// Illegal always - MUST throw an error
instance = new IncompatibleType();

// Dynamic typed declaration
dynamic otherInstance = new MyParentType();
// Legal for variables declared dynamic - MUST NOT throw an error
otherInstance = new IncompatibleType();
</code>```

Note that, as demonstrated, neither C# or JS support both types of variable declarations for different reasons.

Title: is JS a gradually typed language?

Body:
To elaborate on why JavaScript is not gradually typed, let's look in the other direction at C#, which is statically typed with implicit typing.

According to MSDN, C# introduced a var keyword with version 3.0 released in 2007. It is only allowed on "variables that are declared at method scope", what I would call local variables. The var keyword falls short of being a dynamic type, because it allows the compiler to figure out what type the declaration should, but then treats all references to that variable as the given type exactly as if you had declared it statically yourself.

Here are some examples of how it can and cannot be used.

class MyClass {
    // Standard member variable
    public string MyName = "Patrick";

    // Illegal declaration - var cannot be used here even though the type may be inferred
    // from the literal definition; compiler throws an error
    private var LuckyNumber = 7;
    // Have to do it like this:
    private int LuckyNumber = 7;

    private MyClass(int luckyNumber) {
         LuckyNumber = luckyNumber;
    }

    public MyClass MyClassFactory(int newLucky) {
         // Legal - myInstance is in the method scope
         var myInstance = new MyClass(newLucky);
         // Not legal - myInstance is not a dynamic type just because we declared it with var
         myInstance = new MyOtherClass();

         // We can return myInstance because its type matches the method signature
         return myInstance;
     }
}

In other words, C# does not provide a way to declare an variable that can hold an arbitrary type. The closest you can get is with polymorphism, where assignments are restricted to the inheritance tree.

Note that in sharp contrast, JavaScript would allow the illegal line in MyClassFactory. The following is perfectly legal in JS:

var foo = "foo";
foo = 1;
foo = 2.0;
foo = new Date();
foo = [];
foo = {};
foo = function() {};

Every line changes the type of foo. Furthermore, there is no way to declare foo as a type that may not be changed.

Note that there are ways to shoehorn static typing into JavaScript, but they are actually wrapper layers around the actual JS code, which ends up every bit as dynamically typed as if you had written it by hand. There are way more ways than I would have imagined, as it turns out: here is a comprehensive-seeming list of languages (or more properly syntaxes or parsers) that can churn out JavaScript. Of these, CoffeeScript is the most common in my experience.

Finally, a language must provide both dynamic and static declarations in order to be considered dynamically typed. In other words, the following must be possible with some syntax:

// Statically typed declaration
Integer myNumber = 3;
// May be legal if the language provides for auto-conversion or dynamic-casting; may
// throw an error. It depends on the language
myNumber = 7.5;

// Static type declaration of an object class
MyParentType instance = new MyParentType();
// legal if MyChildType inherits/extends MyParentType - illegal otherwise
instance = new MyChildType();

// Illegal always - MUST throw an error
instance = new IncompatibleType();

// Dynamic typed declaration
dynamic otherInstance = new MyParentType();
// Legal for variables declared dynamic - MUST NOT throw an error
otherInstance = new IncompatibleType();

Note that, as demonstrated, neither C# or JS support both types of variable declarations for different reasons.


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

答:
Why not include some sort of template preprocessor\code generation for this system?
A custom extra build step that executes and emits extra java source files before compiling the rest of the code.  This is how including web clients off of wsdl and xsd files often works.

You'll of course have the maintenance of that preprocessor\code generator, but you won't have the duplicated core code maintenance to worry about.

Since compile time Java code is being emitted, there is no performance penalty to be paid for extra code.  But you gain maintenance simplification by having the template instead of all of the duplicated code.

Java generics give no performance benefit due to type erasure in the language, simple casting is used in its place.

From my understanding of C++ templates, they are compiled into several functions per each template invocation.  You'll wind up with duplicated mid-compile time code for each type you store in a std::vector for example.