问:
Should you use "internal abbreviations" in code comments?
Should you use "internal abbreviations/slang" inside comments, that is, abbreviations and slang people outside the project could have trouble understanding, for instance, using something like //NYI instead of //Not Yet Implemented?

There are advantages of this, such as there is less "code" to type (though you could use autocomplete on the abbreviations) and you can read something like NYE faster than something like Not Yet Implemented, assuming you are aware of the abbreviation and its (unabbreviated) meaning.

Myself, I would be careful with this as long as it is not a project on which I for sure will be the only developer.

答:
A case in point as to why using abbreviations like this is in your own example. You typo-ed "NYE" when you meant "NYI". So you're telling people about new year's eve, it seems. However if you typo-ed "not yet emplemented" they'd still get the idea, whilst just thinking you can't spell.

Coding is not a race, so I don't think "saving keystrokes" is really a valid consideration. The object of the exercise is to write clean, understandable code, and this extends to any "necessary" comment in said code. Parsing an abbrev. is just that little bit more taxing than reading what it says (which one basically does automatically, without any effort).


问:
The Programmers Bill of Responsibilities
So, we've all heard of The Programmers Bill of Rights and XP has a similar concept.

It's a common complaint these days that we hear a lot about people's rights but not so much about their responsibilities, so what should be on the programmers bill of responsibilities.  That is things that they should do, which they may find unpalatable, but that which separate programmers acting professionally and responsibly, from those who do not.

I'm primarily interested in the unpalatable ones and the ones which tend not to happen.  That is the ones that programmers tend to shirk and avoid, rather than the ones which 90% of programmers actually want to do (such as always refactor and use source control).

So, what should be on the Programmers Bill of Responsibilities?

答:
A Programmer's responsibility is to create software that satisfies the needs of the requirements, analysis, design, and specifications as set in any contracts between the programmer and the client.

A Programmer's responsibility is to create software that is economical, reliable, and works efficiently on real machines.

A Programmer's responsibility is to work as efficiently, ethically, and with as much integrity as they can and conduct themselves with utmost professionalism.

Some of that applies to "A Programming Company's" Responsibilities.

ContentLicense: CC BY-SA 2.5


问:
Python classes with only one instance: When to create a (single) class instance and when to work with the class instead?
Given a Python class which will be instantiated only once, i.e. there will be only one object of the class. I was wondering in which cases it makes sense to create a single class instance instead of working directly with the class instead.

There is a similar question, but it has a different focus:

it is about grouping global variables and functions into a class and

It isn't Python-specific. The latter means it does not consider the fact that (in Python) classes are objects too.

UPDATE:

In Python, I can do the following with both classes and objects:

```<code>class A(object):
    pass

A.some_state_var = True
# Then later
A.some_state_var = False

my_a = A()

my_a.some_state_var = True
# Then later
my_a.some_state_var = False
</code>```

So I don't see how the choice between a class and an instance of that class is about state (in Python). I can maintain a state with either of the two.

Furthermore, the motivation to create my class / class instance is not about enforcing a Singleton requirement.

Also, it is not so much about creating a new Type.

The motivation is to group related code and data and having an interface to it. This is why I initially modeled it as a class in a class diagram. Only when it came to the implementation I started wondering whether to instantiate this class or not.

答:
I was wondering in which cases it makes sense to create a single class instance instead of working directly with the class instead.

This is one of those things that will cause a religious war if you get into it to much.

But in general a practice that I have seen many times is that class methods should concern themselves only with creating instances of that class.

If you think about what a class is, what its purpose/behaviour is, then this makes sense. The purpose of a class is to create instances of objects that are based on itself. It is a blueprint that can also build the building. A "User" class creates "user" objects. A "Dog" class creates "dog" objects etc etc

Give this is the behaviour of a class it makes sense then that methods you add to the class "X" will concern themselves with creating "x" objects.

So even if you are only ever going to need one "x" object you should still instanciate it.

Adding methods to the X class that are not related to creating instances of "x" objects can lead to confusing unexpected code. There are of course tons of examples in the real world where people have done this anyway, but like I said that path leads to religious war.

ContentLicense: CC BY-SA 3.0


问:
Appropriate to put known issues directly in software?
I've taken over maintenance of an Android app, and there are a few residual problems that I've more or less fixed, but still have issues because of different Android OS versions.

For example, sending a web request with the MediaPlayer class has custom HTTP headers stripped by the OS before the request is sent out, but only on Android 4.X (I exhaustively tested), and that causes this particular feature to fail because it relies on those headers.

This is a known issue and I'm trying to work around it, but would it be a good idea to have a conditional check like

```<code>if (OS.VERSION == 4) {
    knownIssueDialog(This feature will not work on your Android version... etc.");
}
</code>```

Obviously we would have this noted on our support channel, but I'm wondering if it would be a good idea (assuming everything is kept track of) to have these known issues also embedded in software, and to present them when and where necessary, such as what I described above.

We keep getting multiple bad reviews and a lot of support emails based on these kinds of issues, so in my mind it would save everyone a lot of time and headache by simply blocking a feature where it is known not to work properly.

I see two potential problems:

Users have probably never seen anything like a "known issue" dialog before; a lot of users simply might not understand what it means.

There is a bit of development overhead - one would need to make sure to keep track of these issues somewhere in the code. Fortunately, with Java annotations, any conditional check like that could be preceded by @KnownIssue or something like that, making finding/modifying them very simple.

Would putting 'known issue' prompts in software make sense?

Edit: I'll add that this is an issue that just started occurring about a week ago. I have half-fixed the issue, and am very unlikely to be able to fix it for 4.X because it's the OS that is causing the problem. I could release a new version with the fix and make 50% of the user base happy again, and warn the other 50% (4.X users) that the issue will persist on 4.X, and to suggest an upgrade (or something). The question is whether or not to do that in software (i.e. show a dialog to 4.X users), or to just let them spam us support emails saying "your fix didn't work!!!" and then direct them to the support page that discusses the issue in further detail.

答:
If the problematic features are available via options, buttons or something similar, you could disable or hide these elements: I expect this to be less frustrating to the user than being offered a feature only to be told "doesn't work". If you know it's not going to work, then don't make it appear like it could.

Disabling the option/button will allow you to add a note stating "not supported on your OS".

Hiding the option/button will not confuse new users but might cause complaints by existing users that are no longer able to find the item.


答:
Yes, this is very acceptable for some more obscure features, especially when they are hidden away in the option menu. Perhaps it's nicer to disable the buttons and add some extra text "this feature on XXX and below" or "this feature works optimal on XXX and above" if it only works partial.

No, this is not acceptable on a key function that takes up 75% of the screen when you start your app. Your uses will get really annoyed every time they see the pop-up. You are better off just hiding the feature, no need to poke your users about something they can't fix.

It would be different if your users can easily fix it, for example by installing an additional app. I've often seen messages like "To use this option, you need to install the (free) compass app" or "To use this option, you need to upgrade to the paid pro app" etc.

The bottom line is, you can do this, but only after careful consideration and after other solutions fail, not as a quick shortcut. It will annoy your users, but that might be an acceptable trade-off you make.

(ps. I have the feeling this question should go to UX)

Title: Appropriate to put known issues directly in software?

Body:
I've taken over maintenance of an Android app, and there are a few residual problems that I've more or less fixed, but still have issues because of different Android OS versions.

For example, sending a web request with the MediaPlayer class has custom HTTP headers stripped by the OS before the request is sent out, but only on Android 4.X (I exhaustively tested), and that causes this particular feature to fail because it relies on those headers.

This is a known issue and I'm trying to work around it, but would it be a good idea to have a conditional check like

```<code>if (OS.VERSION == 4) {
    knownIssueDialog(This feature will not work on your Android version... etc.");
}
</code>```

Obviously we would have this noted on our support channel, but I'm wondering if it would be a good idea (assuming everything is kept track of) to have these known issues also embedded in software, and to present them when and where necessary, such as what I described above.

We keep getting multiple bad reviews and a lot of support emails based on these kinds of issues, so in my mind it would save everyone a lot of time and headache by simply blocking a feature where it is known not to work properly.

I see two potential problems:

Users have probably never seen anything like a "known issue" dialog before; a lot of users simply might not understand what it means.

There is a bit of development overhead - one would need to make sure to keep track of these issues somewhere in the code. Fortunately, with Java annotations, any conditional check like that could be preceded by @KnownIssue or something like that, making finding/modifying them very simple.

Would putting 'known issue' prompts in software make sense?

Edit: I'll add that this is an issue that just started occurring about a week ago. I have half-fixed the issue, and am very unlikely to be able to fix it for 4.X because it's the OS that is causing the problem. I could release a new version with the fix and make 50% of the user base happy again, and warn the other 50% (4.X users) that the issue will persist on 4.X, and to suggest an upgrade (or something). The question is whether or not to do that in software (i.e. show a dialog to 4.X users), or to just let them spam us support emails saying "your fix didn't work!!!" and then direct them to the support page that discusses the issue in further detail.


问:
The urge to organize code in a cleaner way
Every time I am working on a project, specially a project from scratch, I always feel like I am doing a messy job. I feel bugged all the time by the need or organizing code that is clean or proper way.

For example;

Avoid hard-coding file paths in gulpfile.

Require all node modules in similar fashion.

What should be the ideal directory structure for this project.

UI. The *** UI.

The Question

What are the strategies I can follow to not drown into that world? Thinking over and over on the organization aspect of the project gets me really low on productivity.

In general, how to approach a project from scratch so I can get the most done without the code organization overhead?

Notes after the possible duplicate flag

I can understand why this is flagged as possible duplicate as the question is more of an overview rather than a specific question.

