问:
How do I support interfaces for different devices in the same input scenario?
I asked this question on SO but someone pointed out that I would be better off here. He's most likely right. So here I go!

So I just wanted an opinion. I have 2 different ways to approach the problem. Okay so I have a system that I wanna design toward the future. I have some types of objects wich takes as parameters an object implementing an Interface wich can itself contain another object Implementing another interface and so on.

In this way i have

```A(InterfaceB B)->B(InterfaceC C)->C(InterfaceD D) ...```

Until i get to a point where the object does not contain another one. Every interfaces implement a common interface. So I have

```Parent->InterfaceB   ---   Parent->InterfaceC   ---   Parent->InterfaceD```

But InterfaceD does not necessarily implement InterfaceB. Because an interface does not have only one implemention, I have multiple possible trees.

```A(InterfaceB B)->B(InterfaceC C)->C(InterfaceD D)->...```

and

```A(InterfaceB B)->B(InterfaceC Y)->Y(InterfaceZ Z)->...```

So my question is this : If i want to manage the possible trees, Am I better off using reflection to generate the possible trees on startup? Or would I be better off to hold the different trees in a xml file that I would parse on startup? I have to keep in mind that those Interface types and their implementations will keep coming on. So every time I add a new type, it has to be managed. I know both solution will work. My question is more like this : What would be the best approach to orient the system toward the future.

To add some context to the situation, here's an example of a case

All those interfaces expose an adaptor. Each adaptor may need another one to do its task. For instance, I have an adaptor wich parse some data. But then this data has to be communicated with a remote target. To do this it can use ethernet, serial port, etc... So I could have a generic parser wich takes a generic communicator. That's one of the different possibilities.

If you need some clarifications dont hesitate!

答:
I will answer your question with a question.  Why do you need to manage the trees in such a way that you need to know what contains what?

The point of interfaces is to set up an abstract contract where the user doesn't need to know what the object does and how it does it.  All the user needs to know is the interface.  Knowing what is contained in what violates the boundaries of the object.

The system should be able to unroll itself at the end without you needing to know the specific details of what contains what.


问:
How can I find all connections in a mesh network/graph?
Suppose I have a mesh of relationships, such as

Friends who trust some friends and not others

A IPv6 router that needs to locate peers across the Internet

A PGP Web Of Trust that needs two people to locate each other's trust level

I'm interested in determining not only the shortest path, but the cost of each (an arbitrary weight by be added), the nodes of each path, and other information typically used in this general purpose need.

What approaches are there to accommodate this need?  Ideally this will be something that I can run locally on a phone or computer and search a large graph in O(N) speed or better.

答:
There are 2 major algorithms that are used to compute shortest path; Dijkstra's Algorithm & Bellman-Ford. If you're looking for weighted values to be calculated as well you need to look into priority queues. You'll also need to understand the Routing Information Protocol (RIPng for IPV6) to understand just how the Routing Table is organized.

For examples of implementations of Dijkstra's Algorithm you can see the implementation here.
A Java implementation of Dijkstra's Algorithm with Fast Priority Queueing here.

And, something that looks to be a rather old page dedicated to something close to your requirements here

ContentLicense: CC BY-SA 3.0


问:
How to find bottlenecks in an application?
I'm building an application with lots of components, a lot of which are third-party so I only know what I can get from their documentation.

From time to time, by pure luck, I find out one of these components was pretty heavy and had an option to cache stuff.

I can't stop thinking that if I weren't lucky, one of these components would end up killing the performance of my app and I wouldn't have a clue what to do. I would end up adding more hardware like an idiot.

So how do you find these kind of bottlenecks? I mean I wouldn't have a nice report saying "this part is slow", like it happens with the database.

For example, today I found that a serializer I was using was heavy and wasn't being cached. Are there repeatable steps I could have followed to discover that the serializer was slowing things down?

答:
Performance tuning should be guided by observing which resource is actually critical for the execution time or for the throughput. In a multi-user multi-processing system, this is difficult to assess with a general purpose profiler and largely depends on the type of application.

The following steps should be gone through as often as necessary:

Define a performance target in terms of time and/or throughput you are aiming at.

Determine the overloaded resource (CPU, RAM, Lan, graphics board, separate database, processes/handles ...).

Find out why the overload occurs.

Change the application to reduce the load.

Back to 2. until target is reached or your time budget is exhausted

For PC-based applications, Microsoft/Sysinterals Process Explorer gives a good overview which resource might limit the performance. Use tools like top, ntop, iostat or vmstat to get an overview on Unix systems. Excessive page file traffic indicates too high memory consumption. Databases like Oracle usually have a tool to find SQL statements which cause most of the database load.

Make sure that the system under test is free of any interfering external influences (malware scanners for example). Repeat the tests to make your results reliable.

Once you have cured one bottleneck, the next bottleneck might become visible.


问:
How do you convince development teams to move to a new version of middleware?
I'm working on a project to update our (out of support) middleware stack to a stable but supported version.  There are several teams with applications running on the version we currently have in production and understandably nobody wants to carry the risk of being the first to run on the newer version.

What strategies have you used or found most compelling to move to a new release like this in the past?

There are some performance and functional benefits offered by the newer version but there isn't really any major technical incentive for the teams to move that's a must-have right now.  This is mainly being driven by the cost of extended support for the old version and also a desire by the infrastructure teams to be running on a supported version with the improved management offered by the newer version.

It's more of a people question than a technology question.

答:
Deprecated or obsolete products or frameworks are usually best categorized (and "sold") as Technical Debt.

If the new version offers fantastic improvements or benefits, then your job is easier. But even if it doesn't, staying on an older version incurs several risks:

Lack of developer support. This is never a problem until it's a problem - get it?

Lack of community support. Over time, the forums, Q&A sites, mailing lists, etc. that you've come to rely on will start ignoring your questions because nobody uses your version anymore.

Rev-lock. Upgrades become progressively more painful the more versions you are behind. Upgrading from 1.0 to 1.1 or from 1.9 to 2.0 is usually no big deal, but upgrading from 1.0 to 2.0 might take weeks or months to sort out all the issues. Paradoxically for managers, the more frequently you upgrade, the less overall time you will spend on upgrades, because the scope of changes is small for each, and problems are easy to fix.

Loss of productivity (AKA opportunity cost). "Some" performance and functional benefits may not seem very interesting, but that 10% boost is compounded over every feature/sprint/release and amortized over a period of several weeks or months. If you could complete an estimated 12-month project in 10 months by spending 1 week on the upgrade, wouldn't that be a wise investment?

Legacy code problems. Once a new version has fairly wide distribution, the developer will usually stop fixing bugs, security vulnerabilities, and other serious problems on the older versions. This significantly increases your chance of encountering a critical failure or a system being compromised or your data being stolen. Zero-day vulnerabilities exist but their exploitation is nowhere near as common as those from old, unpatched systems.

This doesn't mean that you always need to be on the latest and greatest version of everything, as there are problems associated with that as well. But on my team I make a point of upgrading at least one framework to the latest version at the beginning of every sprint. If it causes problems, fix them or roll it back. It's not a difficult pace to maintain, and it means we're usually no more than a month or two behind on any single product or framework, except sometimes where IT or corporate needs to be involved.


问:
What will be the better way for data retrieval on application that needs to handle limited amount of data.?
This is not really a coding question since, I am not adding any code in here. Since, adding my code snippets itself would make this question really long. Instead, I am pretty interested in knowing a better ways for data retrieval on application that needs to handle limited amount of data which isn't updated regularly. Let's take this example:

I am writing an application which gets a schedule as an XML from server. I have written a logic in order to parse XML version and update database only if the version is newer than the local version. Although the update is checked automatically/manually on daily basis based on user preference, the actual version update happens only once per few months or so. Since, this  is done by some other authority which doesn't provide API but, rather inform publicly on their changes.

The actual XML contains a "(n number of groups)(days in a week) (n number of schedule)" . The group is usually 6 and the number of schedule is usually 2. So basically there would usually be only around 100 strings.

Now although I have used SQLite at the moment. I want to know how to make update on database. Should I show progress dialog that the application is updating and exit the app when it's done? Since, my updates are infrequent i don't think this will really harm user experience but, is there any better ways to do it? Because I don't want update to be made when user is searching which is done using database. This will cause an database already open exception. Atleast I have faced this problem before.

Is it better to rather parse XML every time when user wants to view certain things or to use SQLite? Since, I make lots of use of adapter in my app to create lists, will that degrade the performance?

It would really be a great help if anyone can give me better overview about it. Or may be counter argument against each.

Many thanks!

答:
Your architecture is fine, you just need some tweaks for updates:

have your app close the SQLite file when not actually reading/writing to it. This will let the background process update most of the time.

have your background process loop around, waiting for the sqlite file to be free

(alternately) have your background process write to a updates file, and your app checks for the updates file at startup and periodically (when running). It then imports the data from the updates file. (Note: when creating the updates file, write somewhere else, them 'move' the file to the updates file to prevent races from a partially-written updates file.)

Also, do you need updates when the app is not running? If not, just have the app update at startup (if the data is stale) and periodically (in case the app is running for days).

There is no need for a progress bar as long as updates are quick.  Even if updates are slow, you may not need a progress bar -- especially if you do background updates when the user is working on something else.

Ideally, at app startup you show the stale data, but have a little indicator that says "updating". When the indicator goes away, the user can assume the data is up-to-date.

OwnerDisplayName: Milanix


问:
What are the advantages and disadvantages of cryptographically signing commits and tags in Git?
So someone peer reviewed my work, and he told me that I should always sign my commits and tags cryptographically. When asked why, he didn't know to explain it to me, and said "It's just a good thing to do".