The question I have is more about what kind of mentality a programmer should have when starting a project from scratch so they end up delivering more rather than getting trapped by code organization issues.

答:
This post reads like you really are feeling the frustration - I can empathise. There are a few things that could help you through this;

A good book on code construction etc. Code complete 2 is often cited in this regard

More or better familiarity with you tools

Using their features well

Making peace with their short comings, no tool is perfect

Time, it takes practise to get really good at what you do. Some say 10 years/10'000 hours

Study and follow common techniques with the tools and languages you use, study your favourite open source projects - they may not be perfect, but there are lessons there

Do not forget that shipping code is a feature, get it out the door; best is the enemy of good, get it good enough, make peace with that and ship it.


问:
What non-programming books should a programmer read to help develop programming/thinking skills?
There are a lot of questions about what programming books should be on the programmer's bookshelf. How about non-programming related books that can help you become a better programmer or developer? It would also be interesting to know why they would help.

My first choice would be Sun Tzu's "Art of War" (however cliché), because it made it obvious that the success of any project depends on the strength of its weakest link (and warfare is a big project).

答:
Zen and the Art of Motorcycle Maintenance

Robert Pirsig

It teach us how to do right maintenance on software.


答: The programmer is responsible for the privacy and security of all user provided data. Especially passwords, credit card numbers, email addresses, and physical location.</p>

Title: The Programmers Bill of Responsibilities

Body:
So, we've all heard of The Programmers Bill of Rights and XP has a similar concept.

It's a common complaint these days that we hear a lot about people's rights but not so much about their responsibilities, so what should be on the programmers bill of responsibilities.  That is things that they should do, which they may find unpalatable, but that which separate programmers acting professionally and responsibly, from those who do not.

I'm primarily interested in the unpalatable ones and the ones which tend not to happen.  That is the ones that programmers tend to shirk and avoid, rather than the ones which 90% of programmers actually want to do (such as always refactor and use source control).

So, what should be on the Programmers Bill of Responsibilities?


问:
My web app uses ASP, but does-it need it?
I’m relatively new to web development, and I’m amazed at the variety of new concepts in the field. I could probably use some help to synthetize.

I have to deal with is a backend written in Delphi, that provides some poorly written SOAP services.
I originally developed an ASP MVC 5 web app making use of the SOAP API. My fatty controllers select and call the SOAP services, use a bunch of Mappers to transform the DTOs into my C#-wise model objects, and execute some business logic at times. Sometimes, they have to use consecutively two mappers, one to transform the DTO into a “model object”, and one to transform the model object into the “view model” object. I know… I’m anxious just thinking about it.

Besides, I wanted to do a Single-page app (at the time, I didn’t even know that this concept existed) with a mix of Razor, JQuery, and a third-party MVC components library (DevExpress).

This project proved to be extremely cumbersome. I managed to bring the monster to life nonetheless, but performances are still an issue, and any modification of the beast requires an excessive amount of time. As an aside, approximately half of my controllers’ methods returns PartialView, and the other half return Json objects.

I recently started creating a “Service” layer, in a separate VS project, whose purpose is to handle the SOAP end point, sometimes execute some business logic, and mostly to do the mapping from DTOs to some model objects (I think I could also introduce some caching here, that’s another debate).

For the web client, I started writing an AngularJs app, which framework indeed simplifies my life a lot. So far I outlined a handful of views, and I can switch from one view to the other in a snap, having total control on the round trips to the server. I had to do little work to outline this new app as compared to my previous approach.

Now I’m left wondering: do I still need ASP MVC? Do I even need ASP at all?
Is it possible (is it easy?) to call a SOAP web service from an Angular service? If yes, an extreme solution could be to get rid of ASP, and develop my web app completely in Javascript (Angular).

I immediately see at least one drawback here. My Angular services could only be used in that specific context. Let’s say I want to create a native Android app, it would have to call the SOAP web services and would probably need another Service layer, which probably would do most of what my Angular services layer already does.
Moreover, the SOAP end-point, which I didn’t write and is currently only available to the IIS apps on the same server, would need to be exposed to the outside world. It is not ready for that in terms of security.

An intermediate solution could be that I keep my services layer written in C#, and create a REST end-point on top of it, for the use of my angular app as well as various other apps that could be written, in the future, for any platform in any language.

Would this solution mean that I don’t need the “MVC framework” anymore? What would be the role of “ASP” in this context? Only mapping request parameters to .NET objects, and some routing? Let’s not forget about authentication. My previous app used [Authenticate] on every controller as well as some basic roles management. I believe I would have to deal with this “manually” in the context of a REST API?

I also get confused because of things changing so fast. I find information about “Web API” that was true for ASP MVC4, and is no longer true for MVC5. Now, ASP.NET 5 is out, but I wasn’t able to find a clear and comprehensive list of ASP’s features and new features. I also heard of Rails and Node.js, but I’m afraid I currently use a lot ASP features without even knowing

答:
Is it easy to call a SOAP web service from an Angular service?

No it is usually not possible because browsers are limited to making requests to the same domain as the webpage is hosted unless you apply some CORS. I have never seen anyone try and call SOAP from javascript. If we ignore the security limitations of the browser any credentials for the service would have to be exposed to all users in javascript and there is no way around this. Also SOAP is a very bloated protocol which doesn't mix well with javascript.

Would this solution mean that I don’t need the “MVC framework” anymore?

Yes

What would be the role of “ASP” in this context?

The role will be the web api. The role of web api is to expose your service layer to the client over the wire by mapping parameters and result and of course some routing.

Let’s not forget about authentication.

Web Api still uses controllers and you can still put [Authenticate] attributes on method and controller class. You just need to decide if you want to use Bearer tokens or Cookies for auth. The more modern approach is using Bearer tokens.

Also REST api means it conforms to richardson maturity level 3 which you may or may not want.


问:
Can symbolic AI 'learn' a data model?
Perceptrons, a simple form of supervised machine learning, must be trained with a set of known good inputs before they can "learn" by adjusting internal weights assigned to inputs, based on the accuracy of its results.

Similarly, we know that reinforcement learning and unsupervised neural networks are able to learn without any known model of the problem; they can be designed to collect information about an environment only by interacting with it.

Can symbolic AI be used to design a system that can achieve this "naive learning," or is this a property exclusive to certain soft computing techniques?

答:
The symbolic methods of machine learning encompass both supervised and unsupervised learning.

Supervised symbolic learning covers mining logical rules and dependencies from data:

"if-then" rules

decision trees

and also learning concepts from data:

mining ontologies from data

hypothesis generation

...

For unsupervised symbolic learning the well known example is conceptual clustering.

So supervised and unsupervised learning aren't a sub-symbolic (i.e. artificial neural networks, Bayesian classifiers...) only AI topic.

Title: Can symbolic AI 'learn' a data model?


问:
Misunderstanding about "Evidence Based Scheduling" in estimation tasks
I read the Spolsky blog the post with title "Evidence based scheduling" (http://www.joelonsoftware.com/items/2007/10/26.html) but I don't understand the mechanism to predict and estimate interruptions.

If I understand, Splosky says to prepare 100 scenario for a task in ramdom way

At point 3 of the article, Spolsky says

1) "While calculating each possible future for a given developer, you’re going divide each task’s estimate by a randomly-selected velocity from that developer’s historical velocities, which we’ve been gathering"

2) "Do that 100 times; each total has 1% probability, and now you can figure out the probability that you will ship on any given date"

3) Spolsky says that, more the velocity of a developer has been regular in the past, more the differents values are convergent in the same value (as every Montecarlo simulation, I says too).

4) In next paragraph ("Obsessive-compulsive disorder not required") I tell us that there are a lot of different interruptions with differen amount of time (him example is about "Painful conversation about marlin"), but EBS don't receive any problem in precision of estimation.

Well, I don't understand why

at the point 2, what total have 1% probability in every case? The total of example? But it has only 5 tasks.

at the point 4, I don't understand the sentence "is exactly the same as the probability that John’s boss would interrupt him during any given feature"

I think to lose same details, but I feel a bit confused.

What is my error?

PS I don't know if this question is more correct here or in Project Management Exchange: if I got wrong I'm sorry.

答:
at the point 2, what total have 1% probability in every case? The total of example? But it has only 5 tasks.

The estimation system takes 100 velocities calculated from the developers history. Each velocity is the ratio between estimated time and actual time for a given task.

at the point 4, I don't understand the sentence "is exactly the same as the probability that John’s boss would interrupt him during any given feature"

It just means that because the interruption affects the velocity for a certain percentage of the tasks, the interruption will be appropriately represented in estimates that are based on 100 random velocities from the developers history.


问:
Where to store average value in db?
I have a restaurant review app which stores reviews in a db, MySql.

There's 2 tables. 1 for Restaurant. Another for reviews.

To increase the performance, I am considering to store the avg review of restaurant instead of calculating it on the fly.

I am not sure where to store that bit though. Should it go into Restaurant table or separate table?

I was thinking if I should create a new table called RestaurantStats to store more than just avg reviews, but is that overkill?

Is it safe to store the avg in main table?

Currently, I am getting around a thousand reviews per day now and expect it to swell in a few months.

I have to show avg of reviews for a list of restaurants by area.

As part of performance tuning, I have created a new table that notes which restaurants were reviewed and then a event is scheduled to run every x minutes to calculate the avg for restaurants that were recently reviewed so that I dont have to calculate avg on every request.

I have my db hosted on AWS, and want to keep the CPU usage down.

答:
You can store this whereever you like. I would store it in the Restaurant table but another one for stats might make sense - it depends how often you update it, and whether you update the restaurant entries often or at all.

An alternative approach would be to store the average in the business logic that fetches and returns the data. The average is then calculated on startup of your services and is dynamically updated (ie cached). You would not have to update the average in the DB then - which is often more expensive than reading a lot of data (ie if you update the average you've turned a read of rows in your table into a single write. If you write this every time a review is added, you're going to be making a lot of relatively expensive update calls)

Title: Where to store average value in db?


答:
Updated answer

There are benefits and drawbacks to adding a new table, and to storing it on the Restaurant table.

Benefits to putting it directly on the restaurant table is that you get all your Restaurant info in a single read.  However if this is a large row with lots of data you may not want to update it all the time.

Putting it on a secondary "stats" table also has merit, in that it's essentially transient data. You loose nothing by dropping the table and regenerating it, and updates are fast and light.

Original Answer before it was clear that caching the average was necessary

To increase performance sounds like premature optimization to me. I'll bet that in this case the performance gain is negligible and not worth the overhead.

Consider the overhead, in your application logic when a review is added, you've to fetch all the other scores, average them, and update the stored average.

You've to isolate this operation (probably using a Db transaction), because you can't have two reviews added at the same time.

You've to do this when reviews are added, removed and updated.

Db transactions are expensive, and they're blocking. If you're that worried about performance this will harm your application far more than an simple aggregation.

If you manually change data, or archive data directly then you've to update ALL the affected averages.

Conversely, your Db engine has been insanely well optimised for doing aggregate operations on the fly.

So to answer the question as asked . . .

I'd only do this if you have measured your application performance and you know you absolutely do need it. In that case, store it on the Restaurant table.

Otherwise don't store the value, calculate it on the fly.

Title: Where to store average value in db?

Body:
I have a restaurant review app which stores reviews in a db, MySql.

There's 2 tables. 1 for Restaurant. Another for reviews.

To increase the performance, I am considering to store the avg review of restaurant instead of calculating it on the fly.

I am not sure where to store that bit though. Should it go into Restaurant table or separate table?

I was thinking if I should create a new table called RestaurantStats to store more than just avg reviews, but is that overkill?

Is it safe to store the avg in main table?

Currently, I am getting around a thousand reviews per day now and expect it to swell in a few months.

I have to show avg of reviews for a list of restaurants by area.

As part of performance tuning, I have created a new table that notes which restaurants were reviewed and then a event is scheduled to run every x minutes to calculate the avg for restaurants that were recently reviewed so that I dont have to calculate avg on every request.

I have my db hosted on AWS, and want to keep the CPU usage down.


问:
"Party on my branch" workflow support in mercurial
When I'm on a git project, I have a workflow that goes something like this:

Start a new feature (open a new branch)

Write some code, commit some code, repeat

Push the code to a remote, possibly with my initials in the branch name, and 'WIP' commits, indicating that it's unfinished

Once things start taking shape, squash commits together, change their messages, delete them, rearrange them, etc.

Keep working

Decide things are ready for review, submit a pull/merge request (possibly after force-pushing to destroy my old, work-in-progress, branch)

Get some review, put more changes that came from that review on top

Get approval to merge the branch