Trying to avoid an obvious chimpanzee scenario, why should I really? Are there really so many distinct advantages and no disadvantages?

What are the practical reasons which would make me want to sign every commit and tag I make?

答:
(This is largely based on A Git Horror Story: Repository Integrity With Signed Commits—a very good read, and more information than I could put into an answer.)

There are a number of ways in which a git repository can be compromised (this isn't a security flaw, just a fact of life—one should not avoid using git because of this). For example, someone may have pushed to your repository claiming to be you. Or for that matter, someone could have pushed to someone else's repository claiming to be you (someone could push to their own repository claiming to be you too). This is just part of life in a DVCS.

Just as an example:

```<code>$ git config --global user.name 'Madara Uchiha'
$ git config --global user.email muchiha@example.com
</code>```

There, I've changed my git configuration to pretend I'm you. And now I can commit away and let those commits somehow make their way into the production build, and it looks like you've done it.

With signing of the commits (and tags), one can prove that certain commits and tags were from you (and things that aren't signed shouldn't have made it into the production build). That's really the key to it all—by signing commits you've said it's your work.

The "your work" aspect is particularly important in the linux kernel (and thus git) that is occasionally hit with copyright lawsuits. By signing commits you say that you have the right to the software—it tracks the origin. It may be that you've got no access to the source that is being claimed as copyright and the claim is groundless. It may be that the company forgot that you were working for them a few years ago and under their direction added material to the kernel, or whatever.

There is some debate as to if every commit should be signed. From GPG signing for git commit? (back in '09), Linus wrote:

Signing each commit is totally stupid. It just means that you automate it, and you make the signature worth less. It also doesn't add any real value, since the way the git DAG-chain of SHA1's work, you only ever need one signature to make all the commits reachable from that one be effectively covered by that one. So signing each commit is simply missing the point.

Much more about the thoughts on signing in git can be read there too.

That said, it made its way into git anyways.

There seems to be a majority consensus that signing commits is unnecessary, but signing tags is very good. That blog post linked at the top suggests that one should sign everything anyways. As I said, there's some debate about if every commit is necessary or not.

The key to the "sign every commit" debate probably has to do with the workflow you use. Most people make a bunch of commits in their local repo, and then push that set. It should be sufficient to tag the final collection (assuming, that is, you make sure that all the changes are correct). If you are working in an environment where lots of single commits are moving around, the distinction between a tag and a commit becomes less… distinct—and signing commits may become more useful.

Body:
(This is largely based on A Git Horror Story: Repository Integrity With Signed Commits—a very good read, and more information than I could put into an answer.)

There are a number of ways in which a git repository can be compromised (this isn't a security flaw, just a fact of life—one should not avoid using git because of this). For example, someone may have pushed to your repository claiming to be you. Or for that matter, someone could have pushed to someone else's repository claiming to be you (someone could push to their own repository claiming to be you too). This is just part of life in a DVCS.

Just as an example:

$ git config --global user.name 'Madara Uchiha'
$ git config --global user.email muchiha@example.com

There, I've changed my git configuration to pretend I'm you. And now I can commit away and let those commits somehow make their way into the production build, and it looks like you've done it.

With signing of the commits (and tags), one can prove that certain commits and tags were from you (and things that aren't signed shouldn't have made it into the production build). That's really the key to it all—by signing commits you've said it's your work.

The "your work" aspect is particularly important in the linux kernel (and thus git) that is occasionally hit with copyright lawsuits. By signing commits you say that you have the right to the software—it tracks the origin. It may be that you've got no access to the source that is being claimed as copyright and the claim is groundless. It may be that the company forgot that you were working for them a few years ago and under their direction added material to the kernel, or whatever.

There is some debate as to if every commit should be signed. From GPG signing for git commit? (back in '09), Linus wrote:

Signing each commit is totally stupid. It just means that you automate it, and you make the signature worth less. It also doesn't add any real value, since the way the git DAG-chain of SHA1's work, you only ever need one signature to make all the commits reachable from that one be effectively covered by that one. So signing each commit is simply missing the point.

Much more about the thoughts on signing in git can be read there too.

That said, it made its way into git anyways.

There seems to be a majority consensus that signing commits is unnecessary, but signing tags is very good. That blog post linked at the top suggests that one should sign everything anyways. As I said, there's some debate about if every commit is necessary or not.

The key to the "sign every commit" debate probably has to do with the workflow you use. Most people make a bunch of commits in their local repo, and then push that set. It should be sufficient to tag the final collection (assuming, that is, you make sure that all the changes are correct). If you are working in an environment where lots of single commits are moving around, the distinction between a tag and a commit becomes less… distinct—and signing commits may become more useful.

ContentLicense: CC BY-SA 4.0


问:
Factory for arrays of objects in python
Ok, the title might be a little misleading.

I have a Window class that draws widgets inside itself in the constructor. The widgets are all of the same type.

So I pass a list of dictionaries, which contain the parameters for each widget. This works quite nicely, but I am worried that the interface to callers is obfuscated.

That is, in order to use Window, one has to study the class, construct a correct list of dictionaries, and then call the constructor with only one parameter - widgets_params.

Is this good or bad design? What alternatives does the python syntax provide?

答:
I don't know what your widget parameters are, but why not a Widget class ? Hence, you can check parameters inside the Widget constructor, and name the parameters:

```<code>class Widget:
    def __init__(self, x0, y0, x1, y1): # Given these are the parameters
        ... stuff including possibly some check

w = Window()
w.draw([Widget(x0=12,y0=20,x1=10,y1=20), Widget(x0=...,y0=...)])
</code>```

I stop here, but you see the idea

Title: Factory for arrays of objects in python

Body:
I don't know what your widget parameters are, but why not a Widget class ? Hence, you can check parameters inside the Widget constructor, and name the parameters:

class Widget:
    def __init__(self, x0, y0, x1, y1): # Given these are the parameters
        ... stuff including possibly some check

w = Window()
w.draw([Widget(x0=12,y0=20,x1=10,y1=20), Widget(x0=...,y0=...)])

I stop here, but you see the idea


问:
What causes bad performance in consumer apps?
My Comcast DVR takes at least three seconds to respond to every remote control keypress, making the simple task of watching television into a frustrating button-mashing experience. My iPhone takes at least fifteen seconds to display text messages and crashes ¼ of the times I try to bring up the iPod app; simply receiving and reading an email often takes well over a minute. Even the navcom in my car has mushy and unresponsive controls, often swallowing successive inputs if I make them less than a few seconds apart.

These are all fixed-hardware end-consumer appliances for which usability should be paramount, and yet they all fail at basic responsiveness and latency. Their software is just too slow.

What's behind this? Is it a technical problem, or a social one? Who or what is responsible?

Is it because these were all written in managed, garbage-collected languages rather than native code?  Is it the individual programmers who wrote the software for these devices? In all of these cases the app developers knew exactly what hardware platform they were targeting and what its capabilities were; did they not take it into account? Is it the guy who goes around repeating "optimization is the root of all evil," did he lead them astray? Was it a mentality of "oh it's just an additional 100ms" each time until all those milliseconds add up to minutes?  Is it my fault, for having bought these products in the first place?

This is a subjective question, with no single answer, but I'm often frustrated to see so many answers here saying "oh, don't worry about code speed, performance doesn't matter" when clearly at some point it does matter for the end-user who gets stuck with a slow, unresponsive, awful experience.

So, at what point did things go wrong for these products? What can we as programmers do to avoid inflicting this pain on our own customers?

答:
Is it because these were all written in managed, garbage-collected languages rather than native code?

No. Slow code will perform poorly regardless. Sure, a particular language may introduce certain classes of problems while solving others. But good programmers are quite capable of finding workarounds given enough time.

Is it the individual programmers who wrote the software for these devices?

Partly. In many cases it is quite likely at least a contributing factor. This is an unfortunate side-effect of an industry where good programmers are in high demand and short supply. Also the gulfs between various levels of technical ability can be quite large. So it stands to reason that sometimes the programmers tasked to implement certain software could be congratulated just for getting it to work (sort of).

In all of these cases the app developers knew exactly what hardware platform they were targeting and what its capabilities were; did they not take it into account?

Partly. For a start, the exact hardware platform is probably not known, as that is often negotiated with various manufacturers in parallel during software development. In fact, there can even be small (but not necessarily insignificant) changes to underlying hardware after initial release. However, I would agree that the general capabilities will be known.

Part of the problem is that software probably isn't developed on the hardware, it's done in emulators. This makes it difficult to account for true device performance even if the emulators are 100% accurate - which they aren't.

Of course this doesn't really justify insufficient testing on the appropriate prototype hardware before release. That blame probably lies outside of dev/qa control.

Is it the guy who goes around repeating "optimization is the root of all evil," did he lead them astray?

No. I'm pretty certain they don't listen to him anyway; otherwise he wouldn't be misquoted so often (that's supposed to be "premature optimisation ..."). :-D

It's more likely that too many programmers take one of 2 extremes with regards optimisation.

Either they either ignore it completely.

Or they obsess themselves with minutiae that has nothing to do with the actual performance requirements. The net effect being that budget runs out and the code is too obfuscated to optimise the real performance problems safely.

Was it a mentality of "oh it's just an additional 100ms" each time until all those milliseconds add up to minutes?

Possibly. Obviously if Sleep(100) has been used as the equivalent of tissue paper used to slow the bleeding of a severed limb - then problems are to be expected. However, I suspect the problem is more subtle than that.

The thing is modern computing hardware (including embedded devices) is much faster than people give them credit for. Most people, even "experienced" programmers fail to appreciate just how fast computers are. 100ms is a long time - a very long time. And as it so happens, this "very long time" cuts 2 ways:

The first is that programmers worry unnecessarily about the things that a computer does extremely quickly. (It so happens that it was just such a concern "incrementing a value 300 times per second" that led me here in the first place.)

The second is that they sometimes fail to show due concern when things do take a very long time (on the computing timescale). So:

if they ignore the effects of latency when communicating over a network or with a storage device;

if they ignore the impact of a thread blocked and waiting for another thread;

if they forget that because computers work so quickly it is very capable of repeating a task far more often than it should, without the developer being aware of a problem

... if any combination of such oversights occur, a routine will unexpectedly run very slowly (on the computing timescale). A few repeats and it will even be noticeable by humans - but may be tricky to pin down because hundreds of interconnected things are all running quickly by themselves.

Is it my fault, for having bought these products in the first place?

Yes definitely. Well, not you personally but consumers in general. Products are sold (and bought) by feature checklists. Too few consumers are demanding better performance.

To illustrate my point: The last time I wanted to buy a cell-phone, the store couldn't even offer a demo model to play with in-store. All they had were plastic shells with stickers to show what the screen would look like. You can't even get a feel for the weight like that - let alone performance or usability. My point is that if enough people objected to that business model, and voted with their wallets to voice their objection, we would be one small step in the right direction.

But they don't, so we aren't; and every year new cell-phones run slower on faster hardware.

(The questions not asked.)

Are marketing people to blame? Partly. They need release dates. And when said date looms, the choice between "get it working" and "make it faster" is a no-brainer.

Are sales people to blame? Partly. They want more features in the checklist. They hype up feature lists and ignore performance. They (sometimes) make unrealistic promises.

Are managers to blame? Partly. Inexperienced managers might make many mistakes, but even very experienced managers may (quite rightly) sacrifice time to resolve performance issues in favour of others concerns.

Are specifications to blame? Partly. If something is left out of specification, it's that much easier to "forget" about it later. And if it's not specifically stated, what's the target? (Although I do personally believe that if a team takes pride in its work, they would worry about performance regardless.)

Is education to blame? Maybe. Education will probably always be on the back-foot. I certainly disapprove of "education" that rapidly churns out beginners with a superficial understanding software development. However, education that is backed up with theory, and instills a culture of learning can't be bad.

Are upgrades to blame? Partly. New software, old hardware really is tempting fate. Even before version X is released, X + 1 is in planning. The new software is compatible, but is the old hardware fast enough? Was it tested? A particular performance fix may be rolled into the new software - encouraging an ill-advised software upgrade.

Basically, I believe there are many contributing factors. So, unfortunately there's no silver bullet to fix it. But that doesn't mean it's doom and gloom. There are ways to contribute to improving things.

So, at what point did things go wrong for these products?

IMHO we can't really identify any single point. There are many contributing factors that evolved over time.

Bean counters: cost cutting, market timing. But then again would we have made the advances we have achieved without the pressure?

High demand and low supply of skilled people in the industry. Not just programmers, but also managers, testers, and even sales-people. Lack of skills & experience leads to mistakes. But then again it also leads to learning.

Bleeding-edge technology. Until a technology matures, it will regularly bite in unexpected ways. But then again it often provided a number of advantages in the first place.

Compounded complication. Over time, the industry has evolved: adding more tools, technologies, layers, techniques, abstractions, hardware, languages, variation, options. This makes it somewhat impossible to have a "full" understanding of modern systems. However, we are also capable of doing a lot more in a far shorter time as a result.

What can we as programmers do to avoid inflicting this pain on our own customers?

I have a few suggestions (both technical and non-technical) which may help:

In sofar as it's possible - use your own product. There's nothing like first hand experience to reveal things that are awkward, slow or inconvenient. However you will need to consciously avoid bypassing deficiencies due to "insider knowledge". E.g. If you have no problems synching contacts because you do it with a backdoor Python script - you're not using "the product". Which brings up the next point...

Listen to your users (preferably first hand, but at least second hand via support). I know programmers (generally) prefer to stay hidden away and avoid human interaction; but that doesn't help you discover the problems other people experience when using your product. E.g. You might not notice that the menu options are slow, because you know all the shortcuts and use those exclusively. Even if the manual fully documents all shortcuts, some people will still prefer the menus - despite being insufferably slow.

Strive to improve your technique skills and knowledge on a continuous basis. Develop the skill to critically analyse everything you learn. Reassess your knowledge regularly. In some cases, be prepared to forget what you thought you knew. Which brings up...

Some technologies / techniques can be very tricky leading to subtle misunderstandings and incorrect implementations. Others through the evolution of common knowledge or available tools may fall in or out of favour (e.g. Singletons). Some topics are so tricky that they breed a bunch of "hocus-pocus pundits" that propagate a huge body of misinformation. A particular bugbear of mine is the misinformation surrounding multi-threading. A good multi-threaded implementation can significantly improve user experience. Unfortunately a lot of misinformed approaches to multi-threading will significantly reduce performance, increase erratic bugs, increase dead-lock risks, complicate debugging etc. So remember: just because an "expert" said it, doesn't make it true.

Take ownership. (No seriously, I'm not playing boardroom bingo.) Negotiate with managers, product owners, sales people for performance features taking precedence over some checklist items. Demand better specifications. Not childishly, but by asking questions that get people thinking about performance.

Be a discerning consumer. Pick the phone that has less features but is faster. (Not faster CPU, faster UI.) Then brag about it! The more consumers start demanding performance, the more bean counters will start budgeting for it.


问:
estimation method at the "just finished definition phase"
We are basically using Waterfall life cycle methodology.
Requirement Analysis: I get a use case created by some one else.
Design (talking only about Low level design): I get some little feeling about how would I design it, may be either instantly/ or after some time.
Coding+Unit Testing: In case of unit Testing I am not using any TDD, but I am trying to get full code coverage, through mocks and etc. after the coding is done.

I am being asked about estimates just after the Requirement walk through.
Since I have only a fair amount of idea about how the design will look like, I have no way to say about estimates.
As for the coding part is considered, how can I get the total number of methods at the "just finished definition phase" (I never know how much will I be refactoring at this stage), Unit Testing with full code coverage: I haven't written a code, then How can I know how many behaviors are there to test for one method and hence time.

Is there some scientific way/ or other way to know this at this stage?

Note: I have already read this possible similar question.

I can break down all my tasks to small units, but I am having problem to give an estimate for each unit.

Edit1

This is part of my problem too it all started from here. Our Organization also unit tested (or correctly saying performed integration testing) manually or through emulators etc. So whenever some enhancements come for a particular client You need to create test data again, and what about any breaking changes You have introduced. So, I introducing Automated Unit Testing, but now there is again a problem for correct estimation which is necessary to give the organization farsighted view of "time estimate of creating a test suite with code" in simple words build to validation team.

Kindly help.

答:
I suggest that you read about something called the Cone of Uncertainty.

It is provably impossible to accurately estimate the completion date of a project before implementation or even design has actually started. That's not to say you can't estimate at all, but at this stage of planning, the actual duration could be as much as 4x your estimate, even if you are able to come up with highly accurate task estimates.

This is why waterfall is evil. Even Royce only proposed it as a straw-man for what you shouldn't do. At least try to get buy-in for the RUP and allow for some degree of iteration, otherwise you're screwed.

If you're really going to be held to whatever estimate you come up with (in other words, it's not actually an estimate, but rather a deadline), then spend a few days or weeks developing an architecture and usability model, estimate your features/tasks, add it up, and multiply by 4. That is about the best heuristic available.

If you anticipate any problems with overhead (organizational busywork), training, turnover, etc... then add more fudge factor to account for it. Estimate the percentage of time per day that the project team will actually spend on project work, and divide by that number to get an adjusted estimate. This is separate from the 400% margin of error above; that estimate is for effort whereas your adjusted estimate is for time.


问:
Software Licenses: No Distribution and Private Selling Using Dual Licenses
I recently wrote a couple of WordPress Themes in PHP and was wondering what license I should put on it. I don't mind users reusing my code, but I don't want them to be able to sell and redistribute my themes as I want to retain that right. I heard somewhere that an all rights reserved link would stop the distributing etc... Is that true or do I need to include another license and dual license my Themes?

So to sum it up I want to use a license to stop others from selling and distributing my themes, while at the same time letting others use the code if they want to.

答:
"All rights reserved" will not have the desired effect. Without specifying a license this will imply general copyright, which won't let viewers of the code copy it in any way: no reselling, but also no noncommercial reuse. Dual licensing also would not be suitable. In the event software is available under two different licenses the licensee can pick which terms they prefer to abide by.

Researching the answer to this question lead me to a brief but comprehensive thread on this topic at Stack Overflow. In the name of semantic content, a TL,DR:

None of the popular free software licenses prohibit commercial sale of freely obtained source code (although in practice the GPL discourages it). This is a philosophical thing; cf. linked SO article. The closest license to what you're asking for is the Noncommercial version of the Creative Commons license.

Creative Commons discourage the use of the CC license for software, but I would say this is a corner case. A WP theme is a creative work which happens to contain code.


问:
Consolidating hotels data from various booking sites with different IDs or reference
In one of my projects, I have data for hotels, and other booking sites are able to book this hotel. For example:

Hotel A - Booking (ID = 4002), Expedia (ID = 123), Priceline (ID = 147)

The three booking engines each uses their own Id to reference to Hotel A. I would need to check manually and make the right reference to the hotel. If I have 100,000 hotels, I have to check manually 300,000 (considering 3 booking sites) times?

They might provide API, then I can cross check the name, address or latitude/longitude, but if they differ a little bit then I might give the wrong reference to the wrong hotel.

I'm sure there are better ways to do this. There are many travel sites out there which do hotel price checking on many booking sites, but how do they do to make sure they are checking the right hotel on these booking sites?

Anyone has any experience on this?

答:
If I have 100,000 hotels, I have to check manually 300,000 (considering 3 booking sites) times?

No. That would not be the best way to do it.

They might provide API, then I can cross check the name, address or latitude/longitude, but if they differ a little bit then I might give the wrong reference to the wrong hotel.

You have the right idea.

Here is what you need to do:

"Clean" the incoming addresses with an address normalizer service.

Here's a Stackoverflow question to get you started, but you can find much more information through Google.

Anticipate that the address normalizer service will not be a silver bullet.

Emphasis: You may need to link/resolve a very small number of addresses on your own.

When all addresses have been normalized/linked, you can create a linking table in your database so that you can translate addresses to codes for each booking site.


问:
Is it possible to build a custom email client for Gmail using Java APIs?
Is it possible to build a custom email client for Gmail using Java APIs?

Or only Google can do that?

答: Yes, you can connect to Gmail using IMAP and POP3. In other words, you can use any (?) IMAP/POP3 client, such as Mozilla Thunderbird or Outlook. You can also write your own client using Java IMAP client.</p>


问:
What is the benefit of 64 bit A7 in iPhone
I'm trying to figure out why going to 64 bit processors is such a big deal in an iPhone. I understand that there will be twice as many registers so the processor can work with twice as much data which should increase performance.

However I don't see many phones going to more than 4GB of memory any time soon. It seems like overkill and it would negatively impact battery life.

Another problem that I see is that most variables now need twice as much memory. This will create problems in a mobile environment with small amounts of memory.

I believe that the folks at Apple are intelligent and they probably have great reasons for doing this, I'm just trying to understand them.

EDIT

Don't know much about GPU's but I was told that with 64 bit registers 2 pixels can be loaded into each register and operations can be performed on them individually. Is there a graphical advantage regarding 64 bit?

答:
Benchmarks.

For some implementations capable of both 32 vs. 64 bit architectural modes of with x86, MIPS and ARM ISAs, the 64 bit mode benchmarked faster on certain important applications.  One key reason is that the 64 bit ISAs are newer and the ISA architects thus knew more about the application statistics and how to optimize for that set of application behaviors when defining the ISA.  And a new processor ISA needs to be future-proof against application memory needs that are growing at Moore's law pace, and  which have already grown over a million-fold in the mobile device area.

Thus the new arm64 ISA likely benchmarks faster on any performance constrained code you might develop (it has on my code), as well as allowing dumb C pointers to address the vast virtual address spaces likely to become common a decade or more hence (which is much less time than the original 32 bit ARM ISA has already existed).

Performance on your particular set of applications (measure to confirm) is a great reason to prefer arm64.


问:
Why do development devices give you more resources than a typical device?
I have created an app that works on my 4th generation iPod Touch and my company's 5th generation iPod touch.

We were about to release, when we found a crash that occurs after any non-developer device runs the app*.

The notion came up that a device registered as a 'developer device' gives your app more resources to use. This doesn't seem right to me, since I couldn't think of any reason that would exist - I feel like it is more likely an issue with building or provision profiling.

However, that prompted a discussion. Why do devices such as game console development kits, devices that have more capabilities than the target platform, exist in the first place? Of course it is nice to stress test a program, but wouldn't a more accurate representation of the target platform make more sense?

TL;DR - Why do development kits have more resources than target platforms?

*With a non-developer device being any >3rd gen. iOS device  that downloads the app from our server, not directly from a computer with the app & xcode installed.

Note there is another question that reads similar, but it is actually different, because that other question is asking about simulator, and I understand that there are massive differences between using a simulator and an actual device.

答:
With iOS, a device enabled for Development allows you to directly run Debug builds, which may contain a different set of compiler bugs than a Release build, as well as run apps under a debug nub, which may subtly change thread timing and memory usage, which can also show/hide various threading and leaked memory bugs.

A development device would not be of much use without a debug capability, and a user device with debug capability would present a (more) severe app and app data security problem.


问:
MPL 2.0. dynamically linking to GPL
Let say that library "A" is published under GPL.

Library "A" exposes some API functions for dynamic linking.

I wrote a wrapper library "B" for usage of "A" in another language.

Library "B" dynamically links to the library "A" (calls are made to the exposed API functions) .

I would like to publish my "B" wrapper library under MPL v.2.0.

The main question is... is this legal?

答: As long as "A" is published under GPL rather than LGPL, "B" is considered a derived work and must be distributed under GPL. GPL only stops at process boundary, only LGPL stops at dynamic link boundary.</p>

Title: MPL 2.0. dynamically linking to GPL


问:
How do I unit test multi-threaded code?
Are there ways to unit test your multi-threaded code for race conditions and deadlocks?

To see if they are performing the way they should be...

答:
Valgrind has Helgrind which really helps. Not only does it help point out races that could lead to starvation or deadlock, the slight slowdown of having the program profiled sometimes exposes races that might not be seen otherwise.

So, even if you go commando with some kind of lock free method, it still helps :)

It is POSIX centric, however. It ships with headers that easily make simple unit test libraries like TAP aware that it is running, which is also really helpful. For instance, you could have a thread that normally would not block when trying to acquire a lock go ahead and block (perhaps randomly), just to simulate starvation.

ContentLicense: CC BY-SA 2.5

Title: How do I unit test multi-threaded code?


问:
Node.JS or Scala for mobile and web apps
I am coming from a php background with some python as well. I want to start working on a different language for both web and mobile development. I am also interested in real time apps dealing with games.

I am looking at node.js because I can use tools like titanium and/or phone gap to have my apps ported and compiled to native java code, or in a way that makes it runnable on mobile (web views). I like this path because I can use existing JS knowledge to build apps.

I am also looking at scala. I have done some C# as well as tinkered with Java about 5 years ago. And I do like that I can use scala to make native android apps. But unlike node/js which can be made to also work on other mobile os's, this only works on android. In a way, that doesn't really bother me. But scala seems like it would have much better performance for gaming that JS compiled to android. But I do not know how well.

Ine the end I want to focus on socket and REST based web apps for API's that users can have access to, as well as some mobile development. I want to get towards games and interactive apps.

The question is, what features of Scala would benefit me over the node/js side of things for making real time applications on web or mobile? I was looking at using frameworks like lift or play for web.

Node also makes real time easy with socket.io and node handles much of that in the background. This is why I think node could be a great choice. So I was hoping someone could give some insight on features in Node, that would have some benefit over scala. I don't really want to hear 'this is better cause its webscale or related things. I was hoping for more facts about features that would benefit what I want to do. I already understand why node is good. I just dont know much of anything about scala. Or how they may compare for what I want to accomplish.

答:
I agree with all that @BraveNewCurrency said. I'd like to add some comments.

Personally, I'd use Scala in the server and CoffeeScript in the client, AFAIK Play allows to integrate them in the development (placement of the folders, etc.), CoffeeScript has the same interoperability of Javascript and a nicer syntax and Scala has the same maturity and library availability of Java, with a nicer syntax (and semantics?).

On the other hand, if you don't need the maturity and availability of libraries of Java then Node.js provides a uniform language for the development and you may be more confident with Javascript than Scala (and its ecosystem, like SBT or Maven, etc. when compared with npm, etc). It's not a silver bullet for the system, but it may be comfortable for the developer. That really depends on the person. Personally I prefer to have types in the server, they help to use code written by other people that may not be the most disciplined or best programmers in the world, which statistically should happen quite often.

To wrap it up, for the client it's either Javascript or Coffeescript. Scala wouldn't make much sense there, it's a no brainer.

In the server there are Node.js gurus doing impressive stuff, and it may be better suited for something quick (and "dirty") if your kung fu is strong enough. On the other hand Scala is going to allow better integration into something big (and "enterprisey") specially if you would like to collaborate with more people at some point. So that is more a matter of suitability for (a not yet specified) purpose and personal tastes.


问:
Will a binary include methods that are not called in the source code?
[Potentially misleading title, but I'm not sure how best to word it.]

Theoretical question on compilers and language design.

Say I'm re-implementing a method in a code base. Instead of removing or commenting out the method that I'm re-implementing I leave it where it is, for reference and testing purposes, and just remove all the calls to it. Something like the following (in C-style pseudo code):

```<code>public void aMethodToCallFooVariants()
{
   // oldFoo();
   newFoo();
}

private void oldFoo ()
{
   // Some code here that's not very good
}

private void newFoo ()
{
   // Some better code here
}
</code>```

newFoo is called by the method that originally called oldFoo, meaning that oldFoo is no longer called anywhere in the source code, but it still in the listing.

Are compilers smart enough such that when I run my build script, the code for oldFoo isn't included in the compiled binary, or will oldFoo still be included but not called anywhere? I can understand if public method will still be included, they could be called by code that is external to the compiled binary (especially if it's compiled as a library). But would the private method still be compiled into the binary?

答:
That depends on the compiler and linker and how well their dead code elimination works. It is important to note however that in a turing-complete language (with reflection) it is undecidable whether a certain piece of code ever gets reached (halting problem hard)

In other words if you use a source control press that delete button and leave a message in the commit and/or mention is in the documentation of the new method.

You can use a transition period where you mark the method deprecated and have the compiler issue a warning each time the old version is used.


问:
Optimized Special Character Escaper vs Matcher/Pattern
I need to escape special characters which are sent to Apache Lucene.

Since the code will run on a production server, I want the code to be the fastest possible.

I've seen multiple ways to do it:

Using Pattern

Using Replace

Using Library

See: http://www.javalobby.org/java/forums/t86124.html

I'm wondering:

For trivial cases such as this, should I use RegEx or custom?

Can the below code be optimized further?

```<code>/*
 * Lucene supports escaping special characters that are part of the
 * query syntax. The current list special characters are + - && || !
 * ( ) { } [ ] ^ " ~ * ? : \
 *
 * To escape these character use the \ before the character.
 */
String query = "http://This+*is||a&&test(whatever!!!!!!)";
char[] queryCharArray = new char[query.length()*2];
char c;
int length = query.length();
int currentIndex = 0;
for (int i = 0; i < length; i++)
{
    c = query.charAt(i);
    switch (c) {
    case ':':
    case '\\':
    case '?':
    case '+':
    case '-':
    case '!':
    case '(':
    case ')':
    case '{':
    case '}':
    case '[':
    case ']':
    case '^':
    case '"':
    case '~':
    case '*':
        queryCharArray[currentIndex++] = '\\';
        queryCharArray[currentIndex++] = c;
    break;

    case '&':
    case '|':
        if(i+1 < length && query.charAt(i+1) == c)
        {
            queryCharArray[currentIndex++] = '\\';
            queryCharArray[currentIndex++] = c;
            queryCharArray[currentIndex++] = c;
            i++;
        }
    break;

    default:
        queryCharArray[currentIndex++] = c;

    }

}

query = new String(queryCharArray,0,currentIndex);

System.out.println("TEST="+query);
</code>```

答:
I would use a boolean[65536] which flags if the character has to be escaped.
I am quite confident that this is faster than the switch.

But only profiling can show if it is really faster.

```<code>String query = "http://This+*is||a&&test(whatever!!!!!!)";
char[] queryCharArray = new char[query.length()*2];
char c;
int length = query.length();
int currentIndex = 0;
for (int i = 0; i < length; i++)
{
    c = query.charAt(i);
    if(mustBeEscaped[c]){
      if('&'==c || '|'==c){
        if(i+1 < length && query.charAt(i+1) == c){
            queryCharArray[currentIndex++] = '\\';
            queryCharArray[currentIndex++] = c;
            queryCharArray[currentIndex++] = c;
            i++;
        }
      }
      else{
        queryCharArray[currentIndex++] = '\\';
        queryCharArray[currentIndex++] = c;
      }
    }
    else{
        queryCharArray[currentIndex++] = c;
    }
}

query = new String(queryCharArray,0,currentIndex);

System.out.println("TEST="+query);
</code>```

```<code>private static final boolean[] mustBeEscaped = new boolean[65536];
static{
mustBeEscaped[':']=  //
  for(char c: "\\?+-!(){}[]^\"~*&|".toCharArray()){
     mustBeEscaped[c]=true;
  }
}
</code>```

Body:
I would use a boolean[65536] which flags if the character has to be escaped.
I am quite confident that this is faster than the switch.

But only profiling can show if it is really faster.

String query = "http://This+*is||a&&test(whatever!!!!!!)";
char[] queryCharArray = new char[query.length()*2];
char c;
int length = query.length();
int currentIndex = 0;
for (int i = 0; i < length; i++)
{
    c = query.charAt(i);
    if(mustBeEscaped[c]){
      if('&'==c || '|'==c){
        if(i+1 < length && query.charAt(i+1) == c){
            queryCharArray[currentIndex++] = '\\';
            queryCharArray[currentIndex++] = c;
            queryCharArray[currentIndex++] = c;
            i++;
        }
      }
      else{
        queryCharArray[currentIndex++] = '\\';
        queryCharArray[currentIndex++] = c;
      }
    }
    else{
        queryCharArray[currentIndex++] = c;
    }
}

query = new String(queryCharArray,0,currentIndex);

System.out.println("TEST="+query);

private static final boolean[] mustBeEscaped = new boolean[65536];
static{
mustBeEscaped[':']=  //
  for(char c: "\\?+-!(){}[]^\"~*&|".toCharArray()){
     mustBeEscaped[c]=true;
  }
}


问:
What is Continous Integration (CI) and how is it useful?
Can some one explain to me the concept of Continious Integration, how it works in an easy to understand way? And why should a company adopt  CI in their code delivery workflow? I am a developer and my company (mainly the build team ) uses Team City. As a developer I always  checkout, update and commit code to SVN but never really had to bother about TeamCity or CI in general. So I  would like to understand what is the usefulness of CI? Is CI a part of Agile methodologies?</p>

答:
You might have a certain style in development: You checkout, code, compile, check, curse, change, compile, cheer, commit. You only commit working code, perhaps even in a less granular fashion like at the end of you work day, or when a feature is complete.
You verify your dependencies whenever you import API libraries.

When you start coding together with others and when there are mutual dependencies it makes sense to adopt continuous integration. Simply because you cannot know the impact of changes to people that depend on your code, and you receive no signal every time you need to update your imports.

So when either of you make a change, both projects should be built and tested together, i.e. run against each other's API, built and tested with the new library, etc. Such tests, your code and someone else's, are called integration tests.

Why continuous? Because it is easier to delegate coordination of integration to a system that tests a clean build whenever there is a change in either code base than it is to organize all of that for a human. The system is able to scale.


答:
There are two aspects to continuous integration.

The development source control strategy ensuring that developers are able to continually integrate their ongoing work with other developers stable code.

The automatic building and testing of source code triggered by a
commit to the source control

Point 1 is critical. It is the move to make the merges that developers actually perform to be frequent, and small in nature that makes the merges much more likely to be successful.

Point 2 is the tools and framework that's needed to allow point 1 to occur safely, quickly identifying merges that have failed by breaking existing code.

How useful is it?

Incredibly. As a developer working on a project it enables you to spend most of your time focusing on what you are doing, and not worry about the concurrent work from the rest of the team.  When your current work is complete, you then publish your changes to the rest of the team and over the next few hours they all merge your changes into their current work.

Without it, developers are doing big bang merges. Typically taking several days of their work, and having to merge it with all the changes made by the rest of the team at one go.  When a merge goes noticeably bad, the other developer will probably have moved onto other work, and be starting to forget the fine details to help unpick the merge mess. Even worse, without the continual building and testing, as long as the code compiles, merge bugs can appear in the code and will not be picked up until testing (or customers) find them.

Title: What is Continous Integration (CI) and how is it useful?

Body: Can some one explain to me the concept of Continious Integration, how it works in an easy to understand way? And why should a company adopt  CI in their code delivery workflow? I am a developer and my company (mainly the build team ) uses Team City. As a developer I always  checkout, update and commit code to SVN but never really had to bother about TeamCity or CI in general. So I  would like to understand what is the usefulness of CI? Is CI a part of Agile methodologies?</p>


问:
When will be safe to choose Multi-thread design without dead lock?
Sometime we really need to choose a multi-threaded design, because single-threading will block the UI or block another thread.

But sometimes using multiple threads is just one of the choices, for example, you may able to replace multi-threading with timer. In that situation, you may want to avoid the effort of investigating the performance risk of using timer and directly go to the multi-threaded design. But as we know, threading has a lot of drawbacks:

Sync issue.

Debugging is tough for sync issue.

Deadlock issue.

The #1 can always resolved by adding locks, and #3 is the hardest to resolve, it may need design level changes.
So let's focus on when will be safe to choose multi-threaded design without having deadlock issues.

I use the Following rules to judge it is safe or not:

The component only has input data and entry function call interaction.

Or the component only has output data and exit function call interaction.

Or you have entry and exit data or function call, but you can make sure all the data that goes in can be handled asynchronously. (I cannot think out of case, because you almost always need to syncronized to push the data into an queue.)

Does that make sense to you, any thought is welcome.

答:
This is a large topic. The general idea is to not share mutable state among threads. If one thread can change a value another thread is using, or depends on, you have issues that must be handled.

Your first rule is incomplete. Is the data shared? You might need atomic semantics here. For example an increment is (indirectly) a goes-in function.

The second may be sufficient, it may not be. It depends on what data it returns, on what uses the data and what other data depends on the data returned so I think there is still the possibility of deadlock here.


问:
How do I distribute my scientific software with as few dependencies as possible?
As part of my research, I write a lot of Python and MATLAB code that never needs to be distributed to anyone else. Even if I need to distribute my software, Python and MATLAB, both being interpreted, make sharing it relatively simple.

Now I am writing some software in C++ that I'd like to distribute. I have a handle on how to compile the software on my own machine, but what I don't have an understanding of is what needs to be done in order to give other people the software.

First, more about my project: I'm writing some code to compute and display visualizations. The project is graph-based, and so I am using the LEMON graph library. I'm exploring VTK and OpenGL implementations for the purpose of displaying the visualization. I'd like to write Python and MATLAB bindings for users of those environments to be able to use my software, and I'd like to produce Windows and Linux versions (I haven't thought about OS X yet...).

So, let's take the LEMON graph library as an example. It is a bunch of headers along with a small shared object. On my development system, I compile the library with CMake and link it with my project.

Now say I want to give my software to someone running on Windows. I want them to be able to download an installer, click a button or two, and have everything taken care of. I don't want them to worry about installing the LEMON library, or OpenGL. They shouldn't have to knowingly compile anything. Is this possible?

I have a feeling it is, but I come up short when searching for references. I have a vague idea that if I compile a binary on Windows I should be able to distribute that binary to anyone running a Windows OS. But what about the libraries I use? I'm guessing I need to statically link them on Windows, and that will take care of the dependency issue there. But in the back of my mind I have read that statically linking is not good practice (or is this just on Linux?)

As you can tell, I'm somewhat lost. I'd appreciate a nudge in the right direction, and some references to read if you happen to know of any!

答:
So long as the licence of the VTK libraries permits it, you might be able to write an NSIS Installer script (which will create a redistributable installer) that will install the VTK libraries in quiet mode. Quiet mode (if the VTK installer has this) will install the libraries without prompting the user for any input - this is how most video game installers work (required software is installed without prompting you to agree to the terms of use, or where to install it).

However, just blindly installing extra software might leave you in a precarious legal position. I'm not entirely sure on the legality of it, but I'd guess that you have to inform the user of all of the extra software you are about to install on their machine.

As an example, one of the installers I've scripted (for a product I work on) requires SQL Server 2005 to be installed alongside the binary. In the install script, if the user's machine doesn't have the required version of SQL server (or later) installed, it calls the MSI file for SQL Server 2005 (packaged within the NSIS installer) with the /q switch. This installs the SQL server with default settings, and all the user sees is the "installing SQL server 2005" prompt that get's thrown up whilst the MSI does it's work. We make a point of informing the user about this, and giving them the choice to install our software without it.

You might be able to create a make that will build all of your libraries for you, then call the NSIS script builder, but I'm not sure. I've not looked that far down the rabbit hole for NSIS, as we're not automating out installer builds.

Of course, you can replace NSIS with any other installer scripting environment. I've only used it here as an example, because I have a little experience with it.


答:
There are two sources of deadlock to consider.

There is designed deadlock, where the actual architectural design is the cause of the deadlock. To solve this, you need to understand the mechanism that leads up to the deadlock, and redesign the architecture.  Common issues include having two resources that need exclusive access and different sections of code obtaining the locks for these resources in a different order.

The second source of deadlock is caused by not releasing locks In this scenario, its not the design but the implementation that is at fault.  The implementation grabs exclusive access, but when it no longer needs the exclusive access it fails to release the locking mechanism.  These bugs are not always easy to identify the source because the bug is not always where the code is blocked.

There are two good strategies to adopt with dealing with multi threaded applications.

Have a really clearly designed architecture.  This will allow you to
identify and avoid designed in deadlock.

Use a logging package to log application flow and have a trace logging level that logs locks and unlocks to the log.

With both of these in place you have the evidence of what has happened in the run up to a deadlock occurring.

Title: When will be safe to choose Multi-thread design without dead lock?

Body:
Sometime we really need to choose a multi-threaded design, because single-threading will block the UI or block another thread.

But sometimes using multiple threads is just one of the choices, for example, you may able to replace multi-threading with timer. In that situation, you may want to avoid the effort of investigating the performance risk of using timer and directly go to the multi-threaded design. But as we know, threading has a lot of drawbacks:

Sync issue.

Debugging is tough for sync issue.

Deadlock issue.

The #1 can always resolved by adding locks, and #3 is the hardest to resolve, it may need design level changes.
So let's focus on when will be safe to choose multi-threaded design without having deadlock issues.

I use the Following rules to judge it is safe or not:

The component only has input data and entry function call interaction.

Or the component only has output data and exit function call interaction.

Or you have entry and exit data or function call, but you can make sure all the data that goes in can be handled asynchronously. (I cannot think out of case, because you almost always need to syncronized to push the data into an queue.)

Does that make sense to you, any thought is welcome.


问:
Is Dependency Injection worth it outside of UnitTesting
Given a constructor that will never, ever, have to use any different implementations of several objects that it initializes, is it still practical to use DI? After all, we might still want to unit test.

The class in question initializes a few other classes in its constructor and the classes it uses are pretty specific. It will never use another implementation. Are we justified in avoiding trying to program to an interface?

答:
It depends on various parameters but here are a few reasons why you could still want to use DI:

testing is quite a good reason in itself I believe

the classes required by your object might be used in other places - if you inject them it enables you to pool the resources (for example if the classes in question are threads or database connections - you don't want each of your classes to create new connections)

if initialising those other objects can fail, code higher up the stack will probably be better at dealing with problems than your class which will then probably simply forward the errors

Bottom line: you can probably live without DI in that case but there are chances that using DI will end up in cleaner code.


答:
Are we justified in avoiding trying to program to an interface?

While the advantage of coding against an interface is pretty evident, you should ask yourself what exactly is gained by not doing it.

The next question is: is part of the responsibility of the class in question to choose the implementations or not? That may or may not be the case and you should act accordingly.

Ultimately, there's always potential for some goofy constraint to come out of the blue. You may want to run the same piece of code concurrently, and the possibility of injecting the implementation might help with synchronization. Or after profiling your app you may discover you want an allocation strategy different from plain instantiation. Or cross-cutting concerns come up and you don't have AOP support at hand. Who knows?

YAGNI suggest that when writing code, it's important not to add anything superfluous. One of the things that programmers tend to add to their code without even being aware of it, are superfluous assumptions. Like "this method might come in handy" or "this'll never change". Both add clutter to your design.

Title: Is Dependency Injection worth it outside of UnitTesting

Body:
Given a constructor that will never, ever, have to use any different implementations of several objects that it initializes, is it still practical to use DI? After all, we might still want to unit test.

The class in question initializes a few other classes in its constructor and the classes it uses are pretty specific. It will never use another implementation. Are we justified in avoiding trying to program to an interface?


问:
Is such modification allowed by GPL? Which licences allow this which not?
Assume that I have library X which contains class A with method b and that library X is realeased under GPL licence.

```<code>public class A {
  public void b() {
     // this is an example of b method's body. But assume that the body of method b
     // is very complex
     System.out.println("operation a");
     System.out.println("operation b");
     System.out.prinltn("operation c");
   }
}
</code>```

Assume that I am using library X and that I need a behaviour similar to the behaviour of  the method b but with one addtition which I cannot achieve by simple extension of class A and overriding some of theirs methods.

The first question is: May I extend class A and override method b in shown below way and is it really still allowed by the GPL licence.

```<code>public class AExt extends A {
  public void b() {
     // this is an example of b method's body. But assume that the body of method b
     // is very complex
     System.out.println("operation a");
     System.out.println("operation b");
     doOperationINeed();
     System.out.prinltn("operation c");
   }
}
</code>```

The 2nd question is: Which from the common used opensource licences allow such extension and which do not?

答:
Open Source licenses, and even a lot of propriety closed source licenses will allow you to make a change like that.  However, they all put additional constraints on what you can then do with the software afterwards.

If you want to distribute the modified code, you need to read through and understand all the license terms that you received with the original code.

In the case of the (L)GPL, you must follow the terms of the (L)GPL in distributing derived code bases, which will include crediting the original author and protecting all the rights in the (L)GPL that your users must also receive for your code changes too.


答:
It depends on how certain you are that "never, ever" is correct (during the time your app will be used).

In general:

Don't modify your design just for testability. Unit tests are there to serve you, not vice versa.

Don't repeat yourself. Making an interface that will only ever have one inheritor is useless.

If a class isn't testable, it's likely not flexible/extensible for real use cases either. Sometimes that's fine - you're unlikely to need that flexibility, but simplicity/reliability/maintainability/performance/whatever is more important.

If you don't know, code to the interface. Requirements change.


答:
When you design a program or a feature, part of the thought process should be how you are going to test it.  Dependency Injection is one of the testing tools, and should be considered as part of the mix.

The additional benefits of Dependency Injection and using interfaces instead of classes are also beneficial when an application is extended, but they can also be retrofitted to the source code later quite easily and safely using search and replace.  - even on very large projects.


问:
Javascript - Avoiding variable redundancy in nested for loops
Please bear with me, I could only explain the problem in the comments of the code snippet below. Please read through them carefully. Question at the end:

I usually tend to name the variables used in for loops with i, like this:

```<code> for (var i = 0; i < arr.length; i++){
      // do some COMPLEX operations here
 }
</code>```

This looks fairly simple; but when I'm at it I may require nested for loops within the above for loop. So, introducing the complexity now:

```<code> for (var i = 0; i < arr.length; i++) {
      // do some
      // VERY
      // COMPLEX
      // operations
      // here

      for (var i = 0; i < javascript_object.list.length; i++) {
          // I may have inadvertently forgot of the variable 'i' was been used earlier
          for (var j = 0; j < javascript_object.list[i].another_list.length; j++) {
              // Perform more complex operations here
          }
      }

      this.getReports(arr[i]) // the value of this i
         // which I now think refer to the first for loop might have been changed
         // in second for loop and may lead to dangerous results!
 }
</code>```

How to avoid this from happening? How could the variables be named carefully so that it wouldn't clash with other variables being declared elsewhere?

答:
One common approach, which is also used in the code you posted is to simply to use the next letter in the alphabet, so:

```<code>for(var i = 0; i < length; i++) {
    for(var j = 0; j < length; j++) {
        for(var k = 0; k < length; k++) {
            // More loops?
        }
    }
}
</code>```

This approach is lazy, but it works.  However, I find that it can get confusing when you're not looping the same array or accessing a multi-dimensional array.  In that case, a better approach might be to simply provide more meaningful names:

```<code>for(var nameIndex = 0; nameIndex < names.length; nameIndex++) {
    for(var classroomIndex = 0; classroomIndex < classrooms.length; classroomIndex++) {
        // And so forth
    }
}
</code>```

Of course this may be a little wordy for you, but I figure better a little wordy than completely uncomprehensible code.  You were probably hoping for a neat hack here to be able to keep the i variable in its own scope.  There may even exist a way to do so, however I don't believe in that kind of solution to a problem like this for two reasons:

Nested loops should generally be discouraged anyway.  You cannot apply a best practice in a situation in which you're not following a best practice.  Call a method instead.

It would leave the next programmer scratching his head wondering why you did it that way, and it is difficult to justify such a decrease in readability just to account for name clashing.

I hope that helps!

Body:
One common approach, which is also used in the code you posted is to simply to use the next letter in the alphabet, so:

for(var i = 0; i < length; i++) {
    for(var j = 0; j < length; j++) {
        for(var k = 0; k < length; k++) {
            // More loops?
        }
    }
}

This approach is lazy, but it works.  However, I find that it can get confusing when you're not looping the same array or accessing a multi-dimensional array.  In that case, a better approach might be to simply provide more meaningful names:

for(var nameIndex = 0; nameIndex < names.length; nameIndex++) {
    for(var classroomIndex = 0; classroomIndex < classrooms.length; classroomIndex++) {
        // And so forth
    }
}

Of course this may be a little wordy for you, but I figure better a little wordy than completely uncomprehensible code.  You were probably hoping for a neat hack here to be able to keep the i variable in its own scope.  There may even exist a way to do so, however I don't believe in that kind of solution to a problem like this for two reasons:

Nested loops should generally be discouraged anyway.  You cannot apply a best practice in a situation in which you're not following a best practice.  Call a method instead.

It would leave the next programmer scratching his head wondering why you did it that way, and it is difficult to justify such a decrease in readability just to account for name clashing.

I hope that helps!


答:
Simple: </p>

```<code>  // This block with a
  // VERY
  // COMPLEX
  // operation
  // here
  // is far too large.
</code>```

<p>When blocks become so large that you cannot see all of your local variable definitions any more, they are definitely too large. Refactor such a parts to a function, this will help a lot to avoid accidentally double declarations. </p>

Title: Javascript - Avoiding variable redundancy in nested for loops

Body:
Please bear with me, I could only explain the problem in the comments of the code snippet below. Please read through them carefully. Question at the end:

I usually tend to name the variables used in for loops with i, like this:

```<code> for (var i = 0; i < arr.length; i++){
      // do some COMPLEX operations here
 }
</code>```

This looks fairly simple; but when I'm at it I may require nested for loops within the above for loop. So, introducing the complexity now:

```<code> for (var i = 0; i < arr.length; i++) {
      // do some
      // VERY
      // COMPLEX
      // operations
      // here

      for (var i = 0; i < javascript_object.list.length; i++) {
          // I may have inadvertently forgot of the variable 'i' was been used earlier
          for (var j = 0; j < javascript_object.list[i].another_list.length; j++) {
              // Perform more complex operations here
          }
      }

      this.getReports(arr[i]) // the value of this i
         // which I now think refer to the first for loop might have been changed
         // in second for loop and may lead to dangerous results!
 }
</code>```

How to avoid this from happening? How could the variables be named carefully so that it wouldn't clash with other variables being declared elsewhere?

Body:
Simple:

  // This block with a
  // VERY
  // COMPLEX
  // operation
  // here
  // is far too large.

When blocks become so large that you cannot see all of your local variable definitions any more, they are definitely too large. Refactor such a parts to a function, this will help a lot to avoid accidentally double declarations.


答:
In your example the value of i will definitely be using the one that is in the second for-loop. This is because variables are function scoped in JavaScript. So it doesn't matter how many times you var it in a function, it will be the same variable.

To avoid this, either give the variables new names or enclose them in other function calls. Since you haven't specified what these "complex" operations are, I can't suggest any good refactoring method other than extracting the second for loop into it's own function.


问:
Arguments for conforming to PSR-2
I am trying to convince the lead developer of an open-source project I'm contributing to, to conform to the PSR standards (PSR-2 in particular) created by the PHP Framework Interop Group.

He is willing to adopt PSR-0 and PSR-1, but he is opposed to PSR-2. His argument is that PSR-2 is too inconsistent: opening braces for classes and methods MUST go on the next line, but opening braces for control structures MUST go on the same line.

I believe that the difference between classes / methods at one side and control structures at the other is not an inconsistency, in fact they are different things. I also believe that consistency between different projects is far more important than treating classes / methods and control structures like they are the same, and that consistancy between projects should outweigh personal preferences... but I can't convince him.

Are there any more arguments I can use to try to convince him to use PSR-2, instead of a seperate, yet-another coding standard?

答:
Really sorry, but I think you are probably on the loosing side on this one.  Coding standards are great, but the only coding standard that is worth the disk space on the project server is the one that is actually enforced by the lead developer during code reviews.

What your lead developer is probably saying (but in different words) is that he doesn't want to be spending the time in code reviews saying that brace is in the wrong place, and then having to justify it when the other developers start grumbling about his pettiness.

Title: Arguments for conforming to PSR-2


答:
Yes you are - firstly, forget about unit testing as a reason to design your code around the unit test tools, it is never a good idea to bend your code design to fit an artificial constraint. If your tools force you to do this, get better tools (eg Microsoft Fakes/Moles that allow you many more options for creating mock objects).

For example, would you split your classes up into only-public methods just because the test tools do not work with private methods? (I know the prevailing wisdom is to pretend you don't need to test private methods, but I feel this is a reaction to the difficulty in doing so with current tools, not a genuine reaction to not needing to test privates).,

All in all it comes down to what kind of TDDer you are - the "mockist" as Fowler describes them, need to change the code to suit the tools they use, whereas the "classical" testers create tests that are more integration in nature (ie test the class as a unit, not each method) so there is less need for interfaces, especially if you use the tools that can mock concrete classes.


答:
There is a difference between a standard existing and a standard being adopted.

Standards are adopted only when either or both of the following happen:

The standard makes sense and provides more value to the project that the "costs" incurred by conforming to the standard.  Note that costs can take a variety of forms, including time spent in conforming.

There is a standards body with enough leverage that they can force others to conform to the standard in order to participate in the domain.  Hardware specifications are good examples of this scenario.

Apparently, you have neither of those cases occurring with your project.

"Yet-another-standard" standards occur in situations exactly like this.  If part, but not all, of a standard makes sense, then domain participants cherry pick the parts they like and then wrap whatever else around it to fill in the gaps.  De facto standards are frequently created this way, and if you look at the evolution of the SQL standard you'll see numerous situations where domain participants pushed the evolution of the next standard based upon functionality they had already delivered.

Sounds like you've got an in-road with PSR-0 and PSR-1.  Start with those.

Lobby the organization responsible for PSR-2 and let them know why your project isn't adopting it yet.  (Good) Standards bodies don't exist in vacuums and appreciate feedback from the domain.  Perhaps you'll be able to affect PSR-3 and make it a little bit more palatable for your team.

Title: Arguments for conforming to PSR-2

Body:
I am trying to convince the lead developer of an open-source project I'm contributing to, to conform to the PSR standards (PSR-2 in particular) created by the PHP Framework Interop Group.

He is willing to adopt PSR-0 and PSR-1, but he is opposed to PSR-2. His argument is that PSR-2 is too inconsistent: opening braces for classes and methods MUST go on the next line, but opening braces for control structures MUST go on the same line.

I believe that the difference between classes / methods at one side and control structures at the other is not an inconsistency, in fact they are different things. I also believe that consistency between different projects is far more important than treating classes / methods and control structures like they are the same, and that consistancy between projects should outweigh personal preferences... but I can't convince him.

Are there any more arguments I can use to try to convince him to use PSR-2, instead of a seperate, yet-another coding standard?


答:
With C and C++ compilers, the answer is yes - when a code unit is compiled into object code (by the compiler) all functions are listed explicitly. The linker then takes each of these object files and resolves the references to the functions - and all the functions that are left over after this linkage step, can be discarded. This is especially useful for static libraries where you only want a small part of the lib to be included, the rest is ignored and not linked into the final binary.

(obviously this doesn't happen for dynamic libraries, in this case the stubs that are present in the import library are not linked in).

Title: Will a binary include methods that are not called in the source code?

Body:
[Potentially misleading title, but I'm not sure how best to word it.]

Theoretical question on compilers and language design.

Say I'm re-implementing a method in a code base. Instead of removing or commenting out the method that I'm re-implementing I leave it where it is, for reference and testing purposes, and just remove all the calls to it. Something like the following (in C-style pseudo code):

```<code>public void aMethodToCallFooVariants()
{
   // oldFoo();
   newFoo();
}

private void oldFoo ()
{
   // Some code here that's not very good
}

private void newFoo ()
{
   // Some better code here
}
</code>```

newFoo is called by the method that originally called oldFoo, meaning that oldFoo is no longer called anywhere in the source code, but it still in the listing.

Are compilers smart enough such that when I run my build script, the code for oldFoo isn't included in the compiled binary, or will oldFoo still be included but not called anywhere? I can understand if public method will still be included, they could be called by code that is external to the compiled binary (especially if it's compiled as a library). But would the private method still be compiled into the binary?


问:
What is the history of why bytes are eight bits?
What were the historical forces at work, the tradeoffs to make, in deciding to use groups of eight bits as the fundamental unit?

There were machines, once upon a time, using other word sizes. But today, for non-eight-bitness, you must look to museum pieces, specialized chips for embedded applications, and DSPs. How did the byte evolve out of the chaos and creativity of the early days of computer design?

I can imagine that fewer bits would be ineffective for handling enough data to make computing feasible, while too many would have lead to expensive hardware. Were other influences in play? Why did these forces balance out to eight bits?

(BTW, if I could time travel, I'd go back to when the byte was declared to be 8 bits, and convince everyone to make it 12 bits, bribing them with some early 21st century trinkets.)

答:
A byte has been variously (at least) 1, 4, 6, 7, 8, 9, 12, 18, 20 and possibly 36 bits, depending on what computer you are looking at. I am taking "byte" here to mean "smallest addressable unit of memory", rather than using any sort of text-centric interpretation. (For example, the Saturn CPU, a 64-bit CPU used in the popular HP48SX/GX calculator line addresses memory in nibbles -- 4-bits.)

The 20-bit bytes were extremely common in the "IAS machines", in the 50s. 6, 12, 18 (and maybe 36) were quite popular in a variety of architectures in the 60s, 70s and to some degree 80s.

In the end, having a nice correspondence between "powers of 2" and "bits in an addressable unit" seem to have won out.


问:
Why are CIL and CLR required in .NET?
I saw this nice image here. I learned that all the compilers that support .net language convert the source code to CIL format. Now Microsoft is never bringing in .NET for all the operating system by writing a CLR for all operating systems. Then why keep such an intermediate code format and a CLR to execute that CIL. Is that not an headache to deal with. Why did Microsoft choose be like this ?

EDIT This kinda architecture has its price. It will reduce the performance, wouldn't it ? Java does this to maintain platform independence, for what reason .NET do it ? Why not keep a simple plain C like compiler. Any way will also require a compiler to convert the code to CIL if I need to add up any new language, the only difference it would make is the target language. Tat's all.

答:
Because they only need to write one compiler for C# to CIL - which is the hard part. Making an interpreter (or more often, Just-In-Time compiler) for the CIL per platform is relatively easy compared to writing a compiler from C# to (per platform) executable code.

Beyond that, the runtime can handle anything that compiles to CIL. If you want a new language (like F#) you only have to write one compiler for it and you auto-magically get all the platform support for things .NET supports.

Oh, and I can take a .NET dll and run that on windows or on linux via Mono without recompilation (assuming all of my dependencies are satisfied).

As for performance, it's debatable. There are "pre-compilers" essentially that take the CIL and make native binaries. Others argue that just-in-time compilers can make optimizations that static compilers simply cannot. In my experience, it depends a lot on what your application is doing and what platform you're running it on (mostly how good the JITer is on that platform). It's extremely rare for me to run into a scenario where .NET wasn't good enough.

Title: Why are CIL and CLR required in .NET?


答:
```<code> > Dependency Injection worth it **outside** of UnitTesting?
 > Are we justified in avoiding trying to program to an interface?
</code>```

Many answers to this question can be debated as "you might need it because .." as YAGNI if you do not want to do unittesting.

If you are asking what reasons beside unittests require to program to an interface

Yes, Dependency Injection worth it outside of UnitTesting  if you need inversion of control. For example if one module implementation need an other module that is not accessable in its layer.

Example: if you have the modules gui => businesslayer => driver => common.

In this scenario businesslayer can use driver but driver can not use businesslayer.

If driver needs some higherlevel functionality you can implement this functionality in businesslayer which implements an interface in common layer.
driver only needs to know the interface in common layer.

Body:
 > Dependency Injection worth it **outside** of UnitTesting?
 > Are we justified in avoiding trying to program to an interface?

Many answers to this question can be debated as "you might need it because .." as YAGNI if you do not want to do unittesting.

If you are asking what reasons beside unittests require to program to an interface

Yes, Dependency Injection worth it outside of UnitTesting  if you need inversion of control. For example if one module implementation need an other module that is not accessable in its layer.

Example: if you have the modules gui => businesslayer => driver => common.

In this scenario businesslayer can use driver but driver can not use businesslayer.

If driver needs some higherlevel functionality you can implement this functionality in businesslayer which implements an interface in common layer.
driver only needs to know the interface in common layer.


答:
The Windows OS is available for different CPU types, today mostly x64, x86, Intel, ARM.

CIL/CLR is independent from that hardware platform - these differences are "abstracted away" by the IL execution environment. For example, a .NET assembly compiled for "any CPU" can typically executed on Win64 as a 64 bit process, and Win32 as a 32 bit process, without the need of providing different executables.

Moreeover, the CIL allows metadata to be stored in assemblies which is not easily possible with native DLLs (it is possible, of course, MS did this before with COM components, but that technology was never as easy to handle as .NET components). That makes creation of software components a hell lot simpler and is the foundation of reflection / introspection in all .NET languages.

Title: Why are CIL and CLR required in .NET?

Body:
I saw this nice image here. I learned that all the compilers that support .net language convert the source code to CIL format. Now Microsoft is never bringing in .NET for all the operating system by writing a CLR for all operating systems. Then why keep such an intermediate code format and a CLR to execute that CIL. Is that not an headache to deal with. Why did Microsoft choose be like this ?

EDIT This kinda architecture has its price. It will reduce the performance, wouldn't it ? Java does this to maintain platform independence, for what reason .NET do it ? Why not keep a simple plain C like compiler. Any way will also require a compiler to convert the code to CIL if I need to add up any new language, the only difference it would make is the target language. Tat's all.


问:
Why normalization improves numerical precision?
I was reading the following article:

Polynomial interpolation of GPS satellite
coordinates, Milan Horemuz and Johan Vium Andersson 2006

and it states the following:

"The estimation procedure of the ai coefficients is done
with the Matlab function polyfit, which estimates the
coefficients in a least squares sense. To improve the
numerical precision, the dataset p is normalized by
centering it at a zero mean; by subtracting its mean value
p; and scaling it to a unit standard deviation by dividing
each observation with the standard deviation σp as follows..."

My question is how does the value normalization improves the numerical precision of computational operations?

答:
Imagine for a moment that the quantity you are interested in has a value in the range 42.0 - 42.999.

Imagine further that you want as much precision as possible.

As it stands, you are spending a chunk of your available bits representing the value 42, and that leaves fewer bits available to represent the 0.000 - 0.999, which in some sense is what you are really interested in.

By subtracting out the constant 42, you can now spend all of your bits representing the 0.000 - 0.999 delta, that you are really interested in.

Now, suppose you don't actually know that the values are all centered around 42.5, but you do know that they are all centered around SOME mean value.  You can calculate that mean, subtract it out, and use all your bits to represent the delta from the mean.

This is the concept behind normalization about a mean.  You spend your bits representing the quantity you are interested in, which is the delta from the mean, and you don't waste bits representing the mean itself.


答:
Dependency Injection also makes it clearer that your object HAS dependencies.

When someone else goes to use your object naively (without looking at the constructor), they will find that they will need to set up services, connections, etc.  That were not obvious because they didn't have to pass them in to the constructor.  Passing in the dependencies makes it clearer what is needed.

You are also potentially hiding the fact that you class may be violating SRP.  If you are passing in many dependencies (more than 3), your class may be doing too much and should be refactored.  But if you are creating them in the constructor, this code smell will be hidden.


问:
Functional Programming - Does Knowing It Help Job Prospects?
The main language that I use at the moment is C# and I am the most comfortable with it. However, I have started dabbling in F# and Haskell and really enjoy those langauges. I would love to improve my skills in either of those languages over time since it truly is fun for me to use them (as opposed to Ruby, which is hyped as "fun", I just don't get where the fun is, but I digress...). My question is directed at those who have hired/interviewed for programming positions (junior/mid-level): if you see a functional programming language on a resume, does it affect your opinion (whether positive or negatively) of that candidate?

My rationale for knowledge of functional programming affecting the view of a candidate is because it can show that the candidate can adapt to different methodologies and take a mulit-dimensional approach to problems rather than the "same old OO approach". (This may be off-base, please let me know if this assumption is as well!)

答:
Knowing the functional paradigm makes you a better programmer. Dabbling in languages like Haskell shows that you're interested in having more than one instrument in your mental toolbox.

That should have a concrete boost in your attractiveness as a hire. (If it doesn't, I wouldn't be interested in working for that company.)


问:
Memory allocation of Classes that don't have any global data and locks
```<code>    static void Main(string[] args)
    {
        var c2 = new Class2();
        var c3 = new Class3();
        var c1 = new Class1(c2, c3);
        c1.Method1();
    }

    class Class1
    {
        readonly Class2 _class2;
        readonly Class3 _class3;
        public Class1(Class2 class2, Class3 class3)
        {
            _class2 = class2;
            _class3 = class3;
        }
        public void Method1() {
            _class2.PerformM1();
            _class3.PerformM2();
        }
    }
    class Class2
    {
        public void PerformM1()
        {
            //do some operation
        }
    }
    class Class3
    {
        public void PerformM2()
        {
            //do some operation
        }
    }
</code>```

Question based on above code:

How much memory does object of Class1 has when it is created?

Does any memory increases or decreases when I perform c1.Method1();
keeping in mind that none of the classes have any global fields that
might acquire any space.

Edit

Expanding with one more question:

If creating new objects of Class1 and calling methods of c1 object does not involve much memory usage, then is it correct to say that I don't need a lock in the above provided sample code.

I can simply create n number of objects and assign individual object to individual Task( or thread)?

答:
You can use GC.GetTotalmemory(false) method to measure the current memory usage.

You can also use some kind of memory profilers like red gate ANTS memory profiler

Memory consumption should not increase when c1.Method1(); is performed, given C2,C3 do not have any objects initialized or refer to other classes which has objects initialized.