Merge the branch. Bask in the beautiful history of the feature it is that I just merged, but never rewrite history on the master/default branch (unless I'm the only one on the project)

Is this workflow supported in mercurial? How about without plugins? I'm fairly new to mercurial, but I know enough (and lean on this cheatsheet enough) to get what I want to get done. However I'm not able to use this workflow. There is much care in crafting the perfect commit, and just piling stuff on top of it because otherwise I seem to get error messages. This seems to be by design, but I'd really rather use my workflow for my branches.. and then conform to the type of history management (e.g. merges/rebases/no rewriting) for branches that many people work on.

答:
If you exclude p.3 from your workflow (can't see strong reasoning for this operation) and slightly change related p.6 , you can migrate full cycle to Mercurial "as is"

Even if MQ noted as "feature of last resort" it can be useful tool (probably paired with MQCollab extension) for your "must to be shared" WIP (is it really must be shared even in dirty chaotic state?!)

Manipulating history for non-published changesets is really easy task in Mercurial (at least not harder and not weaker, than it Git)


问:
Does cherry-pick just pull changes into the current working tree as uncommitted changes?
My team uses Mercurial for version control. Our development / version control routine is:

all been committing to the same branch

pulling for changes and rebasing our commits locally before pushing back to the hosted repository

This keeps everyone in sync. And the latest code (even unfinished code) is than grabbed from the tip of this branch and put into our test environment.

I've been tasked with creating a management process where we can more cleanly extract "completed features" into the test environment.

I've advocated that we begin to branch->pull-request->merge->close branch process, but I've been told that branching is not an option, and that the project director would prefer too be able to manually select commits representing completed features/bug fixes and only include those commits in a deployment to testing.

I am not sure what terminology besides cherry-pick in GIT / HG that would represent this process, and if it would even be advisable as the commits would no-longer have a proper revision history as it's my understanding that cherry-pick just pulls changes into the current working tree as uncommitted changes correct?

答:
Cherry-pick for Mercurial is hg graft

History of grafted commits are easy recoverable, especially if graft performed with --log option and without --edit+madcap editing commit-message. Also the good GUI (TortoiseHG) reveals the history of grafting.

Toy-repo with some grafting in it (release+devel branching model)

Glog ouput in console:

```<code>hg glog --style changelog
2015-08-05  Author <email>

@       * c.txt, cd.txt:
|       Cnange 4
|       [769d5ba1b198] [tip] <release>
|
o       * c.txt:
|       Cnange 3 (grafted from 3044bbf6fe3542b86d0a1a84b7455d76928b559b)
|       [e58f524b1203] <release>
|
o       * a.txt:
|       Cnange 1
|       [23d4aaf0c632] <release>
|
o       * Release branch created
|       [9f39dda2e0d9] <release>
|
| o     * c.txt, cd.txt:
| |     Cnange 4
| |     [c5523fade515]
| |
| o     * b.txt:
| |     Edit 2
| |     [7efeb998f47e]
| |
| o     * a.txt:
| |     Edit 1
| |     [4f2e0bffed8a]
| |
| o     * c.txt:
| |     Cnange 3
| |     [3044bbf6fe35]
| |
| o     * b.txt:
| |     Cnange 2
| |     [278066927656]
| |
| o     * a.txt:
|/      Cnange 1
|       [e233699bf798]
|
o       * .hgignore:
        Initial structure
        [3bf949e66c66]
</code>```

(grafted changesets 1,3,6. Only changeset 3 grafted with --log added. Note unchanged commit-message for 1 and 6)

and this repository after all grafting in TortoiseHG

Body:
Cherry-pick for Mercurial is hg graft

History of grafted commits are easy recoverable, especially if graft performed with --log option and without --edit+madcap editing commit-message. Also the good GUI (TortoiseHG) reveals the history of grafting.

Toy-repo with some grafting in it (release+devel branching model)

Glog ouput in console:

hg glog --style changelog
2015-08-05  Author <email>

@       * c.txt, cd.txt:
|       Cnange 4
|       [769d5ba1b198] [tip] <release>
|
o       * c.txt:
|       Cnange 3 (grafted from 3044bbf6fe3542b86d0a1a84b7455d76928b559b)
|       [e58f524b1203] <release>
|
o       * a.txt:
|       Cnange 1
|       [23d4aaf0c632] <release>
|
o       * Release branch created
|       [9f39dda2e0d9] <release>
|
| o     * c.txt, cd.txt:
| |     Cnange 4
| |     [c5523fade515]
| |
| o     * b.txt:
| |     Edit 2
| |     [7efeb998f47e]
| |
| o     * a.txt:
| |     Edit 1
| |     [4f2e0bffed8a]
| |
| o     * c.txt:
| |     Cnange 3
| |     [3044bbf6fe35]
| |
| o     * b.txt:
| |     Cnange 2
| |     [278066927656]
| |
| o     * a.txt:
|/      Cnange 1
|       [e233699bf798]
|
o       * .hgignore:
        Initial structure
        [3bf949e66c66]

(grafted changesets 1,3,6. Only changeset 3 grafted with --log added. Note unchanged commit-message for 1 and 6)

and this repository after all grafting in TortoiseHG

ContentLicense: CC BY-SA 4.0


答:
I would not store it at all.

What you want to use here is a "VIEW". Not a new table.
The view is the result of a query, kind of a virtual table.

Last: think hard about your architecture, your solution might not scale well on an RDBMS

Title: Where to store average value in db?


问:
What is a good way for Tomcat to interact with another Java application running on the local machine
I'm new to using Java within a web environment. At the moment I have a Java application that we run on a local machine, we'll call it the server app. We want to add the ability to communicate with this application by means of a RESTful interface.

I've been playing around with Tomcat and Glassfish and I have something that sort of works, but I'm certain I'm doing things in a weird way. I have a listener in the web application that creates an instance of my server application every time Tomcat is started.

When a connection is created the servlet grabs the instance of this server application so I can interact with it and pass data to a jsp. I can't help but feel this isn't a conventional approach.

I'm leaning towards just running the server jar entirely separately and using sockets on the local machine for the servlets to interact, but I can't help but think this is overkill. I've looked around and it looks like RMI might be a solution, but I'm unfamiliar with it.

Here is what I need to be able to do:

Tomcat needs to be running to accept REST requests

I need a way for the web application to check to see if the server app is running

I need the web app to be able to get an instance of the server app so that I can call it's methods or at least send it some JSON

Overall I think it's a fairly basic task, I'm just getting a bit lost trying to find a good way to organize my project.

Should I run the server app outside of the Tomcat environment and just use sockets and some JSON?

Should I run the server app outside of Tomcat and use RMI (will require some research, but that's no big deal)

Should I keep the server app within the Tomcat environment like I have it currently?

答:
Just use external IP to to interact with server machine, means u can pass.

1) start the Remote server (tomcat)

2) check the network , if Client and server in same network use internal ip otherwise use external ip.


问:
Entity Framework Lookup Tables
I am coming from working with ADO.net DataSets and feel fairly comfortable with how they work. Mainly, I usually have a DATA table with a large number of REF tables for lookups.

In DataSets it was fairly simple to define a query and some access functions to get a REF table bound to a dataset or a class. I could also create a table in the dataset that was comprised of a large number of tables joined together.

However, this seems like not the norm in the entity structure. Usually in tutorials, I see people adding entries to a table without any lookups which does not work for my database model.

What are my misconceptions and assumptions here?

答:
For implicit relationship generation when creating a database-first model in Entity Framework, the tables must have primary keys and reference the other tables' primary keys with foreign keys.

If you like having the joins kept inside in the SQL layer (in code, I meant, most times LINQ creates a SQL join in the statement), create a stored procedure and map that procedure in EF, which can just get called as a function call once mapped.  The select results from the procedure would map to an IEnumerable of "usp_myprocnameResults" entity.

A nice little example:
http://www.entityframeworktutorial.net/stored-procedure-in-entity-framework.aspx

```<code>using (var context = new SchoolDBEntities())
        {
            var courses = context.GetCoursesByStudentId(1);

            foreach (Course cs in courses)
                Console.WriteLine(cs.CourseName);
        }
</code>```

Title: Entity Framework Lookup Tables

Body:
For implicit relationship generation when creating a database-first model in Entity Framework, the tables must have primary keys and reference the other tables' primary keys with foreign keys.

If you like having the joins kept inside in the SQL layer (in code, I meant, most times LINQ creates a SQL join in the statement), create a stored procedure and map that procedure in EF, which can just get called as a function call once mapped.  The select results from the procedure would map to an IEnumerable of "usp_myprocnameResults" entity.

A nice little example:
http://www.entityframeworktutorial.net/stored-procedure-in-entity-framework.aspx

using (var context = new SchoolDBEntities())
        {
            var courses = context.GetCoursesByStudentId(1);

            foreach (Course cs in courses)
                Console.WriteLine(cs.CourseName);
        }


问:
Do you actually write 'clean code'?
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

答:
Honestly it depends. I like how everyone spouts the party line about how "anything less than clean well documented code is a sheer travesty!", but I work in a business with ridiculous deployment cycles and zero oversight: I do the best I can, but I write so much code it's extremely difficult to write the clean perfect code that everyone else claims they write.

I try to write code that can be easily maintained by someone who has roughly my ability. I comment the tricky parts, I name the programs, variables, and classes friendly names, I deploy, and I move on. I don't have time to do anything else.

Sometimes I feel a bit guilty about it, but not very. You should see some of the horrors I deal with on a daily basis. Decades of custom code in obscure languages with zero documentation. One of my coworkers develops exclusively in Visual Basic 6.0 and deploys cryptically named binaries all over the place. The woman I replaced programmed exclusively in RPG.

It's just extremely difficult for me to believe, as much horrible crap as I've seen in my years as a programmer, that everyone only generates clean code.

Title: Do you actually write 'clean code'?


问:
TDD, configuration management, configuration patterns (PHP)
I'm writing a PHP application, following test driven development principles.

I want two different configurations: one for development, and one for production.

I will be continually expanding the application's features, so one problem is I don't want the production credentials/configuration to be overwritten each time I upload an upgrade. This is just one heuristic. And it could be done 100 different ways. I can't see the wood for the trees, I need help!

Example 1: the application interracts with Ebay's API. For the application to authenticate itself with Ebay, it needs to submit authentication keys. But I'll need two sets of keys: one for development in Ebay's sandbox, and another for production. Eventually these will be stored a database or similar, since they expire and need renewing, but pretend that's not the case - assume they are static.

Example 2: Database host, name and credentials which would be different in testing and production

I'm having trouble articulating my question. In short, want to follow TDD best practice.

My instinct would be to have a configuration file which is read by some class. That gives two options:

Either there would be two files, one for tests and one for production, or

just one config file, who's contents would be altered for production.

But say we choose option 1, we're back to square one, because somewhere there needs to be a setting saying whether this the test or production environment.

And say we choose option 2, the file's location would still need(?) to be hard coded somewhere.

And then there's the scenario where objects need to be swapped depending on whether it's production or development. AFAIK the factory pattern solves this, but again, somewhere, the code needs to be told what environment we're in, and/or which of the two classes to use.

In books I've read, the principle I think is to treat the application as an onion, feeding in configuration information to the application so the whole application is context-independent. So for a command-line tool, configuration could be given by command line arguments. But how might this be done for a Java Swing application, or a PHP web app?

答:
One solution that sounds vaguely reasonable stems from this 12 factor methodology page on configuration.

The most focused guidance I have found so far is here in the 12 factor methodology. They suggest that such configurations should be stored in environment variables. But how would that be done in PHP? Here it is suggested to use a .htaccess file.


答: One solution I've used in the past is to have the application use the hostname of the machine it's running on to locate the configuration file, so if it's running on a machine called www7, it'll load config.www7.inc, whereas if it's running on minerva it'll load config.minerva.inc.  It takes a moment to set up a new machine, but after that it's pretty easy.

Title: TDD, configuration management, configuration patterns (PHP)

Body:
I'm writing a PHP application, following test driven development principles.

I want two different configurations: one for development, and one for production.

I will be continually expanding the application's features, so one problem is I don't want the production credentials/configuration to be overwritten each time I upload an upgrade. This is just one heuristic. And it could be done 100 different ways. I can't see the wood for the trees, I need help!

Example 1: the application interracts with Ebay's API. For the application to authenticate itself with Ebay, it needs to submit authentication keys. But I'll need two sets of keys: one for development in Ebay's sandbox, and another for production. Eventually these will be stored a database or similar, since they expire and need renewing, but pretend that's not the case - assume they are static.

Example 2: Database host, name and credentials which would be different in testing and production

I'm having trouble articulating my question. In short, want to follow TDD best practice.

My instinct would be to have a configuration file which is read by some class. That gives two options:

Either there would be two files, one for tests and one for production, or

just one config file, who's contents would be altered for production.

But say we choose option 1, we're back to square one, because somewhere there needs to be a setting saying whether this the test or production environment.

And say we choose option 2, the file's location would still need(?) to be hard coded somewhere.

And then there's the scenario where objects need to be swapped depending on whether it's production or development. AFAIK the factory pattern solves this, but again, somewhere, the code needs to be told what environment we're in, and/or which of the two classes to use.

In books I've read, the principle I think is to treat the application as an onion, feeding in configuration information to the application so the whole application is context-independent. So for a command-line tool, configuration could be given by command line arguments. But how might this be done for a Java Swing application, or a PHP web app?


答:
You don't need a setting that says if you are in development or production or not. You just need settings that tell your application how to handle certain things. API keys, database connection strings,... these are all basic 'read this value and use it' things and this is the kind of stuff that configuration files are good at.

It's a little different if your implementation differs. For example, let's say that you want your development environment to write e-mails to a logging directory and the production environment to actually mail them to the recipient. You write all your code against an interface ('IMailer') and write two implementations: SMTPMailer and LogMailer. Your config file contains an entry that says what implementation IMailer should use. For development/testing environment, you simply have that entry point to the LogMailer. Look into IoC and IoC frameworks for that.


答: Without seeing the actual code or tests it's hard to say, but why do you need to actually use the service in the test? You'd be better off mocking the ebay API and not worrying about live/production differences.</p>


问:
Context specific API updates to developer
Let's say I have a API with regular updates and many developer who are using the API. Whenever the API updates I don't want to bother the developers with all the change updates. I want to send them updates about only the functions or classes that they are using in their code.

I have a faint idea, but not sure if this would work.

A service which will have an index of all the changes made to the files functions based on the git commits in the last day.

A module or plugin on the client side(where the API resides) which will check with this service on a cron run regarding the changes made to the API, compare it with its internal index of files and functions used and send updates to the developer if there is a match.

Is there something implemented on these lines already? If not what would be the right way to go forward.

答:
I would consider this to be a solution in search of a problem. I've never seen developers care that a changelog contains extra information - they fall into 2 broad groups, those who don't read the changelog anyway and those who read it all to see what's been happening.

What you can do is make the changelog easier to read and parse.

I would simply categorise the changes in each release, possibly by including the API function or class or area that is changes, and mark bugs or features.
eg. Jenkins changelog has coloured dots for butgs, features, major bugs etc so you can see at a glance if an update can be ignored or needs to be applied soon. Boost's changelog has groups for bugfixes, general changes or breaking changes.

What both these lack is a marker to show which area has been changed. Given such a thing (eg a boost which library the change applies to) would be just as good as a customised changelog per developer, significantly easier to create and maintain, and would satisfy the curiosity of those dev who do read changelogs.

Oh, and some devs will not be using a particular API because of a lack of feature or bug.. how will they be informed when the API is enhanced or fixed to make it suitable for them to want to start using it if they can't see it in the changelog?!


答:
A very clean way is using Git:

Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.

For more information and downloads: https://git-scm.com

With Git you use branches, such as develop, master, feature/, etc. Read more here: https://www.atlassian.com/git/tutorials/comparing-workflows

Store production config in the master branch, the development config in develop branch, etc.


问:
Why Microsoft’s Web API is named as ASP.Net Web API
ASP.Net is Active Server Pages using .Net Framework

Wikipedia says

It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology.

While answering this question following thought came to me – why Microsoft named it’s Web API as “ASP.Net Web API”. There are no Pages involved in Web API. Then why do some people call it as “Active Server Pages .Net Web Api” ?

I believe there are some fundamental features of ASP.Net shared with Web API. So what are they?

Another observation - why is the tag in programmers naming it as "asp.net-mvc-web-api"?

Reference:

ScottGu's Blog- ASP.NET Web API

答:
While their earlier attempts at .Net API were under the WCF namespaces (we wont go into asmx services, they just failed) people found it much easier to use MVC controller classes and route patterns to do rest style APIs and WCF was always a bit awkward at simple rest as it was designed around a bunch of complex soap or binary use cases like replacing remoting.

Many use cases for APIs shifted toward sites and services consuming them and keeping the API in a completely separate app was tedious, so over time the WebAPI style apis have moved closer and closer to being the same thing, in the same namespaces and event model and MVC controllers.  If you were working in the guts of security or httpmodules at time time the designation of which event model you were stuck with was a very important detail in what you needed to implement manually to accomplish a task.  Saying that they are part of the ASP pattern was important before the push to unify those namespaces.

The active server pages name itself goes back to the mid 90's and was mostly a designation between pages that did something through script versus cbi-bin where dlls just took over the whole process.

If you ignore the original meaning of the name and look at it as a category that has evolved over the course of almost 20 years it does make some sense.


问:
Is this considered an implementation of the Template Method design pattern?
Please consider a StringBank class. This class holds a list of Strings and can return them to the client.

It's code (irrelevant stuff omitted):

```<code>abstract class StringBank{

    List<String> strings;

    public List<String> getStrings(){

        for(String string : strings){
            if(!stringValid(string)){
                strings.remove(string);
            }
        }

        return strings;

    }

    public abstract boolean stringValid(String s);

}
</code>```

As you can see, stringValid is an abstract method, meant to be implemented by the subclasses. This way subclasses serve as 'filters' of the string bank, filtering out invalid strings (e.g. a particular subclass may return false for strings that end with an 'a').

My question is: is this considered an implementation of the Template Method design pattern?

The purpose of Template Method is to define steps of an algorithm in an abstract superclass, and have the subclasses define the implementation of some of these steps.

Usually, the 'template method' - where the algorithm is defined, would look something like this:

```<code>void algorithm(){
    step1(); // implemented in this class
    step2(); // implemented in this class
    step3(); // abstract method, implemented in subclasses.
    step4(); // implemented in this class
}
</code>```

However in StringBank, the algorithm is very simple, so it only involves one method call: stringValid(). The rest of the steps of the algorithm are defined in the method itself (looping through the strings, removing strings and returning them).

getStrings() doesn't really 'look like' a 'template method', so I'm not sure if this is considered a Template Method pattern implementation.

The algorithm could be described as:

For each string:

1.1. Check if valid. (implemented by the subclasses).

1.2. If invalid, remove from list.

Return list of strings.

Would you define the implementation I described as an implementation of the Template Method design pattern, even though getStrings() doesn't 'feel' like a classic template method?

答:
This is the template method pattern. In this example though, composition should be preferred over inheritence; use the strategy pattern.

Do not make your StringBank abstract, but give it a string validator filter function as parameter.


问:
White Boards -- Who Uses Them?
So as both a full-time programmer and hobbyist as well (developing my own things for personal use and maybe to sell one day), I feel that me purchasing a big white board to hang in my room at home or something would be very useful.

Does anyone here have one as well, to use for high level designs (UML, Architecture, etc.) and things like very early UI mockups, etc.?

If you guys do have them, which ones have you bought? I can't seem to pin one that would be good for home use and I'm not sure of the pricing/other things.

Thanks!

答:
I use the whiteboard for everything. It seems to help me work through problems much more easily and I find myself thinking about ideas much deeper when using a whiteboard.

If you're put off by the prices of large whiteboards, they have paint that you can use to cover an entire wall. Then you're able to simply draw on the walls. I haven't done it myself but a co-worker has and he swears by it. Here is an example.

Title: White Boards -- Who Uses Them?


问:
Are data type declarators like "int" and "char" stored in RAM when a C program executes?
When a C program is running, the data is stored on the heap or the stack. The values are stored in RAM addresses. But what about the type indicators (e.g., int or char)? Are they also stored?

Consider the following code:

```<code>char a = 'A';
int x = 4;
</code>```

I read that A and 4 are stored in RAM addresses here. But what about a and x? Most confusingly, how does the execution know that a is a char and x is an int? I mean, is the int and char mentioned somewhere in RAM?

Let's say a value is stored somewhere in RAM as 10011001; if I am the program which executes the code, how will I know whether this 10011001 is a char or an int?

What I don't understand is how the computer knows, when it reads a variable's value from an address such as 10001, whether it is an int or char. Imagine I click on a program called anyprog.exe. Immediately the code starts executing. Does this executable file include information on whether the variables stored are of the type int or char?

答:
In C, it is not. Other languages (e.g., Lisp, Python) have dynamic types but C is statically-typed. That means that your program must know what type the data is to properly interpret is as a character, an integer, etc.

Usually the compiler takes care of this for you, and if you do something wrong, you'll get a compile-time error (or warning).


答:
It doesn't. Once C is compiled to machine code, the machine just sees a bunch of bits. How those bits are interpreted depends on what operations are being performed on them as opposed to some additional metadata.

The types you enter in your source code are just for the compiler. It takes what type you say the data is supposed to be and, to the best of its ability, tries to make sure that that data is only used in ways that make sense. Once the compiler has done as good a job as it can in checking the logic of your source code, it converts it to machine code, and discards the type data, because machine code has no way of representing that (at least on most machines).

Title: Are data type declarators like "int" and "char" stored in RAM when a C program executes?

Body:
When a C program is running, the data is stored on the heap or the stack. The values are stored in RAM addresses. But what about the type indicators (e.g., int or char)? Are they also stored?

Consider the following code:

```<code>char a = 'A';
int x = 4;
</code>```

I read that A and 4 are stored in RAM addresses here. But what about a and x? Most confusingly, how does the execution know that a is a char and x is an int? I mean, is the int and char mentioned somewhere in RAM?

Let's say a value is stored somewhere in RAM as 10011001; if I am the program which executes the code, how will I know whether this 10011001 is a char or an int?

What I don't understand is how the computer knows, when it reads a variable's value from an address such as 10001, whether it is an int or char. Imagine I click on a program called anyprog.exe. Immediately the code starts executing. Does this executable file include information on whether the variables stored are of the type int or char?


问:
Using static classes as namespaces
I have seen other developers using static classes as namespaces

```<code>public static class CategoryA
{
    public class Item1
    {
        public void DoSomething() { }
    }
    public class Item2
    {
        public void DoSomething() { }
    }
}

public static class CategoryB
{
    public class Item3
    {
        public void DoSomething() { }
    }
    public class Item4
    {
        public void DoSomething() { }
    }
}
</code>```

To instantiate the inner classes, it will look like the following

```<code>CategoryA.Item1 item = new CategoryA.Item1();
</code>```

The rationale is that namespaces can be hidden by using the "using" keyword. But by using the static classes, the outer-layer class names have to be specified, which effectively preserves the namespaces.

Microsoft advises against that in the guidelines. I personally think it impacts the readability. What are your thoughts?

答:
I know that this is an old question, but one very valid reason to use a class as a namespace (a non-static one at that) is that C# does not support the definition of parametric or generic namespaces.  I've written up a blog post on this very topic here: http://tyreejackson.com/generics-net-part5-generic-namespaces/.

The gist of it is, when using generics to abstract huge swaths of boilerplate code, it is sometimes necessary to share multiple generic parameters between related classes and interfaces.  The conventional way to do this would be to redefine the generic parameters, constraints and all in each interface and class signature.  Over time this can lead to a proliferation of parameters and constraints not to mention constantly having to qualify the related types by forwarding the type parameters from one type to the type arguments of the related type.

Using an outer Generic class and nesting the related types within can dramatically DRY up the code and simplify its abstraction.  One can then derive the parametric namespace class with a concrete implementation that supplies all of the concrete details.

Here is a trivial example:

```<code>public  class   Entity
                <
                    TEntity,
                    TDataObject,
                    TDataObjectList,
                    TIBusiness,
                    TIDataAccess,
                    TIdKey
                >
        where   TEntity         : Entity<TEntity, TDataObject, TDataObjectList, TIBusiness, TIDataAccess, TIdKey>, subclassed
        where   TDataObject     : Entity<TEntity, TDataObject, TDataObjectList, TIBusiness, TIDataAccess, TIdKey>.BaseDataObject, subclassed
        where   TDataObjectList : Entity<TEntity, TDataObject, TDataObjectList, TIBusiness, TIDataAccess, TIdKey>.BaseDataObjectList, subclassed
        where   TIBusiness      : Entity<TEntity, TDataObject, TDataObjectList, TIBusiness, TIDataAccess, TIdKey>.IBaseBusiness
        where   TIDataAccess    : Entity<TEntity, TDataObject, TDataObjectList, TIBusiness, TIDataAccess, TIdKey>.IBaseDataAccess
{

    public class    BaseDataObject
    {
        public TIdKey Id { get; set; }
    }

    public class BaseDataObjectList : Collection<TDataObject> {}

    public interface IBaseBusiness
    {

        TDataObject     LoadById(TIdKey id);
        TDataObjectList LoadAll();
        void            Save(TDataObject item);
        void            Save(TDataObjectList items);
        void            DeleteById(TIdKey id);
        bool            Validate(TDataObject item);
        bool            Validate(TDataObjectList items);

    }

    public interface IBaseDataAccess
    {

        TDataObject     LoadById(TIdKey id);
        TDataObjectList LoadAll();
        void            Save(TDataObject item);
        void            Save(TDataObjectList items);
        void            DeleteById(TIdKey id);

    }

}
</code>```

Used like this:

```<code>public  class   User
:
                Entity
                <
                    User,
                    User.DataObject,
                    User.DataObjectList,
                    User.IBusiness,
                    User.IDataAccess,
                    Guid
                >
{
    public class DataObject : BaseDataObject
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class DataObjectList : BaseDataObjectList {}

    public interface IBusiness : IBaseBusiness
    {
        void DeactivateUserById(Guid id);
    }

    public interface IDataAcccess : IBaseDataAccess {}
}
</code>```

Consume the derivatives like this:

```<code>public class EntityConsumer
{
    private User.IBusiness       userBusiness;
    private Permission.IBusiness permissionBusiness;

    public EntityConsumer(User.IBusiness userBusiness, Permission.IBusiness permissionBusiness) { /* assign dependencies */ }

    public void ConsumeEntities()
    {
        var users       = new User.DataObjectList();
        var permissions = this.permissionBusiness.LoadAll();

        users.Add
        (new User.DataObject()
        {
            // Assign property values
        });

        this.userBusiness.Save(users);

    }
}
</code>```

The benefit to writing the types this way is added type safety and less casting of types in the abstract classes.  Its the equivalent of ArrayList vs List<T> on a larger scale.

Title: Using static classes as namespaces

Body:
I know that this is an old question, but one very valid reason to use a class as a namespace (a non-static one at that) is that C# does not support the definition of parametric or generic namespaces.  I've written up a blog post on this very topic here: http://tyreejackson.com/generics-net-part5-generic-namespaces/.

The gist of it is, when using generics to abstract huge swaths of boilerplate code, it is sometimes necessary to share multiple generic parameters between related classes and interfaces.  The conventional way to do this would be to redefine the generic parameters, constraints and all in each interface and class signature.  Over time this can lead to a proliferation of parameters and constraints not to mention constantly having to qualify the related types by forwarding the type parameters from one type to the type arguments of the related type.

Using an outer Generic class and nesting the related types within can dramatically DRY up the code and simplify its abstraction.  One can then derive the parametric namespace class with a concrete implementation that supplies all of the concrete details.

Here is a trivial example:

public  class   Entity
                <
                    TEntity,
                    TDataObject,
                    TDataObjectList,
                    TIBusiness,
                    TIDataAccess,
                    TIdKey
                >
        where   TEntity         : Entity<TEntity, TDataObject, TDataObjectList, TIBusiness, TIDataAccess, TIdKey>, subclassed
        where   TDataObject     : Entity<TEntity, TDataObject, TDataObjectList, TIBusiness, TIDataAccess, TIdKey>.BaseDataObject, subclassed
        where   TDataObjectList : Entity<TEntity, TDataObject, TDataObjectList, TIBusiness, TIDataAccess, TIdKey>.BaseDataObjectList, subclassed
        where   TIBusiness      : Entity<TEntity, TDataObject, TDataObjectList, TIBusiness, TIDataAccess, TIdKey>.IBaseBusiness
        where   TIDataAccess    : Entity<TEntity, TDataObject, TDataObjectList, TIBusiness, TIDataAccess, TIdKey>.IBaseDataAccess
{

    public class    BaseDataObject
    {
        public TIdKey Id { get; set; }
    }

    public class BaseDataObjectList : Collection<TDataObject> {}

    public interface IBaseBusiness
    {

        TDataObject     LoadById(TIdKey id);
        TDataObjectList LoadAll();
        void            Save(TDataObject item);
        void            Save(TDataObjectList items);
        void            DeleteById(TIdKey id);
        bool            Validate(TDataObject item);
        bool            Validate(TDataObjectList items);

    }

    public interface IBaseDataAccess
    {

        TDataObject     LoadById(TIdKey id);
        TDataObjectList LoadAll();
        void            Save(TDataObject item);
        void            Save(TDataObjectList items);
        void            DeleteById(TIdKey id);

    }

}

Used like this:

public  class   User
:
                Entity
                <
                    User,
                    User.DataObject,
                    User.DataObjectList,
                    User.IBusiness,
                    User.IDataAccess,
                    Guid
                >
{
    public class DataObject : BaseDataObject
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class DataObjectList : BaseDataObjectList {}

    public interface IBusiness : IBaseBusiness
    {
        void DeactivateUserById(Guid id);
    }

    public interface IDataAcccess : IBaseDataAccess {}
}

Consume the derivatives like this:

public class EntityConsumer
{
    private User.IBusiness       userBusiness;
    private Permission.IBusiness permissionBusiness;

    public EntityConsumer(User.IBusiness userBusiness, Permission.IBusiness permissionBusiness) { /* assign dependencies */ }

    public void ConsumeEntities()
    {
        var users       = new User.DataObjectList();
        var permissions = this.permissionBusiness.LoadAll();

        users.Add
        (new User.DataObject()
        {
            // Assign property values
        });

        this.userBusiness.Save(users);

    }
}

The benefit to writing the types this way is added type safety and less casting of types in the abstract classes.  Its the equivalent of ArrayList vs List<T> on a larger scale.


答:
To address the question you've posted in several comments(which I think you should edit into your post):

What I don't understand is how does the computer know lets when it reads a variable's value from and address such as 10001 if is an int or char. Imagine I click on a program called anyprog.exe. Immediately the code starts executing. Does this exe file include information about if the variables are stored as in or char?

So lets put some code to it.  Let's say you write:

```<code>int x = 4;
</code>```

And let's assume that it gets stored in RAM:

```<code>0x00010004: 0x00000004
</code>```

The first part being the address, the second part being the value.  When your program(which executes as machine code) runs, all it sees at 0x00010004 is the value 0x000000004.  It doesn't 'know' the type of this data, and it doesn't know how it is 'supposed' to be used.

So, how does your program figure out the right thing to do?  Consider this code:

```<code>int x = 4;
x = x + 5;
</code>```

We have a read and a write here.  When your program reads x from memory, it finds 0x00000004 there.  And your program knows to add 0x00000005 to it.  And the reason your program 'knows' this is a valid operation, is because the compiler ensures that the operation is valid through type-safety.  Your compiler has already verified that you can add 4 and 5 together.  So when your binary code runs(the exe), it doesn't have to make that verification.  It just executes each step blindly, assuming everything is OK(bad things happen when they are in fact, not OK).

Another way to think of it is like this.  I give you this information:

```<code>0x00000004: 0x12345678
</code>```

Same format as before - address on the left, value on the right.  What type is the value?  At this point, you know just as much information about that value as your computer does when it's executing code.  If I told you to add 12743 to that value, you could do it.  You have no idea what the repercussions of that operation will be on the whole system, but adding two numbers is something you're really good at, so you could do it.  Does that make the value an int?  Not necessarily - All you see is two 32-bit values and the addition operator.

Perhaps some of the confusion is then getting the data back out.  If we have:

```<code>char A = 'a';
</code>```

How does the computer know to display a in the console?  Well, there are a lot of steps to that.  The first is to go to As location in memory and read it:

```<code>0x00000004: 0x00000061
</code>```

The hex value for a in ASCII is 0x61, so the above might be something you'd see in memory.  So now our machine code knows the integer value.  How does it know to turn the integer value into a character to display it?  Simply put, the compiler made sure to put in all of the necessary steps to make that transition.  But your computer itself(or the program/exe) has no idea what the type of that data is.  That 32-bit value could be anything - int, char, half of a double, a pointer, part of an array, part of a string, part of an instruction, etc.

Here's a brief interaction your program (exe) might have with the computer/operating system.

Program: I want to start up.  I need 20 MB of memory.

Operating System: finds 20 free MB of memory that aren't in use and hands them over

(The important note is that this could return any 20 free MB of memory, they don't even have to be contiguous.  At this point, the program can now operate within the memory it has without talking to the OS)

Program: I'm going to assume that the first spot in memory is a 32-bit integer variable x.

(The compiler makes sure that accesses to other variables will never touch this spot in memory.  There's nothing on the system that says the first byte is variable x, or that variable x is an integer.  An analogy: you have a bag.  You tell people that you will only put yellow colored balls in this bag.  When someone later pulls something out of the bag, then it would be shocking that they would pull out something blue or a cube - something has gone horribly wrong.  The same goes for computers: your program is now assuming the first memory spot is variable x and that it is an integer.  If something else is ever written over this byte of memory or it's assumed to be something else -  something horrible has happened.  The compiler ensures these kinds of things don't happen)

Program: I will now write 2 to the first four bytes where I'm assuming x is at.

Program: I want to add 5 to x.

Reads the value of X into a temporary register

Adds 5 to the temporary register

Stores the value of the temporary register back into the first byte, which is still assumed to be x.

Program: I'm going to assume the next available byte is the char variable y.

Program: I will write a to variable y.

A library is used to find the byte value for a

The byte is written to the address the program is assuming is y.

Program: I want to display the contents of y

Reads the value in the second memory spot

Uses a library to convert from the byte to a character

Uses graphics libraries to alter the console screen(setting pixels from black to white, scrolling one line, etc)

(And it goes on from here)

What you're probably getting hung up on is - what happens when the first spot in memory is no longer x? or the second is no longer y?  What happens when someone reads x as a char or y as a pointer?  In short, bad things happen.  Some of these things have well-defined behavior, and some have undefined behavior.  Undefined behavior is exactly that - anything can happen, from nothing at all, to crashing the program or the operating system.  Even well-defined behavior can be malicious.  If I can change x to a pointer to my program, and get your program to use it as a pointer, then I can get your program to start executing my program - which is exactly what hackers do.  The compiler is there to help make sure we don't use int x as a string, and things of that nature.  The machine code itself is not aware of types, and it will only do what the instructions tell it to do.  There is also a large amount of information that's discovered at run-time: which bytes of memory is the program allowed to use?  Does x start at the first byte or the 12th?

But you can imagine how horrible it would be to actually write programs like this(and you can, in the assembly language).  You start off by 'declaring' your variables - you tell yourself that byte 1 is x, byte 2 is y, and as you write each line of code, loading and storing registers, you (as a human) have to remember which one is x and which one is y, because the system has no idea.  And you (as a human) have to remember what types x and y are, because again - the system has no idea.

Body:
To address the question you've posted in several comments(which I think you should edit into your post):

What I don't understand is how does the computer know lets when it reads a variable's value from and address such as 10001 if is an int or char. Imagine I click on a program called anyprog.exe. Immediately the code starts executing. Does this exe file include information about if the variables are stored as in or char?

So lets put some code to it.  Let's say you write:

int x = 4;

And let's assume that it gets stored in RAM:

0x00010004: 0x00000004

The first part being the address, the second part being the value.  When your program(which executes as machine code) runs, all it sees at 0x00010004 is the value 0x000000004.  It doesn't 'know' the type of this data, and it doesn't know how it is 'supposed' to be used.

So, how does your program figure out the right thing to do?  Consider this code:

int x = 4;
x = x + 5;

We have a read and a write here.  When your program reads x from memory, it finds 0x00000004 there.  And your program knows to add 0x00000005 to it.  And the reason your program 'knows' this is a valid operation, is because the compiler ensures that the operation is valid through type-safety.  Your compiler has already verified that you can add 4 and 5 together.  So when your binary code runs(the exe), it doesn't have to make that verification.  It just executes each step blindly, assuming everything is OK(bad things happen when they are in fact, not OK).

Another way to think of it is like this.  I give you this information:

0x00000004: 0x12345678

Same format as before - address on the left, value on the right.  What type is the value?  At this point, you know just as much information about that value as your computer does when it's executing code.  If I told you to add 12743 to that value, you could do it.  You have no idea what the repercussions of that operation will be on the whole system, but adding two numbers is something you're really good at, so you could do it.  Does that make the value an int?  Not necessarily - All you see is two 32-bit values and the addition operator.

Perhaps some of the confusion is then getting the data back out.  If we have:

char A = 'a';

How does the computer know to display a in the console?  Well, there are a lot of steps to that.  The first is to go to As location in memory and read it:

0x00000004: 0x00000061

The hex value for a in ASCII is 0x61, so the above might be something you'd see in memory.  So now our machine code knows the integer value.  How does it know to turn the integer value into a character to display it?  Simply put, the compiler made sure to put in all of the necessary steps to make that transition.  But your computer itself(or the program/exe) has no idea what the type of that data is.  That 32-bit value could be anything - int, char, half of a double, a pointer, part of an array, part of a string, part of an instruction, etc.

Here's a brief interaction your program (exe) might have with the computer/operating system.

Program: I want to start up.  I need 20 MB of memory.

Operating System: finds 20 free MB of memory that aren't in use and hands them over

(The important note is that this could return any 20 free MB of memory, they don't even have to be contiguous.  At this point, the program can now operate within the memory it has without talking to the OS)

Program: I'm going to assume that the first spot in memory is a 32-bit integer variable x.

(The compiler makes sure that accesses to other variables will never touch this spot in memory.  There's nothing on the system that says the first byte is variable x, or that variable x is an integer.  An analogy: you have a bag.  You tell people that you will only put yellow colored balls in this bag.  When someone later pulls something out of the bag, then it would be shocking that they would pull out something blue or a cube - something has gone horribly wrong.  The same goes for computers: your program is now assuming the first memory spot is variable x and that it is an integer.  If something else is ever written over this byte of memory or it's assumed to be something else -  something horrible has happened.  The compiler ensures these kinds of things don't happen)

Program: I will now write 2 to the first four bytes where I'm assuming x is at.

Program: I want to add 5 to x.

Reads the value of X into a temporary register

Adds 5 to the temporary register

Stores the value of the temporary register back into the first byte, which is still assumed to be x.

Program: I'm going to assume the next available byte is the char variable y.

Program: I will write a to variable y.

A library is used to find the byte value for a

The byte is written to the address the program is assuming is y.

Program: I want to display the contents of y

Reads the value in the second memory spot

Uses a library to convert from the byte to a character

Uses graphics libraries to alter the console screen(setting pixels from black to white, scrolling one line, etc)

(And it goes on from here)

What you're probably getting hung up on is - what happens when the first spot in memory is no longer x? or the second is no longer y?  What happens when someone reads x as a char or y as a pointer?  In short, bad things happen.  Some of these things have well-defined behavior, and some have undefined behavior.  Undefined behavior is exactly that - anything can happen, from nothing at all, to crashing the program or the operating system.  Even well-defined behavior can be malicious.  If I can change x to a pointer to my program, and get your program to use it as a pointer, then I can get your program to start executing my program - which is exactly what hackers do.  The compiler is there to help make sure we don't use int x as a string, and things of that nature.  The machine code itself is not aware of types, and it will only do what the instructions tell it to do.  There is also a large amount of information that's discovered at run-time: which bytes of memory is the program allowed to use?  Does x start at the first byte or the 12th?

But you can imagine how horrible it would be to actually write programs like this(and you can, in the assembly language).  You start off by 'declaring' your variables - you tell yourself that byte 1 is x, byte 2 is y, and as you write each line of code, loading and storing registers, you (as a human) have to remember which one is x and which one is y, because the system has no idea.  And you (as a human) have to remember what types x and y are, because again - the system has no idea.


答:
Your problem has a solution on other RDBMS (postgresql/oracle) without creating any table : a materialized view

Update it with your scheduled task with refresh materialized view

Since you got MySQL you can only simulate a materialized view via a temporary table. :

http://www.materialized.info/ or

https://dev.mysql.com/doc/refman/5.0/en/create-view.html (search for Rafael Palacios comment)

Title: Where to store average value in db?


问:
sort multidimensional array recursively - is this reasonable
In a nutshell, I needed to traverse any number of dimensions of a multidimensional array (or not) and I wanted the process to be as predictable as possible (in order to proliferate the pattern throughout a larger body of work). So I came up with this - it feels too easy. Are there any performance sinks using ksort like this that I'm not aware of? Is there a cleaner / more performant way to accomplish this? My goal was to sort (numerically) a vast body of misshapen data groups for the purpose of lets say a tiered score system with nested, associative values which some are arrays of more associative information (think a really complex golf card or something similar).

Is this bad practice? :

```<code>function recursive_key_sort(&$by_ref_array)
{
    ksort($by_ref_array, SORT_NUMERIC );
    foreach ($by_ref_array as $key => $value) {
        if (is_array($value))
        {
            recursive_key_sort($by_ref_array[$key]);
        }
    }
}
</code>```

didn't see a similar question so I apologize in advance - again my main interest/concern is "this seemed too easy" thanks.

答:
After some investigation, I would say this seems pretty optimal. Please see my gist here.

In the PHP file in the gist I've generated some nested arrays with unsorted keys using one function, counted the total number of keys (including keys in nested arrays) using the recursive option to count, timed sorting the array using your function above, generated a flat array with unsorted keys and timed sorting this using ksort.

I've done this for a range of different top-level keys, and each 16 times, taken the average and then run the output data through gnuplot.

You can see from the output graph that your recursive function (purple) is tending towards the ksort of the flat array(blue) to the extent that at greater than 1 million total keys, the recursive sort only takes on average about 1.5x the time of the flat sort for an equivalent number of keys.

Note that this was run on PHP 5.6.10 on ArchLinux, YMMV


答:
The computer doesn't "know" what addresses are what, but the knowledge of what's what is baked into the instructions of your program.

When you write a C program that writes and reads a char variable, the compiler creates assembly code that writes that piece of data somewhere as a char, and there is some other code somewhere else that reads a memory address and interprets it as a char. The only thing tying these two operations together is the location of that memory address.

When it comes time to read, the instructions don't say "see what data type is there", it just says something like "load that memory as a float". If the address to be read from has been changed, or something has overwritten that memory with something other than a float, the CPU will just happily load that memory as a float anyway, and all kinds of weird stuff can happen as a result.

Bad analogy time: imagine a complicated shipping warehouse, where the warehouse is memory and people picking things is the CPU. One part of the warehouse 'program' places various items on the shelf. Another program goes and grabs items off the warehouse and puts them into boxes. When they are pulled off, they are not checked, they just go into the bin. The whole warehouse functions by everything working in sync, with the right items always being in the right place at the right time, otherwise everything crashes, just like in an actual program.


问:
How should I structure these Python classes?
Base Class

I have a class called Remote. This class represents a remote machine and has properties such as ip, hostname, username, and password, as well as methods for transferring files to/from the machine and running code on the machines command line.

Classes Based on Specific VM Providers

I have multiple subclasses of Remote, such as SLRemote, for remote machines running on SoftLayer, VBRemote for machines running in Virtual Box, and potentially in the future I might create other subclasses like an AWSRemote for remote machines running on Amazon Web Services, for example.

These classes have the __init__ method set so that they can take in a few arguments specific to the VM provider and properly find an existing VM, or provision a new VM. Since this may take awhile (IE, SoftLayer takes 2-20 minutes to set up a new VM, depending on image size and network conditions), the __init__ method runs these tasks on a separate thread, and I define a __getattribute__ method which joins the creation thread if it requires that the VM be finished (IE, how can you transfer files to/from the machine if it hasn't finished provisioning?)

Classes Based on Specific Software

I also have classes like DB2Server, WASServer, and FTPServer, which represent remote machines which have specific software installed on them. It seems to me that these classes should also somehow inherit from Remote. Just like Remote, they have an ip, a hostname, a username, and a password. Just like you want to transfer files to a Remote, you want to transfer files to these classes.

Solutions I've Considered

1 - So I want to subclass Remote, right? Well, no, not really, because DB2Server could be installed on a SLRemote or a VBRemote or a AWSRemote, in addition to the generic Remote.

2 - What about multiple inheritance? Again, no, not really, because then I have to write a set of classes for inheriting from each specific VM Provider with the specific software. Plus what if you install multiple things on the same server?

3 - Currently, the design I'm going with is that the classes based on specific software being installed inherit from object (I'm using Python 2), and the __init__ method takes in a remote argument. I've written __getattribute__ and __setattr__ so that in addition to querying the object directly for attributes, it also checks the remote object for those same attributes.

But this is annoying because it requires me to write the exact same __getattribute__ and __setattr__ method in each of my specific software classes, and as my team is growing and more people are having to write classes like these, they're having to come to understand that I'm using these methods and they need to replicate that code, too. It has a bad code smell in it.

4 - As I was writing up what I'm currently doing, this just came to me (the benefits of writing out your problem on Stack Exchange... or a sticky note... or an email... or telling it to someone who knows nothing at all about the problem you're talking about). I could write a base Software class which just takes in a  Remote instance and defines the __getattribute__ and __setattr__ methods. Then DB2Server, WASServer, and FTPServer would inherit from that instead.

Other Things that I'm vaguely aware of that might help?

Metaclasses? Aspect Oriented Programming? Mix-ins? These are all concepts that I'm vaguely aware of... would any of these help me with my problem?

What is the right way of doing this? What is the standard and correct design to apply to my situation?

Getting meta with these questions now:

How can I better summarize this problem and make a helpful title for the question with it?

Is this even the right place to ask? The question doesn't involve a single full line of code, so CodeReview is definitely not the right place, and StackOverflow doesn't seem right, either.

答: It seems to me like "remote" is a property of an object, not something which defines it. In other words, have you thought about using composition rather than inheritance? For example, an AWSRemote is really a VM and a Remote, and a DB2Server could either be a specific VM or a physical machine, either locally or remotely. A DB2Server constructor could for example take an object which enables you to install and configure it, and another objects which lets you communicate with it as a user.


问:
Why does this use of IEnumerable, List, and Arrays seem to get modified when it shouldn't be?
I have started learning c# and am confused by the following feature.

The following code uses a function Algs.Combinations(n,m) to produce an IEnumerable which contains the combinations of n objects taken from m. Its implementation is exactly as can be found on the Rosetta code page for combinations. For example, applying .toList() to Algs.Combinations(2,3) would produce the list [[0,1],[0,2],[1,2]].

Now in the foreach loop I add each int[] to a new list. I also print out the values of each array(ie the combination) after turning it to a list and then using the built in ForEach. Everything works as expected.

In the next block I use the built in ForEach on my new list and it seems every int[] has become [2,2]. What is going on here? Presumably in my foreach I am not actually adding the integer array but some kind of pointer?

```<code>using System;
using System.Collections.Generic;
using System.Linq;

namespace Examples
{
    class main
    {
        public static IEnumerable<int[]> Combinations(int m, int n)
        {
            int[] result = new int[m];
            Stack<int> stack = new Stack<int>();
            stack.Push(0);

            while (stack.Count > 0)
            {
                int index = stack.Count - 1;
                int value = stack.Pop();

                while (value < n)
                {
                    result[index++] = value++;
                    stack.Push(value);
                    if (index == m)
                    {
                        yield return result;
                        break;
                    }
                }
            }
        }

        static void Main(String[] args)
        {
            var l = Combinations(2, 3);
            var newL = new List<int[]>();
            foreach (int[] combs in l)
            {
                newL.Add(combs);
                combs.ToList().ForEach(p => Console.Write(p + " ")); // prints 0 1, 0 2, 1 2
                Console.WriteLine();
            }
            newL.ForEach(p =>
            {
                p.ToList().ForEach(q => Console.Write(q + " ")); // prints 2 2, 2 2, 2 2
                Console.WriteLine();
            });
         }

    }
 }
</code>```

Googling hasn't helped so far. Any links to literature I should look at will be appreciated.

答:
Your problem is that you are only returning a single array from your Combinations function, but returning it multiple times with the values changed inside the array between each iteration.

Methods which use yield return are coroutines - in each foreach iteration they execute up to the next yield statement they find and then they exit, picking up where they left off in the next iteration. In your first foreach loop you are taking the enumerated int[] value and putting it into your newL variable - but it's always the same int[] value because Combinations only ever creates one array. The print out in the first foreach works fine because the coroutine is paused waiting for the next iteration to start.

You have a couple of options. The best option is to make your Combinations have a sane implementation, in that it returns a new object for each yield return statement. That might look something like this:

```<code>    public static IEnumerable<int[]> Combinations(int m, int n)
    {
        while (weStillHaveMoreResultsToBuild)
        {
            int[] result = new int[m];

            while (value < n)
            {
                // fill result and break out of loop when done
            }

            yield return result;
        }
    }
</code>```

Another option would be to not use yield return at all, and instead build a list inside Combinations and return that. This approach could take a lot more memory if your n and m values are large.

A third option is to make a copy of the objects returned by Combinations and store those instead:

```<code>newL.Add(combs.ToArray()); // Calling ToArray() will make a copy
</code>```

This is my least favorite option, because it requires any caller of Combinations to know that the same object will be returned multiple times but changed in each iteration.

Body:
Your problem is that you are only returning a single array from your Combinations function, but returning it multiple times with the values changed inside the array between each iteration.

Methods which use yield return are coroutines - in each foreach iteration they execute up to the next yield statement they find and then they exit, picking up where they left off in the next iteration. In your first foreach loop you are taking the enumerated int[] value and putting it into your newL variable - but it's always the same int[] value because Combinations only ever creates one array. The print out in the first foreach works fine because the coroutine is paused waiting for the next iteration to start.

You have a couple of options. The best option is to make your Combinations have a sane implementation, in that it returns a new object for each yield return statement. That might look something like this:

    public static IEnumerable<int[]> Combinations(int m, int n)
    {
        while (weStillHaveMoreResultsToBuild)
        {
            int[] result = new int[m];

            while (value < n)
            {
                // fill result and break out of loop when done
            }

            yield return result;
        }
    }

Another option would be to not use yield return at all, and instead build a list inside Combinations and return that. This approach could take a lot more memory if your n and m values are large.

A third option is to make a copy of the objects returned by Combinations and store those instead:

newL.Add(combs.ToArray()); // Calling ToArray() will make a copy

This is my least favorite option, because it requires any caller of Combinations to know that the same object will be returned multiple times but changed in each iteration.


答:
I think your main question seems to be: "If the type is erased at compile-time and not retained at runtime, then how does the computer know whether to execute code wich interprets it as an int or to execute code which interprets it as a char?"

And the answer is … the computer doesn't. However, the compiler does know, and it will have simply put the correct code in the binary in the first place. If the variable were typed as char, then the compiler wouldn't put the code for treating it as an int in the program, it would put the code to treat it is a char.

There are reasons to retain the type at runtime:

Dynamic Typing: in dynamic typing, type checking happens at runtime, so, obviously, the type has to be known at runtime. But C isn't dynamically typed, so the types can be safely erased. (Note that this is a very different scenario, though. Dynamic Types and Static Types aren't really the same thing, and in a mixed-typing language, you could still erase the static types and only keep the dynamic types.)

Dynamic Polymorphism: if you execute different code based on the runtime type, then you need to keep the runtime type around. C doesn't have dynamic polymorphism (it doesn't have any polymorphism at all, really, except in some special hard-coded cases, e.g. the + operator), so it doesn't need the runtime type for that reason. However, again, the runtime type is something different to the static type anyway, e.g. in Java, you could theoretically erase the static types and still keep the runtime type for polymorphism. Note also, that if you decentralize and specialize the type-lookup code and put it inside the object (or class), then you also don't necessarily need the runtime-type, e.g. C++ vtables.

Runtime Reflection: if you allow the program to reflect on its types at runtime, then you obviously need to keep the types at runtime. You can easily see this with Java, which keeps first-order types at runtime, but erases type arguments to generic types at compile time, so you can only reflect on the type constructor ("raw type") but not the type argument. Again, C doesn't have runtime reflection, so it doesn't need to keep the type at runtime.

The only reason to keep the type at runtime in C would be for debugging, however, debugging is usually done with the source available, and then you can simply look up the type in the source file.

Type Erasure is quite normal. It doesn't impact type safety: the types are checked at compile time, once the compiler is satisfied that the program is type-safe, the types are no longer needed (for that reason). It doesn't impact static polymorphism (aka overloading): once overload resolution is complete, and the compiler has picked the right overload, it doesn't need the types anymore. Types can also guide optimization, but again, once the optimizer has picked its optimizations based on the types, it doesn't need them anymore.

Retaining types at runtime is only required when you want to do something with the types at runtime.

Haskell is one of the most strict, most rigorous, type-safe statically typed languages, and Haskell compilers usually erase all types. (The exception being the passing of method dictionaries for type classes, I believe.)